@param string $dn ldap dn

@return mixed string user's username value of FALSE
14679
public function userUsernameFromDn($dn) {

    $ldap_entry = @$this->dnExists($dn, 'ldap_entry', array());
    if (!$ldap_entry || !is_array($ldap_entry)) {
      return FALSE;
    }
    else {
      return $this->userUsernameFromLdapEntry($ldap_entry);
    }

  }
758455
public function getUserForUsername($username)
    {
        if (!$this->accessControlManager->hasAccessEntityForName(self::ACCESS_ENTITY_TYPE, $username)) {
            return false;
        }
        
        // Get the access entity
        $accessEntity = $this->accessControlManager->getAccessEntityForName(self::ACCESS_ENTITY_TYPE, $username);

        if ($accessEntity === false) {
            return false;
        }
        
        return $accessEntity;
    }
1117639
def _get_user(self, username, attrs=ALL_ATTRS):
        """"""

        username = ldap.filter.escape_filter_chars(username)
        user_filter = self.user_filter_tmpl % {
            'username': self._uni(username)
        }
        r = self._search(self._byte_p2(user_filter), attrs, self.userdn)

        if len(r) == 0:
            return None

        # if NO_ATTR, only return the DN
        if attrs == NO_ATTR:
            dn_entry = r[0][0]
        # in other cases, return everything (dn + attributes)
        else:
            dn_entry = r[0]
        return dn_entry
35480
public static function extractDsn($dsn)
    {
        // Parse DSN to array
        $dsn = str_replace(';', "\n", $dsn);

        $values = [];

        foreach (explode("\n", $dsn) as $value) {
            [$k, $v] = explode('=', trim($value));

            $values[$k] = $v;
        }

        return $values;
    }
1373350
def _load_user_dn(self):
        
        if self._using_simple_bind_mode():
            self._user_dn = self._construct_simple_user_dn()
        else:
            if self.settings.CACHE_TIMEOUT > 0:
                cache_key = valid_cache_key(
                    "django_auth_ldap.user_dn.{}".format(self._username)
                )
                self._user_dn = cache.get_or_set(
                    cache_key, self._search_for_user_dn, self.settings.CACHE_TIMEOUT
                )
            else:
                self._user_dn = self._search_for_user_dn()
969046
public function plainAuth(string $username, string $password): bool
    {
        $resource = $this->ldap->getResource();

        $esc_username = ldap_escape($username);
        $filter = htmlspecialchars_decode(sprintf($this->account_filter, $esc_username));
        $result = ldap_search($resource, $this->ldap->getBase(), $filter, ['dn', $this->identity_attribute]);
        $entries = ldap_get_entries($resource, $result);

        if (0 === $entries['count']) {
            $this->logger->warning("user not found with ldap filter [{$filter}]", [
                'category' => get_class($this),
            ]);

            return false;
        }
        if ($entries['count'] > 1) {
            $this->logger->warning("more than one user found with ldap filter [{$filter}]", [
                'category' => get_class($this),
            ]);

            return false;
        }

        $dn = $entries[0]['dn'];
        $this->logger->info("found ldap user [{$dn}] with filter [{$filter}]", [
            'category' => get_class($this),
        ]);

        $result = ldap_bind($resource, $dn, $password);
        $this->logger->info("bind ldap user [{$dn}]", [
            'category' => get_class($this),
            'result' => $result,
        ]);

        if (false === $result) {
            return false;
        }

        if (!isset($entries[0][$this->identity_attribute])) {
            throw new Exception\IdentityAttributeNotFound('identity attribute not found');
        }

        $this->identifier = $entries[0][$this->identity_attribute][0];
        $this->ldap_dn = $dn;

        return true;
    }
315809
public function dnExists($dn)
    {
        if (PEAR::isError($dn)) {
            return $dn;
        }
        if ($dn instanceof Net_LDAP2_Entry) {
             $dn = $dn->dn();
        }
        if (false === is_string($dn)) {
            return PEAR::raiseError('Parameter $dn is not a string nor an entry object!');
        }

        // search LDAP for that DN by performing a baselevel search for any
        // object. We can only find the DN in question this way, or nothing.
        $s_opts = array(
            'scope'      => 'base',
            'sizelimit'  => 1,
            'attributes' => '1.1' // select no attrs
        );
        $search = $this->search($dn, '(objectClass=*)', $s_opts);

        if (self::isError($search)) {
            return $search;
        }

        // retun wehter the DN exists; that is, we found an entry
        return ($search->count() == 0)? false : true;
    }
