You are here

public function SimpleLdapUser::__construct in Simple LDAP 7

Same name and namespace in other branches
  1. 7.2 simple_ldap_user/SimpleLdapUser.class.php \SimpleLdapUser::__construct()

Constructor.

@throw SimpleLdapException

Parameters

string $name: The drupal user name or email address to search for, and load from LDAP.

File

simple_ldap_user/SimpleLdapUser.class.php, line 28
Class defining a simple LDAP user.

Class

SimpleLdapUser
@file Class defining a simple LDAP user.

Code

public function __construct($name) {

  // Load the LDAP server object.
  $this->server = SimpleLdapServer::singleton();

  // Load up the map.
  $this->mapObject = SimpleLdapUserMap::singleton();

  // Get the LDAP configuration.
  $base_dn = simple_ldap_user_variable_get('simple_ldap_user_basedn');
  $scope = simple_ldap_user_variable_get('simple_ldap_user_scope');
  $attribute_name = simple_ldap_user_variable_get('simple_ldap_user_attribute_name');
  $attribute_mail = simple_ldap_user_variable_get('simple_ldap_user_attribute_mail');
  $safe_name = preg_replace(array(
    '/\\(/',
    '/\\)/',
  ), array(
    '\\\\(',
    '\\\\)',
  ), $name);
  $filter = '(&(|(' . $attribute_name . '=' . $safe_name . ')(' . $attribute_mail . '=' . $safe_name . '))' . self::filter() . ')';

  // List of attributes to fetch from the LDAP server.
  $attributes = array(
    $attribute_name,
    $attribute_mail,
  );
  foreach ($this->mapObject->map as $attribute) {
    if (isset($attribute['ldap'])) {
      $attributes[] = $attribute['ldap'];
    }
  }

  // Include the userAccountControl attribute for Active Directory.
  try {
    if ($this->server->type == 'Active Directory') {
      $attributes[] = 'useraccountcontrol';
    }
  } catch (SimpleLdapException $e) {
  }

  // Attempt to load the user from the LDAP server.
  try {
    $result = $this->server
      ->search($base_dn, $filter, $scope, $attributes, 0, 1);
  } catch (SimpleLdapException $e) {
    if ($e
      ->getCode() == -1) {
      $result = array(
        'count' => 0,
      );
    }
    else {
      throw $e;
    }
  }

  // Populate the attribute array.
  if ($result['count'] == 1) {
    $this->dn = $result[0]['dn'];
    foreach ($attributes as $attribute) {
      $attribute = strtolower($attribute);
      if (isset($result[0][$attribute])) {
        $this->attributes[$attribute] = $result[0][$attribute];
      }
    }
    $this->exists = TRUE;
  }
  else {
    $this->attributes[$attribute_name] = array(
      'count' => 1,
      0 => $name,
    );
  }
}