Index: ldapauth.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapauth.info,v
retrieving revision 1.3
diff -u -p -r1.3 ldapauth.info
--- ldapauth.info	19 Feb 2009 16:56:16 -0000	1.3
+++ ldapauth.info	5 Feb 2011 05:42:39 -0000
@@ -5,3 +5,9 @@ package = LDAP integration
 core = 6.x
 php = 5.0
 
+
+; Information added by drupal.org packaging script on 2010-10-13
+version = "HEAD"
+project = "ldap_integration"
+datestamp = "1286971903"
+
Index: ldapdata.admin.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapdata.admin.inc,v
retrieving revision 1.9
diff -u -p -r1.9 ldapdata.admin.inc
--- ldapdata.admin.inc	28 Jul 2009 14:03:05 -0000	1.9
+++ ldapdata.admin.inc	5 Feb 2011 05:42:39 -0000
@@ -9,7 +9,7 @@
 //////////////////////////////////////////////////////////////////////////////
 // ldapdata settings
 
- /**
+/**
  * Implements the settings page.
  *
  * @return
@@ -76,17 +76,17 @@ function ldapdata_admin_list() {
   while ($row = db_fetch_object($result)) {
     $rows[] = array(
       'data' => array(
-        $row->name,
-        l(t('edit'), 'admin/settings/ldap/ldapdata/edit/'. $row->sid),
-        l(t('reset'), 'admin/settings/ldap/ldapdata/reset/'. $row->sid),
-      ),
+    $row->name,
+    l(t('edit'), 'admin/settings/ldap/ldapdata/edit/'. $row->sid),
+    l(t('reset'), 'admin/settings/ldap/ldapdata/reset/'. $row->sid),
+    ),
       'class' => $row->status ? 'menu-enabled' : 'menu-disabled',
     );
   }
 
   $header = array(
-    t('Server'),
-    array('data' => t('Operations'), 'colspan' => 2),
+  t('Server'),
+  array('data' => t('Operations'), 'colspan' => 2),
   );
 
   return theme('table', $header, $rows);
@@ -112,14 +112,14 @@ function ldapdata_admin_edit(&$form_stat
     $form['sid'] = array(
       '#type' => 'value',
       '#value' => $sid,
-      );
+    );
     return confirm_form(
-      $form,
-      t('Are you sure you want to reset the fields mapping to defaults ?'),
+    $form,
+    t('Are you sure you want to reset the fields mapping to defaults ?'),
       'admin/settings/ldap/ldapdata',
-      t('<em>This action cannot be undone.</p>'),
-      t('Reset'),
-      t('Cancel')
+    t('<em>This action cannot be undone.</p>'),
+    t('Reset'),
+    t('Cancel')
     );
   }
   elseif ($op == "edit" && $sid) {
@@ -146,13 +146,15 @@ function ldapdata_admin_edit(&$form_stat
       '#title' => t('Drupal user profile field mapping'),
       '#default_value' => isset($ldapdata_mappings['access']) ? $ldapdata_mappings['access'] : LDAPDATA_MAP_ATTRIBUTES,
       '#options' => array(
-        LDAPDATA_MAP_NOTHING => t('No mapping. (Clears any mappings defined below.)'),
-        LDAPDATA_MAP_ATTRIBUTES_READ_ONLY => t('Read only: Drupal user profile fields have LDAP attributes.'),
-        LDAPDATA_MAP_ATTRIBUTES => t('Read/write: Drupal user profile fields have LDAP attributes. LDAP attributes updated upon Drupal profile change.'),
-      ),
+    LDAPDATA_MAP_NOTHING => t('No mapping. (Clears any mappings defined below.)'),
+    LDAPDATA_MAP_ATTRIBUTES_READ_ONLY => t('Read only: Drupal user profile fields have LDAP attributes.'),
+    LDAPDATA_MAP_ATTRIBUTES => t('Read/write: Drupal user profile fields have LDAP attributes. LDAP attributes updated upon Drupal profile change.'),
+    ),
     );
     $profile_fields = _ldapdata_retrieve_profile_fields();
     $standard_fields = _ldapdata_retrieve_standard_user_fields();
+    $content_profile_fields = _ldapdata_retrieve_content_profile_fields();
+
     $drupal_fields = $profile_fields + $standard_fields;
     $form['mapping']['mapping_pre'] = array(
       '#value' => t('<div class="form-item"><label>Specify mappings below if you selected the second or third option. </label><table><thead><tr><th> Drupal field</th><th>LDAP attribute</th></tr></thead><tbody>'),
@@ -170,9 +172,52 @@ function ldapdata_admin_edit(&$form_stat
       );
     }
     $form['mapping']['mapping_post'] = array(
-      '#value' => '</tbody></table></div>',
+      '#value' => '</tr></tbody></table></div>',
     );
 
+    if (module_exists('content_profile')) {
+      // Content profile mapping
+      $form['mapping']['mapping_cp'] = array(
+      '#value' => t('<div class="form-item"><table><thead><tr><th> Content Profile field</th><th>LDAP attribute</th></tr></thead><tbody>'),
+      );
+
+      foreach ($content_profile_fields as $key => $field) {
+        $field_lookup = content_fields($field);
+        $field_tmp = "ldap_amap-". $key;
+        $_prefix = "<tr><td><label for=\"edit[$field_tmp]\">$field</label></td><td>";
+
+        if ($field_lookup['type'] == 'content_taxonomy') {
+
+          $form['mapping'][$field_tmp] = array(
+            '#type' => 'textfield',
+            '#default_value' => isset($ldapdata_mappings[$field_tmp]) ? $ldapdata_mappings[$field_tmp] : NULL,
+            '#size' => '20',
+            '#prefix' => $_prefix,
+          );
+          $form['mapping'][$field_tmp . '_add_new_terms'] = array(
+            '#type' => 'checkbox',
+            '#default_value' => isset($ldapdata_mappings[$field_tmp . '_add_new_terms']) ? $ldapdata_mappings[$field_tmp . '_add_new_terms'] : NULL,
+            '#size' => '20',
+            '#title' => t("Add new terms to vocabulary."),
+          );
+        }
+        else{
+          $form['mapping'][$field_tmp] = array(
+        '#type' => 'textfield',
+        '#default_value' => isset($ldapdata_mappings[$field_tmp]) ? $ldapdata_mappings[$field_tmp] : NULL,
+        '#size' => '20',
+        '#prefix' => $_prefix,
+          );
+        }
+        $form['mapping'][$field_tmp . '_post'] = array(
+        '#value' => '</td>',
+        );
+      }
+      $form['mapping']['mapping_cp_post'] = array(
+      '#value' => '</tr></tbody></table></div>',
+      );
+    }
+
     // Attribute access control.
     $form["attributes"] = array(
       '#type' => 'fieldset',
@@ -184,7 +229,7 @@ function ldapdata_admin_edit(&$form_stat
     );
     $attributes = '';
     foreach ($ldapdata_attrs as $attr => $data)
-      $attributes .= $attr .'|'. implode('|', $data) ."\n";
+    $attributes .= $attr .'|'. implode('|', $data) ."\n";
     $form['attributes']['ldapdata_attrs'] = array(
       '#type' => 'textarea',
       '#title' => t('Attributes'),
@@ -202,9 +247,9 @@ function ldapdata_admin_edit(&$form_stat
       $rwoptions[$attr]  = '';
 
       if (in_array($attr, $ldapdata_roattrs))
-        $roattrs[] = $attr;
+      $roattrs[] = $attr;
       if (in_array($attr, $ldapdata_rwattrs))
-        $rwattrs[] = $attr;
+      $rwattrs[] = $attr;
 
       $form['attributes']['table'][$attr] = array(
         '#value' => $attr_name,
@@ -223,10 +268,10 @@ function ldapdata_admin_edit(&$form_stat
     $form['attributes']['header'] = array(
       '#type' => 'value',
       '#value' => array(
-        array('data' => t('Attribute name')),
-        array('data' => t('Readable by user?')),
-        array('data' => t('Editable by user?')),
-      )
+    array('data' => t('Attribute name')),
+    array('data' => t('Readable by user?')),
+    array('data' => t('Editable by user?')),
+    )
     );
     $form['attributes']['ldapdata_filter_php'] = array(
       '#type' => 'textarea',
@@ -308,19 +353,21 @@ function ldapdata_admin_edit_validate($f
       $ldapdata_attrs = TRUE;
       foreach ((trim($values['attributes']['ldapdata_attrs']) ? explode("\n", trim($values['attributes']['ldapdata_attrs'])) : array()) as $line) {
         if (count($data = explode('|', trim($line))) == 6)
-          $form_state['ldapdata_attrs'] += array(trim(array_shift($data)) => $data);
+        $form_state['ldapdata_attrs'] += array(trim(array_shift($data)) => $data);
         else
-          $ldapdata_attrs = FALSE;
+        $ldapdata_attrs = FALSE;
       }
       if (!$ldapdata_attrs)
-        form_set_error('attributes][ldapdata_attrs', t('Bad attribute syntax.'));
+      form_set_error('attributes][ldapdata_attrs', t('Bad attribute syntax.'));
 
       $form_state['ldapdata_mappings'] = array();
       $form_state['ldapdata_mappings']['access'] = $values['ldapdata_mapping'];
       if ($form_state['ldapdata_mappings']['access'] >= 4) {
         foreach (element_children($values) as $attr) {
-          if (preg_match("/ldap_amap/", $attr) && $values[$attr])
+          if (preg_match("/ldap_amap/", $attr) && $values[$attr]) {
+            //TODO check for create_tags_if_new checkbox
             $form_state['ldapdata_mappings'][$attr] = $values[$attr];
+          }
         }
       }
       $form_state['ldapdata_mappings'] = !empty($form_state['ldapdata_mappings']) ? serialize($form_state['ldapdata_mappings']) : '';
Index: ldapdata.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapdata.info,v
retrieving revision 1.3
diff -u -p -r1.3 ldapdata.info
--- ldapdata.info	19 Feb 2009 16:56:16 -0000	1.3
+++ ldapdata.info	5 Feb 2011 05:42:39 -0000
@@ -5,3 +5,9 @@ package = LDAP integration
 dependencies[] = ldapauth
 core = 6.x
 
+
+; Information added by drupal.org packaging script on 2010-10-13
+version = "HEAD"
+project = "ldap_integration"
+datestamp = "1286971903"
+
Index: ldapdata.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapdata.module,v
retrieving revision 1.31
diff -u -p -r1.31 ldapdata.module
--- ldapdata.module	27 Oct 2009 14:29:17 -0000	1.31
+++ ldapdata.module	5 Feb 2011 05:42:40 -0000
@@ -37,12 +37,12 @@ function ldapdata_theme() {
     'ldapdata_admin_edit' => array(
       'arguments' => array('form' => NULL),
       'file' => 'ldapdata.theme.inc'
-    ),
+      ),
     'ldapdata_ldap_attribute' => array(
       'arguments' => array('value' => NULL, 'type' => NULL),
       'file' => 'ldapdata.theme.inc'
-    ),
-  );
+      ),
+      );
 }
 
 /**
@@ -57,7 +57,7 @@ function ldapdata_menu() {
       'page arguments' => array('ldapdata_admin_settings'),
       'access arguments' => array('administer ldap modules'),
       'file' => 'ldapdata.admin.inc',
-    ),
+  ),
     'admin/settings/ldap/ldapdata/edit' => array(
       'title' => 'Data',
       'page callback' => 'drupal_get_form',
@@ -65,7 +65,7 @@ function ldapdata_menu() {
       'type' => MENU_CALLBACK,
       'access arguments' => array('administer ldap modules'),
       'file' => 'ldapdata.admin.inc',
-    ),
+  ),
     'admin/settings/ldap/ldapdata/edit/%/test' => array(
       'title' => 'Test LDAP Server',
       'page callback' => '_ldapdata_ajax_test',
@@ -73,7 +73,7 @@ function ldapdata_menu() {
       'type' => MENU_CALLBACK,
       'access arguments' => array('administer ldap modules'),
       'file' => 'ldapdata.admin.inc',
-    ),
+  ),
     'admin/settings/ldap/ldapdata/reset' => array(
       'title' => 'Data',
       'page callback' => 'drupal_get_form',
@@ -81,7 +81,7 @@ function ldapdata_menu() {
       'type' => MENU_CALLBACK,
       'access arguments' => array('administer ldap modules'),
       'file' => 'ldapdata.admin.inc',
-    ),
+  ),
   );
 }
 
@@ -116,13 +116,13 @@ function ldapdata_user($op, &$edit, &$ac
  */
 function _ldapdata_user_categories() {
   return array(
-    array(
+  array(
       'name' => LDAPDATA_USER_DATA,
       'title' => t(LDAPDATA_USER_TAB),
       'weight' => 50,
       'access callback' => 'ldapdata_category_access',
       'access arguments' => array(1)
-    )
+  )
   );
 }
 