227128
function password_expire($username) {
        $result = 0;

        $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);

        $ldapconnection = $this->ldap_connect();
        $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
        $search_attribs = array($this->config->expireattr);
        $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
        if ($sr)  {
            $info = ldap_get_entries_moodle($ldapconnection, $sr);
            if (!empty ($info)) {
                $info = $info[0];
                if (isset($info[$this->config->expireattr][0])) {
                    $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
                    if ($expiretime != 0) {
                        $now = time();
                        if ($expiretime > $now) {
                            $result = ceil(($expiretime - $now) / DAYSECS);
                        } else {
                            $result = floor(($expiretime - $now) / DAYSECS);
                        }
                    }
                }
            }
        } else {
            error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
        }

        return $result;
    }
194766
protected function findLdapUserDnByUsername($username)
    {
        $ldapClient = $this->getLdapClient();
        $options = $this->getUtils()->getOptions();

        $loginFilterString = '';
        if (!empty($options['userLoginFilter'])) {
            $loginFilterString = $this->convertToFilterFormat($options['userLoginFilter']);
        }

        $searchString = '(&(objectClass='.$options['userObjectClass'].')('.$options['userNameAttribute'].'='.$username.')'.$loginFilterString.')';
        $result = $ldapClient->search($searchString, null, LDAP\Client::SEARCH_SCOPE_SUB);
        $GLOBALS['log']->debug('LDAP: user search string: "' . $searchString . '"');

        foreach ($result as $item) {
            return $item["dn"];
        }
    }
968348
function user_info($username,$fields=NULL){
        if ($username==NULL){ return (false); }
        if (!$this->_bind){ return (false); }
        if  ('' == $this->_users_dn) {
            $this->_users_dn = $this->_base_dn;
        }

        $filter = "(&(".$this->_cn_identifier."=".$username."))";
        if ($fields==NULL){ $fields=array($this->_cn_identifier,"mail",$this->_group_attribute,"department","description","displayname","gecos","telephonenumber","primarygroupid"); }
        $sr=ldap_search($this->_conn,$this->_users_dn,$filter,$fields);
        $entries = $this->ldap_get_entries_raw($sr);
        
        // AD does not return the primary group in the ldap query, we may need to fudge it
        // SysCo/al added a test to check if $entries[0]["primarygroupid"][0] exists
        $add_primary_group = FALSE;
        if ($this->_real_primarygroup){
            if (isset($one_entry["primarygroupid"][0])) {
                $pri_grp_rid = $one_entry["primarygroupid"][0];
                if (isset($this->_cache_group_dn[$pri_grp_rid])) {
                    $dn_group = $this->_cache_group_dn[$pri_grp_rid];
                    $one_entry[$this->_group_attribute][] = $dn_group;
                    $add_primary_group = TRUE;
                } else {
                    $r = ldap_read($this->_conn, $this->_base_dn, "(objectclass=*)", array("objectSid")) or exit();
                    $data = ldap_get_entries($this->_conn, $r);
                    if (isset($data[0]["objectsid"][0])) {
                        $domain_sid = $data[0]["objectsid"][0];
                        $domain_sid_s = sid2str($domain_sid);
                        $r = ldap_search($this->_conn, $this->_base_dn, "objectSid=".$domain_sid_s."-".$pri_grp_rid, array("distinguishedname")) or exit();
                        $data = ldap_get_entries($this->_conn, $r);
                        if (isset($data[0]["distinguishedname"][0])) {
                            $dn_group = $data[0]["distinguishedname"][0];
                            $one_entry[$this->_group_attribute][] = $dn_group;
                            $add_primary_group = TRUE;
                                if (count($this->_cache_group_dn) < 1000) { // Don't overload the memory cache
                                $this->_cache_group_dn[$pri_grp_rid] = $dn_group;
                            }
                        }
                    }
                }
            }
        } else {
            $entries[0][$this->_group_attribute][]="CN=Domain Users,CN=Users,".$this->_base_dn;
            $add_primary_group = TRUE;
        }
        if ($add_primary_group) {
            @$entries[0][$this->_group_attribute]["count"]++;
        }

        return ($entries);
    }
