You are here

public function SimpleLdapUserManager::getLdapUser in Simple LDAP 8

Checks if a user exists on the LDAP server with a certain name.

It first checks using the name attribute, and then the email attribute.

Parameters

string $name: The name to search for on the server.

Return value

mixed A SimpleLdapUser object if the user exists on the server, FALSE if otherwise.

Throws

\Drupal\simple_ldap\SimpleLdapException

File

modules/simple_ldap_user/src/SimpleLdapUserManager.php, line 64

Class

SimpleLdapUserManager
Manages the loading and syncing of data between LDAP server and Drupal.

Namespace

Drupal\simple_ldap_user

Code

public function getLdapUser($name) {
  $cid = sprintf('LdapUser::%s', $name);
  if (array_key_exists($cid, $this->cache)) {
    return $this->cache[$cid];
  }
  $name = $this
    ->cleanName($name);
  $name_attribute = $this->config
    ->get('name_attribute');
  $mail_attribute = $this->config
    ->get('mail_attribute');
  $base_dn = $this->config
    ->get('basedn');
  $scope = $this->config
    ->get('user_scope');
  if (empty($name_attribute) || empty($mail_attribute)) {
    throw new SimpleLdapException('Unable to find valid configuration for LDAP User Drupal module.', NULL);
  }
  $object_classes = $this->config
    ->get('object_class');
  $object_class_filter = '';
  if (isset($object_classes)) {
    $object_class_filter = '(&(objectclass=' . implode(')(objectclass=', $object_classes) . '))';
  }
  $filter_list = array();
  $filter_list[] = '(&(' . $name_attribute . '=' . $name . ')' . $object_class_filter . ')';
  $filter_list[] = '(&(' . $mail_attribute . '=' . $name . ')' . $object_class_filter . ')';
  if (!$this->server
    ->bind()) {
    $this->cache[$cid] = FALSE;
    return FALSE;
  }
  foreach ($filter_list as $filter) {
    try {

      // @TODO get the full attributes to pass into this search
      $results = $this->server
        ->search($base_dn, $filter, $scope, [], 0, 1);
    } catch (SimpleLdapException $e) {
      if ($e
        ->getCode() == -1) {
        $results = array();
      }
      else {
        $this->cache[$cid] = FALSE;
        throw $e;
      }
    }
    if (count($results) == 1) {
      $simple_ldap_user = new SimpleLdapUser(key($results), array_shift($results));
      $this->cache[$cid] = $simple_ldap_user;
      return $simple_ldap_user;
    }
  }
  return FALSE;
}