@@ -133,10 +133,10 @@ function ldapdata_category_access($accou
   global $user;
 
   if (!($user->uid > 0 && $user->uid == $account->uid || user_access('administer users')))
-    return FALSE;
+  return FALSE;
 
   if (!isset($account->ldap_authentified))
-    return FALSE;
+  return FALSE;
 
   return (_ldapdata_ldap_info($account, 'mapping_type') == LDAPDATA_MAP_ATTRIBUTES && count(_ldapdata_ldap_info($account, 'ldapdata_rwattrs')) > 0) ? TRUE : FALSE;
 }
@@ -154,7 +154,7 @@ function _ldapdata_user_form(&$user, $ca
   $attributes = _ldapdata_ldap_info($user, 'ldapdata_rwattrs');
 
   if (!isset($user->ldap_dn) || $category != LDAPDATA_USER_DATA || _ldapdata_ldap_info($user, 'mapping_type') != LDAPDATA_MAP_ATTRIBUTES || !$attributes)
-    return;
+  return;
 
   $bind_info = _ldapdata_edition($user);
   if (!$_ldapdata_ldap->connect($bind_info['dn'], $bind_info['pass'])) {
@@ -162,7 +162,7 @@ function _ldapdata_user_form(&$user, $ca
     return;
   }
 
-  $entry = $_ldapdata_ldap->retrieveAttributes($user->ldap_dn);
+  $entry = $_ldapdata_ldap->retrieveAttributes($user->ldap_dn, array_values(_ldapdata_reverse_mappings($account->ldap_config)));
 
   $form['ldap_attributes'] = array(
     '#title' => t(LDAPDATA_PROFILE),
@@ -185,15 +185,16 @@ function _ldapdata_user_form(&$user, $ca
 /**
  * Implements hook_user() load operation.
  */
-function _ldapdata_user_load(&$account, $sync = FALSE) {
+function _ldapdata_user_load(&$account, $sync = FALSE, $existing_entries = NULL) {
   global $user, $_ldapdata_ldap;
 
   // Setup the global $_ldapdata_ldap object.
   if (!_ldapdata_init($account))
-    return;
+  return;
 
+  //TODO is this condition correct?
   if (!$sync && (LDAPDATA_SYNC < 1 || LDAPDATA_SYNC < 2 && $user->uid != $account->uid))
-    return;
+  return;
 
   static $accounts_synced = array();
   if (isset($accounts_synced[$account->uid])) {
@@ -208,42 +209,129 @@ function _ldapdata_user_load(&$account, 
   }
 
   $accounts_synced[$account->uid] = TRUE;
-  $bind_info = _ldapdata_edition($account);
-  if (!$_ldapdata_ldap->connect($bind_info['dn'], $bind_info['pass'])) {
-    watchdog('ldapdata', "User load: user %name's data could not be read in the LDAP directory", array('%name' => $account->name), WATCHDOG_WARNING);
-    return;
+
+  // If the LDAP user was already passed in, don't look up again
+  if (array_key_exists($account->name, $existing_entries)) {
+    $entry = $existing_entries[$account->name]['attribs'];
   }
+  else {
+    $bind_info = _ldapdata_edition($account);
+    if (!$_ldapdata_ldap->connect($bind_info['dn'], $bind_info['pass'])) {
+      watchdog('ldapdata', "User load: user %name's data could not be read in the LDAP directory", array('%name' => $account->name), WATCHDOG_WARNING);
+      return;
+    }
+    $entry = $_ldapdata_ldap->retrieveAttributes($account->ldap_dn, array_values(_ldapdata_reverse_mappings($account->ldap_config)));
+  }
+
+  if (isset($entry)) {
+    $ldapsync_settings = variable_get('ldapsync_settings', '');
+    $settings = $ldapsync_settings[$_ldapdata_ldap->getOption('sid')];
 
-  if ($entry = $_ldapdata_ldap->retrieveAttributes($account->ldap_dn)) {
     $ldap_drupal_reverse_mappings = _ldapdata_reverse_mappings($account->ldap_config);
 
     // Retrieve profile fields list.
-    $profile_fields = _ldapdata_retrieve_profile_fields();
-
     $drupal_fields = array();
-    foreach (_ldapdata_reverse_mappings($account->ldap_config) as $drupal_field => $ldap_attr) {
+    $content_profile_nodes = array();
+    $content_profile_fields = _ldapdata_retrieve_content_profile_fields();
+    foreach ($ldap_drupal_reverse_mappings as $drupal_field => $ldap_attr) {
       $value = isset($entry[strtolower($ldap_attr)]) ? $entry[strtolower($ldap_attr)][0] : '';
 
       // Is it a profile field?
+      //TODO same fix for profile fields - should not update field by field
       if (is_numeric($drupal_field)) {
-        if ($profile_field = isset($profile_fields[$drupal_field]) ? $profile_fields[$drupal_field] : NULL) {
-          if ($row = db_fetch_array(db_query("SELECT value FROM {profile_values} WHERE fid = '%d' AND uid = '%d'", $drupal_field, $account->uid))) {
-            if ($row['value'] != $value)
+        if (module_exists('profile') && $settings['ldapsync_settings_sync_profile_']) {
+          $profile_fields = _ldapdata_retrieve_profile_fields();
+          if ($profile_field = isset($profile_fields[$drupal_field]) ? $profile_fields[$drupal_field] : NULL) {
+            if ($row = db_fetch_array(db_query("SELECT value FROM {profile_values} WHERE fid = '%d' AND uid = '%d'", $drupal_field, $account->uid))) {
+              if ($row['value'] != $value) //TODO can this comparison go in the query?
               db_query("UPDATE {profile_values} SET value = '%s' WHERE fid = '%d' AND uid = '%d'", $value, $drupal_field, $account->uid);
+            }
+            else {
+              db_query("INSERT INTO {profile_values} (value, fid, uid) VALUES ('%s', '%d', '%d')", $value, $drupal_field, $account->uid);
+            }
+            $account->$drupal_field = $value;
           }
-          else {
-            db_query("INSERT INTO {profile_values} (value, fid, uid) VALUES ('%s', '%d', '%d')", $value, $drupal_field, $account->uid);
+        }
+      }
+      // Is it a content profile field?
+      elseif (strpos($drupal_field, 'field_') === 0) {
+        if (module_exists('content_profile') && $settings['ldapsync_settings_sync_content_profile_']) {
+          if ($content_profile_field = isset($content_profile_fields[$drupal_field]) ? $content_profile_fields[$drupal_field] : NULL) {
+            $cp_types = content_profile_get_types('types');
+            //TODO ensure this works when multiple profile content types are enabled
+            foreach ($cp_types as $type_obj) {
+              $type = $type_obj->type;
+              $modified = FALSE;
+              $profile = !empty($content_profile_nodes[$type]) ? $content_profile_nodes[$type] :
+                content_profile_load($type, $account->uid, '', TRUE);
+              if (!$profile) {
+                $profile = new stdClass();
+                $profile->type = $type;
+                $profile->title = (isset($account->name) ? $account->name : '');
+                $profile->uid = $account->uid;
+                $modified = TRUE;
+              }
+
+              // Determine what kind of field we are dealing with
+              $field_lookup = content_fields($drupal_field);
+              $field_type = $field_lookup['type'];
+              switch ($field_type) {
+                case 'content_taxonomy':
+                  $value = trim($value);
+                  if ($value == '') continue;
+                  // Check to see if there are any terms that match
+                  $term = taxonomy_get_term_by_name($value);
+                  // If so, check to make sure they match the vocabulary
+                  $term_exists = !empty($term) && $term[0]->vid == $field_lookup['vid'];
+                  if ($term_exists && $profile->{$drupal_field}[0]['value'] != $term[0]->tid) {
+                    $profile->{$drupal_field}[0]['value'] = $term[0]->tid;
+                    
+                    // $profile->taxonomy = array();
+                    // $profile->taxonomy[$field_lookup['vid']] = array($term[0]);
+                    // taxonomy_node_save($profile, array($term[0]));
+                    
+                    $modified = TRUE;
+                  }
+                  $ldapdata_mappings = _ldapdata_ldap_info($account, 'ldapdata_mappings');
+                  $add_new_terms = $ldapdata_mappings['ldap_amap-' . $drupal_field . '_add_new_terms'];
+                  if (!$term_exists && $add_new_terms) {
+                    $newtid = _ldapdata_add_taxonomy_term($value, $field_lookup['vid']);
+                    $profile->{$drupal_field}[0]['value'] = $newtid;
+                    // $profile->taxonomy = array();
+                    // $profile->taxonomy[$field_lookup['vid']] = array($newtid);
+                    $modified = TRUE;
+                  }
+                  break;
+                default:
+                  if ($profile->{$drupal_field}[0]['value'] != $value) {
+                    $profile->{$drupal_field}[0]['value'] = $value;
+                    $modified = TRUE;
+                  }
+              }
+              if ($modified) {
+                $content_profile_nodes[$type] = $profile;
+              }
+            }//end loop over profile content types
           }
-          $account->$drupal_field = $value;
+
         }
       }
       // Then it might be a Drupal field.
-      else if (isset($account->$drupal_field) && !in_array($drupal_field, array('pass'))) {
-        $drupal_fields = array_merge($drupal_fields, array($drupal_field => $value));
+      elseif (isset($account->$drupal_field) && !in_array($drupal_field, array('pass'))) {
+        if ($account->$drupal_field != $value) {
+          $drupal_fields = array_merge($drupal_fields, array($drupal_field => $value));
+        }
       }
     }
-    if (!empty($drupal_fields))
+    if (!empty($drupal_fields) && $settings['ldapsync_settings_sync_user_']) {
       $account = user_save($account, $drupal_fields);
+    }
+    foreach ($content_profile_nodes as $modified) {
+      watchdog('ldapdata', "Saving content profile node: %title [%nid]", array('%title' => $modified->title, '%nid' => $modified->nid), WATCHDOG_NOTICE);
+      node_save($modified);
+    }
+    unset($content_profile_nodes, $content_profile_fields, $drupal_fields, $account,
+    $existing_entries, $entry, $profile, $ldap_drupal_reverse_mappings);
   }
   $_ldapdata_ldap->disconnect();
 }
@@ -256,7 +344,7 @@ function _ldapdata_user_login(&$user) {
 
   // Force LDAP sync.
   if (LDAPDATA_SYNC == 0)
-    _ldapdata_user_load($user, TRUE);
+  _ldapdata_user_load($user, TRUE);
 }
 
 /**
@@ -267,11 +355,11 @@ function _ldapdata_user_submit(&$edit, &
 
   // Setup the global $_ldapdata_ldap object.
   if (!_ldapdata_init($user))
-    return;
+  return;
 
   $authmap = user_get_authmaps($user->name);
   if (!isset($authmap['ldapauth']))
-    return;
+  return;
 
   // Three cases here:
   //   1. User logged on and editing his LDAP entry attributes ($category == LDAPDATA_USER_DATA).
@@ -286,7 +374,7 @@ function _ldapdata_user_submit(&$edit, &
     // Case 1:
     $writeout = array_merge($writeout, _ldapdata_user_update_ldap_attributes($edit, $user));
   }
-  else if ($category == 'account') {
+  elseif ($category == 'account') {
     // Cases 2 && 3:
     $writeout = array_merge($writeout, _ldapdata_user_update_drupal_account($edit, $user));
   }
@@ -314,11 +402,11 @@ function _ldapdata_user_view(&$user) {
 
   // Setup the global $_ldapdata_ldap object.
   if (!_ldapdata_init($user))
-    return;
+  return;
 
   $authmap = user_get_authmaps($user->name);
   if (!isset($authmap['ldapauth']))
-    return;
+  return;
 
   $bind_info = _ldapdata_edition($user);
   if (!$_ldapdata_ldap->connect($bind_info['dn'], $bind_info['pass'])) {
@@ -326,7 +414,7 @@ function _ldapdata_user_view(&$user) {
     return;
   }
 
-  $entry = $_ldapdata_ldap->retrieveAttributes($user->ldap_dn);
+  $entry = $_ldapdata_ldap->retrieveAttributes($user->ldap_dn, array_values(_ldapdata_reverse_mappings($account->ldap_config)));
   $allowed_attrs = _ldapdata_ldap_info($user, 'ldapdata_roattrs');
   $items = array();
   $i = 0;
@@ -372,8 +460,8 @@ function _ldapdata_user_update_ldap_attr
   foreach ($edit as $edit_attr => $value) {
     // Preventing a POST data injection: we check allowance to write value.
     if (($ldap_attr = preg_replace('/^ldap_(.*)$/', '$1', $edit_attr)) && in_array($ldap_attr, $editables))
-      $writeout[$ldap_attr] = $value;
-      unset($edit[$edit_attr]);
+    $writeout[$ldap_attr] = $value;
+    unset($edit[$edit_attr]);
   }
 
   return $writeout;
@@ -427,7 +515,7 @@ function _ldapdata_user_update_drupal_ac
  */
 function _ldapdata_user_update_profile(&$edit, &$user) {
   if (_ldapdata_ldap_info($user, 'mapping_type') != LDAPDATA_MAP_ATTRIBUTES)
-    return array();
+  return array();
 
   $ldap_drupal_reverse_mappings = _ldapdata_reverse_mappings($user->ldap_config);
 
@@ -501,6 +589,32 @@ function _ldapdata_retrieve_profile_fiel
 }
 
 /**
+ * Retrieve content profile fields.
+ *
+ * @return
+ *   An array of the form element.
+ */
+function _ldapdata_retrieve_content_profile_fields() {
+  $fields = array();
+  if (module_exists('content_profile')) {
+    $cp_types = content_profile_get_types('types');
+    foreach ($cp_types as $type_obj) {
+      $type = $type_obj->type;
+      if ($all_fields = content_fields(NULL, $type)) {
+        foreach ($all_fields as $field_name => $field_attributes) {
+          if ($field_attributes['type_name'] == $type) {
+            //TODO do these need to be mapped by type, eg: $fields[$type][$field_name]?
+            $fields[$field_name] = $field_name;
+          }
+        }
+      }
+    }
+
+  }
+  return $fields;
+}
+
+/**
  * Retrieve drupal user fields which can be synced with LDAP.
  *
  * @return
@@ -538,7 +652,7 @@ function _ldapdata_reverse_mappings($sid
   $map = array();
   foreach (_ldapdata_ldap_info($sid, 'ldapdata_mappings') as $key => $value) {
     if (($drupal_key = preg_replace('/^ldap_amap-(.*)$/', '$1', $key)) && !in_array($drupal_key, array('access', 'status')))
-      $map[$drupal_key] = $value;
+    $map[$drupal_key] = $value;
   }
   return $map;
 }
@@ -554,7 +668,7 @@ function _ldapdata_reverse_mappings($sid
  */
 function _ldapdata_edition($sid) {
   if (!($sid = is_object($sid) ? (isset($sid->ldap_config) ? $sid->ldap_config : NULL) : $sid))
-    return;
+  return;
 
   $row = db_fetch_object(db_query("SELECT ldapdata_binddn, ldapdata_bindpw FROM {ldapauth} WHERE sid = %d", $sid));
 
@@ -577,7 +691,7 @@ function _ldapdata_edition($sid) {
  */
 function _ldapdata_attribute_filter($sid, $attributes) {
   if ($code = _ldapdata_ldap_info($sid, 'ldapdata_filter_php'))
-    $attributes = eval($code);
+  $attributes = eval($code);
 
   return $attributes;
 }
@@ -594,11 +708,11 @@ function _ldapdata_init($sid) {
   global $_ldapdata_ldap;
 
   if (!($sid = is_object($sid) ? (isset($sid->ldap_config) ? $sid->ldap_config : NULL) : $sid))
-    return;
+  return;
 
   static $servers = array();
   if (!isset($servers[$sid]))
-    $servers[$sid] = db_fetch_object(db_query("SELECT * FROM {ldapauth} WHERE status = 1 AND sid = %d", $sid));
+  $servers[$sid] = db_fetch_object(db_query("SELECT * FROM {ldapauth} WHERE status = 1 AND sid = %d", $sid));
 
   if ($servers[$sid]) {
     // Other modules can invoke user load from hook_init() before ldapdata.
@@ -632,11 +746,11 @@ function _ldapdata_init($sid) {
  */
 function _ldapdata_ldap_info($sid, $req) {
   if (!($sid = is_object($sid) ? (isset($sid->ldap_config) ? $sid->ldap_config : NULL) : $sid))
-    return;
+  return;
 
   static $servers = array();
   if (!isset($servers[$sid]))
-    $servers[$sid] = db_fetch_object(db_query("SELECT * FROM {ldapauth} WHERE sid = %d", $sid));
+  $servers[$sid] = db_fetch_object(db_query("SELECT * FROM {ldapauth} WHERE sid = %d", $sid));
 
   switch ($req) {
     case 'mapping_type':
@@ -659,3 +773,16 @@ function _ldapdata_ldap_info($sid, $req)
   }
 }
 
+/**
+ * Adds a new taxonomy term
+ */
+function _ldapdata_add_taxonomy_term($name, $vid, $description = '', $weight = 0) {
+  $form_values = array();
+  $form_values['name'] = $name;
+  $form_values['description'] = $description;
+  $form_values['vid'] = $vid;
+  $form_values['weight'] = $weight;
+  taxonomy_save_term($form_values);
+
+  return $form_values['tid'];
+}
Index: ldapgroups.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapgroups.inc,v
retrieving revision 1.2
diff -u -p -r1.2 ldapgroups.inc
--- ldapgroups.inc	25 Aug 2009 13:53:20 -0000	1.2
+++ ldapgroups.inc	5 Feb 2011 05:42:40 -0000
@@ -234,7 +234,7 @@ function _ldapgroups_mapping($user, $gro
   $ldapgroups_mappings = _ldapgroups_ldap_info($user, 'ldapgroups_mappings');
   if (isset($ldapgroups_mappings[$group]))
     return $ldapgroups_mappings[$group];
-  else if (preg_match('/^[^=]+=([^,]+),.*$/', $group, $matches))
+  elseif (preg_match('/^[^=]+=([^,]+),.*$/', $group, $matches))
     return $matches[1];
   else
     return $group;
Index: ldapgroups.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapgroups.info,v
retrieving revision 1.4
diff -u -p -r1.4 ldapgroups.info
--- ldapgroups.info	19 Feb 2009 16:56:16 -0000	1.4
+++ ldapgroups.info	5 Feb 2011 05:42:40 -0000
@@ -5,3 +5,9 @@ package = LDAP integration
 dependencies[] = ldapauth
 core = 6.x
 
+
+; Information added by drupal.org packaging script on 2010-10-13
+version = "HEAD"
+project = "ldap_integration"
+datestamp = "1286971903"
+
Index: ldapsync.admin.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapsync.admin.inc,v
retrieving revision 1.1
diff -u -p -r1.1 ldapsync.admin.inc
--- ldapsync.admin.inc	25 Mar 2010 11:00:16 -0000	1.1
+++ ldapsync.admin.inc	5 Feb 2011 05:42:40 -0000
@@ -17,44 +17,145 @@
  */
 function ldapsync_admin_settings() {
 
-  $form['options'] = array(
+  $profile_module_exists = module_exists('profile');
+  $content_profile_module_exists = module_exists('content_profile');
+  $ldapgroups_module_exist = module_exists('ldapgroups');
+  $ldapsync_settings = variable_get('ldapsync_settings', '');
+
+  $form['servers'] = array(
     '#type' => 'fieldset',
-    '#title' => t('LDAPsync settings'),
+    '#title' => t('Server synchronization settings'),
     '#collapsible' => TRUE,
     '#collapsed' => FALSE,
   );
-  $form['options']['ldapsync_filter'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Filter'),
-    '#default_value' => variable_get('ldapsync_filter', ''),
-    '#size' => 100,
-    '#maxlength' => 255,
-    '#description' => t('This will filter the LDAP query. See <a href="http://www.php.net/manual/en/function.ldap-search.php">PHP Help</a> for filter syntax. <br/ >example: (objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=nwindenv,DC=com)'),
-    '#required' => FALSE,
+
+  $form['servers']['table_pre'] = array(
+    '#value' => t('<table><thead><tr>
+      <th>LDAP server</th>
+      <th>Sync users</th>
+      ' . ((module_exists('profile')) ? '<th>Sync profile</th>' : '') . '
+      ' . ((module_exists('content_profile')) ? '<th>Sync content profile</th>' : '') . '
+      ' . ((module_exists('ldapgroups')) ? '<th>Sync groups</th>' : '') . '
+      <th>Sync blocked status</th>
+      <th>User filter</th>
+      <th>Blocked user filter</th>
+      </tr></thead><tbody>'),
+  );
+
+
+  $result = db_query("SELECT sid, name, status FROM {ldapauth} ORDER BY sid");
+  while ($row = db_fetch_object($result)) {
+    $sid = $row->sid;
+    $name = $row->name;
+    $active = $row->status;
+    $settings = $ldapsync_settings[$sid];
+
+    $form['servers'][$sid]['ldapsync_settings_sid_' . $sid] = array(
+      '#type' => 'hidden',
+      '#default_value' => $sid,
+    );
+
+    $form['servers'][$sid]['ldapsync_settings_sync_user_' . $sid] = array(
+      '#type' => 'checkbox',
+      '#disabled' => FALSE,
+      '#default_value' => $settings['ldapsync_settings_sync_user_'],
+      '#prefix' => '<tr><td>' . ($active ? $name : '<em>' . $name . '</em>') . '</td><td>',
+      '#suffix' => '</td>',
+    );
+
+    if (module_exists('profile')) {
+      $form['servers'][$sid]['ldapsync_settings_sync_profile_' . $sid] = array(
+      '#type' => 'checkbox',
+      '#disabled' => !$profile_module_exists,
+      '#default_value' => $settings['ldapsync_settings_sync_profile_'],
+      '#prefix' => '<td>',
+      '#suffix' => '</td>',
+      );
+    }
+
+    if (module_exists('content_profile')) {
+      $form['servers'][$sid]['ldapsync_settings_sync_content_profile_' . $sid] = array(
+      '#type' => 'checkbox',
+      '#disabled' => !$content_profile_module_exists,
+      '#default_value' => $settings['ldapsync_settings_sync_content_profile_'],
+      '#prefix' => '<td>',
+      '#suffix' => '</td>',
+      );
+    }
+
+    if (module_exists('ldapgroups')) {
+      $form['servers'][$sid]['ldapsync_settings_sync_groups_' . $sid] = array(
+      '#type' => 'checkbox',
+      '#disabled' => !$ldapgroups_module_exist,
+      '#default_value' => $settings['ldapsync_settings_sync_groups_'],
+      '#prefix' => '<td>',
+      '#suffix' => '</td>',
+      );
+    }
+
+    $form['servers'][$sid]['ldapsync_settings_sync_block_' . $sid] = array(
+      '#type' => 'checkbox',
+      '#disabled' => FALSE,
+      '#default_value' => $settings['ldapsync_settings_sync_block_'],
+      '#prefix' => '<td>',
+      '#suffix' => '</td>',
+    );
+
+    $form['servers'][$sid]['ldapsync_settings_filter_' . $sid] = array(
+      '#type' => 'textfield',
+      '#default_value' => $settings['ldapsync_settings_filter_'],
+      '#size' => 50,
+      '#maxlength' => 255,
+    // '#description' => t('LDAP Filter to find users to synchronize. Example: (mail=*)'),
+      '#required' => FALSE,
+      '#prefix' => '<td>',
+      '#suffix' => '</td>',
+    );
+
+    $form['servers'][$sid]['ldapsync_settings_blocked_' . $sid] = array(
+      '#type' => 'textfield',
+      '#default_value' => $settings['ldapsync_settings_blocked_'],
+      '#size' => 50,
+      '#maxlength' => 255,
+    // '#description' => t('LDAP filter to find blocked users. Active directory example: (lockoutTime>=1)'),
+      '#required' => FALSE,
+      '#prefix' => '<td>',
+      '#suffix' => '</td></tr>',
+    );
+
+  }
+  $form['servers']['table_post'] = array(
+      '#value' => '</tbody></table></div>',
+  );
+
+  $form['cron'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Cron settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
   );
-  
   $options_time_interval = array(
-    0 => t('As often as possible'),
-    1*3600 => t('1 hour'),
-    6*3600 => t('6 hours'),
-    12*3600 => t('12 hours'),
-    24*3600 => t('24 hours'),
-    24*7*3600 => t('1 week'),
-    -1 => t('never (only sync manually)')
+  0 => t('As often as possible'),
+  1*3600 => t('1 hour'),
+  6*3600 => t('6 hours'),
+  12*3600 => t('12 hours'),
+  24*3600 => t('24 hours'),
+  24*7*3600 => t('1 week'),
+  -1 => t('never (only sync manually)')
   );
-  $form['options']['ldapsync_time_interval'] = array(
+  $form['cron']['ldapsync_time_interval'] = array(
     '#type' => 'select',
     '#title' => t('Sync time interval'),
     '#description' => t('The number of hours between each sync. A larger setting reduces server load for large LDAP directories.<br />You must have enabled cron, and ldapsync will not run more often than cron.'),
     '#default_value' => variable_get('ldapsync_time_interval', -1),
     '#options' => $options_time_interval,
   );
-  $form['options']['ldapsync_missing_users_action'] = array(
-    '#type' => 'select',
-    '#title' => t('Missing users action'),
-    '#description' => t("What to do when LDAP-authentified Drupal users don't exist or are disabled in LDAP. Choose block to disable the user accounts in Drupal. Choose warn to only log a warning to the Drupal log."),
-    '#default_value' => variable_get('ldapsync_missing_users_action', 'warn'),
-    '#options' => array(t('warn') => t('warn'), t('block') => t('block')),
+
+  $form['submit'] = array(
+    '#type'  => 'submit',
+    '#value' => t('Save settings'),
+    '#prefix' => '<div class="buttons">',
+    '#suffix' => '</div>',
   );
 
   $form['manual'] = array(
@@ -68,10 +169,10 @@ function ldapsync_admin_settings() {
     '#value' => t('Sync now'),
     '#submit' => array('ldapsync_admin_settings_sync_now'),
   );
-
-  $form['submit'] = array(
+  $form['manual']['reportonly'] = array(
     '#type'  => 'submit',
-    '#value' => t('Save settings'),
+    '#value' => t('Report only'),
+    '#submit' => array('ldapsync_admin_settings_sync_now'),
   );
 
   return $form;
@@ -81,6 +182,48 @@ function ldapsync_admin_settings() {
  * Validate hook for the settings form.
  */
 function ldapsync_admin_settings_validate($form, &$form_state) {
+  $op = $form_state['clicked_button']['#value'];
+  $values = $form_state['values'];
+
+  $settings = array();
+  // Get the sids
+  foreach (element_children($values) as $attr) {
+    if (preg_match("/ldapsync_settings_sid_/", $attr) && $values[$attr]) {
+      $sid = $values[$attr];
+      $settings[$sid] = array();
+    }
+  }
+
+  // Set the values
+  foreach ($settings as $sid => $server_settings) {
+    foreach (element_children($values) as $attr) {
+      if (preg_match("/ldapsync_settings_sync_user_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_sync_user_'] = $values[$attr];
+      }
+      elseif (preg_match("/ldapsync_settings_sync_groups_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_sync_groups_'] = $values[$attr];
+      }
+      elseif (preg_match("/ldapsync_settings_sync_profile_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_sync_profile_'] = $values[$attr];
+      }
+      elseif (preg_match("/ldapsync_settings_sync_content_profile_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_sync_content_profile_'] = $values[$attr];
+      }
+      elseif (preg_match("/ldapsync_settings_sync_block_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_sync_block_'] = $values[$attr];
+      }
+      elseif (preg_match("/ldapsync_settings_filter_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_filter_'] = $values[$attr];
+      }
+      elseif (preg_match("/ldapsync_settings_blocked_" . $sid . "/", $attr)) {
+        $server_settings['ldapsync_settings_blocked_'] = $values[$attr];
+      }
+    }
+    $settings[$sid] = $server_settings;
+  }
+
+  $form_state['ldapsync_settings'] = $settings;
+
 }
 
 /**
@@ -89,16 +232,20 @@ function ldapsync_admin_settings_validat
 function ldapsync_admin_settings_submit($form, &$form_state) {
   $values = $form_state['values'];
   variable_set('ldapsync_time_interval', $values['ldapsync_time_interval']);
-  variable_set('ldapsync_filter', $values['ldapsync_filter']);
-  variable_set('ldapsync_missing_users_action', $values['ldapsync_missing_users_action']);
+  variable_set('ldapsync_settings', $form_state['ldapsync_settings']);
+
   drupal_set_message(t('Settings saved'));
 }
 
 /**
  * Syncs accounts.
  */
-function ldapsync_admin_settings_sync_now() {
-  $message = _ldapsync_sync();
+function ldapsync_admin_settings_sync_now($form, &$form_state) {
+  $op = $form_state['clicked_button']['#value'];
+  $values = $form_state['values'];
+  $report_only = $op == t('Report only');
+
+  $message = _ldapsync_sync($report_only);
   drupal_set_message(t($message));
-}
 
+}
Index: ldapsync.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapsync.info,v
retrieving revision 1.1
diff -u -p -r1.1 ldapsync.info
--- ldapsync.info	25 Mar 2010 11:00:16 -0000	1.1
+++ ldapsync.info	5 Feb 2011 05:42:40 -0000
@@ -5,3 +5,9 @@ package = LDAP integration
 dependencies[] = ldapauth
 core = 6.x
 
+
+; Information added by drupal.org packaging script on 2010-10-13
+version = "HEAD"
+project = "ldap_integration"
+datestamp = "1286971903"
+
Index: ldapsync.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapsync.install,v
retrieving revision 1.1
diff -u -p -r1.1 ldapsync.install
--- ldapsync.install	25 Mar 2010 11:00:16 -0000	1.1
+++ ldapsync.install	5 Feb 2011 05:42:40 -0000
@@ -18,8 +18,7 @@ function ldapsync_uninstall() {
 
   variable_del('ldapsync_time_interval');
   variable_del('ldapsync_last_sync_time');
-  variable_del('ldapsync_filter');
-  variable_del('ldapsync_missing_users_action');
+  variable_del('ldapsync_settings');
 
   return $ret;
 }
Index: ldapsync.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/ldapsync.module,v
retrieving revision 1.1
diff -u -p -r1.1 ldapsync.module
--- ldapsync.module	25 Mar 2010 11:00:16 -0000	1.1
+++ ldapsync.module	5 Feb 2011 05:42:40 -0000
@@ -46,7 +46,7 @@ function ldapsync_menu() {
       'page arguments' => array('ldapsync_admin_settings'),
       'access arguments' => array('administer ldap modules'),
       'file' => 'ldapsync.admin.inc',
-    ),
+  ),
   );
 }
 
@@ -66,104 +66,126 @@ function ldapsync_cron() {
 /**
  * Main routine.
  */
-function _ldapsync_sync() {
+function _ldapsync_sync($report_only = FALSE) {
   global $_ldapsync_ldap;
-  
+
   // If ldapgroups is enabled, include it for groups-role sync.
   if (module_exists('ldapgroups')) {
     include_once(drupal_get_path('module', 'ldapauth') .'/ldapgroups.inc');
   }
 
+  $ldapsync_settings = variable_get('ldapsync_settings', '');
   // Find all users in specified OU (using base DN and bind information from ldapauth).
+
   $ldap_users = _ldapsync_search();
 
   // Cycle through LDAP users and take appropriate action on the Drupal side.
-  $count_new_users=0;
-  $count_orphaned_users=0;
+  $count_new_users = 0;
+  $count_blocked_users = 0;
+  $uids_to_enable = array();
   foreach ($ldap_users as $name => $data) {
-    // LDAP object must be a named account
-    if (!$name) continue;
+//    var_dump(memory_get_usage());
+    $user_sid = $ldap_users[$name]['sid'];
+    $settings = $ldapsync_settings[$user_sid];
 
-    // check whether user is in an OU mapped in module settings (need to create admin/settings/ldapsync page)
-    $dn = $data['dn'];
+    if (!$name || !$settings['ldapsync_settings_sync_user_']) continue;
 
     // Does user exist in Drupal (find by username)? If not, create it (using process in ldapauth).
     $account = user_load(array('name' => $name));
+    // User does not exist in Drupal
     if (!$account->uid) {
-
-      // User does not exist in Drupal. Let's create it.
-      $pass = user_password(20);  // Generate a random password (Drupal will auth against ldap anyway).
-      $mail = $data['mail'];
-      $init = $mail = key_exists(($_ldapsync_ldap->getOption('mail_attr') ? $_ldapsync_ldap->getOption('mail_attr') : LDAPAUTH_DEFAULT_MAIL_ATTR), $data) ? $data[$_ldapsync_ldap->getOption('mail_attr')] : $name;
-      $userinfo = array(
-        // new row to table "users":
-        'name' => $name,
-        'pass' => $pass,
-        'mail' => $mail,
-        'init' => $init,
-        'status' => 1,
-        'ldap_authentified' => TRUE,
-        'ldap_dn' => $dn,
-        'ldap_config' => $_ldapsync_ldap->getOption('sid'),
-        // new row to table "authmap": module='ldapauth', authname=$name
-        'authname_ldapauth' => $name,
-      );
-
-      // Save user.
-      $account = user_save('', $userinfo);
       $count_new_users++;
-
+      if (!$report_only) {
+        // User does not exist in Drupal. Let's create it.
+        $pass = user_password(20);  // Generate a random password (Drupal will auth against ldap anyway).
+        $mail = $data['mail'];
+        $init = $mail = key_exists(($_ldapsync_ldap->getOption('mail_attr') ? $_ldapsync_ldap->getOption('mail_attr') : LDAPAUTH_DEFAULT_MAIL_ATTR), $data) ? $data[$_ldapsync_ldap->getOption('mail_attr')] : $name;
+        $userinfo = array(
+          // new row to table "users":
+          'name' => $name,
+          'pass' => $pass,
+          'mail' => $mail,
+          'init' => $init,
+          'status' => 1,
+          'ldap_authentified' => TRUE,
+          'ldap_dn' => $data['dn'],
+          'ldap_config' => $_ldapsync_ldap->getOption('sid'),
+          // new row to table "authmap": module='ldapauth', authname=$name
+          'authname_ldapauth' => $name,
+        );
+        // Save user.
+        $account = user_save('', $userinfo);
+      }
     }
     else {
-      // User exists in Drupal -- check a few things, but most users will require no further action.
-
-      // Check authentication method.
+      // User exists in Drupal
       $data = unserialize($account->data);
-      if (!$data['ldap_authentified']) {
+      if (!$data['ldap_authentified']) { //TODO can also check if SIDs don't match
         // User exists as a local Drupal account -- name conflict! -- log and stop processing this user.
-        watchdog('ldapsync', 'Could not create ldap-authentified account for user %name because a local user by that name already exists.', array('%name' => $name));
+        watchdog('ldapsync', 'Could not create ldap-authenticated account for user %name because a local user by that name already exists.', array('%name' => $name));
         continue;
       }
     }
 
     // Update user's groups if ldapgroups is enabled.
-    if (function_exists('ldapgroups_user_login')) {
-      ldapgroups_user_login($account);
+    if (!$report_only) {
+      if (module_exists('ldapgroups') && $settings['ldapsync_settings_sync_groups_']) {
+        ldapgroups_user_login($account);
+      }
+
+      // Update user's data if ldapdata is enabled.
+      if (module_exists('ldapdata')) {
+        _ldapdata_user_load($account, TRUE, $ldap_users);
+      }
     }
-    
+
     // Enable any blocked user who is enabled in LDAP.
-    if (!$account->status) {
-      db_query("UPDATE {users} SET status = %d where uid = %", 1, $account->uid);
-      watchdog('ldapsync', 'Enabled LDAP-authentified user %name because the corresponding LDAP account is enabled.', array('%name' => $row['name']));
+    if ($account->status == 0 && $account->uid && $settings['ldapsync_settings_sync_block_']) {
+      $uids_to_enable[] = $account->uid;
     }
+//    var_dump(memory_get_usage());
   }
 
-  // Do we have any LDAP-authentified Drupal users who don't exist in LDAP?
+  if (count($uids_to_enable) > 0 && !$report_only) {
+    db_query("UPDATE {users} SET status = %d where uid in (%d)", 1, implode(',', $uids_to_enable)); //TODO this is not working, only updates one record
+    watchdog('ldapsync', 'Enabled LDAP-authenticated users %uids because the corresponding LDAP account is enabled.', array('%uids' => implode(',', $uids_to_enable)));
+  }
+
+  // Do we have any LDAP-authenticated Drupal users who don't exist in LDAP?
+  //TODO this is broken as it doesn't take FILTER into account! ie: you can't change user filter
   if ($ldap_users) {
     $result = db_query("SELECT uid, name, data FROM {users} WHERE status = %d", 1);
     while ($row = db_fetch_array($result)) {
       if (!in_array($row['name'], array_keys($ldap_users))) {
         $data = unserialize($row['data']);
-        if ($data['ldap_authentified']) {
-          // Block user if appropriate module setting is set.
-          if (variable_get('ldapsync_missing_users_action', 'warn') == 'block') {
-            // Block user.
+        if ($data['ldap_authentified'] && $ldapsync_settings[$data['ldap_config']]['ldapsync_settings_sync_block_']) {
+          $count_blocked_users++;
+          // Block user
+          if (!$report_only) {
             db_query("UPDATE {users} SET status=0 WHERE uid=%d", $row['uid']);
-            // Log out blocked user.
             $account = user_load(array('uid' => $row['uid']));
-            $array = array();
-            user_module_invoke('logout', $array, $account);
+            $var = array();
+            user_module_invoke('logout', $var, $account);
             // Log this.
-            watchdog('ldapsync', 'Disabled LDAP-authentified user %name because the corresponding LDAP account does not exist or is disabled.', array('%name' => $row['name']));
+            watchdog('ldapsync', 'Disabled LDAP-authenticated user %name because the corresponding LDAP account does not exist or is disabled.', array('%name' => $row['name']));
           }
-          $count_orphaned_users++;
         }
       }
     }
   }
 
   // Send watchdog message with process summary.
-  $summary = t('Completed LDAP sync. New users: %count_new. LDAP-authentified users that do not have an enabled LDAP account: %count_orphaned.', array('%count_new' => $count_new_users, '%count_orphaned' => $count_orphaned_users));
+  $summary = t('Completed LDAP sync%report_only.<ul>
+      <li>LDAP users found: %count_ldap_users</li>
+      <li>Drupal users created: %count_new_users</li>
+      <li>Drupal users blocked: %count_blocked_users</li>
+      <li>Drupal users unblocked: %count_disabled_users</li>
+    </ul>', array(
+      '%report_only' => $report_only ? ' (report only)' : '',
+      '%count_ldap_users' => count($ldap_users),
+      '%count_new_users' => $count_new_users,
+      '%count_blocked_users' => $count_blocked_users,
+      '%count_disabled_users' => count($uids_to_enable)));
   watchdog('ldapsync', $summary);
 
   // Update last sync time variable, so that we don't sync again until the specified time period passes again.
@@ -180,30 +202,23 @@ function _ldapsync_search() {
   global $_ldapsync_ldap;
 
   // Cycle through LDAP configurations.
-  $result = db_query("SELECT sid FROM {ldapauth} WHERE status = %d ORDER BY sid", 1);
+  $result = db_query("SELECT * FROM {ldapauth} WHERE status = %d ORDER BY sid", 1);
+  $ldapsync_settings = variable_get('ldapsync_settings', '');
+  $users=array();
   while ($row = db_fetch_object($result)) {
     // Initialize LDAP.
-    if (!_ldapsync_init($row->sid)) {
+    if (!_ldapsync_init($row)) {
       watchdog('ldapsync', 'ldapsync init failed for ldap server %sid.', array('%sid' => $row->sid));
       continue;
     }
-
-    /*
-    // Data mapping.
-    $server_obj = db_fetch_object(db_query("SELECT ldapdata_mappings FROM {ldapauth} WHERE sid = %d", $row->sid));
-    $ldapdata_mappings = !empty($server_obj->ldapdata_mappings) ? unserialize($server_obj->ldapdata_mappings) : array();
-    if (!empty($ldapdata_mappings) && $ldapdata_mappings['access'] >= 4) {
-      unset($ldapdata_mappings['access'], $ldapdata_mappings['ldap_amap-mail'], $ldapdata_mappings['ldap_amap-pass']);
-      print "<pre>Drupal user fields to be synchronized from the LDAP attributes listed below:\n";
-      print_r($ldapdata_mappings);
-      print '</pre>';
-      # To be continued
+    $settings = $ldapsync_settings[$_ldapsync_ldap->getOption('sid')];
+    if (!$settings['ldapsync_settings_sync_user_']) {
+      continue;
     }
-    */
 
     // If there is no bindn and bindpw - the connect will be an anonymous connect.
     $_ldapsync_ldap->connect($_ldapsync_ldap->getOption('binddn'), $_ldapsync_ldap->getOption('bindpw'));
-    $users=array();
+
     foreach (explode("\r\n", $_ldapsync_ldap->getOption('basedn')) as $base_dn) {
       if (empty($base_dn)) {
         continue;
@@ -214,36 +229,27 @@ function _ldapsync_search() {
 
       // Execute LDAP search.
       $name_attr = $_ldapsync_ldap->getOption('user_attr') ? $_ldapsync_ldap->getOption('user_attr') : LDAPAUTH_DEFAULT_USER_ATTR;
-      $ldapsync_filter = variable_get('ldapsync_filter', 0);
-      $filter = ($ldapsync_filter == "") ? "$name_attr=*" : $ldapsync_filter; // Find all users if no filter set.
+      $mail_attr = drupal_strtolower($_ldapsync_ldap->getOption('mail_attr'));
+
+      // Build filter
+      $filter = '('. ($settings['ldapsync_settings_filter_'] == '' ? $name_attr . '=*' : $settings['ldapsync_settings_filter_']) . ')';
+      // Filter out disabled users if synchronizing blocked Users
+      if ($settings['ldapsync_settings_blocked_'] != '' && $settings['ldapsync_settings_sync_block_']) {
+        $filter = '(&(!(' . $settings['ldapsync_settings_blocked_'] . '))' . $filter . ')';
+      }
 
-      if (!($ldapresult = $_ldapsync_ldap->search($base_dn, $filter))) {
+      $attributes = _ldapsync_get_ldap_attributes($_ldapsync_ldap);
+      if (!($ldapresult = $_ldapsync_ldap->search($base_dn, $filter, $attributes))) {
         continue;
       }
 
-      $user_attr = drupal_strtolower($_ldapsync_ldap->getOption('user_attr')); 
-      $mail_attr = drupal_strtolower($_ldapsync_ldap->getOption('mail_attr')); 
-      
       // Need to set default mail domain for LDAP users without a mail attribute.
       // Cycle through results to build array of user information.
       foreach ($ldapresult as $entry) {
-        $name = drupal_strtolower($entry[$user_attr][0]);
-
-        // Don't include if no name attribute.
-        if (empty($name)) {
-          continue;
+        $name = drupal_strtolower($entry[$name_attr][0]);
+        if (!empty($name)) {
+          $users[$name] = array('sid' => $_ldapsync_ldap->getOption('sid'), 'dn' => $entry['dn'], 'mail' => $entry[$mail_attr][0], 'attribs' => $entry);
         }
-
-        // Don't include if LDAP account is disabled.
-        $status = $entry['useraccountcontrol'][0];
-        if (($status & 2) != 0) {  // This only works for Active Directory -- search includes disabled accounts in other directories.
-          continue;
-        }
-
-        $users[$name] = array(
-          'dn' => $entry['dn'],
-          'mail' => $entry[$mail_attr][0],
-        );
       }
     }
   }
@@ -251,6 +257,21 @@ function _ldapsync_search() {
   return $users;
 }
 
+function _ldapsync_get_ldap_attributes($ldap) {
+  $name_attr = $ldap->getOption('user_attr') ? $ldap->getOption('user_attr') : LDAPAUTH_DEFAULT_USER_ATTR;
+  $mail_attr = drupal_strtolower($ldap->getOption('mail_attr'));
+  $attrs = !function_exists('_ldapdata_reverse_mappings') ? array() : array_values(_ldapdata_reverse_mappings($ldap->getOption('sid')));
+
+  if (!in_array($name_attr, $attrs)) {
+    $attrs[] = $name_attr;
+  }
+  if (!in_array($mail_attr, $attrs)) {
+    $attrs[] = $mail_attr;
+  }
+  return $attrs;
+}
+
+
 //////////////////////////////////////////////////////////////////////////////
 // Auxiliary functions
 
@@ -262,10 +283,10 @@ function _ldapsync_search() {
  *
  * @return
  */
-function _ldapsync_init($sid) {
+function _ldapsync_init($row) {
   global $_ldapsync_ldap;
 
-  if ($row = db_fetch_object(db_query("SELECT * FROM {ldapauth} WHERE sid = %d", $sid))) {
+  if ($row) {
     $_ldapsync_ldap = new LDAPInterface();
     $_ldapsync_ldap->setOption('sid', $row->sid);
     $_ldapsync_ldap->setOption('name', $row->name);
@@ -281,3 +302,4 @@ function _ldapsync_init($sid) {
     return $_ldapsync_ldap;
   }
 }
+
Index: includes/LDAPInterface.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/ldap_integration/includes/LDAPInterface.inc,v
retrieving revision 1.6
diff -u -p -r1.6 LDAPInterface.inc
--- includes/LDAPInterface.inc	27 Oct 2009 14:29:18 -0000	1.6
+++ includes/LDAPInterface.inc	5 Feb 2011 05:42:40 -0000
@@ -116,16 +116,11 @@ class LDAPInterface {
   }
 
   function connect($dn = '', $pass = '') {
-    $ret = FALSE;
     // http://drupal.org/node/164049
     // If a connection already exists, it should be terminated
     $this->disconnect();
 
-    if ($this->connectAndBind($dn, $pass)) {
-      $ret = TRUE;
-    }
-
-    return $ret;
+    return $this->connectAndBind($dn, $pass);
   }
 
   function initConnection() {
@@ -147,11 +142,11 @@ class LDAPInterface {
         watchdog('ldap', 'Could not start TLS, only supported by LDAP v3.', array(), WATCHDOG_ERROR);
         return;
       }
-      else if (!function_exists('ldap_start_tls')) {
+      elseif (!function_exists('ldap_start_tls')) {
         watchdog('ldap', 'Could not start TLS. It does not seem to be supported by this PHP setup.', array(), WATCHDOG_ERROR);
         return;
       }
-      else if (!ldap_start_tls($con)) {
+      elseif (!ldap_start_tls($con)) {
         watchdog('ldap', 'Could not start TLS. (Error %errno: %error).', array('%errno' => ldap_errno($con), '%error' => ldap_error($con)), WATCHDOG_ERROR);
         return;
       }
@@ -208,9 +203,10 @@ class LDAPInterface {
   // WARNING! WARNING! WARNING!
   // This function returns its entries with lowercase attribute names.
   // Don't blame me, blame PHP's own ldap_get_entries()
-  function retrieveAttributes($dn) {
+  function retrieveAttributes($dn, $attributes = array()) {
     set_error_handler(array('LDAPInterface', 'void_error_handler'));
-    $result = ldap_read($this->connection, $dn, 'objectClass=*');
+    $result = empty($attributes) ? ldap_read($this->connection, $dn, 'objectClass=*') :
+    ldap_read($this->connection, $dn, 'objectClass=*', $attributes);
     $entries = ldap_get_entries($this->connection, $result);
     restore_error_handler();
 