1053214
public function dnStrToArr($dnStr, $excludeBaseDn = true, $includeAttributes = false)
    {
        if ($excludeBaseDn) {
            return ldap_explode_dn($dnStr, ($includeAttributes ? 0 : 1));
        } else {
            return ldap_explode_dn($this->adldap->getBaseDn().$dnStr, ($includeAttributes ? 0 : 1));
        }
    }
24427
public function usernameToGuid($username)
    {
        $this->adldap->utilities()->validateNotNull('Username', $username);

        $this->adldap->utilities()->validateLdapIsBound();

        $filter = $this->adldap->getUserIdKey().'='.$username;

        $fields = ['objectGUID'];

        $results = $this->connection->search($this->adldap->getBaseDn(), $filter, $fields);

        $numEntries = $this->connection->countEntries($results);

        if ($numEntries > 0) {
            $entry = $this->connection->getFirstEntry($results);

            $guid = $this->connection->getValuesLen($entry, 'objectGUID');

            $strGUID = $this->adldap->utilities()->binaryToText($guid[0]);

            return $strGUID;
        }

        return false;
    }
291990
public function getDsn(): string
  {
/*
MYSQL:
  $connection = new \PDO('mysql:host=localhost;port=3306;dbname=test', $user, $pass,
    array(
      \PDO::ATTR_PERSISTENT => true
      \PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      \PDO::ATTR_AUTOCOMMIT => FALSE,
      \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"           // Set UTF8 as charset
    )
  );
*/
    # Build the DSN
    $_dsn = $this->getDriver().':'.
            'host='.$this->getHost().($this->getPort()!=0 ? ';port='.$this->getPort() : '' ).
            ';dbname='.$this->getSchema().
            ';charset='.$this->getCharset();

    # Set it
    $this->setDsn($_dsn);

    return $_dsn;
  }
1093694
protected function _bindLdapAdminUser()
    {
        $connect = $this->_getLinkId();
        if (!$connect) {
            jLog::log('ldapdao: impossible to connect to ldap', 'auth');
            return false;
        }

        if ($this->_params['adminUserDn'] == '') {
            $bind = ldap_bind($connect);
        } else {
            $bind = ldap_bind($connect, $this->_params['adminUserDn'], $this->_params['adminPassword']);
        }
        if (!$bind) {
            if ($this->_params['adminUserDn'] == '') {
                jLog::log('ldapdao: impossible to authenticate to ldap as anonymous admin user', 'auth');
            } else {
                jLog::log('ldapdao: impossible to authenticate to ldap with admin user '.$this->_params['adminUserDn'], 'auth');
            }
            ldap_close($connect);
            return false;
        }
        return $connect;
    }
572743
public static function getXDomainUserId($domain_username, $domain)
	{
		$db = \App::get('db');

		if (empty($domain) || ($domain == 'hubzero'))
		{
			return $domain_username;
		}

		$query = 'SELECT uidNumber FROM #__xdomain_users,#__xdomains WHERE ' .
				 '#__xdomains.domain_id=#__xdomain_users.domain_id AND ' .
				 '#__xdomains.domain=' . $db->quote($domain) . ' AND ' .
				 '#__xdomain_users.domain_username=' . $db->quote($domain_username);
		$db->setQuery($query);

		$result = $db->loadObject();

		if (empty($result))
		{
			return false;
		}

		return $result->uidNumber;
	}
408333
function group_add_user($group,$user){
        //adding a user is a bit fiddly, we need to get the full DN of the user
        //and add it using the full DN of the group
        
        //find the user's dn
        $user_info=$this->user_info($user,array("cn"));
        if ($user_info[0]["dn"]==NULL){ return (false); }
        $user_dn=$user_info[0]["dn"];
        
        //find the group's dn
        $group_info=$this->group_info($group,array("cn"));
        if ($group_info[0]["dn"]==NULL){ return (false); }
        $group_dn=$group_info[0]["dn"];
        
        $add=array();
        $add["member"] = $user_dn;
        
        $result=@ldap_mod_add($this->_conn,$group_dn,$add);
        if ($result==false){ return (false); }
        return (true);
    }
827560
public function setDn($dn)
    {
        if ($dn === null) {
            $this->dn = null;
        } else {
            $this->dn = (string) $dn;
        }

        return $this;
    }