function _ldap_login_validate_ldap_user($form, &$form_state) {
// Get the LDAP configuration.
$options = _ldap_login_get_ldap_settings();
// Make the LDAP connection.
try {
$adldap = new adLDAP($options);
}
catch (adLDAPException $e) {
// Throws an error to the user.
drupal_set_message(t('An error occurred while trying to log you in.'), 'error');
// Logs the errors into the DB.
watchdog('ldap_login', $e, array(), WATCHDOG_NOTICE, 'error_login');
}
// User info from the form submission.
$user_name = $form_state['values']['name'];
$user_pass = $form_state['values']['pass'];
if (is_object($adldap)) {
// Tries to authenticate the user.
$ldap_is_user = $adldap->authenticate($user_name, $user_pass);
}
// Checks if the user exists on LDAP. If not, jump to normal Drupal workflow.
// If the user exists, check if it's a Drupal user already. If not create.
if ($ldap_is_user) {
// Get the user mail from the AD.
$ldap_user = $adldap->user()->infoCollection($user_name);
// Check if the user is already a Drupal user.
// TODO: remove this mail creation once all the users from LDAP have the respective email.
$user_mail = isset($ldap_user->mail) ? $ldap_user->mail : rand('1', '1000') . '@drupalized.co';
// $user_mail = !(empty($ldap_user->mail)) ? $ldap_user->mail : rand('1', '1000') . '@drupalized.co';
$field_full_name = isset($ldap_user->displayname) ? $ldap_user->displayname : '';
// $field_full_name = !(empty($ldap_user->displayname)) ? $ldap_user->displayname : '';
//var_dump($ldap_user->mail);
//var_dump($ldap_user->displayname);
//var_dump($ldap_user);exit;
// Load the user.
$user = user_load_by_mail($user_mail);
$user = !empty($user) ? $user : user_load_by_name($user_name);
// If it is a Drupal user, update based on user account.
$user_account = (!empty($user) && isset($user->uid)) ? $user : '';
$old_roles = _ldap_login_get_old_roles(trim($user_name));
// Get the roles according to the ones mapped on the Drupal admin interface.
$drupal_user = array(
'name' => $user_name,
'pass' => $user_pass,
'mail' => $user_mail,
'status' => 1,
'init' => $user_mail,
'roles' => !empty($old_roles)?$old_roles:_ldap_login_get_mapped_roles($ldap_user->memberOf),//原来有角色,就用原来的角色,否则用ldap映射的角色
);
// Allow other modules to modify the user entity in case of custom fields.
if (count(module_implements('ldap_login_user_alter')) > 0) {
// Call all modules that implement the hook,
// and let them make changes to $drupal_user.
$drupal_user = module_invoke_all('ldap_login_user_alter', $drupal_user);
}
// If the first parameter is sent blank, a new user is created.
// Otherwise, user is updated.
//var_dump($drupal_user);exit;
$user_account = user_save($user_account, $drupal_user);//这里要返回一个值$user_account,后面的user_save 才是更新,而不是新建
$user_account->field_full_name['und'][0]['value'] = $field_full_name;
user_save($user_account);
}
}