commit 59ae487e168119e2d2993c24c22dd9f9ebbf774f
Author: Assos Assos <assos+forge@centrale-marseille.fr>
Date:   Thu May 25 00:10:47 2017 +0200

    Weekly update of contrib modules

diff --git a/drupal7/sites/all/modules/entityreference/entityreference.info b/drupal7/sites/all/modules/entityreference/entityreference.info
index 3692ea0f..2695e465 100644
--- a/drupal7/sites/all/modules/entityreference/entityreference.info
+++ b/drupal7/sites/all/modules/entityreference/entityreference.info
@@ -29,9 +29,9 @@ files[] = tests/entityreference.admin.test
 files[] = tests/entityreference.feeds.test
 files[] = tests/entityreference.entity_translation.test
 
-; Information added by Drupal.org packaging script on 2017-05-10
-version = "7.x-1.3"
+; Information added by Drupal.org packaging script on 2017-05-23
+version = "7.x-1.4"
 core = "7.x"
 project = "entityreference"
-datestamp = "1494450489"
+datestamp = "1495557187"
 
diff --git a/drupal7/sites/all/modules/entityreference/entityreference.install b/drupal7/sites/all/modules/entityreference/entityreference.install
index 57f85a6e..ce610185 100644
--- a/drupal7/sites/all/modules/entityreference/entityreference.install
+++ b/drupal7/sites/all/modules/entityreference/entityreference.install
@@ -165,16 +165,24 @@ function entityreference_update_7002() {
 }
 
 /**
+ * Implements hook_update_N().
+ *
  * Remove duplicate rows in the taxonomy_index table.
  */
 function entityreference_update_7100() {
   if (db_table_exists('taxonomy_index')) {
+    if (db_table_exists('taxonomy_index_tmp')) {
+      db_drop_table('taxonomy_index_tmp');
+    }
+
     $tx_schema = drupal_get_schema('taxonomy_index');
     db_create_table('taxonomy_index_tmp', $tx_schema);
     $select = db_select('taxonomy_index', 'tx');
-    $select->fields('tx');
+    $select->fields('tx', array('nid', 'tid'));
     $select->groupBy('tx.nid');
     $select->groupBy('tx.tid');
+    $select->addExpression('MAX(sticky)', 'sticky');
+    $select->addExpression('MAX(created)', 'created');
     db_insert('taxonomy_index_tmp')->from($select)->execute();
     db_drop_table('taxonomy_index');
     db_rename_table('taxonomy_index_tmp', 'taxonomy_index');
diff --git a/drupal7/sites/all/modules/entityreference/examples/entityreference_behavior_example/entityreference_behavior_example.info b/drupal7/sites/all/modules/entityreference/examples/entityreference_behavior_example/entityreference_behavior_example.info
index db5a09e9..6f21bac5 100644
--- a/drupal7/sites/all/modules/entityreference/examples/entityreference_behavior_example/entityreference_behavior_example.info
+++ b/drupal7/sites/all/modules/entityreference/examples/entityreference_behavior_example/entityreference_behavior_example.info
@@ -4,9 +4,9 @@ core = 7.x
 package = Fields
 dependencies[] = entityreference
 
-; Information added by Drupal.org packaging script on 2017-05-10
-version = "7.x-1.3"
+; Information added by Drupal.org packaging script on 2017-05-23
+version = "7.x-1.4"
 core = "7.x"
 project = "entityreference"
-datestamp = "1494450489"
+datestamp = "1495557187"
 
diff --git a/drupal7/sites/all/modules/entityreference/tests/modules/entityreference_feeds_test/entityreference_feeds_test.info b/drupal7/sites/all/modules/entityreference/tests/modules/entityreference_feeds_test/entityreference_feeds_test.info
index 0bcc324b..dace68b7 100644
--- a/drupal7/sites/all/modules/entityreference/tests/modules/entityreference_feeds_test/entityreference_feeds_test.info
+++ b/drupal7/sites/all/modules/entityreference/tests/modules/entityreference_feeds_test/entityreference_feeds_test.info
@@ -8,9 +8,9 @@ dependencies[] = feeds
 dependencies[] = feeds_ui
 dependencies[] = entityreference
 
-; Information added by Drupal.org packaging script on 2017-05-10
-version = "7.x-1.3"
+; Information added by Drupal.org packaging script on 2017-05-23
+version = "7.x-1.4"
 core = "7.x"
 project = "entityreference"
-datestamp = "1494450489"
+datestamp = "1495557187"
 
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.field.inc b/drupal7/sites/all/modules/file_entity/file_entity.field.inc
index 1701c88f..66a5c490 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.field.inc
+++ b/drupal7/sites/all/modules/file_entity/file_entity.field.inc
@@ -284,45 +284,58 @@ function file_entity_field_formatter_view($entity_type, $entity, $field, $instan
       foreach ($items as $delta => $item) {
         // Protect ourselves from recursive rendering.
         static $recursive_render_depth = array();
-        $recursive_render_id = $entity_type . $field['field_name'] . $item['fid'];
+        if (!empty($item)) {
+          $recursive_render_id = $entity_type . $field['field_name'] . $item['fid'];
+          if (isset($recursive_render_depth[$recursive_render_id])) {
+            $recursive_render_depth[$recursive_render_id]++;
+          }
+          else {
+            $recursive_render_depth[$recursive_render_id] = 1;
+          }
 
-        if (isset($recursive_render_depth[$recursive_render_id])) {
-          $recursive_render_depth[$recursive_render_id]++;
-        }
-        else {
-          $recursive_render_depth[$recursive_render_id] = 1;
-        }
+          if ($recursive_render_depth[$recursive_render_id] > 20) {
+            watchdog(
+              'file_entity',
+              'Recursive rendering detected when rendering entity %entity_type: %entity_id, using the %field_name field. Aborting rendering.',
+              array(
+                '%entity_type' => 'file',
+                '%entity_id' => $item['fid'],
+                '%field_name' => $field['field_name'],
+              ),
+              WATCHDOG_ERROR
+            );
+            return $element;
+          }
+
+          $file = file_load($item['fid']);
+
+          // Add some references to the referencing entity.
+          // @see https://www.drupal.org/node/2333107
+          $file->referencing_entity = $entity;
+          $file->referencing_entity_type = $entity_type;
+          $file->referencing_field = $field['field_name'];
 
-        if ($recursive_render_depth[$recursive_render_id] > 20) {
+          $element[$delta] = file_view($file, $settings['file_view_mode'], $langcode);
+        } else {
           watchdog(
             'file_entity',
-            'Recursive rendering detected when rendering entity %entity_type: %entity_id, using the %field_name field. Aborting rendering.',
+            'In the %referencing_entity_type, the %field_name field refers to a %entity_type which does not exist. Aborting the render for it.',
             array(
-              '%entity_type' => 'file',
-              '%entity_id' => $item['fid'],
+              '%referencing_entity_type' => $entity_type,
               '%field_name' => $field['field_name'],
+              '%entity_type' => 'file',
             ),
             WATCHDOG_ERROR
           );
-          return $element;
         }
-
-        $file = (object) $item;
-
-        // Add some references to the referencing entity.
-        // @see https://www.drupal.org/node/2333107
-        $file->referencing_entity = $entity;
-        $file->referencing_entity_type = $entity_type;
-        $file->referencing_field = $field['field_name'];
-
-        $element[$delta] = file_view($file, $settings['file_view_mode'], $langcode);
       }
       break;
 
     case 'file_download_link':
+      // Prevent 'empty' fields from causing a WSOD.
+      $items = array_filter($items);
       foreach ($items as $delta => $item) {
-        $file = (object) $item;
-        if (file_entity_access('download', $file)) {
+        if (!empty($item['fid']) && ($file = file_load($item['fid'])) && file_entity_access('download', $file)) {
           $element[$delta] = array(
             '#theme' => 'file_entity_download_link',
             '#file' => $file,
@@ -342,14 +355,14 @@ function file_entity_field_formatter_view($entity_type, $entity, $field, $instan
       $source_lists = array();
       if ($multiple_file_behavior == 'tags') {
         foreach ($items as $delta => $item) {
-          if ($item['type'] == 'audio') {
+          if (file_entity_file_get_mimetype_type($item) == 'audio') {
             $source_lists[$delta] = array($item);
           }
         }
       }
       else {
         foreach ($items as $delta => $item) {
-          if ($item['type'] == 'audio') {
+          if (file_entity_file_get_mimetype_type($item) == 'audio') {
             $source_lists[0][$delta] = $item;
           }
         }
@@ -378,14 +391,14 @@ function file_entity_field_formatter_view($entity_type, $entity, $field, $instan
       $source_lists = array();
       if ($multiple_file_behavior == 'tags') {
         foreach ($items as $delta => $item) {
-          if ($item['type'] == 'video') {
+          if (file_entity_file_get_mimetype_type($item) == 'video') {
             $source_lists[$delta] = array($item);
           }
         }
       }
       else {
         foreach ($items as $delta => $item) {
-          if ($item['type'] == 'video') {
+          if (file_entity_file_get_mimetype_type($item) == 'video') {
             $source_lists[0][$delta] = $item;
           }
         }
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.info b/drupal7/sites/all/modules/file_entity/file_entity.info
index 03afc179..5476c7f1 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.info
+++ b/drupal7/sites/all/modules/file_entity/file_entity.info
@@ -9,6 +9,7 @@ dependencies[] = ctools
 dependencies[] = system (>=7.33)
 
 test_dependencies[] = token
+test_dependencies[] = views
 
 files[] = views/views_handler_argument_file_type.inc
 files[] = views/views_handler_field_file_rendered.inc
@@ -24,15 +25,16 @@ files[] = views/views_handler_field_file_link_usage.inc
 files[] = views/views_plugin_row_file_rss.inc
 files[] = views/views_plugin_row_file_view.inc
 files[] = file_entity.test
+files[] = file_entity_views.test
 
 configure = admin/config/media/file-settings
 
 ; We have to add a fake version so Git checkouts do not fail Media dependencies
 version = 7.x-2.x-dev
 
-; Information added by Drupal.org packaging script on 2016-05-31
-version = "7.x-2.0-beta3"
+; Information added by Drupal.org packaging script on 2017-05-22
+version = "7.x-2.0"
 core = "7.x"
 project = "file_entity"
-datestamp = "1464653173"
+datestamp = "1495456387"
 
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.module b/drupal7/sites/all/modules/file_entity/file_entity.module
index 36f82830..bbd4d2f1 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.module
+++ b/drupal7/sites/all/modules/file_entity/file_entity.module
@@ -1794,7 +1794,7 @@ function file_entity_query_file_access_alter(QueryAlterableInterface $query) {
  * access conditions are added for field values belonging to files only.
  */
 function file_entity_query_entity_field_access_alter(QueryAlterableInterface $query) {
-  //_file_entity_query_file_entity_access_alter($query, 'entity');
+  _file_entity_query_file_entity_access_alter($query, 'entity');
 }
 
 /**
@@ -1822,6 +1822,12 @@ function _file_entity_query_file_entity_access_alter($query, $type) {
 
   $tables = $query->getTables();
   $base_table = $query->getMetaData('base_table');
+  // Do not use the base table for general entity queries unless this is
+  // querying the file_managed table directly.
+  if ($base_table && $type == 'entity' && $base_table != 'file_managed') {
+    $base_table = '';
+  }
+
   // If no base table is specified explicitly, search for one.
   if (!$base_table) {
     $fallback = '';
@@ -1853,6 +1859,10 @@ function _file_entity_query_file_entity_access_alter($query, $type) {
               $fallback = $table;
             }
           }
+          elseif (isset($schema['fields']['entity_id']) && isset($schema['fields']['entity_type']) && isset($schema['fields']['deleted']) && isset($schema['fields']['delta'])) {
+            // The table is a field data table, use it as fallback.
+            $base_table = $table;
+          }
         }
       }
     }
@@ -1863,6 +1873,11 @@ function _file_entity_query_file_entity_access_alter($query, $type) {
         $base_table = $fallback;
       }
       else {
+        // Ignore this query as it was a general field query and no
+        // relationships were found to the file_managed table.
+        if ($type == 'entity') {
+          return;
+        }
         throw new Exception(t('Query tagged for file access but there is no fid. Add foreign keys to file_managed.fid in schema to fix.'));
       }
     }
@@ -1925,33 +1940,36 @@ function _file_entity_query_file_entity_access_alter($query, $type) {
         }
       }
 
-      if ($subquery_conditions->count()) {
+      // If there is no subquery conditions, the query is likely for file usage.
+      // Or user can only access public files.
+      // If there are subquery conditions then add them to the subquery.
+      if ($subquery_conditions->count() >= 1) {
         $subquery->condition($subquery_conditions);
+      }
 
-        $field = 'fid';
-        // Now handle entities.
-        if ($type == 'entity') {
-          // Set a common alias for entities.
-          $base_alias = $falias;
-          $field = 'entity_id';
-        }
-        $subquery->where("$falias.$field = fm_access.fid");
+      $field = 'fid';
+      // Now handle entities.
+      if ($type == 'entity') {
+        // Set a common alias for entities.
+        $base_alias = $falias;
+        $field = ($falias == 'file_managed' ? 'fid' : 'entity_id');
+      }
+      $subquery->where("$falias.$field = fm_access.fid");
 
-        // For an entity query, attach the subquery to entity conditions.
-        if ($type == 'entity') {
-          $file_conditions->exists($subquery);
-        }
-        // Otherwise attach it to the node query itself.
-        elseif ($table == 'file_managed') {
-          // Fix for https://drupal.org/node/2073085
-          $db_or = db_or();
-          $db_or->exists($subquery);
-          $db_or->isNull($falias . '.' . $field);
-          $query->condition($db_or);
-        }
-        else {
-          $query->exists($subquery);
-        }
+      // For an entity query, attach the subquery to entity conditions.
+      if ($type == 'entity') {
+        $file_conditions->exists($subquery);
+      }
+      // Otherwise attach it to the node query itself.
+      elseif ($table == 'file_managed') {
+        // Fix for https://drupal.org/node/2073085
+        $db_or = db_or();
+        $db_or->exists($subquery);
+        $db_or->isNull($falias . '.' . $field);
+        $query->condition($db_or);
+      }
+      else {
+        $query->exists($subquery);
       }
     }
   }
@@ -1959,14 +1977,19 @@ function _file_entity_query_file_entity_access_alter($query, $type) {
   if ($type == 'entity' && $file_conditions->count()) {
     // All the file access conditions are only for field values belonging to
     // files.
-    $file_conditions->condition("$base_alias.entity_type", 'file');
-    $or = db_or();
-    $or->condition($file_conditions);
-    // If the field value belongs to a non-file entity type then this function
-    // does not do anything with it.
-    $or->condition("$base_alias.entity_type", 'file', '<>');
-    // Add the compiled set of rules to the query.
-    $query->condition($or);
+    if ($base_alias !== 'file_managed') {
+      $file_conditions->condition("$base_alias.entity_type", 'file');
+      $or = db_or();
+      $or->condition($file_conditions);
+      // If the field value belongs to a non-file entity type then this function
+      // does not do anything with it.
+      $or->condition("$base_alias.entity_type", 'file', '<>');
+      // Add the compiled set of rules to the query.
+      $query->condition($or);
+    }
+    else {
+      $query->condition($file_conditions);
+    }
   }
 }
 
@@ -2479,6 +2502,9 @@ function file_entity_download_uri($file) {
 }
 
 function file_entity_file_get_mimetype_type($file) {
+  if (is_array($file)) {
+    $file = (object) $file;
+  }
   list($type, $subtype) = explode('/', $file->filemime, 2);
   return $type;
 }
@@ -2600,3 +2626,4 @@ function file_entity_features_pipe_file_type_alter(&$pipe, $data, $export) {
     $pipe['variable'][] = "pathauto_file_{$file_type}_pattern";
   }
 }
+
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.pages.inc b/drupal7/sites/all/modules/file_entity/file_entity.pages.inc
index 9d6e359b..e10cfe61 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.pages.inc
+++ b/drupal7/sites/all/modules/file_entity/file_entity.pages.inc
@@ -35,10 +35,12 @@ function file_entity_download_page($file) {
   if (!is_file($file->uri)) {
     return MENU_NOT_FOUND;
   }
-
+  // @todo Remove this once drupal_basename is fixed for PHP versions greater
+  //  than '5.3.29'.
+  $basename_function = version_compare(PHP_VERSION,'5.3.29','>') ? 'basename' : 'drupal_basename';
   $headers = array(
     'Content-Type' => mime_header_encode($file->filemime),
-    'Content-Disposition' => 'attachment; filename="' . mime_header_encode(drupal_basename($file->uri)) . '"',
+    'Content-Disposition' => 'attachment; filename="' . mime_header_encode($basename_function($file->uri)) . '"',
     'Content-Length' => $file->filesize,
     'Content-Transfer-Encoding' => 'binary',
     'Pragma' => 'no-cache',
@@ -77,7 +79,10 @@ function file_entity_download_page($file) {
  * - Edit fields
  *   Skip this step if there are no fields on this entity type.
  */
-function file_entity_add_upload($form, &$form_state, array $options = array()) {
+function file_entity_add_upload($form, &$form_state, $options = array()) {
+  if (!is_array($options)) {
+    $options = array($options);
+  }
   $step = (isset($form_state['step']) && in_array($form_state['step'], array(1, 2, 3, 4))) ? $form_state['step'] : 1;
   $form['#step'] = $step;
   $form['#options'] = $options;
@@ -398,6 +403,7 @@ function file_entity_add_upload_submit($form, &$form_state) {
   // We have the filetype, check if we can skip step 4.
   if (($form['#step'] == 3 && $trigger == 'edit-next')) {
     $file = file_load($form_state['storage']['upload']);
+    $form_state['file'] = $file;
     if (!field_info_instances('file', $form_state['storage']['type'])) {
       // This filetype doesn't have fields, save the file.
       $save = TRUE;
@@ -800,21 +806,25 @@ function file_entity_edit_submit($form, &$form_state) {
   if (!empty($form_state['values']['replace_upload'])) {
     $replacement = $form_state['values']['replace_upload'];
     // Move file from temp to permanent home.
-    $destination_uri = rtrim($file->uri, drupal_basename($file->uri)) . drupal_basename($replacement->uri);
-    $replace_mode = $destination_uri == $file->uri ? FILE_EXISTS_REPLACE : FILE_EXISTS_RENAME;
-    if ($new_file_uri = file_unmanaged_copy($replacement->uri, $destination_uri, $replace_mode)) {
-      // @todo Add watchdog() about replaced file here?
-
-      // Remove temporary file.
-      file_delete($replacement);
-
-      // Update if the uri target has changed.
-      if ($new_file_uri != $file->uri) {
-       // Store the original file uri to delete if save is successful.
-       $orphaned_uri = $file->uri;
-
-        // Update file entity uri.
-        $file->uri = $new_file_uri;
+    if (pathinfo($replacement->uri, PATHINFO_EXTENSION) == pathinfo($file->uri, PATHINFO_EXTENSION)) {
+        file_unmanaged_copy($replacement->uri, $file->uri, FILE_EXISTS_REPLACE);
+    } else {
+      $destination_uri = rtrim($file->uri, drupal_basename($file->uri)) . drupal_basename($replacement->uri);
+      $replace_mode = $destination_uri == $file->uri ? FILE_EXISTS_REPLACE : FILE_EXISTS_RENAME;
+      if ($new_file_uri = file_unmanaged_copy($replacement->uri, $destination_uri, $replace_mode)) {
+        // @todo Add watchdog() about replaced file here?
+
+        // Remove temporary file.
+        file_delete($replacement);
+
+        // Update if the uri target has changed.
+        if ($new_file_uri != $file->uri) {
+         // Store the original file uri to delete if save is successful.
+         $orphaned_uri = $file->uri;
+
+          // Update file entity uri.
+          $file->uri = $new_file_uri;
+        }
       }
     }
   }
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.pathauto.inc b/drupal7/sites/all/modules/file_entity/file_entity.pathauto.inc
index 3b3d6957..98befe3a 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.pathauto.inc
+++ b/drupal7/sites/all/modules/file_entity/file_entity.pathauto.inc
@@ -27,7 +27,7 @@ function file_entity_pathauto($op) {
       $settings['token_type'] = 'file';
       $settings['groupheader'] = t('File paths');
       $settings['patterndescr'] = t('Default path pattern (applies to all file types with blank patterns below)');
-      $settings['patterndefault'] = 'files/[file:name]';
+      $settings['patterndefault'] = '';
       $settings['batch_update_callback'] = 'file_entity_pathauto_bulk_update_batch_process';
       $settings['batch_file'] = drupal_get_path('module', 'file_entity') . '/file_entity.pathauto.inc';
 
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.test b/drupal7/sites/all/modules/file_entity/file_entity.test
index 20f47cab..96a45102 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.test
+++ b/drupal7/sites/all/modules/file_entity/file_entity.test
@@ -1205,7 +1205,7 @@ class FileEntityTypeTestCase extends FileEntityTestHelper {
     $this->drupalGet('admin/structure/file-types');
     $this->assertResponse(403, 'File types UI page is not accessible to unauthorized users.');
 
-    $user = $this->drupalCreateUser(array('administer file types'));
+    $user = $this->drupalCreateUser(array('administer file types', 'administer fields'));
     $this->drupalLogin($user);
 
     $this->drupalGet('admin/structure/file-types');
@@ -1671,4 +1671,132 @@ class FileEntityAttributeOverrideTestCase extends FileEntityTestHelper {
       $this->assertEqual($build['#file']->$attribute, $expected_value, format_string('The %attribute was overridden correctly.', array('%attribute' => $attribute)));
     }
   }
+
+  /**
+   * @param EntityFieldQuery $query
+   * @param $expected
+   *   An associative array of expected result. Keys are file ids, values are
+   *   booleans to indicate if the result should include the file.
+   */
+  function assertEntityFieldQueryAccess(EntityFieldQuery $query, $expected, $account = NULL, $query_name = 'unnamed') {
+    if ($account) {
+      $query->addMetaData('account', $account);
+    }
+    $query->addTag('entity_field_access');
+    $results = $query->execute();
+    $fids = isset($results['file']) ? array_keys($results['file']) : array();
+    foreach ($expected as $fid => $in_result) {
+      if ($in_result) {
+        $this->assertTrue(in_array($fid, $fids), format_string("For the %name query, the result should contain %fid", array('%name' => $query_name, '%fid' => $fid)));
+      }
+      else {
+        $this->assertFalse(in_array($fid, $fids), format_string("For the %name query, the result should not contain %fid", array('%name' => $query_name, '%fid' => $fid)));
+      }
+    }
+  }
+
+  /**
+   * Test file entity access for entity field queries.
+   */
+  function testEntityFieldQueryAccess() {
+    // Attach a text field to the default image file type.
+    $field = array(
+      'field_name' => drupal_strtolower($this->randomName()),
+      'type' => 'text',
+      'settings' => array(
+        'max_length' => 255,
+      )
+    );
+    field_create_field($field);
+    $instance = array(
+      'field_name' => $field['field_name'],
+      'entity_type' => 'file',
+      'bundle' => 'document',
+      'widget' => array(
+        'type' => 'text_textfield',
+      ),
+      'display' => array(
+        'default' => array(
+          'type' => 'text_default',
+        ),
+      ),
+    );
+    field_create_instance($instance);
+    // Create test files.
+    $file_owner = $this->drupalCreateUser(array('view own files', 'view own private files'));
+    $public_file = $this->createFileEntity(array(
+      'status' => 0,
+    ));
+    $private_file = $this->createFileEntity(array('scheme' => 'private'));
+    $owned_public_file = $this->createFileEntity(array(
+      'uid' => $file_owner->uid,
+      'scheme' => 'public',
+    ));
+    $owned_private_file = $this->createFileEntity(array(
+      'uid' => $file_owner->uid,
+      'scheme' => 'private',
+    ));
+    $fids = array(
+      $public_file->fid,
+      $private_file->fid,
+      $owned_public_file->fid,
+      $owned_private_file->fid,
+    );
+    foreach (file_load_multiple($fids) as $file) {
+      $file->{$field['field_name']}[LANGUAGE_NONE][0] = array('value' => 'find me');
+      file_save($file);
+    }
+
+    $efq_fids = new EntityFieldQuery();
+    $queries['entity type and id conditions'] = $efq_fids
+      ->entityCondition('entity_type', 'file')
+      ->entityCondition('entity_id', $fids);
+    $efq_field_name = new EntityFieldQuery();
+    $queries['single field condition'] = $efq_field_name
+      ->fieldCondition($field['field_name'], 'value', 'find me');
+
+    foreach($queries as $name => $query) {
+      $message = format_string('');
+      // User should not see private files, only his own public files.
+      $this->assertEntityFieldQueryAccess(clone $query, array(
+        $public_file->fid => TRUE,
+        $private_file->fid => FALSE,
+        $owned_public_file->fid => TRUE,
+        $owned_private_file->fid => FALSE,
+      ), $this->drupalCreateUser(array('create files')), $name);
+
+      // A user with the 'view own files' and 'view own private files' permissions should only see owned files and public files.
+      $this->drupalLogin($file_owner);
+      $this->assertEntityFieldQueryAccess(clone $query, array(
+        $public_file->fid => TRUE,
+        $private_file->fid => FALSE,
+        $owned_public_file->fid => TRUE,
+        $owned_private_file->fid => TRUE,
+      ), $file_owner, $name);
+
+      // User with the 'view files' permission should only see public files but cannot create files.
+      $this->assertEntityFieldQueryAccess(clone $query, array(
+        $public_file->fid => TRUE,
+        $private_file->fid => FALSE,
+        $owned_public_file->fid => TRUE,
+        $owned_private_file->fid => FALSE,
+      ), $this->drupalCreateUser(array('view files')), $name);
+
+      // User with the 'view files' and 'view private files' permissions should only see all files.
+      $this->assertEntityFieldQueryAccess(clone $query, array(
+        $public_file->fid => TRUE,
+        $private_file->fid => TRUE,
+        $owned_public_file->fid => TRUE,
+        $owned_private_file->fid => TRUE,
+      ), $this->drupalCreateUser(array('view files', 'view private files')), $name);
+
+      // User with the 'bypass file access' permissions should only see all files.
+      $this->assertEntityFieldQueryAccess(clone $query, array(
+        $public_file->fid => TRUE,
+        $private_file->fid => TRUE,
+        $owned_public_file->fid => TRUE,
+        $owned_private_file->fid => TRUE,
+      ), $this->drupalCreateUser(array('bypass file access')), $name);
+    }
+  }
 }
diff --git a/drupal7/sites/all/modules/file_entity/file_entity.theme.inc b/drupal7/sites/all/modules/file_entity/file_entity.theme.inc
index c05d3320..aa78d5d2 100644
--- a/drupal7/sites/all/modules/file_entity/file_entity.theme.inc
+++ b/drupal7/sites/all/modules/file_entity/file_entity.theme.inc
@@ -12,18 +12,37 @@
  */
 function theme_file_entity_file_link($variables) {
   $file = $variables['file'];
-  $icon_directory = $variables['icon_directory'];
+  $uri = entity_uri('file', $file);
+
+  // Human-readable names, for use as text-alternatives to icons.
+  $mime_name = array(
+    'application/msword' => t('Microsoft Office document icon'),
+    'application/vnd.ms-excel' => t('Office spreadsheet icon'),
+    'application/vnd.ms-powerpoint' => t('Office presentation icon'),
+    'application/pdf' => t('PDF icon'),
+    'video/quicktime' => t('Movie icon'),
+    'audio/mpeg' => t('Audio icon'),
+    'audio/wav' => t('Audio icon'),
+    'image/jpeg' => t('Image icon'),
+    'image/png' => t('Image icon'),
+    'image/gif' => t('Image icon'),
+    'application/zip' => t('Package icon'),
+    'text/html' => t('HTML icon'),
+    'text/plain' => t('Plain text icon'),
+    'application/octet-stream' => t('Binary Data'),
+  );
+
+  $mimetype = file_get_mimetype($file->uri);
 
-  $url = 'file/' . $file->fid;
-  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));
+  $icon = theme('file_icon', array(
+    'file' => $file,
+    'icon_directory' => $variables['icon_directory'],
+    'alt' => !empty($mime_name[$mimetype]) ? $mime_name[$mimetype] : t('File'),
+  ));
 
   // Set options as per anchor format described at
   // http://microformats.org/wiki/file-format-examples
-  $options = array(
-    'attributes' => array(
-      'type' => $file->filemime . '; length=' . $file->filesize,
-    ),
-  );
+  $uri['options']['attributes']['type'] = $file->filemime . '; length=' . $file->filesize;
 
   // Use the description as the link text if available.
   if (empty($file->description)) {
@@ -44,10 +63,33 @@ function theme_file_entity_file_link($variables) {
  */
 function theme_file_entity_download_link($variables) {
   $file = $variables['file'];
-  $icon_directory = $variables['icon_directory'];
-
   $uri = file_entity_download_uri($file);
-  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));
+
+  // Human-readable names, for use as text-alternatives to icons.
+  $mime_name = array(
+    'application/msword' => t('Microsoft Office document icon'),
+    'application/vnd.ms-excel' => t('Office spreadsheet icon'),
+    'application/vnd.ms-powerpoint' => t('Office presentation icon'),
+    'application/pdf' => t('PDF icon'),
+    'video/quicktime' => t('Movie icon'),
+    'audio/mpeg' => t('Audio icon'),
+    'audio/wav' => t('Audio icon'),
+    'image/jpeg' => t('Image icon'),
+    'image/png' => t('Image icon'),
+    'image/gif' => t('Image icon'),
+    'application/zip' => t('Package icon'),
+    'text/html' => t('HTML icon'),
+    'text/plain' => t('Plain text icon'),
+    'application/octet-stream' => t('Binary Data'),
+  );
+
+  $mimetype = file_get_mimetype($file->uri);
+
+  $icon = theme('file_icon', array(
+    'file' => $file,
+    'icon_directory' => $variables['icon_directory'],
+    'alt' => !empty($mime_name[$mimetype]) ? $mime_name[$mimetype] : t('File'),
+  ));
 
   // Set options as per anchor format described at
   // http://microformats.org/wiki/file-format-examples
diff --git a/drupal7/sites/all/modules/file_entity/file_entity_views.test b/drupal7/sites/all/modules/file_entity/file_entity_views.test
new file mode 100644
index 00000000..5e0bac55
--- /dev/null
+++ b/drupal7/sites/all/modules/file_entity/file_entity_views.test
@@ -0,0 +1,114 @@
+<?php
+
+/**
+ * @file
+ * Definition of FileEntityViewsFieldLinkUsageHandlerTest.
+ */
+
+/**
+ * Tests for file_entity views file usage handlers.
+ */
+class FileEntityViewsFieldLinkUsageHandlerTest extends FileEntityTestHelper {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function setUp() {
+    parent::setUp('views');
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function getInfo() {
+    return array(
+      'name' => 'File entity views integration: file link usage',
+      'description' => 'Test file usage Views field.',
+      'group' => 'File entity',
+    );
+  }
+
+  /**
+   * Test views file usage handlers.
+   */
+  public function testViewsUsageField() {
+    $file = $this->createFileEntity();
+    file_usage_add($file, 'foo', 'bar', 1,1);
+    file_usage_add($file, 'foo', 'bar', 1,2);
+    $file2 = $this->createFileEntity();
+    file_usage_add($file2, 'foo', 'bar', 1, 99);
+
+    $view = $this->getTestView();
+    $view->set_display();
+    $view->pre_execute();
+    $view->execute();
+
+    $row = $view->result[0];
+    $render = $view->field['usage']->render_link($row, $row);
+    $this->assertEqual($render, '1 place');
+
+    $row = $view->result[1];
+    $render = $view->field['usage']->render_link($row, $row);
+    $this->assertEqual($render, '1 place');
+
+    $view->field['usage']->options['count_entities_once'] = 0;
+
+    $row = $view->result[0];
+    $render = $view->field['usage']->render_link($row, $row);
+    $this->assertEqual($render, '3 places');
+
+    $row = $view->result[1];
+    $render = $view->field['usage']->render_link($row, $row);
+    $this->assertEqual($render, '99 places');
+  }
+
+  /**
+   * Creates a test view containing a file usage field.
+   */
+  protected function getTestView() {
+    $view = new view();
+    $view->name = 'file_list';
+    $view->description = '';
+    $view->tag = 'default';
+    $view->base_table = 'file_managed';
+    $view->human_name = 'File List';
+    $view->core = 7;
+    $view->api_version = '3.0';
+    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+
+    /* Display: Master */
+    $handler = $view->new_display('default', 'Master', 'default');
+    $handler->display->display_options['title'] = 'File List';
+    $handler->display->display_options['use_more_always'] = FALSE;
+    $handler->display->display_options['access']['type'] = 'perm';
+    $handler->display->display_options['cache']['type'] = 'none';
+    $handler->display->display_options['query']['type'] = 'views_query';
+    $handler->display->display_options['exposed_form']['type'] = 'basic';
+    $handler->display->display_options['pager']['type'] = 'none';
+    $handler->display->display_options['style_plugin'] = 'default';
+    $handler->display->display_options['row_plugin'] = 'fields';
+    /* Field: File: Name */
+    $handler->display->display_options['fields']['filename']['id'] = 'filename';
+    $handler->display->display_options['fields']['filename']['table'] = 'file_managed';
+    $handler->display->display_options['fields']['filename']['field'] = 'filename';
+    $handler->display->display_options['fields']['filename']['label'] = '';
+    $handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
+    $handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
+    /* Field: File: Usage link */
+    $handler->display->display_options['fields']['usage']['id'] = 'usage';
+    $handler->display->display_options['fields']['usage']['table'] = 'file_managed';
+    $handler->display->display_options['fields']['usage']['field'] = 'usage';
+    $handler->display->display_options['fields']['usage']['count_entities_once'] = 1;
+    /* Field: File Usage: Use count */
+    $handler->display->display_options['fields']['count']['id'] = 'count';
+    $handler->display->display_options['fields']['count']['table'] = 'file_usage';
+    $handler->display->display_options['fields']['count']['field'] = 'count';
+
+    /* Display: Page */
+    $handler = $view->new_display('page', 'Page', 'page');
+    $handler->display->display_options['path'] = 'file-list';
+
+    return $view;
+  }
+
+}
diff --git a/drupal7/sites/all/modules/file_entity/plugins/tasks/file_view.inc b/drupal7/sites/all/modules/file_entity/plugins/tasks/file_view.inc
index 5b823758..be14e5a4 100644
--- a/drupal7/sites/all/modules/file_entity/plugins/tasks/file_view.inc
+++ b/drupal7/sites/all/modules/file_entity/plugins/tasks/file_view.inc
@@ -105,6 +105,7 @@ function file_entity_file_view_page($file) {
   }
 
   // Otherwise, fall back.
+  module_load_include('inc', 'file_entity', 'file_entity.pages');
   return $function($file);
 }
 
diff --git a/drupal7/sites/all/modules/file_entity/tests/file_entity_test.info b/drupal7/sites/all/modules/file_entity/tests/file_entity_test.info
index e9b51c51..5ea94f73 100644
--- a/drupal7/sites/all/modules/file_entity/tests/file_entity_test.info
+++ b/drupal7/sites/all/modules/file_entity/tests/file_entity_test.info
@@ -5,9 +5,9 @@ core = 7.x
 dependencies[] = file_entity
 hidden = TRUE
 
-; Information added by Drupal.org packaging script on 2016-05-31
-version = "7.x-2.0-beta3"
+; Information added by Drupal.org packaging script on 2017-05-22
+version = "7.x-2.0"
 core = "7.x"
 project = "file_entity"
-datestamp = "1464653173"
+datestamp = "1495456387"
 
diff --git a/drupal7/sites/all/modules/file_entity/views/views_handler_field_file_link_usage.inc b/drupal7/sites/all/modules/file_entity/views/views_handler_field_file_link_usage.inc
index 49e1df8d..aa461c82 100644
--- a/drupal7/sites/all/modules/file_entity/views/views_handler_field_file_link_usage.inc
+++ b/drupal7/sites/all/modules/file_entity/views/views_handler_field_file_link_usage.inc
@@ -12,6 +12,28 @@
  */
 class views_handler_field_file_link_usage extends views_handler_field_file_link {
 
+  /**
+   * {@inheritdoc}
+   */
+  function option_definition() {
+    $options = parent::option_definition();
+    $options['count_entities_once'] = array('default' => TRUE);
+    return $options;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  function options_form(&$form, &$form_state) {
+    $form['count_entities_once'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Count each unique entity once'),
+      '#description' => t('Files can be used multiple times for an entity, especially when an entity is revisionable.'),
+      '#default_value' => !empty($this->options['count_entities_once']),
+    );
+    parent::options_form($form, $form_state);
+  }
+
   /**
    * Renders the link.
    */
@@ -27,10 +49,19 @@ class views_handler_field_file_link_usage extends views_handler_field_file_link
 
     // Get total count for each file.
     $total_count = 0;
-    foreach (file_usage_list($file) as $module => $usage) {
+    $file_usage = file_usage_list($file);
+    $count_entities_once = !empty($this->options['count_entities_once']);
+    foreach ($file_usage as $module => $usage) {
       foreach ($usage as $entity_type => $entity_ids) {
-        foreach ($entity_ids as $id => $count) {
-          $total_count += $count;
+        if ($count_entities_once) {
+          // Just count each unique entity once.
+          $total_count += count($entity_ids);
+        }
+        else {
+          // Count multiple usages for each entity.
+          foreach ($entity_ids as $id => $count) {
+            $total_count += $count;
+          }
         }
       }
     }
diff --git a/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.api.php b/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.api.php
index ca1251d5..cde4a31b 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.api.php
+++ b/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.api.php
@@ -20,7 +20,6 @@
  *
  *  @return boolean &$hook_result passed by reference
  */
-
 function hook_ldap_authentication_allowuser_results_alter($ldap_user, $name, &$hook_result) {
 
   if ($hook_result === FALSE) { // other module has denied user, should not override
@@ -34,4 +33,12 @@ function hook_ldap_authentication_allowuser_results_alter($ldap_user, $name, &$h
 
 }
 
-
+/**
+ * Allow a custom module to alter $ldap_user before validating user login.
+ *
+ *  @param array $ldap_user
+ *    See README.developers.txt for structure
+ */
+function hook_ldap_entry_alter(&$ldap_user) {
+  $ldap_user['mail'] = 'newmail@example.com';
+}
diff --git a/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.inc b/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.inc
index c0586ac2..3d188276 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.inc
+++ b/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.inc
@@ -237,6 +237,7 @@ function _ldap_authentication_user_login_authenticate_validate(&$form_state, $re
    * IV. test credentials and if available get corresponding ldap user and ldap server
    */
   list($authentication_result, $ldap_user, $ldap_server_authenticated_on) = ldap_authentication_test_credentials($auth_conf, $sso_login, $authname, $form_state['values']['pass'], $watchdog_tokens);
+  drupal_alter('ldap_entry', $ldap_user);
   if ($authentication_result != LDAP_AUTHENTICATION_RESULT_SUCCESS) {
     ldap_authentication_fail_response($authentication_result, $auth_conf, $detailed_watchdog_log, $watchdog_tokens);
     return;
diff --git a/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.info b/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.info
index cbead42c..7acf8060 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.info
+++ b/drupal7/sites/all/modules/ldap/ldap_authentication/ldap_authentication.info
@@ -14,9 +14,9 @@ files[] = ldap_authentication.theme.inc
 files[] = ldap_authentication.admin.inc
 files[] = tests/ldap_authentication.test
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_authentication/tests/ldap_authentication.test b/drupal7/sites/all/modules/ldap/ldap_authentication/tests/ldap_authentication.test
index 94fe308f..3c994640 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authentication/tests/ldap_authentication.test
+++ b/drupal7/sites/all/modules/ldap/ldap_authentication/tests/ldap_authentication.test
@@ -416,7 +416,6 @@ class LdapAuthenticationTestCase extends LdapTestCase {
       'drupal_role_authentication_test'
       );
 
-    //debug($this->testFunctions);
     $ldap_servers = ldap_servers_get_servers($sid, 'enabled');
     $this->assertTrue(count($ldap_servers) == 1, ' ldap_authentication test server setup successful', $testid);
 
@@ -807,9 +806,7 @@ class LdapAuthenticationTestCase extends LdapTestCase {
         $value = $conf['values'][$i];
         $property = isset($conf['property']) ? $conf['property'] : $field_name;
         $edit[$field_name] = $value;
-      //  debug("$field_name $value"); debug($conf);debug($edit);
       }
-     // debug($edit);
       $this->drupalPost('admin/config/people/ldap/authentication', $edit, t('Save'));
       $ldap_authentication_conf_post = ldap_authentication_get_valid_conf(TRUE);
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerAbstract.class.php b/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerAbstract.class.php
index 50e68b6d..e2e45196 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerAbstract.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerAbstract.class.php
@@ -341,7 +341,6 @@ class LdapAuthorizationConsumerAbstract {
         $log .= "revoking existing consumer object, ";
         if ($user_has_authorization) {
           // revoke case 1: user has authorization, revoke it.  revokeSingleAuthorization will remove $user_auth_data[$consumer_id]
-          //debug("op=revoke, consumer_id=$consumer_id, calling revokeSingleAuthorization");
           $results[$consumer_id] = $this->revokeSingleAuthorization($user, $consumer_id, $consumer, $user_auth_data, $user_save);  // defer to default for $user_save param
           $log .= t(',result=') . (boolean)($results[$consumer_id]);
         }
@@ -364,7 +363,6 @@ class LdapAuthorizationConsumerAbstract {
     }
     $watchdog_tokens['%consumer_ids_log'] = (count($consumer_ids_log)) ? join('<hr/>', $consumer_ids_log) : t('no actions');
 
-   // debug("user->data and user_auth_data"); debug($user->data); debug($user_auth_data);
     if ($user_save) {
       $user = user_load($user->uid, TRUE);
       $user_edit = $user->data;
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerConfAdmin.class.php b/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerConfAdmin.class.php
index 07050933..ad282a33 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerConfAdmin.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/LdapAuthorizationConsumerConfAdmin.class.php
@@ -45,7 +45,6 @@ class LdapAuthorizationConsumerConfAdmin extends LdapAuthorizationConsumerConf {
         $values->export_type = NULL;
         $result = ctools_export_crud_save('ldap_authorization', $values);
       } catch (Exception $e) {
-        //  debug($e); Integrity constraint violation: 1062 Duplicate entry
         $values->export_type = EXPORT_IN_DATABASE;
         $result = ctools_export_crud_save('ldap_authorization', $values);
       }
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.inc b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.inc
index 4d5dfd18..f5ed4ac4 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.inc
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.inc
@@ -483,7 +483,6 @@ function _ldap_authorization_ldap_authorization_maps_alter(&$user, &$user_ldap_e
 
   // traditional groups (dns)
   $group_dns = $consumer_conf->server->groupMembershipsFromUser($user, 'group_dns');
- // debug("groupMembershipsFromUser, group_dns"); debug($group_dns);
   if (!$group_dns) {
     $group_dns = array();
   }
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.info b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.info
index bdaf0ff7..f0a3e57b 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.info
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization.info
@@ -17,9 +17,9 @@ files[] = tests/BasicTests.test
 files[] = tests/Og2Tests.test
 configure = admin/config/people/ldap/authorization
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_drupal_role/ldap_authorization_drupal_role.info b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_drupal_role/ldap_authorization_drupal_role.info
index 52727904..5ab3e704 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_drupal_role/ldap_authorization_drupal_role.info
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_drupal_role/ldap_authorization_drupal_role.info
@@ -9,9 +9,9 @@ files[] = LdapAuthorizationConsumerRole.class.php
 files[] = ldap_authorization_drupal_role.module
 files[] = ldap_authorization_drupal_role.inc
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/LdapAuthorizationConsumerOG.class.php b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/LdapAuthorizationConsumerOG.class.php
index ef192518..62c03724 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/LdapAuthorizationConsumerOG.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/LdapAuthorizationConsumerOG.class.php
@@ -429,12 +429,10 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
         unset($diff[$i]);
       }
     }
-   // dpm("diff"); dpm($diff); dpm("existing"); dpm($existing);  dpm("desired"); dpm($desired); dpm("final diff"); dpm($diff);
     return $diff;
   }
 
   protected function grantsAndRevokes($op, &$user, &$user_auth_data, $consumers, &$ldap_entry = NULL, $user_save = TRUE) {
-   // debug("grantsAndRevokes, op=$op, user_save=$user_save"); debug($user_auth_data); debug($consumers);
 
     if (!is_array($user_auth_data)) {
       $user_auth_data = array();
@@ -468,7 +466,6 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
     $consumer_ids_log = "";
     $log = "";
 
-    //dpm('consumers');dpm($consumers); dpm('users_authorization_consumer_ids'); dpm($users_authorization_consumer_ids);
     foreach ($consumers as $consumer_id => $consumer) {
       if ($detailed_watchdog_log) {
         watchdog('ldap_authorization', "consumer_id=$consumer_id, user_save=$user_save, op=$op", $watchdog_tokens, WATCHDOG_DEBUG);
@@ -573,7 +570,6 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
      * - remove and grant og roles
      * - flush appropriate caches
      */
-    //debug("og_actions"); debug($og_actions); debug("user_auth_data"); debug($user_auth_data);
     if ($this->ogVersion == 1) {
       $this->og1Grants($og_actions, $user, $user_auth_data);
       $this->og1Revokes($og_actions, $user, $user_auth_data);
@@ -639,8 +635,7 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
         $users_group_rids = array_keys(og_get_user_roles($group_entity_type, $gid, $user->uid, TRUE)); // users current rids w/authen or anon roles returned
         $users_group_rids = array_diff($users_group_rids, array($anonymous_rid));
         $new_rids = array_diff($granting_rids, $users_group_rids, array($anonymous_rid)); // rids to be added without anonymous rid
-      //  debug("new rids"); debug($new_rids);debug("granting_rids"); debug($granting_rids);debug("users_group_rids"); debug($users_group_rids);
-        
+
         // if adding OG_AUTHENTICATED_ROLE or any other role and does not currently have OG_AUTHENTICATED_ROLE, group
         if (!in_array($authenticated_rid, $users_group_rids) && count($new_rids) > 0) {
           $values = array(
@@ -650,7 +645,6 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
             'state' => OG_STATE_ACTIVE,
           );
           $og_membership = og_group($group_entity_type, $gid, $values);
-          // debug("consumer_id=$consumer_id, og group called( $group_entity_type, $gid, values:"); debug($values); debug("response og_membership"); debug($og_membership);
           $consumer_id = join(':', array($group_entity_type, $gid, $authenticated_rid));
           $user_auth_data[$consumer_id] = array(
             'date_granted' => time(),
@@ -660,7 +654,6 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
          
         }
         foreach ($new_rids as $i => $rid) {
-        //  debug("role grant $group_entity_type $gid $user->uid $rid");
           og_role_grant($group_entity_type, $gid, $user->uid, $rid);
         }
         foreach ($granting_rids as $i => $rid) {
@@ -886,28 +879,26 @@ class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
 
       if (!empty($og_fields['bundles'])) {
         foreach ($og_fields['bundles'] as $entity_type => $bundles) {
-
           foreach ($bundles as $i => $bundle) {
-
             $query = new EntityFieldQuery();
             $query->entityCondition('entity_type', $entity_type)
               ->entityCondition('bundle', $bundle)
               ->range(0, 5)
               ->addMetaData('account', user_load(1)); // run the query as user 1
             $result = $query->execute();
-            $entities = entity_load($entity_type, array_keys($result[$entity_type]));
-            $i=0;
-            foreach ($entities as $entity_id => $entity) {
-              $i++;
-              $rid = ldap_authorization_og2_rid_from_role_name($entity_type, $bundle, $entity_id, OG_AUTHENTICATED_ROLE);
-              $title = (is_object($entity) && property_exists($entity, 'title')) ? $entity->title : '';
-              $middle = ($title && $i < 3) ? $title : $entity_id;
-              $group_role_identifier = ldap_authorization_og_authorization_id($middle, $rid, $entity_type);
-              $example = "<code>ou=IT,dc=myorg,dc=mytld,dc=edu|$group_role_identifier</code>";
-              $rows[] = array("$entity_type $title - $role_name", $example);
-
+            if (!empty($result)) {
+              $entities = entity_load($entity_type, array_keys($result[$entity_type]));
+              $i=0;
+              foreach ($entities as $entity_id => $entity) {
+                $i++;
+                $rid = ldap_authorization_og2_rid_from_role_name($entity_type, $bundle, $entity_id, OG_AUTHENTICATED_ROLE);
+                $title = (is_object($entity) && property_exists($entity, 'title')) ? $entity->title : '';
+                $middle = ($title && $i < 3) ? $title : $entity_id;
+                $group_role_identifier = ldap_authorization_og_authorization_id($middle, $rid, $entity_type);
+                $example = "<code>ou=IT,dc=myorg,dc=mytld,dc=edu|$group_role_identifier</code>";
+                $rows[] = array("$entity_type $title - $role_name", $example);
+              }
             }
-
           }
         }
       }
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/ldap_authorization_og.info b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/ldap_authorization_og.info
index 5e87dd8a..d485f2b3 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/ldap_authorization_og.info
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/ldap_authorization_og/ldap_authorization_og.info
@@ -13,9 +13,9 @@ files[] = ldap_authorization_og.inc
 
 core = "7.x"
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/tests/BasicTests.test b/drupal7/sites/all/modules/ldap/ldap_authorization/tests/BasicTests.test
index cf67f170..446f2767 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/tests/BasicTests.test
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/tests/BasicTests.test
@@ -437,7 +437,6 @@ function testFlags() {
       'error_message' => '',
       );
   $this->consumerAdminConf['drupal_role']->save();
-//  debug('mappings'); debug($this->consumerAdminConf['drupal_role']->mappings);
 
   $edit = array(
     'name' => 'hpotter',
@@ -446,7 +445,6 @@ function testFlags() {
   $this->drupalPost('user', $edit, t('Log in'));
 
   $new_role_created = in_array($new_role, array_values(user_roles()));
- // debug("roles"); debug(user_roles());
   $roles_by_name = array_flip(user_roles());
   $hpotter = user_load_by_name('hpotter');
   $hpotter = user_load($hpotter->uid, TRUE);
@@ -548,7 +546,6 @@ function testFlags() {
           if (count($mismatches)) {
             debug('mismatches between ldap server properties and form submitted values');
             debug($mismatches);
-           // debug($ldap_consumer);  // throw recursion
             debug($consumer_form_data);
           }
           $this->assertTrue(count($mismatches) == 0, 'Add form for ldap consumer properties match values submitted.',  $this->ldapTestId . ' Add consumer conf');
@@ -574,7 +571,6 @@ function testFlags() {
           if (count($mismatches)) {
             debug('mismatches between ldap server properties and form submitted values');
             debug($mismatches);
-           // debug($ldap_consumer); // throw recursion
             debug($consumer_form_data);
           }
           $this->assertTrue(count($mismatches) == 0, 'Update form for ldap server properties match values submitted.',  $this->ldapTestId . '.Update consumer conf');
diff --git a/drupal7/sites/all/modules/ldap/ldap_authorization/tests/Og2Tests.test b/drupal7/sites/all/modules/ldap/ldap_authorization/tests/Og2Tests.test
index e97977c7..408b1875 100644
--- a/drupal7/sites/all/modules/ldap/ldap_authorization/tests/Og2Tests.test
+++ b/drupal7/sites/all/modules/ldap/ldap_authorization/tests/Og2Tests.test
@@ -285,7 +285,6 @@ class LdapAuthorizationOg2Tests extends LdapTestCase {
      */
 
     list($students_group, $group_entity_id) = ldap_authorization_og2_get_group_from_name('node', 'students');
-    //debug("ldap_authorization_og2_get_group_from_name: students_group"); debug($students_group);
     $this->assertTrue($students_group->title == 'students', 'ldap_authorization_og2_get_group_from_name() function works', $this->ldapTestId);
 
     $test = ldap_authorization_og2_has_role($this->groupType, $group_nids['gryffindor'], $web_user->uid, OG_ADMINISTRATOR_ROLE);
@@ -338,7 +337,6 @@ function testFlags() {
 
   list($new_authorizations, $notifications) = ldap_authorizations_user_authorizations($hpotter, 'query');  // just see if the correct ones are derived.
   $groups1 = $new_authorizations['og_group'];
- // debug('ldap_authorizations_user_authorizations disabled:'); debug($new_authorizations);  debug($notifications);
   $this->assertTrue(
     count($new_authorizations['og_group']) == 0,
     'disabled consumer configuration disallows authorizations.',
@@ -350,7 +348,6 @@ function testFlags() {
   $this->consumerAdminConf['og_group']->status = 1;
   $this->consumerAdminConf['og_group']->save();
   list($new_authorizations, $notifications) = ldap_authorizations_user_authorizations($hpotter, 'query', 'og_group');  // just see if the correct ones are derived.
-  //debug('ldap_authorizations_user_authorizations enabled: '); debug($new_authorizations);  debug($notifications);
 
   $correct_groups = !empty($new_authorizations['og_group'][$consumer_ids['students'][OG_AUTHENTICATED_ROLE]]) &&
     !empty($new_authorizations['og_group'][$consumer_ids['gryffindor'][OG_AUTHENTICATED_ROLE]]);
diff --git a/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.info b/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.info
index e8bc244f..b20e3ffa 100644
--- a/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.info
+++ b/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.info
@@ -12,9 +12,9 @@ configure = admin/structure/feeds
 core = 7.x
 php = 5.2
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.module b/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.module
index f74db6e9..1ccd7cfd 100644
--- a/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.module
+++ b/drupal7/sites/all/modules/ldap/ldap_feeds/ldap_feeds.module
@@ -110,10 +110,8 @@ function ldap_feeds_query_legend(&$form, $importer) {
 
   $source = feeds_source($importer->id);
   $fetcher = feeds_plugin('FeedsLdapQueryFetcher', $source->importer->id);
-  //dpm((array)$fetcher);  dpm((array)$source->importer->parser->ldap_result);
  // $fetcher_result = new FeedsLdapQueryFetcher($source->config);
  // $records = $fetcher->getRaw(); // FeedsSource $source
-// dpm($records);
  // foreach ($records[0] as $field_name => $value) {
   //  $sources[$field_name] = array(
   //    'name' => array('#markup' => $field_name),
diff --git a/drupal7/sites/all/modules/ldap/ldap_help/ldap_help.info b/drupal7/sites/all/modules/ldap/ldap_help/ldap_help.info
index fd82e0d3..e754cb8c 100644
--- a/drupal7/sites/all/modules/ldap/ldap_help/ldap_help.info
+++ b/drupal7/sites/all/modules/ldap/ldap_help/ldap_help.info
@@ -5,9 +5,9 @@ core = 7.x
 
 dependencies[] = ldap_servers
 dependencies[] = ldap_test
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_query/ldap_query.info b/drupal7/sites/all/modules/ldap/ldap_query/ldap_query.info
index 549a33d6..c825066f 100644
--- a/drupal7/sites/all/modules/ldap/ldap_query/ldap_query.info
+++ b/drupal7/sites/all/modules/ldap/ldap_query/ldap_query.info
@@ -17,9 +17,9 @@ files[] = tests/ldap_query.test
 
 configure = admin/config/people/ldap/query
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/LdapServer.class.php b/drupal7/sites/all/modules/ldap/ldap_servers/LdapServer.class.php
index 97d9abcd..6d320a13 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/LdapServer.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/LdapServer.class.php
@@ -172,7 +172,6 @@ class LdapServer {
           $server_record->{$db_field_name} = $value;
         }
       }
-      //debug('ctools record'); debug($server_record);
     }
     else {
       $select = db_select('ldap_servers')
@@ -471,7 +470,6 @@ class LdapServer {
     if (!$result) {
       $error = "LDAP Server ldap_add(%dn) Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
       $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
-      //debug(t($error, $tokens));
       watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
     }
 
@@ -1324,8 +1322,6 @@ class LdapServer {
    */
   public function groupAddGroup($group_dn, $attributes = array()) {
 
-    //debug("this->dnExists(   $group_dn, boolean)"); debug($this->dnExists($group_dn, 'boolean'));
-   // debug("this->dnExists(   $group_dn, boolean)"); debug($this->dnExists($group_dn));
     if ($this->dnExists($group_dn, 'boolean')) {
       return FALSE;
     }
@@ -1451,7 +1447,6 @@ class LdapServer {
    * @return FALSE on error otherwise array of group members (could be users or groups)
    */
   public function groupAllMembers($group_dn) {
-   // debug("groupAllMembers $group_dn, this->groupMembershipsAttr=". $this->groupMembershipsAttr . 'this->groupGroupEntryMembershipsConfigured=' . $this->groupGroupEntryMembershipsConfigured);
     if (!$this->groupGroupEntryMembershipsConfigured) {
       return FALSE;
     }
@@ -1504,7 +1499,6 @@ class LdapServer {
     };
 
     foreach ($current_member_entries as $i => $member_entry) {
-      //dpm("groupMembersResursive:member_entry $i, level=$level < max_levels=$max_levels"); dpm($member_entry);
       // 1.  Add entry itself if of the correct type to $all_member_dns
       $objectClassMatch = (!$object_classes || (count(array_intersect(array_values($member_entry['objectclass']), $object_classes)) > 0));
       $objectIsGroup = in_array($this->groupObjectClass, array_values($member_entry['objectclass']));
@@ -1674,7 +1668,6 @@ class LdapServer {
         $query_for_parent_groups = '(&(objectClass=' . $this->groupObjectClass . ')' . $or . ')';
 
         foreach ($this->basedn as $base_dn) {  // need to search on all basedns one at a time
-          // debug("query for parent groups, base_dn=$base_dn, $query_for_parent_groups");
           $group_entries = $this->search($base_dn, $query_for_parent_groups);  // no attributes, just dns needed
           if ($group_entries !== FALSE  && $level < LDAP_SERVER_LDAP_QUERY_RECURSION_LIMIT) {
             $this->groupMembershipsFromEntryRecursive($group_entries, $all_group_dns, $tested_group_ids, $level + 1, LDAP_SERVER_LDAP_QUERY_RECURSION_LIMIT);
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/LdapServerAdmin.class.php b/drupal7/sites/all/modules/ldap/ldap_servers/LdapServerAdmin.class.php
index 3490f8f0..dabde534 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/LdapServerAdmin.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/LdapServerAdmin.class.php
@@ -158,7 +158,6 @@ class LdapServerAdmin extends LdapServer {
 
     }
 
-  //  debug("values sent to save op=$op, ctools=". (int)module_exists('ctools')); debug($values);
     if ($result) {
       $this->inDatabase = TRUE;
     }
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.info b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.info
index 4b3734ec..5d946166 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.info
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.info
@@ -17,9 +17,9 @@ files[] = ldap_servers.theme.inc
 files[] = tests/ldap_servers.test
 configure = admin/config/people/ldap/servers
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.install b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.install
index 2bffd414..8d5c1f17 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.install
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.install
@@ -703,6 +703,10 @@ function ldap_servers_update_7201() {
   //5. ldap_authentication and ldap_user changes are in variables, not tables
 
   $ldap_authentication_conf_data = variable_get('ldap_authentication_conf', array());
+  if (!is_array($ldap_authentication_conf_data['sids'])) {
+    $ldap_authentication_conf_data['sids'] = array();
+  }
+
   $ldap_user_conf_data = variable_get('ldap_user_conf', array());
 
   $ldap_authentication_sids = array_keys($ldap_authentication_conf_data['sids']);
@@ -757,7 +761,7 @@ function ldap_servers_update_7201() {
       'title' => 'Changes in 7.x-1.x to 7.x-2.x update')
     );
 
-  watchdog('ldap_servers', $summary, WATCHDOG_INFO);
+  watchdog('ldap_servers', $summary, array(), WATCHDOG_INFO);
   return $summary;
 
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.module b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.module
index d34fa513..531b9ea9 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.module
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.module
@@ -347,7 +347,6 @@ function ldap_servers_theme() {
  */
 
 function ldap_servers_ldap_user_attrs_list_alter(&$available_user_attrs, &$params) {
-  //debug('ldap_servers_ldap_user_attrs_list_alter'); debug($available_user_attrs); debug($params);
 
   if (isset($params['ldap_server']) && $params['ldap_server']) {
     $ldap_server = $params['ldap_server'];
@@ -487,8 +486,6 @@ function ldap_servers_ldap_user_attrs_list_alter(&$available_user_attrs, &$param
       }
     }
   }
- // debug('available_user_attrs2'); debug($available_user_attrs);
-
 }
 
 /**
@@ -538,7 +535,6 @@ function ldap_servers_get_servers($sid = NULL, $type = NULL, $flatten = FALSE, $
  * see ldap_servers_get_servers()
  */
 function _ldap_servers_get_servers($sid, $type, $flatten, $reset) {
- // dpm('_ldap_servers_get_servers params'); dpm(array($sid, $type, $flatten, $reset));
   ldap_servers_module_load_include('php', 'ldap_servers', 'LdapServerAdmin.class');
   static $servers;
   $type = ($type) ? $type : 'all';
@@ -814,7 +810,7 @@ function ldap_servers_convert_attribute($value, $conversion = NULL) {
  */
 function ldap_servers_disable_http_check(&$form) {
 
-  if (variable_get('ldap_servers_require_ssl_for_credentials', 0) == 1 && @$_SERVER['HTTPS'] != 'on') {
+  if (variable_get('ldap_servers_require_ssl_for_credentials', 0) == 1 && !drupal_is_https()) {
 
     $tokens = array(
       'site_name' => variable_get('site_name', 'this site'),
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.theme.inc b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.theme.inc
index 2fe10adf..eea40490 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.theme.inc
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/ldap_servers.theme.inc
@@ -122,7 +122,6 @@ function theme_ldap_server_token_table($variables) {
 }
 
 function theme_ldap_server_ldap_entry_table($variables) {
- // debug($variables);
   if (!isset($variables['entry']) || !is_array($variables['entry'])) {
     return '<p>' . t('No Entry Returned.') . t('</p>');
   }
diff --git a/drupal7/sites/all/modules/ldap/ldap_servers/tests/ldap_servers.test b/drupal7/sites/all/modules/ldap/ldap_servers/tests/ldap_servers.test
index 42abfe3f..37c7cc5b 100644
--- a/drupal7/sites/all/modules/ldap/ldap_servers/tests/ldap_servers.test
+++ b/drupal7/sites/all/modules/ldap/ldap_servers/tests/ldap_servers.test
@@ -380,12 +380,10 @@ class LdapServersTestCase extends LdapTestCase {
     foreach ($data as $field_id => $values) {
       $field_id = drupal_strtolower($field_id);
       if (!isset($map[$field_id])) {
-       // debug("no mapping for field: $field_id in item_id $item_id");
         continue;
       }
       $property = $map[$field_id];
       if (!property_exists($object, $property) && !property_exists($object, drupal_strtolower($property))) {
-       // debug("property $property does not exist in object in item_id $item_id");
         continue;
       }
       $property_value = $object->{$property};
diff --git a/drupal7/sites/all/modules/ldap/ldap_sso/ldap_sso.info b/drupal7/sites/all/modules/ldap/ldap_sso/ldap_sso.info
index bd9efbd3..66f50e6a 100644
--- a/drupal7/sites/all/modules/ldap/ldap_sso/ldap_sso.info
+++ b/drupal7/sites/all/modules/ldap/ldap_sso/ldap_sso.info
@@ -6,9 +6,9 @@ dependencies[] = ldap_authentication
 core = 7.x
 configure = admin/config/people/ldap/authentication
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_test/LdapServerTest.class.php b/drupal7/sites/all/modules/ldap/ldap_test/LdapServerTest.class.php
index ddf1170e..a60ce8eb 100644
--- a/drupal7/sites/all/modules/ldap/ldap_test/LdapServerTest.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_test/LdapServerTest.class.php
@@ -47,11 +47,9 @@ class LdapServerTest extends LdapServer {
   }
 
   public function refreshFakeData() {
-   // debug("refreshFakeData sid=". $this->sid);
     $test_data = variable_get('ldap_test_server__' . $this->sid, array());
     $this->methodResponses = (is_array($test_data) && isset($test_data['methodResponses'])) ? $test_data['methodResponses'] : array();
     $this->entries = (is_array($test_data) && isset($test_data['ldap'])) ? $test_data['ldap'] : array();
-  //  debug('this->entries');debug($this->entries);
     $this->searchResults = (isset($test_data['search_results'])) ? $test_data['search_results'] : array();
     $this->detailedWatchdogLog = variable_get('ldap_help_watchdog_detail', 0);
     foreach ($test_data['properties'] as $property_name => $property_value ) {
@@ -139,8 +137,6 @@ class LdapServerTest extends LdapServer {
    */
   function search($base_dn = NULL, $filter, $attributes = array(), $attrsonly = 0, $sizelimit = 0, $timelimit = 0, $deref = LDAP_DEREF_NEVER, $scope = LDAP_SCOPE_SUBTREE) {
 
-   // debug("ldap test server search base_dn=$base_dn, filter=$filter");
-
     $lcase_attribute = array();
     foreach ($attributes as $i => $attribute_name) {
       $lcase_attribute[] = drupal_strtolower($attribute_name);
@@ -154,7 +150,6 @@ class LdapServerTest extends LdapServer {
         $base_dn = $this->basedn[0];
       }
       else {
-        // debug("fail basedn: ldap test server search base_dn=$base_dn, filter=$filter");
         return FALSE;
       }
     }
@@ -164,7 +159,6 @@ class LdapServerTest extends LdapServer {
      * are prepolulated in test data
      */
     if (isset($this->searchResults[$filter][$base_dn])) {
-   //   debug("case1 filter= $filter   base_dn=$base_dn ");
       $results = $this->searchResults[$filter][$base_dn];
       foreach ($results as $i => $entry) {
         if (is_array($entry) && isset($entry['FULLENTRY'])) {
@@ -174,8 +168,7 @@ class LdapServerTest extends LdapServer {
           $results[$i]['dn'] = $dn;
         }
       }
-   //   debug($results);
-      return $results; 
+      return $results;
     }
 
     /**
@@ -188,7 +181,6 @@ class LdapServerTest extends LdapServer {
     $operand = FALSE;
 
     if (strpos($filter, '&') === 0) {
-   //   debug('2.A.');
      /**
      * case 2.A.: filter of form (&(<attribute>=<value>)(<attribute>=<value>)(<attribute>=<value>))
      *  such as (&(samaccountname=hpotter)(samaccountname=hpotter)(samaccountname=hpotter))
@@ -202,7 +194,6 @@ class LdapServerTest extends LdapServer {
       }
     }
     elseif (strpos($filter, '|') === 0) {
-      //debug('2.B.');
      /**
      * case 2.B: filter of form (|(<attribute>=<value>)(<attribute>=<value>)(<attribute>=<value>))
      *  such as (|(samaccountname=hpotter)(samaccountname=hpotter)(samaccountname=hpotter))
@@ -215,12 +206,8 @@ class LdapServerTest extends LdapServer {
       foreach ($parts as $i => $pair) {
         $subqueries[] = explode('=', $pair);
       }
-         // debug("operand=$operand, filter=$filter subqueries"); debug($subqueries);
-   // debug($this->entries['cn=hpotter,ou=people,dc=hogwarts,dc=edu']);
-   // debug($this->entries['cn=clone0,ou=people,dc=hogwarts,dc=edu']);
     }
     elseif (count(explode('=', $filter)) == 2) {
-     // debug('2.C.');
      /**
      * case 2.C.: filter of form (<attribute>=<value>)
      *  such as (samaccountname=hpotter)
@@ -229,7 +216,6 @@ class LdapServerTest extends LdapServer {
       $subqueries[] = explode('=', $filter);
     }
     else {
-    //  debug('no case');
       return FALSE;
     }
 
@@ -243,7 +229,6 @@ class LdapServerTest extends LdapServer {
       foreach ($subqueries as $i => $subquery) {
         $filter_attribute = drupal_strtolower($subquery[0]);
         $filter_value = $subquery[1];
-      //  debug("filter_attribute=$filter_attribute, filter_value=$filter_value");
         foreach ($this->entries as $dn => $entry) {
           $dn_lcase = drupal_strtolower($dn);
 
@@ -254,7 +239,6 @@ class LdapServerTest extends LdapServer {
           //$pos = strpos($dn_lcase, $base_dn);
           $substring = strrev(substr(strrev($dn_lcase), 0, strlen($base_dn)));
           $cascmp =  strcasecmp($base_dn, $substring);
-          //debug("dn_lcase=$dn_lcase, base_dn=$base_dn,pos=$pos,substring=$substring,cascmp=$cascmp");
           if ($cascmp !== 0) {
 
             continue; // not in basedn
@@ -267,13 +251,11 @@ class LdapServerTest extends LdapServer {
               break;
             }
           }
-         // debug("filter value=$filter_value, attr_value_to_compare="); debug($attr_value_to_compare);
           if (!$attr_value_to_compare || drupal_strtolower($attr_value_to_compare[0]) != $filter_value) {
             continue;
           }
 
           // match!
-         // debug("match"); debug($attr_value); debug($attributes);
           $entry['dn'] = $dn;
           if ($attributes) {
             $selected_data = array();
@@ -298,7 +280,6 @@ class LdapServerTest extends LdapServer {
 
           $substring = strrev(substr(strrev($dn_lcase), 0, strlen($base_dn)));
           $cascmp =  strcasecmp($base_dn, $substring);
-          //debug("dn_lcase=$dn_lcase, base_dn=$base_dn,pos=$pos,substring=$substring,cascmp=$cascmp");
           if ($cascmp !== 0) {
             $match = FALSE;
             break; // not in basedn
@@ -311,7 +292,6 @@ class LdapServerTest extends LdapServer {
               break;
             }
           }
-         // debug("filter value=$filter_value, attr_value_to_compare="); debug($attr_value_to_compare);
           if (!$attr_value_to_compare || drupal_strtolower($attr_value_to_compare[0]) != $filter_value) {
             $match = FALSE;
             break; // not in basedn
@@ -335,7 +315,6 @@ class LdapServerTest extends LdapServer {
     }
 
     $results['count'] = count($results);
-  //  debug("ldap test server search results"); debug($results);
     return $results;
   }
 
@@ -354,11 +333,9 @@ class LdapServerTest extends LdapServer {
       $match = (strcasecmp($entry_dn, $find_dn) == 0);
 
       if ($match) {
-      //  debug("testserver:dnExists,match=$match, entry_dn=$entry_dn, find_dn=$find_dn"); debug($entry);
         return ($return == 'boolean') ? TRUE : $entry;
       }
     }
-   // debug("testserver:dnExists, no match");
     return FALSE; // not match found in loop
 
   }
@@ -458,7 +435,6 @@ class LdapServerTest extends LdapServer {
 
     $test_data['entries'][$dn] = $ldap_entry;
     $test_data['ldap'][$dn] = $ldap_entry;
-  //  debug("modifyLdapEntry:server test data before save $dn"); debug($test_data['entries'][$dn]);
     variable_set('ldap_test_server__' . $this->sid, $test_data);
     $this->refreshFakeData();
     return TRUE;
@@ -476,7 +452,6 @@ class LdapServerTest extends LdapServer {
   public function delete($dn) {
 
     $test_data = variable_get('ldap_test_server__' . $this->sid, array());
-   // debug("test ldap server, delete=$dn, test data="); debug(array_keys($test_data['users']));
     $deleted = FALSE;
     foreach (array('entries', 'users', 'groups', 'ldap') as $test_data_sub_array) {
       if (isset($test_data[$test_data_sub_array][$dn])) {
diff --git a/drupal7/sites/all/modules/ldap/ldap_test/LdapTestCase.class.php b/drupal7/sites/all/modules/ldap/ldap_test/LdapTestCase.class.php
index cc1eed19..430a3b48 100644
--- a/drupal7/sites/all/modules/ldap/ldap_test/LdapTestCase.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_test/LdapTestCase.class.php
@@ -139,29 +139,22 @@ class LdapTestCase extends DrupalWebTestCase {
         $test_data['search_results'][$filter][$domain] = array_diff($test_data['search_results'][$filter][$domain], array($group_dn));
         $test_data['search_results'][$filter][$domain]['count'] = count($test_data['search_results'][$filter][$domain] - 1);
       }
-      //debug("removeUserFromGroup:debug test_data[search_results][$filter]"); debug($test_data['search_results']['(&(objectClass=group)(member=$user_dn))']);
-
 
       if (!empty($test_data['users'][$user_dn]['attr']['memberof']) && in_array($group_dn, $test_data['users'][$user_dn]['attr']['memberof'])) {
         $test_data['users'][$user_dn]['attr']['memberof'] = array_diff($test_data['users'][$user_dn]['attr']['memberof'], array($group_dn));
         $test_data['users'][$user_dn]['attr']['memberof']['count'] = count($test_data['users'][$user_dn]['attr']['memberof'] - 1);
       }
-      //debug("removeUserFromGroup:debug test_data[users][$user_dn]"); debug($test_data['users'][$user_dn]);
-
 
       if (!empty($test_data['ldap'][$user_dn]['memberof']) && in_array($group_dn, $test_data['ldap'][$user_dn]['memberof'])) {
         $test_data['ldap'][$user_dn]['memberof'] = array_diff($test_data['ldap'][$user_dn]['memberof'], array($group_dn));
         $test_data['ldap'][$user_dn]['memberof']['count'] = count($test_data['ldap'][$user_dn]['memberof']) - 1;
       }
-      //debug("removeUserFromGroup:debug test_data[ldap][$user_dn]"); debug($test_data['ldap'][$user_dn]);
-
 
       if (!empty($test_data['groups'][$group_dn]['attr']['member']) && in_array($group_dn, $test_data['groups'][$group_dn]['attr']['member']) ) {
         $members = array_diff($test_data['groups'][$group_dn]['attr']['member'], array($group_dn));
         $test_data['groups'][$group_dn]['attr']['member'] = $members;
         $test_data['groups'][$group_dn]['attr']['member'][$i]['count'] = count($members - 1);
       }
-      //debug("removeUserFromGroup:debug test_data[groups][$group_dn]"); debug($test_data['groups'][$group_dn]);
     }
 
   public function AttemptLogonNewUser($name, $goodpwd = TRUE) {
diff --git a/drupal7/sites/all/modules/ldap/ldap_test/ldap_test.info b/drupal7/sites/all/modules/ldap/ldap_test/ldap_test.info
index 2e9d8d3b..36f4611c 100644
--- a/drupal7/sites/all/modules/ldap/ldap_test/ldap_test.info
+++ b/drupal7/sites/all/modules/ldap/ldap_test/ldap_test.info
@@ -18,9 +18,9 @@ files[] = LdapServerTest.class.php
 files[] = LdapTestFunctions.class.php
 files[] = LdapUserTestCase.class.php
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConf.class.php b/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConf.class.php
index 0dac10d9..1d220ed5 100644
--- a/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConf.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConf.class.php
@@ -496,7 +496,6 @@ class LdapUserConf {
    */
 
   public function provisionLdapEntry($account, $ldap_user = NULL, $test_query = FALSE) {
-    //debug('provisionLdapEntry account'); //debug($account);
     $watchdog_tokens = array();
     $result = array(
       'status' => NULL,
@@ -709,8 +708,7 @@ class LdapUserConf {
           );
         }
         else {
-         //  //debug('modifyLdapEntry,dn=' . $proposed_ldap_entry['dn']);  //debug($attributes);
-              // stick $proposed_ldap_entry in $ldap_entries array for drupal_alter call
+          // stick $proposed_ldap_entry in $ldap_entries array for drupal_alter call
           $proposed_dn_lcase = drupal_strtolower($proposed_ldap_entry['dn']);
           $ldap_entries = array($proposed_dn_lcase => $attributes);
           $context = array(
@@ -833,7 +831,6 @@ class LdapUserConf {
       $prov_events = ldap_user_all_events();
     }
     $sid = $this->ldapEntryProvisionServer; //
-    //debug("ldapEntryProvisionServer:$sid");
     if (!$sid) {
       return FALSE;
     }
@@ -911,8 +908,6 @@ class LdapUserConf {
   */
 
   function drupalUserToLdapEntry($account, $ldap_server, $params, $ldap_user_entry = NULL) {
-  //debug('call to drupalUserToLdapEntry, account:'); //debug($account); //debug('ldap_server'); //debug($ldap_server);
-  //debug('params'); //debug($params); //debug('ldap_user_entry');//debug($ldap_user_entry);
     $provision = (isset($params['function']) && $params['function'] == 'provisionLdapEntry');
     $result = LDAP_USER_PROV_RESULT_NO_ERROR;
     if (!$ldap_user_entry) {
@@ -931,9 +926,6 @@ class LdapUserConf {
     $prov_events = empty($params['prov_events']) ? ldap_user_all_events() : $params['prov_events'];
 
     $mappings = $this->getSynchMappings($direction, $prov_events);
-     //debug('prov_events'); //debug(join(",",$prov_events));
-  //  debug('mappings'); debug($mappings);
-      // Loop over the mappings.
     foreach ($mappings as $field_key => $field_detail) {
       list($ldap_attr_name, $ordinal, $conversion) = ldap_servers_token_extract_parts($field_key, TRUE);  //trim($field_key, '[]');
       $ordinal = (!$ordinal) ? 0 : $ordinal;
@@ -942,7 +934,6 @@ class LdapUserConf {
       }
 
       $synched = $this->isSynched($field_key, $params['prov_events'], LDAP_USER_PROV_DIRECTION_TO_LDAP_ENTRY);
-    //  debug("isSynched $field_key: $synched");
       if ($synched) {
         $token = ($field_detail['user_attr'] == 'user_tokens') ? $field_detail['user_tokens'] : $field_detail['user_attr'];
         $value = ldap_servers_token_replace($account, $token, 'user_account');
@@ -1027,7 +1018,7 @@ class LdapUserConf {
         return FALSE;
       }
     }
-   // dpm('ldap_user 675');dpm($ldap_user);
+
     if (!isset($user_edit['name']) && isset($account->name)) {
       $user_edit['name'] = $account->name;
       $watchdog_tokens['%username'] = $user_edit['name'];
@@ -1329,14 +1320,11 @@ class LdapUserConf {
     );
     if (!$result) {
       if (isset($this->synchMapping[$direction][$attr_token])) {
-        //debug($this->synchMapping[$direction][$attr_token]);
       }
       else {
-      //  debug("$attr_token not in ldapUserConf::synchMapping");
       }
     }
     return $result;
   }
 
-
-} // end LdapUserConf class
+}
diff --git a/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConfAdmin.class.php b/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConfAdmin.class.php
index bd984fec..c9fffa8f 100644
--- a/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConfAdmin.class.php
+++ b/drupal7/sites/all/modules/ldap/ldap_user/LdapUserConfAdmin.class.php
@@ -527,7 +527,6 @@ EOT;
           $row_descriptor = t("server %sid row mapping to ldap attribute %ldap_attr", $tokens);
           $tokens['!row_descriptor'] = $row_descriptor;
           $ldap_attribute_maps_in_token = array();
-         // debug('calling ldap_servers_token_extract_attributes from validate, mapping='); debug($mapping['ldap_attr']);
           ldap_servers_token_extract_attributes($ldap_attribute_maps_in_token, $mapping['ldap_attr']);
 
           if ($mapping['direction'] == LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER) {
diff --git a/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.info b/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.info
index a69cecb4..7e4ed755 100644
--- a/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.info
+++ b/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.info
@@ -23,9 +23,9 @@ files[] = tests/ldap_user.test
 stylesheets[all][] = ldap_user.css
 configure = admin/config/people/ldap/user
 
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.install b/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.install
index 477de00d..05136a9f 100644
--- a/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.install
+++ b/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.install
@@ -136,7 +136,7 @@ function ldap_user_user_entity_fields() {
       'label' => 'LDAP Server ID that puid was derived from.  NULL if puid is independent of server configuration instance.',
       'description' => 'This field should not be edited.',
       'required' => 0,
-      'default_value_function' => 'ldap_user_provisioned_sid_default',
+      'default_value' => array(),
       'settings' => array(
         'text_processing' => 0,
       ),
@@ -181,7 +181,7 @@ function ldap_user_user_entity_fields() {
       'label' => 'Value of user\'s permanent unique id.  This should never change for a given ldap identified user.',
       'description' => 'This field should not be edited.',
       'required' => 0,
-      'default_value_function' => 'ldap_user_puid_default',
+      'default_value' => array(),
       'settings' => array(
         'text_processing' => 0,
       ),
@@ -225,7 +225,7 @@ function ldap_user_user_entity_fields() {
       'label' => 'Property specified as user\'s puid.',
       'description' => 'This field should not be edited.',
       'required' => 0,
-      'default_value_function' => 'ldap_user_puid_property_default',
+      'default_value' => array(),
       'settings' => array(
         'text_processing' => 0,
       ),
@@ -269,7 +269,7 @@ function ldap_user_user_entity_fields() {
       'label' => 'User LDAP DN',
       'description' => 'May change when user\'s DN changes. This field should not be edited.',
       'required' => 0,
-      'default_value_function' => 'ldap_user_dn_default',
+      'default_value' => array(),
       'settings' => array(
         'text_processing' => 0,
       ),
diff --git a/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.module b/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.module
index 8cca143a..25e66b90 100644
--- a/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.module
+++ b/drupal7/sites/all/modules/ldap/ldap_user/ldap_user.module
@@ -965,7 +965,6 @@ function ldap_user_user_insert(&$user_edit, $account, $category) {
  */
 
 function ldap_user_user_update(&$user_edit, $account, $category) {
-  //debug("ldap_user_user_update, category=$category"); debug($user_edit); debug($account); // ldap_user_user_insert, category='. $category . 'account->status = ' . $account->status);
   if (ldap_user_ldap_exclude($account, $user_edit)) {
     return;
   }
@@ -1011,7 +1010,6 @@ function ldap_user_user_update(&$user_edit, $account, $category) {
  */
 
 function ldap_user_user_presave(&$user_edit, $account, $category) {
- //debug("ldap_user_user_presave, category=$category"); debug($user_edit); debug($account); // ldap_user_user_insert, category='. $category . 'account->status = ' . $account->status);
 
   if (ldap_user_ldap_exclude($account, $user_edit)) {
     return;
@@ -1060,34 +1058,6 @@ function ldap_user_user_delete($account) {
   }
 }
 
-
-
-/**
- * @return default value for field user->ldap_user_provisioned_sid
- */
-function ldap_user_provisioned_sid_default($entity_type, $entity, $field, $instance, $langcode) {
-  return NULL;
-}
-
-/**
- * @return default value for field user->ldap_user_provisioned_sid
- */
-function ldap_user_puid_default($entity_type, $entity, $field, $instance, $langcode) {
-  return NULL;
-}
-/**
- * @return default value for field user->ldap_user_puid
- */
-function ldap_user_puid_property_default($entity_type, $entity, $field, $instance, $langcode) {
-  return NULL;
-}
-/**
- * @return default value for field user->ldap_user_dn
- */
-function ldap_user_dn_default($entity_type, $entity, $field, $instance, $langcode) {
-  return NULL;
-}
-
 /**
  * Implements hook_field_widget_info().
  * to provide field type for LDAP fields
diff --git a/drupal7/sites/all/modules/ldap/ldap_user/tests/ldap_user.test b/drupal7/sites/all/modules/ldap/ldap_user/tests/ldap_user.test
index 32e4a719..e6c49ae0 100644
--- a/drupal7/sites/all/modules/ldap/ldap_user/tests/ldap_user.test
+++ b/drupal7/sites/all/modules/ldap/ldap_user/tests/ldap_user.test
@@ -189,7 +189,6 @@ class LdapUserUnitTests extends LdapTestCase {
       $array_diff = array_diff($user_edit, $desired_result);
     }
     //@todo need better diff, this will give false positives in most cases
-  //  debug('user_edit,desired_result,diff'); debug( array($user_edit, $desired_result, $array_diff));
     $this->assertTrue(count($array_diff) == 0, t('ldapUserConf::entryToUserEdit retrieved correct property, field, and data values.'), $this->testId('ldapUserConf::entryToUserEdit'));
     if (count($array_diff) != 0) {
       debug('ldapUserConf::entryToUserEdit failed.  resulting user edit array:'); debug($user_edit); debug('desired result:'); debug($desired_result); debug('array_diff:'); debug($array_diff);
@@ -212,7 +211,6 @@ class LdapUserUnitTests extends LdapTestCase {
       foreach ($tests as $boolean_result => $attribute_tokens) {
         foreach ($attribute_tokens as $attribute_token) {
           $is_synched = $ldap_user_conf->isSynched($attribute_token, array($prov_event), LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER);
-          // debug("is_synched_tests: is_synched=$is_synched, attribute_token=$attribute_token, prov_event=$prov_event");
           if ((int)$is_synched !== (int)$boolean_result) {
             $fail = TRUE;
             $debug[$attribute_token] = "isSynched($attribute_token, array($prov_event),
@@ -250,7 +248,6 @@ class LdapUserUnitTests extends LdapTestCase {
     $account->name = 'hpotter';
     $params = array('ldap_context' => 'ldap_user_prov_to_drupal', 'direction' => LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER);
     list($ldap_entry, $error) = $ldap_user_conf->drupalUserToLdapEntry($account, 'activedirectory1', $params);
-  //  debug('ldap_entry'); debug($ldap_entry);
 
     $account = NULL;
     $user_edit = array('name' => 'hpotter');
@@ -580,7 +577,6 @@ class LdapUserUnitTests extends LdapTestCase {
         if ($field_name) {
           $token_attributes = array();
           ldap_servers_token_extract_attributes($token_attributes,  $test['mapping']['ldap_attr']);
-          //debug('token_attributes'); debug($token_attributes);
           foreach ($token_attributes as $attr_name => $attr_parts ) {
             $this->testFunctions->setFakeServerUserAttribute(
               'activedirectory1',
@@ -595,7 +591,6 @@ class LdapUserUnitTests extends LdapTestCase {
 
         $ldap_user_conf->save();
         $ldap_user_conf = ldap_user_conf('admin', TRUE);
-       // debug("ldap_user_conf in prep field_token=$field_token"); debug($ldap_user_conf->synchMapping); debug($ldap_user_conf->ldapUserSynchMappings);
         ldap_user_ldap_provision_semaphore(NULL, NULL, NULL, TRUE);
         ldap_servers_flush_server_cache();
 
@@ -620,12 +615,8 @@ class LdapUserUnitTests extends LdapTestCase {
               debug('field fail,' . $property_name); debug($user_entity->{$property_name}); debug($test['property_results'][0]); //debug($user_entity);
             }
           }
-          else {
-          // debug("property_name=$property_name not configured to provisionDrupalAccount on drupal user create for direction=$direction and prov_event=$prov_event");
-          }
         }
         if ($field_name) {
-          // debug("property_name=$property_name, prov_event=$prov_event, direction=$direction, field_token=$field_token, sid=$sid, ldap_user_conf->ldapUserSynchMappings $direction - $sid"); debug($ldap_user_conf->ldapUserSynchMappings[$direction][$sid]);
 
           if (in_array($prov_event, $ldap_user_conf->ldapUserSynchMappings[$direction][$field_token]['prov_events'])) { // if intended to synch
             $field_success = isset($user_entity->{$field_name}[LANGUAGE_NONE][0]['value']) &&
@@ -872,7 +863,6 @@ class LdapUserIntegrationTests extends LdapTestCase {
 
       $ldap_user_conf->save();
       $ldap_user_conf = ldap_user_conf('default', TRUE);
-     // debug('ldap_user_conf after provisionToLdapEmailVerification setup'); debug($ldap_user_conf);
 
       variable_set('user_email_verification', TRUE);
       variable_set('user_register', USER_REGISTER_VISITORS); // or USER_REGISTER_ADMINISTRATORS_ONLY, USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
@@ -1053,10 +1043,8 @@ class LdapUserIntegrationTests extends LdapTestCase {
     $account_options = $drupal_form['basic_to_drupal']['orphanedDrupalAcctBehavior']['#options'];
     $cn_to_account = array();
     $ldap_server = ldap_servers_get_servers('activedirectory1', NULL, TRUE, TRUE);
-   // debug("ldap_server"); debug(is_object($ldap_server));
 
     foreach ($account_options as $account_option => $account_option_text) {
-     // debug("$account_option - $account_option_text");
       $sids = array('activedirectory1');
       $this->prepTestData('hogwarts', $sids, 'provisionToDrupal', 'default');
       $ldap_user_conf->orphanedDrupalAcctBehavior = $account_option;
@@ -1070,17 +1058,13 @@ class LdapUserIntegrationTests extends LdapTestCase {
       $last_clone_username= 'clone' . (LDAP_TEST_USER_ORPHAN_CLONE_COUNT - 1);
       for ($i = 0; $i < LDAP_TEST_USER_ORPHAN_CLONE_COUNT; $i++) { // 70
         $name = "clone" . $i;
-        //debug("create clone $name, activedirectory1");
         $account = $this->createLdapIdentifiedDrupalAccount(
           $ldap_user_conf,
           $name,
           'activedirectory1'
         );
         $cn_to_account[$name] = $account;
-        //debug("new account"); debug($account);
       }
-    //  debug($cn_to_account['clone0']);
-    //  debug($cn_to_account[$last_clone_username]);
 
       // delete 10 ldap entries
       // @FIXME: Wrapper for broken test.
@@ -1091,23 +1075,19 @@ class LdapUserIntegrationTests extends LdapTestCase {
         $clone_last = user_load($clone_last_uid, TRUE);
       }
 
-      //debug("pre ldap delete, clone0 and cloneN $first_clone_username and $last_clone_username"); debug($clone_first);debug($clone_last); //debug($ldap_server->entries);
       $delete = LDAP_TEST_USER_ORPHAN_CLONE_COUNT - LDAP_TEST_USER_ORPHAN_CLONE_REMOVE_COUNT;
       for ($i = 0; $i < $delete; $i++) {
         $name = "clone" . $i;
         $account = $cn_to_account[$name];
-        //debug("delete ldap entry: ". $account->ldap_user_current_dn[LANGUAGE_NONE][0]['value']);
-      //  ?? is it possible the ldap delete hook is causing the drupal user to get populated with empty values?
+        // ?? is it possible the ldap delete hook is causing the drupal user to get populated with empty values?
         $ldap_server->delete($account->ldap_user_current_dn[LANGUAGE_NONE][0]['value']);
       }
 
       $clone_first = user_load($clone_first_uid, TRUE);
       $clone_last = user_load($clone_last_uid, TRUE);
-      //debug("post ldap delete and pre cron, clone0 and cloneN"); debug($clone_first->status);debug($clone_last->status);// debug($ldap_server->entries);
       drupal_cron_run();
       $clone_first = user_load($clone_first_uid, TRUE);
       $clone_last = user_load($clone_last_uid, TRUE);
-      //debug("post cron, clone0 and cloneN"); debug($clone_first->status);debug($clone_last->status); //debug($ldap_server->entries);
       switch ($account_option) {
 
         case 'ldap_user_orphan_do_not_check':
@@ -1115,12 +1095,9 @@ class LdapUserIntegrationTests extends LdapTestCase {
           for ($i = 0; $i < LDAP_TEST_USER_ORPHAN_CLONE_COUNT; $i++) { // 70
             $name = "clone" . $i;
             $test_uids[] = @$cn_to_account[$name]->uid;
-
-            //debug($account);
           }
           $success = TRUE;
           $accounts = user_load_multiple($test_uids);
-         // debug("accounts for $test_id"); debug($accounts);
           foreach ($accounts as $uid => $account) {
             if ($account->status != 1) {
               $success = FALSE;
@@ -1129,16 +1106,11 @@ class LdapUserIntegrationTests extends LdapTestCase {
           }
           if ($success) {
             $success = ($clone_last && $clone_last->status == 1);
-            if (!$success) {
-             // debug("success = $success, status=" . $clone_last->status);
-            }
           }
 
-
         break;
 
         case 'ldap_user_orphan_email' :
-         // debug('ldap_user_orphan_email');
           // test is if email has 10 users and was sent
           $emails = $this->drupalGetMails();
           if (count($emails)) {
@@ -1153,7 +1125,6 @@ class LdapUserIntegrationTests extends LdapTestCase {
 
         case 'user_cancel_block':
         case 'user_cancel_block_unpublish':
-          //debug('user_cancel_block');
           // test is if clone0-clone9 have a status of 0
           // and clone12,11... have a status of 1
           $test_uids = array();
@@ -1183,8 +1154,6 @@ class LdapUserIntegrationTests extends LdapTestCase {
           for ($i = 0; $i < $delete; $i++) { // 70
             $name = "clone" . $i;
             $test_uids[] = @$cn_to_account[$name]->uid;
-
-            //debug($account);
           }
           $success = TRUE;
           $accounts = user_load_multiple($test_uids);
@@ -1276,8 +1245,6 @@ class LdapUserUITests extends LdapTestCase {
     $this->drupalLogin($this->privileged_user);
 
     $ldap_user_conf = ldap_user_conf();
-  //  debug('ldap_user_conf before form submission'); debug($ldap_user_conf);
-
 
     $this->drupalGet('admin/config/people/ldap/user');
 
@@ -1343,7 +1310,6 @@ class LdapUserUITests extends LdapTestCase {
     $this->drupalPost('admin/config/people/ldap/user', $edit, t('Save'));
 
     $ldap_user_conf = ldap_user_conf(NULL, TRUE);
-   // debug('edit'); debug($edit); debug('user conf object after save'); debug($ldap_user_conf);
 
     foreach ($edit_direct_map as $property => $value) {
       $this->assertTrue($ldap_user_conf->{$property} == $value, $property . ' ' . t('field set correctly'), $this->testId('user interface tests'));
diff --git a/drupal7/sites/all/modules/ldap/ldap_views/ldap_views.info b/drupal7/sites/all/modules/ldap/ldap_views/ldap_views.info
index ff917551..2463c874 100644
--- a/drupal7/sites/all/modules/ldap/ldap_views/ldap_views.info
+++ b/drupal7/sites/all/modules/ldap/ldap_views/ldap_views.info
@@ -21,9 +21,9 @@ files[] = handlers/ldap_views_handler_filter.inc
 files[] = handlers/ldap_views_handler_filter_attribute.inc
 files[] = handlers/ldap_views_handler_sort.inc
 files[] = handlers/ldap_views_handler_sort_attribute.inc
-; Information added by Drupal.org packaging script on 2017-03-18
-version = "7.x-2.0"
+; Information added by Drupal.org packaging script on 2017-05-21
+version = "7.x-2.1"
 core = "7.x"
 project = "ldap"
-datestamp = "1489858388"
+datestamp = "1495392789"
 
diff --git a/drupal7/sites/all/modules/ldap/ldap_views/plugins/ldap_views_plugin_query_ldap.inc b/drupal7/sites/all/modules/ldap/ldap_views/plugins/ldap_views_plugin_query_ldap.inc
index b3efc57b..4a80ee6d 100644
--- a/drupal7/sites/all/modules/ldap/ldap_views/plugins/ldap_views_plugin_query_ldap.inc
+++ b/drupal7/sites/all/modules/ldap/ldap_views/plugins/ldap_views_plugin_query_ldap.inc
@@ -238,13 +238,14 @@ class ldap_views_plugin_query_ldap extends views_plugin_query {
  */
     if ($result !== FALSE) { // not an error
         $entries = array_merge($entries, $result);
-        $num_entries += array_shift($result);
+        $num_entries += $result['count'];
+        unset($result['count']);
       }
     }
     if (property_exists($view->query, 'limit')) {
       $limit     = $view->query->limit;
     }
-    $offset      = $view->query->offset;
+    $offset = property_exists($view->query, 'offset')? $view->query->offset : 0;
     $result      = array();
     $sort_fields = array();
     if (!empty($this->orderby)) {
@@ -269,7 +270,7 @@ class ldap_views_plugin_query_ldap extends views_plugin_query {
             switch ($field->options['multivalue']) {
               case 'v-all':
                 // remove 'count' index
-                array_shift($entry[$alias]);
+                unset($entry[$alias]['count']);
                 $entry[$alias] = implode($field->options['value_separator'], $entry[$alias]);
                 break;
               case 'v-count':
@@ -283,6 +284,7 @@ class ldap_views_plugin_query_ldap extends views_plugin_query {
             }
           }
           // order criteria
+          //If the field with alias $alias has a corresponding entry in $sort_fields, copy its value into the data key of $sort_fields for later sorting.
           if (array_key_exists($alias, $sort_fields)) {
             $sort_fields[$alias]['data'][$key] = $entry[$alias];
           }
@@ -305,13 +307,14 @@ class ldap_views_plugin_query_ldap extends views_plugin_query {
       }
       $params[] = &$entries;
 
-      // Some LDAP setups output a 'count' variable first in the array, which changes the array size;
+      // Some LDAP setups output a 'count' variable in the array, which changes the array size;
       // temporarily remove it, sort the arrays, and then put it back.
       if (array_key_exists('count', $entries)) {
-        $countValue = array_shift($entries); // remove the count variable
+        $countValue = $entries['count']; // remove the count variable
+        unset($entries['count']);
         $params[] = &$entries;
         call_user_func_array('array_multisort', $params);
-        array_unshift($params, $countValue);
+        $params['count'] = $countValue;
       }
       else {
         $params[] = &$entries;
diff --git a/drupal7/sites/all/modules/media_ckeditor/README.txt b/drupal7/sites/all/modules/media_ckeditor/README.txt
index e6b23bed..05cf7cab 100644
--- a/drupal7/sites/all/modules/media_ckeditor/README.txt
+++ b/drupal7/sites/all/modules/media_ckeditor/README.txt
@@ -41,6 +41,12 @@ CKEditor Library Plugins
 INSTALLATION
 ------------
 
+***NEW***
+  For a quicker and easier setup, follow this recipe
+  https://www.drupal.org/node/2843391
+  use this README.txt as additional troubleshooting
+***end NEW***
+
 * Install Media CKEditor via the standard Drupal installation process:
   'http://drupal.org/node/895232'.
 * If you weren't previously using the CKEditor WYSIWYG client-side editor,
@@ -59,3 +65,4 @@ INSTALLATION
   plugin for the desired text formats from the CKEditor configuration
   page: '/admin/config/content/ckeditor'.
 * Disable CKEditor's Advanced Content Filter for each of the text formats.
+
diff --git a/drupal7/sites/all/modules/media_ckeditor/includes/media_ckeditor.pages.inc b/drupal7/sites/all/modules/media_ckeditor/includes/media_ckeditor.pages.inc
new file mode 100644
index 00000000..2bc7dc2f
--- /dev/null
+++ b/drupal7/sites/all/modules/media_ckeditor/includes/media_ckeditor.pages.inc
@@ -0,0 +1,72 @@
+<?php
+
+/**
+ * @file
+ * Common pages for the Media Ckeditor module.
+ */
+
+/**
+ * Callback to fetch the markup of a file with certain overrides.
+ */
+function media_ckeditor_rendered_file_in_wysiwyg() {
+
+  // If you would like to see how the $tag_info variable below is built, please
+  // @see media_ckeditor/js/plugins/media/library.js.
+  $tag_info = drupal_get_query_parameters();
+
+  // Introductory sanity/security check.
+  if (!is_numeric($tag_info['fid'])) {
+    throw new Exception('Invalid file id.');
+  }
+
+  // Start with the file object.
+  $file = file_load($tag_info['fid']);
+  if (!$file) {
+    throw new Exception('Could not load media object');
+  }
+
+  // Now attempt to override any specified fields.
+  $fields = array();
+  foreach ($tag_info['fields'] as $key => $values) {
+
+    // Only operate on actual fields.
+    if (strpos($key, 'field_') === 0) {
+      $parsed_field = explode('[', str_replace(']', '', $key));
+      $field_name = $parsed_field[0];
+
+      if (isset($file->{$field_name})) {
+
+        // Make sure this is a valid field.
+        $field_info = field_info_field($field_name);
+        if ($field_info) {
+          $field_language = $parsed_field[1];
+          $column = key($field_info['columns']);
+
+          // Some field values will show up here as a flat string value, so
+          // convert it into a Drupal-friendly field value array.
+          if (is_string($values)) {
+            $values = array(array($column => $values));
+          }
+
+          // The values need to be urldecoded.
+          foreach ($values as $index => &$value) {
+            if (isset($value[$column])) {
+              $value[$column] = urldecode($value[$column]);
+            }
+          }
+
+          // Override the field on the file entity.
+          $fields[$field_name] = array($field_language => $values);
+        }
+      }
+    }
+  }
+
+  // Make sure it is indicated that this is a wysiwyg rendering.
+  $file->override['wysiwyg'] = TRUE;
+
+  // Now simply print the file entity and exit.
+  $build = media_ckeditor_render_file_with_overrides($file, $tag_info['view_mode'], $fields);
+  print drupal_render($build);
+  drupal_page_footer();
+}
diff --git a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/icons/hidpi/media.png b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/icons/hidpi/media.png
new file mode 100644
index 00000000..0c9c1f7b
Binary files /dev/null and b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/icons/hidpi/media.png differ
diff --git a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/icons/media.png b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/icons/media.png
new file mode 100644
index 00000000..57eaa142
Binary files /dev/null and b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/icons/media.png differ
diff --git a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/images/icon.gif b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/images/icon.gif
deleted file mode 100644
index bf9b501c..00000000
Binary files a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/images/icon.gif and /dev/null differ
diff --git a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/library.js b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/library.js
index 7bc8007b..feedf055 100644
--- a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/library.js
+++ b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/library.js
@@ -7,6 +7,44 @@
 (function ($) {
   Drupal.media = Drupal.media || {};
 
+  /**
+   * Attaches 'insert' button to media widget.
+   */
+  Drupal.behaviors.mediaWidgetInsert = {
+    attach: function (context, settings) {
+      if (Drupal.ckeditorInstance && Drupal.settings.media_ckeditor && Drupal.settings.media_ckeditor.wysiwyg_insert) {
+        // Only add buttons on fields that have been configured so, by
+        // consulting the Drupal.settings.media_ckeditor.wysiwyg_insert var.
+        for (var fieldName in Drupal.settings.media_ckeditor.wysiwyg_insert) {
+          var fieldId = '#edit-' + fieldName.replace(/_/g, '-');
+          // Within the field markup, look for the table of files.
+          $(fieldId, context).find('.media-widget').once('mediaInsertButton', function() {
+            // For each file, check to see if there is a file ID.
+            if ($(this).find('input.fid').val() != 0) {
+              // Now we add the button next to "Remove".
+              var insertButton = $('<a class="media-insert button">' + Drupal.t('Insert') + '</a>')
+                .click(function(e) {
+                  e.preventDefault();
+                  var fid = $(this).parent().parent().find('.fid').val();
+                  var mediaFile = {fid: fid}
+                  Drupal.ckeditorInstance.mediaInsert = {mediaFiles: [mediaFile]};
+                  Drupal.ckeditorInstance.execCommand('media');
+                });
+              // Insert the button, differently for single vs. multi value.
+              var multiValue = $(fieldId + ' table', context).length;
+              if (multiValue) {
+                insertButton.insertBefore($(this).parent().parent().find('input.remove'));
+              }
+              else {
+                insertButton.insertBefore($(this).find('input.remove'));
+              }
+            }
+          });
+        }
+      }
+    }
+  };
+
   Drupal.settings.ckeditor.plugins['media'] = {
     /**
      * Execute the button.
@@ -26,13 +64,22 @@
         else {
           $alreadyInsertedMedia = jQuery(data.node).find('[data-media-element]');
         }
-        if ($alreadyInsertedMedia.length) {
-          // Change the view mode for already-inserted media.
+        // First check to see if we are using an Insert button.
+        if (typeof Drupal.ckeditorInstance.mediaInsert !== 'undefined') {
+          var mediaFile = Drupal.ckeditorInstance.mediaInsert.mediaFiles[0];
+          delete Drupal.ckeditorInstance.mediaInsert;
+          Drupal.media.popups.mediaStyleSelector(mediaFile, function (mediaFiles) {
+            Drupal.settings.ckeditor.plugins['media'].insertMediaFile(mediaFile, mediaFiles, CKEDITOR.instances[instanceId]);
+          }, settings['global']);
+        }
+        // Next check to see if we are editing already-inserted media.
+        else if ($alreadyInsertedMedia.length) {
           var mediaFile = Drupal.media.filter.extract_file_info($alreadyInsertedMedia);
           Drupal.media.popups.mediaStyleSelector(mediaFile, function (mediaFiles) {
             Drupal.settings.ckeditor.plugins['media'].insertMediaFile(mediaFile, mediaFiles, CKEDITOR.instances[instanceId]);
           }, settings['global']);
         }
+        // Otherwise we are embedding new media.
         else {
           Drupal.media.popups.mediaBrowser(function (mediaFiles) {
             Drupal.settings.ckeditor.plugins['media'].mediaBrowserOnSelect(mediaFiles, instanceId);
@@ -54,7 +101,58 @@
       return;
     },
 
-    insertMediaFile: function (mediaFile, formattedMedia, ckeditorInstance) {
+    insertMediaFile: function (mediaFile, formattedMedia, ckeditorInstance, fullyRenderedFile) {
+
+      // See if we should use ajax to get the fully rendered file.
+      if (typeof fullyRenderedFile === 'undefined' &&
+          Drupal.settings.media_ckeditor.fully_rendered_files) {
+
+        $.ajax({
+          url: Drupal.settings.basePath + 'media/rendered-in-wysiwyg',
+          type: 'GET',
+          data: {
+            fid: mediaFile.fid,
+            view_mode: formattedMedia.type,
+            fields: formattedMedia.options
+          },
+          success: function(html) {
+            // To work around an IE issue, preload any image. The issue is
+            // that IE requests the image 2 times, and one request gets a 503,
+            // causing a broken image icon in the WYSIWYG instead of the actual
+            // image.
+            var $images = $(html).find('img');
+            if (!$images.length || $(html).find('picture').length) {
+              // If there are no images, just insert the html immediately, by
+              // re-calling this function with the ajax-retrieved HTML.
+              Drupal.settings.ckeditor.plugins['media'].insertMediaFile(mediaFile, formattedMedia, ckeditorInstance, html);
+            }
+            else {
+              // Otherwise do the same, but only after the first image preloads.
+              // Possible future improvement might be to handle multiple images
+              // instead of just the first, but even better would be to remove
+              // this workaround entirely, when/if IE's behavior changes.
+              var image = new Image();
+              image.onload = function() {
+                Drupal.settings.ckeditor.plugins['media'].insertMediaFile(mediaFile, formattedMedia, ckeditorInstance, html);
+              }
+              image.src = $images.first().attr('src');
+            }
+          },
+          error: function(data) {
+            // Fallback to whatever the HTML was already going to be.
+            Drupal.settings.ckeditor.plugins['media'].insertMediaFile(mediaFile, formattedMedia, ckeditorInstance, formattedMedia.html);
+          }
+        });
+
+        // Stop for now, because the callback above re-calls this same function.
+        return;
+      }
+
+      // See if we already used ajax to get the fully rendered file.
+      if (typeof fullyRenderedFile !== 'undefined') {
+        formattedMedia.html = fullyRenderedFile;
+      }
+
       // Customization of Drupal.media.filter.registerNewElement().
       var element = Drupal.media.filter.create_element(formattedMedia.html, {
         fid: mediaFile.fid,
@@ -197,4 +295,22 @@
     }
   };
 
+  // If media_ckeditor is configured to render items in the wysiwyg as full
+  // rendered file entities, we need to completely hijack a function from
+  // media_wysiwyg.filter.js.
+  if (Drupal.settings.media_ckeditor.fully_rendered_files) {
+
+    // Replaces function of the same name, from media_wysiwyg.filter.js.
+    Drupal.media.filter.replacePlaceholderWithToken = function(content) {
+
+      var $placeholder = $(content);
+      if ($placeholder.hasClass('media-element')) {
+        var macro = Drupal.media.filter.create_macro($placeholder);
+        Drupal.media.filter.ensure_tagmap();
+        Drupal.settings.tagmap[macro] = content;
+        return macro;
+      }
+      return content;
+    }
+  }
 })(jQuery);
diff --git a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/plugin.js b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/plugin.js
index a82f6edb..8b94419e 100644
--- a/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/plugin.js
+++ b/drupal7/sites/all/modules/media_ckeditor/js/plugins/media/plugin.js
@@ -17,6 +17,7 @@ For licensing, see LICENSE.html or http://ckeditor.com/license
     // disabled by default.
     hasWidgetSupport: false,
     mediaLegacyWrappers: false,
+    hidpi: true,
     onLoad: function() {
       // Check if this instance has widget support.
       mediaPluginDefinition.hasWidgetSupport = typeof(CKEDITOR.plugins.registered.widget) != 'undefined';
@@ -37,9 +38,9 @@ For licensing, see LICENSE.html or http://ckeditor.com/license
             content: ''
           };
           var selection = editor.getSelection();
-
           if (selection) {
             data.node = selection.getSelectedElement();
+
             if (data.node) {
               data.node = data.node.$;
             }
@@ -56,6 +57,24 @@ For licensing, see LICENSE.html or http://ckeditor.com/license
               data.content = data.node.parentNode.innerHTML;
             }
           }
+
+          // If we are inside another media element, we need to move the cursor to the end of the element
+          var selected_element = selection.getStartElement();
+          var parent = selected_element.getParent();
+          //if we are inside "a" tag and inside "span" (with class media-element)
+          if (selected_element.is('a') && parent.is('span') && parent.hasClass('media-element')) {
+            selection.selectElement(parent);
+            selected_ranges = selection.getRanges();
+            selected_ranges[0].collapse(false);
+            selection.selectRanges(selected_ranges);
+          }
+          //if we are outside "a" tag but inside "span" (with class media-element)
+          else if (selected_element.is('span') && selected_element.hasClass('media-element')) {
+              selection.selectElement(selected_element);
+              selected_ranges = selection.getRanges();
+              selected_ranges[0].collapse(false);
+              selection.selectRanges(selected_ranges);
+          }
           Drupal.settings.ckeditor.plugins['media'].invoke(data, Drupal.settings.ckeditor.plugins['media'], editor.name);
         }
       });
@@ -88,8 +107,7 @@ For licensing, see LICENSE.html or http://ckeditor.com/license
       editor.ui.addButton( 'Media',
       {
         label: 'Add media',
-        command: 'media',
-        icon: this.path + 'images/icon.gif'
+        command: 'media'
       });
 
       var ckeditorversion = parseFloat(CKEDITOR.version);
diff --git a/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.ckeditor.inc b/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.ckeditor.inc
index 417dfbb3..8cf5063c 100644
--- a/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.ckeditor.inc
+++ b/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.ckeditor.inc
@@ -16,7 +16,7 @@ function media_ckeditor_ckeditor_plugin_alter(&$plugins) {
     'path' => '%base_path%' . drupal_get_path('module', 'media_ckeditor') . '/js/plugins/media/',
     'buttons' => array(
       'Media' => array(
-        'icon' => 'images/icon.gif',
+        'icon' => 'icons/media.png',
         'label' => 'Add media',
       ),
     ),
diff --git a/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.info b/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.info
index 9fb0ddc6..50ecdc77 100644
--- a/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.info
+++ b/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.info
@@ -15,9 +15,9 @@ test_dependencies[] = ckeditor
 test_dependencies[] = views
 test_dependencies[] = ctools
 
-; Information added by Drupal.org packaging script on 2017-01-15
-version = "7.x-2.0-rc3"
+; Information added by Drupal.org packaging script on 2017-05-24
+version = "7.x-2.1"
 core = "7.x"
 project = "media_ckeditor"
-datestamp = "1484494686"
+datestamp = "1495629657"
 
diff --git a/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.module b/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.module
index 9f6e8a69..12728f3f 100644
--- a/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.module
+++ b/drupal7/sites/all/modules/media_ckeditor/media_ckeditor.module
@@ -10,6 +10,7 @@
  */
 function media_ckeditor_element_info_alter(&$types) {
   $types['text_format']['#pre_render'][] = 'media_ckeditor_pre_render_text_format';
+  $types['media']['#pre_render'][] = 'media_ckeditor_pre_render_media';
 }
 
 /**
@@ -36,7 +37,19 @@ function media_ckeditor_pre_render_text_format($element) {
     'data' => drupal_get_path('module', 'media_ckeditor') . '/js/plugins/media/library.js',
     'type' => 'file',
     'scope' => 'footer',
-    'weight' => -20,
+    // It's important that this javascript fire after CKEditor.
+    'weight' => 20,
+  );
+
+  // Communicate to javascript whether we will be displaying fully rendered
+  // file entities in the WYSIWYG.
+  $element['#attached']['js'][] = array(
+    'data' => array(
+      'media_ckeditor' => array(
+        'fully_rendered_files' => _media_ckeditor_fully_rendered_files_in_wysiwyg(),
+      ),
+    ),
+    'type' => 'setting',
   );
 
   return $element;
@@ -73,3 +86,159 @@ function media_ckeditor_media_browser_params_alter(&$stored_params) {
     }
   }
 }
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ */
+function media_ckeditor_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
+  // Add a checkbox that marks this field as needing an "Insert" button.
+  if (!empty($form['#instance']['widget']['module'])) {
+    if ('media' === $form['#instance']['widget']['module']) {
+      $form['instance']['settings']['wysiwyg_insert'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Show button for inserting files into WYSIWYG editor'),
+        '#description' => t('If checked, then an "Insert" button will be available to put attached files into the active WYSIWYG editor.'),
+        '#default_value' => isset($form['#instance']['settings']['wysiwyg_insert']) ? $form['#instance']['settings']['wysiwyg_insert'] : FALSE,
+      );
+    }
+  }
+}
+
+/**
+ * Pre-render callback for media elements.
+ */
+function media_ckeditor_pre_render_media($element) {
+  // If the media widget has been configured to have an Insert button, we'll
+  // communicate that information through javascript settings.
+  $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
+  if (!empty($instance['settings']['wysiwyg_insert'])) {
+    $element['#attached']['js'][] = array(
+      'type' => 'setting',
+      'data' => array(
+        'media_ckeditor' => array(
+          'wysiwyg_insert' => array(
+            $element['#field_name'] => TRUE,
+          ),
+        ),
+      ),
+    );
+  }
+  return $element;
+}
+
+
+/**
+ * Helper function to tell whether we should render full entities in WYSIWYGs.
+ */
+function _media_ckeditor_fully_rendered_files_in_wysiwyg() {
+  if (variable_get('media_ckeditor_fully_rendered_files', FALSE) &&
+      user_access('view overridden file entities in wysiwyg')) {
+    return TRUE;
+  }
+  return FALSE;
+}
+
+/**
+ * Implements hook_menu().
+ */
+function media_ckeditor_menu() {
+  $items = array();
+
+  // Add our AJAX-friendly route for rendering the file entities for use in
+  // the WYSIWYG editor.
+  $items['media/rendered-in-wysiwyg'] = array(
+    'page callback' => 'media_ckeditor_rendered_file_in_wysiwyg',
+    'access callback' => '_media_ckeditor_fully_rendered_files_in_wysiwyg',
+    'file' => 'includes/media_ckeditor.pages.inc',
+    'theme callback' => 'ajax_base_page_theme',
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
+}
+
+/**
+ * A permission to allow users to view overridden files in the WYSIWYG.
+ */
+function media_ckeditor_permission() {
+  return array(
+    'view overridden file entities in wysiwyg' => array(
+      'title' => t('View overridden file entities in wysiwyg'),
+      'description' => t('When users are embedding files in WYSIWYGs, the file entities will be displayed with whatever overrides the user may have specified in the Media popup.'),
+    ),
+  );
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ */
+function media_ckeditor_form_media_admin_config_browser_alter(&$form, &$form_state) {
+
+  // Add our optional settings to the Media Browser admin form.
+  $form['media_ckeditor'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Ckeditor WYSIWYG configuration'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+    '#weight' => 50,
+  );
+  $form['media_ckeditor']['media_ckeditor_fully_rendered_files'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Display fully rendered files in WYSIWYG'),
+    '#description' => t('Check this box to render files in the WYSIWYG dynamically, to reflect any field overrides the user may have specified. Note that this requires the user has the corresponding permission: "View overridden file entities in wysiwyg"'),
+    '#default_value' => variable_get('media_ckeditor_fully_rendered_files', FALSE),
+  );
+}
+
+/**
+ * Implements hook_media_wysiwyg_token_to_markup_alter().
+ */
+function media_ckeditor_media_wysiwyg_token_to_markup_alter(&$element, $tag_info, $settings) {
+
+  // Check to see if files embedded in WYSIWYG should be fully rendered. If so,
+  // replace the simpler Media placeholder with a fully rendered file entity.
+  if (!empty($settings['wysiwyg']) &&
+      _media_ckeditor_fully_rendered_files_in_wysiwyg()) {
+    $file = $tag_info['file'];
+    $file->override['wysiwyg'] = TRUE;
+    $view_mode = $tag_info['view_mode'];
+    $fields = (!empty($settings['fields'])) ? $settings['fields'] : array();
+    $element = media_ckeditor_render_file_with_overrides($file, $view_mode, $fields);
+  }
+}
+
+/**
+ * Helper function to get a fully rendered file entity with optional overrides.
+ */
+function media_ckeditor_render_file_with_overrides($file, $view_mode, $fields = array()) {
+
+  foreach ($fields as $field_name => $value) {
+    if (isset($file->{$field_name})) {
+      $file->{$field_name} = $value;
+    }
+  }
+
+  $file_array = array($file->fid => $file);
+  $build = file_entity_metadata_view_file($file_array, $view_mode);
+
+  // Manually remove contextual links.
+  if (!empty($build['file'][$file->fid]['#contextual_links'])) {
+    unset($build['file'][$file->fid]['#contextual_links']);
+  }
+
+  return $build;
+}
+
+/**
+ * Implements hook_preprocess_file_entity().
+ */
+function media_ckeditor_preprocess_file_entity(&$vars) {
+
+  // If we are rendering this as a fully rendered file entity in a WYSIWYG,
+  // set $page to TRUE so that the title doesn't display.
+  // @see file_entity/file_entity.tpl.php.
+  if (!empty($vars['override']['wysiwyg']) &&
+      _media_ckeditor_fully_rendered_files_in_wysiwyg()) {
+    $vars['page'] = TRUE;
+  }
+}
diff --git a/drupal7/sites/all/modules/media_ckeditor/tests/media_ckeditor_test.info b/drupal7/sites/all/modules/media_ckeditor/tests/media_ckeditor_test.info
index 1e10cc43..f1528d0d 100644
--- a/drupal7/sites/all/modules/media_ckeditor/tests/media_ckeditor_test.info
+++ b/drupal7/sites/all/modules/media_ckeditor/tests/media_ckeditor_test.info
@@ -4,9 +4,9 @@ package = Media
 core = 7.x
 hidden = FALSE
 
-; Information added by Drupal.org packaging script on 2017-01-15
-version = "7.x-2.0-rc3"
+; Information added by Drupal.org packaging script on 2017-05-24
+version = "7.x-2.1"
 core = "7.x"
 project = "media_ckeditor"
-datestamp = "1484494686"
+datestamp = "1495629657"
 
