You are here

function simple_ldap_user_load_or_create_by_name in Simple LDAP 7.2

Same name and namespace in other branches
  1. 7 simple_ldap_user/simple_ldap_user.module \simple_ldap_user_load_or_create_by_name()

Create a valid LDAP user on this site if they don't already exist.

Parameters

string $name: The username or email address to load.

Return value

mixed The Drupal user object, FALSE if the process failed, NULL if there was a conflict.

2 calls to simple_ldap_user_load_or_create_by_name()
simple_ldap_user_import_user in simple_ldap_user/simple_ldap_user.admin.inc
Batch process function for mass user import.
simple_ldap_user_login_name_validate in simple_ldap_user/simple_ldap_user.module
Validate the username on a login or password reset form.

File

simple_ldap_user/simple_ldap_user.module, line 643
Main simple_ldap_user module file.

Code

function simple_ldap_user_load_or_create_by_name($name) {

  // Load the LDAP user with the given username.
  $ldap_user = SimpleLdapUser::singleton($name);
  $attribute_name = strtolower(simple_ldap_user_variable_get('simple_ldap_user_attribute_name'));
  $attribute_mail = strtolower(simple_ldap_user_variable_get('simple_ldap_user_attribute_mail'));
  $puid_attr = strtolower(simple_ldap_user_variable_get('simple_ldap_user_unique_attribute'));

  // If the user doesn't exist in LDAP, there is nothing for us to do.
  if (!$ldap_user->exists) {
    return FALSE;
  }

  // Pull the username
  $user_name = $ldap_user->{$attribute_name}[0];
  if ($puid_attr) {
    $puid = $ldap_user->{$puid_attr}[0];
    $puid_status = simple_ldap_user_update_username_for_puid($puid, $user_name);

    // Abort if there is a conflict.
    if ($puid_status === FALSE) {
      return NULL;
    }
    $name = $user_name;
  }

  // Attempt to load the drupal user.
  $drupal_user = user_load_by_name($name);
  if (!$drupal_user) {
    $drupal_user = user_load_by_mail($name);
  }

  // If the user doesn't already exist in Drupal, create them.
  if (!$drupal_user) {
    $edit = array(
      'name' => $ldap_user->{$attribute_name}[0],
      'mail' => $ldap_user->{$attribute_mail}[0],
      'status' => 1,
    );
    $drupal_user = user_save(NULL, $edit);
    $authmap_attr = $puid_attr ? $puid_attr : 'dn';
    user_set_authmaps($drupal_user, array(
      'authmap_simple_ldap' => $ldap_user->{$authmap_attr}[0],
    ));
  }
  return $drupal_user;
}