function verify($cert, $dn) { $conn = ldap_connect($this->LDAP_HOST); if (!$conn) { return false; } if (!ldap_bind($conn)) { return false; } $resultset = ldap_search($conn, "c=EE", "(serialNumber=38212200301)"); if (!$resultset) { echo "No recs"; return false; } $rec = ldap_first_entry($conn, $resultset); while ($rec !== false) { $values = ldap_get_values($conn, $rec, 'usercertificate;binary'); $certificate = "-----BEGIN CERTIFICATE-----\n" . chunk_split(base64_encode($values[0]), 64, "\n") . "-----END CERTIFICATE-----\n"; if (strcmp($cert, $certificate) == 0) { return "Found"; } $rec = ldap_next_entry($conn, $rec); } // Not found a record with a matching certificate return false; }
/** * @return mixed resource */ public function fetchEntry() { if (!$this->result_resource) { return null; } if (null === $this->entry_resource) { $this->entry_resource = ldap_first_entry($this->resource, $this->result_resource); } else { $this->entry_resource = ldap_next_entry($this->resource, $this->entry_resource); } if (!$this->entry_resource) { return null; } $dn = ldap_get_dn($this->resource, $this->entry_resource); $rawAttributes = ldap_get_attributes($this->resource, $this->entry_resource); $count = $rawAttributes['count']; $attributes = array(); for ($i = 0; $i < $count; $i++) { $attribute = $rawAttributes[$i]; $values = array(); $subCount = $rawAttributes[$attribute]['count']; for ($j = 0; $j < $subCount; $j++) { $values[] = $rawAttributes[$attribute][$j]; } $attributes[$attribute] = $values; } $object = new Object($dn, $attributes); return $object; }
public function fetch_row() { if ($this->get_opt('fetch_pos')) { return ldap_next_entry($this->handle, $this->resource); } else { return ldap_first_entry($this->handle, $this->resource); } }
/** * @return Entry|null * @throws EntryRetrievalFailureException */ public function nextEntry() { if (!($entry = ldap_next_entry($this->link, $this->entry))) { if (0 !== ($errNo = ldap_errno($this->link))) { throw new EntryRetrievalFailureException(ldap_error($this->link), $errNo); } return null; } return new Entry($this->link, $entry); }
public static function readUsers($ldapconn) { $users = array(); $search = ldap_list($ldapconn, USER_DN, User::FILTER_USERS, array("cn", "mail", "displayName", "sn", "givenName", "memberOf")); if (ldap_count_entries($ldapconn, $search) > 0) { $entry = ldap_first_entry($ldapconn, $search); do { $users[] = User::readFromLdapEntry($ldapconn, $entry); } while ($entry = ldap_next_entry($ldapconn, $entry)); } return $users; }
/** * Returns the next entry in the result set or false wether there are no more entries. * * @return \gossi\ldap\LdapEntry The new LdapEntry. */ public function getNextEntry() { if ($this->pointer == null) { return $this->getFirstEntry(); } $this->pointer = ldap_next_entry($this->conn, $this->pointer); if ($this->pointer) { return new LdapEntry($this->conn, $this->pointer); } else { return false; } }
/** * Auxiliar directo de busqueda. Dado un ldap result, itera por el para conseguir sus datos * * @param ldap result $busquedaLdap * @param array $atributos * @return boolean */ private function iterarEntradas($busquedaLdap, array $atributos) { $datos = array(); if ($entrada = ldap_first_entry($this->conexionLdap, $busquedaLdap)) { do { // Ejecutamos al menos una vez el mapeo de entradas con sus atributos, a menos // que no haya nada $datos[] = $this->mapa($atributos, $entrada); } while ($entrada = ldap_next_entry($this->conexionLdap, $entrada)); return $datos; } else { return FALSE; } }
function ldap_flatresults($ad, $sr, $key = false) { for ($entry = ldap_first_entry($ad, $sr); $entry != false; $entry = ldap_next_entry($ad, $entry)) { $user = array(); $attributes = ldap_get_attributes($ad, $entry); for ($i = $attributes['count']; $i-- > 0;) { $user[strtolower($attributes[$i])] = $attributes[$attributes[$i]][0]; } if ($key && $user[$key]) { $users[strtolower($user[$key])] = $user; } else { $users[] = $user; } } return $users; }
public function getIterator() { $con = $this->connection->getResource(); $search = $this->search->getResource(); $current = ldap_first_entry($con, $search); if (0 === $this->count()) { return; } if (false === $current) { throw new LdapException(sprintf('Could not rewind entries array: %s', ldap_error($con))); } (yield $this->getSingleEntry($con, $current)); while (false !== ($current = ldap_next_entry($con, $current))) { (yield $this->getSingleEntry($con, $current)); } }
/** * Retrieves next available entry from the search result set * * @return EntryInterface next entry if available, null otherwise */ public function next() { if ($this->isEndReached) { return null; } if (null === $this->previous) { $this->previous = @ldap_first_entry($this->connection, $this->resultSet); } else { $this->previous = @ldap_next_entry($this->connection, $this->previous); } if (false === $this->previous) { $this->previous = null; $this->isEndReached = true; return null; } return new Entry($this->connection, $this->previous); }
public function getUsers($filter = null) { if ($filter !== null) { $filter = "(&(objectClass=inetOrgPerson)(uid=" . addcslashes($filter, '()\\') . "))"; } else { $filter = "(objectClass=inetOrgPerson)"; } $resource = ldap_search($this->ldapconn, $this->ldapbasedn, $filter); ldap_sort($this->ldapconn, $resource, "uid"); $entry = ldap_first_entry($this->ldapconn, $resource); $users = array(); while ($entry) { $attributes = ldap_get_attributes($this->ldapconn, $entry); $users[] = $attributes["uid"][0]; $entry = ldap_next_entry($this->ldapconn, $entry); } return $users; }
/** * Fetch the next record or return false if there's none. * * @return Record */ public function fetch() { if (!isset($this->_numEntry)) { $this->_numEntry = 0; $this->_entryId = ldap_first_entry($this->_ldapConn->getLink(), $this->_searchId); } else { $this->_numEntry++; $this->_entryId = ldap_next_entry($this->_ldapConn->getLink(), $this->_entryId); } if (!$this->_entryId) { return false; } $record = new $this->fetchClass($this->_ldapConn, $this->_entryId); if (!is_a($record, 'GO\\Base\\Ldap\\Record')) { throw new Exception($this->fetchClass . ' is not a GO\\Base\\Ldap\\Record subclass'); } return $record; }
/** * Get the next LDAP entry from search results. * * @return Entry|null * Next LDAP entry or null if no entries left. */ public function next() { if ($this->entryID === null) { $this->entryID = ldap_first_entry($this->ds, $this->sr); } else { $this->entryID = ldap_next_entry($this->ds, $this->entryID); } if (!$this->entryID) { return null; } $data = Utils::readEntry($this->ds, $this->entryID, $this->binaryFields); if (array_key_exists('nsRole', $data)) { $data['roles'] = Utils::getRoles($this->ds, $data); } $dn = ldap_get_dn($this->ds, $this->entryID); $rdn = Utils::getRDN($dn, $this->baseDN); return new Entry($this->ds, $rdn, $dn, $data); }
/** * @see ResultSet::next() */ public function next() { if (!$this->entry) { $this->entry = ldap_first_entry($this->conn->getResource(), $this->result); } $this->entry = ldap_next_entry($this->conn->getResource(), $this->entry); if (!$this->entry) { $errno = mysql_errno($this->conn->getResource()); if (!$errno) { // We've advanced beyond end of recordset. $this->afterLast(); return false; } else { throw new SQLException("Error fetching result", mysql_error($this->conn->getResource())); } } $this->cursorPos++; return $this->entry; }
public function get_ldap_attribute_for_various_data($pAttributes, $ldapRequest) { $allResults = array(); $ldapc = $this->ldap_conn; //ldap connection if (!is_array($pAttributes)) { throw new Exception("Argument is not an array", E_PARAM); } //search for multiple ldap attributes //search string is prefix notation $search = ldap_search($ldapc, LDAP_O . ", " . LDAP_C, $ldapRequest, $pAttributes); //get ldap attributes for ($entryID = ldap_first_entry($ldapc, $search); $entryID != false; $entryID = ldap_next_entry($ldapc, $entryID)) { foreach ($pAttributes as $attribute) { $value = ldap_get_values($ldapc, $entryID, $attribute); $result[$attribute] = $value[0]; } $allResults[] = $result; } return $allResults; }
/** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(UserContract $user, array $credentials) { $email = $credentials['email']; $password = $credentials['password']; $ldap_conn = ldap_connect($this->ldapConfig['host'], $this->ldapConfig['port']); $ldap_bind = ldap_bind($ldap_conn, $this->ldapConfig['user'], $this->ldapConfig['password']); try { // Find By Email $escEmail = ldap_escape($email, '', LDAP_ESCAPE_FILTER); $filter = "(&(uid=*)(|(mail=" . $escEmail . ")" . "(gosaMailAlternateAddress=" . $escEmail . ")))"; $sr = ldap_search($ldap_conn, $this->ldapConfig['base'], $filter, []); if (!$sr) { return false; } $conn = ldap_connect($this->ldapConfig['host'], $this->ldapConfig['port']); $entry = ldap_first_entry($ldap_conn, $sr); while ($entry) { $dn = ldap_get_dn($ldap_conn, $entry); // Check Credentials // remove warnings for incorrect passwords $level = error_reporting(); error_reporting($level & ~E_WARNING); try { $bind = ldap_bind($conn, $dn, $password); if ($bind) { // successful ldap_unbind($conn); return true; } } finally { // restore warnings error_reporting($level); } $entry = ldap_next_entry($ldap_conn, $entry); } } finally { ldap_unbind($ldap_conn); } return false; }
/** * Gets next entry * * @return peer.ldap.LDAPEntry or NULL if nothing was found * @throws peer.ldap.LDAPException in case of a read error */ public function next() { // If we have reached the number of results reported by ldap_count_entries() // - see constructor, return FALSE without trying to read further. Trying // to read "past the end" results in LDAP error #84 (decoding error) in some // client/server constellations, which is then incorrectly reported as an error. if ($this->iteration[1] >= $this->size) { return null; } // Fetch the next entry. Return FALSE if it was the last one (where really, // we shouldn't be getting here) $entry = ldap_next_entry($this->conn, $this->iteration[0]); if (!$entry) { if ($e = ldap_errno($this->conn)) { throw new LDAPException('Could not fetch next result entry.', $e); } return null; // EOF } // Keep track how many etnries we have fetched so we stop once we // have reached this number - see above for explanation. $this->iteration = [$entry, ++$this->iteration[1]]; return LDAPEntry::create(ldap_get_dn($this->conn, $entry), ldap_get_attributes($this->conn, $entry)); }
/** * Retrieve the immediate children DNs of the given $parentDn * * This method is used in recursive methods like {@see delete()} * or {@see copy()} * * @param string|Zend_Ldap_Dn $parentDn * @return array of DNs */ protected function _getChildrenDns($parentDn) { if ($parentDn instanceof Zend_Ldap_Dn) { $parentDn = $parentDn->toString(); } $children = array(); $search = @ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn')); for ($entry = @ldap_first_entry($this->getResource(), $search); $entry !== false; $entry = @ldap_next_entry($this->getResource(), $entry)) { $childDn = @ldap_get_dn($this->getResource(), $entry); if ($childDn === false) { /** * @see Zend_Ldap_Exception */ #require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception($this, 'getting dn'); } $children[] = $childDn; } @ldap_free_result($search); return $children; }
function _fetch() { if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) { return false; } if ($this->_currentRow == 0) { $this->_entryID = ldap_first_entry($this->connection->_connectionID, $this->_queryID); } else { $this->_entryID = ldap_next_entry($this->connection->_connectionID, $this->_entryID); } $this->fields = ldap_get_attributes($this->connection->_connectionID, $this->_entryID); $this->_numOfFields = $this->fields['count']; switch ($this->fetchMode) { case LDAP_ASSOC: $this->fields = $this->GetRowAssoc(); break; case LDAP_NUM: $this->fields = $this->GetRowNums(); break; case LDAP_BOTH: default: break; } return is_array($this->fields); }
/** * @param string $sSortField * @param string $bAsc 'asc' or 'desc' * @param int $iOffset = null * @param int $iRequestLimit = null * @return array */ public function SortPaginate($sSortField, $bAsc = true, $iOffset = null, $iRequestLimit = null) { $iTotalEntries = @ldap_count_entries($this->rLink, $this->rSearch); $iEnd = 0; $iStart = 0; if ($iOffset === null || $iRequestLimit === null) { $iStart = 0; $iEnd = $iTotalEntries - 1; } else { $iStart = $iOffset; $iStart = $iStart < 0 ? 0 : $iStart; $iEnd = $iStart + $iRequestLimit; $iEnd = $iEnd > $iTotalEntries ? $iTotalEntries : $iEnd; } if (0 < strlen($sSortField)) { @ldap_sort($this->rLink, $this->rSearch, $sSortField); } $aList = array(); for ($iCurrent = 0, $rEntry = ldap_first_entry($this->rLink, $this->rSearch); $iCurrent < $iEnd && is_resource($rEntry); $iCurrent++, $rEntry = ldap_next_entry($this->rLink, $rEntry)) { if ($iCurrent >= $iStart) { array_push($aList, ldap_get_attributes($this->rLink, $rEntry)); } } return $bAsc ? $aList : array_reverse($aList); }
public function searchnamesforgroup($value, $groupdn, $allowgeneric = false) { require FRAMEWORK . DS . 'conf' . DS . 'mycafetaria.php'; $value = $this->adescape($value); $groupdn = $this->adescape($groupdn, true); $agemenegebruikersdn = $this->adescape($agemenegebruikersdn, true); if (!$allowgeneric) { $filter = "(&(objectCategory=user)(objectClass=user)(|(displayname={$value})(samaccountname={$value}))(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(memberof={$agemenegebruikersdn}))(memberof:1.2.840.113556.1.4.1941:={$groupdn}))"; } else { $filter = "(&(objectCategory=user)(objectClass=user)(|(displayname={$value})(samaccountname={$value}))(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberof:1.2.840.113556.1.4.1941:={$groupdn}))"; } $filter2 = "(&(objectCategory=user)(objectClass=user)(|(displayname={$value})(samaccountname={$value}))(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberof:1.2.840.113556.1.4.1941:={$groupdn}))"; $result = ldap_search($this->con, $this->dn, $filter, $this->attributes); if (ldap_errno($this->con)) { throw new searchException('Unable to conduct search: ' . ldap_error($this->con)); } $result2 = ldap_search($this->con2, $this->dn2, $filter2, $this->attributes); if (ldap_errno($this->con2)) { throw new searchException('Unable to conduct search: ' . ldap_error($this->con2)); } $output = array(); if (ldap_count_entries($this->con, $result)) { ldap_sort($this->con, $result, 'samaccountname'); $i = 0; $entry = ldap_first_entry($this->con, $result); do { $attributes = ldap_get_attributes($this->con, $entry); for ($j = 0; $j < $attributes['count']; $j++) { $values = ldap_get_values_len($this->con, $entry, $attributes[$j]); $rows[$i][strtolower($attributes[$j])] = $values; if (strtolower($attributes[$j]) == 'objectguid') { $rows[$i][strtolower($attributes[$j])][0] = bin2hex($values[0]); } if (count($rows[$i][strtolower($attributes[$j])]) == 2) { $rows[$i][strtolower($attributes[$j])] = $rows[$i][strtolower($attributes[$j])][0]; } else { unset($rows[$i][strtolower($attributes[$j])]['count']); } } $i++; } while ($entry = ldap_next_entry($this->con, $entry)); $rows['count'] = ldap_count_entries($this->con, $result); for ($index = 0; $index < $rows['count']; $index++) { $object = $this->fillObject($rows[$index], false); $output[] = $object; } } if (ldap_count_entries($this->con2, $result2)) { ldap_sort($this->con2, $result2, 'samaccountname'); $i = 0; $entry = ldap_first_entry($this->con2, $result2); do { $attributes = ldap_get_attributes($this->con2, $entry); for ($j = 0; $j < $attributes['count']; $j++) { $values = ldap_get_values_len($this->con2, $entry, $attributes[$j]); $rows[$i][strtolower($attributes[$j])] = $values; if (strtolower($attributes[$j]) == 'objectguid') { $rows[$i][strtolower($attributes[$j])][0] = bin2hex($values[0]); } if (count($rows[$i][strtolower($attributes[$j])]) == 2) { $rows[$i][strtolower($attributes[$j])] = $rows[$i][strtolower($attributes[$j])][0]; } else { unset($rows[$i][strtolower($attributes[$j])]['count']); } } $i++; } while ($entry = ldap_next_entry($this->con2, $entry)); $rows['count'] = ldap_count_entries($this->con2, $result2); for ($index = 0; $index < $rows['count']; $index++) { $object = $this->fillObject($rows[$index], false); $output[] = $object; } } return $output; }
/** * Performs an LDAP search * * @param array $filters Search Filters (array of strings) * @param string $dnoverride DN Override * @param array $attributes An array of attributes to return (if empty, all fields are returned). * * @return array Multidimensional array of results * * @since 12.1 */ public function search(array $filters, $dnoverride = null, array $attributes = array()) { $result = array(); if ($dnoverride) { $dn = $dnoverride; } else { $dn = $this->base_dn; } $resource = $this->_resource; foreach ($filters as $search_filter) { $search_result = @ldap_search($resource, $dn, $search_filter, $attributes); if ($search_result && ($count = @ldap_count_entries($resource, $search_result)) > 0) { for ($i = 0; $i < $count; $i++) { $result[$i] = array(); if (!$i) { $firstentry = @ldap_first_entry($resource, $search_result); } else { $firstentry = @ldap_next_entry($resource, $firstentry); } // Load user-specified attributes $result_array = @ldap_get_attributes($resource, $firstentry); // LDAP returns an array of arrays, fit this into attributes result array foreach ($result_array as $ki => $ai) { if (is_array($ai)) { $subcount = $ai['count']; $result[$i][$ki] = array(); for ($k = 0; $k < $subcount; $k++) { $result[$i][$ki][$k] = $ai[$k]; } } } $result[$i]['dn'] = @ldap_get_dn($resource, $firstentry); } } } return $result; }
public function getUsersinGroup($groupDn) { $users = array(); $cn = ldap_explode_dn($groupDn, 0)[0]; $results = ldap_search($this->conn, "OU=Users,OU=People," . $this->basedn, "(memberof:1.2.840.113556.1.4.1941:={$groupDn})", array("cn")); $count = ldap_count_entries($this->conn, $results); if ($count > 0) { $entry = ldap_first_entry($this->conn, $results); do { array_push($users, $this->getFirstValue($entry, "cn")); } while ($entry = ldap_next_entry($this->conn, $entry)); } return $users; }
/** * Gets the userss by the indicated details as well as the role. worker method * @oaram boolean $role Defaults to false * @param array $details of string. The details we wish on the user. Defaults to empty array * @returns array of usernames which mathc the give input */ public function _getUsersByInfo($role = false, $details = array()) { $usernames = array(); if (!($ldap = $this->getConnection())) { return $usernames; } $usernames = array(); $p_attrs = array(); foreach ($details as $detail => $value) { if (array_key_exists($detail, $this->options['p_details'])) { $p_attrs[] = '(' . $this->options['p_details'][$detail] . '=' . $value . ')'; } } //first we get all the people by their people details. then we limit them based on app details if there are any $p_filter = ''; $p_attrs[] = '(cn=*)'; if (count($p_attrs) > 0) { $p_filter = '(&' . implode('', $p_attrs) . ')'; } if (!($r1 = @ldap_list($ldap, $this->getPeopleQry(), $p_filter, array('dn', 'uid')))) { return false; } $entry = ldap_first_entry($ldap, $r1); $e = 0; while ($entry) { $dn = ldap_get_dn($ldap, $entry); $entry = ldap_next_entry($ldap, $entry); $username = $this->getUIDFromDN($dn); if (!$username) { I2CE::raiseError("No username from {$dn}"); continue; } if ($role) { $existingin_role = $this->getRole($username); if ($exisiting_role != $role) { continue; } } $usernames[] = $username; } return $usernames; }
/** * Move forward to next result item * Implements Iterator * * @throws \Zend\Ldap\Exception\LdapException */ public function next() { $code = 0; if (is_resource($this->current) && $this->itemCount > 0) { $resource = $this->ldap->getResource(); ErrorHandler::start(); $this->current = ldap_next_entry($resource, $this->current); ErrorHandler::stop(); if ($this->current === false) { $msg = $this->ldap->getLastError($code); if ($code === Exception\LdapException::LDAP_SIZELIMIT_EXCEEDED) { // we have reached the size limit enforced by the server return; } elseif ($code > Exception\LdapException::LDAP_SUCCESS) { throw new Exception\LdapException($this->ldap, 'getting next entry (' . $msg . ')'); } } } else { $this->current = false; } }
/** * Move forward to next result item * Implements Iterator * * @throws Zend_Ldap_Exception */ public function next() { if (is_resource($this->_current)) { $this->_current = @ldap_next_entry($this->_ldap->getResource(), $this->_current); /** @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; if ($this->_current === false) { $msg = $this->_ldap->getLastError($code); if ($code === Zend_Ldap_Exception::LDAP_SIZELIMIT_EXCEEDED) { // we have reached the size limit enforced by the server return; } else { if ($code > Zend_Ldap_Exception::LDAP_SUCCESS) { throw new Zend_Ldap_Exception($this->_ldap, 'getting next entry (' . $msg . ')'); } } } } }
/** * Fetch data from LDAP server * * Searches the LDAP server for the given username/password * combination. Escapes all LDAP meta characters in username * before performing the query. * * @param string Username * @param string Password * @return boolean */ function fetchData($username, $password) { $this->log('Auth_Container_LDAP::fetchData() called.', AUTH_LOG_DEBUG); $err = $this->_prepare(); if ($err !== true) { return PEAR::raiseError($err->getMessage(), $err->getCode()); } $err = $this->_getBaseDN(); if ($err !== true) { return PEAR::raiseError($err->getMessage(), $err->getCode()); } // UTF8 Encode username for LDAPv3 if (@ldap_get_option($this->conn_id, LDAP_OPT_PROTOCOL_VERSION, $ver) && $ver == 3) { $this->log('UTF8 encoding username for LDAPv3', AUTH_LOG_DEBUG); $username = utf8_encode($username); } // make search filter $filter = sprintf('(&(%s=%s)%s)', $this->options['userattr'], $this->_quoteFilterString($username), $this->options['userfilter']); // make search base dn $search_basedn = $this->options['userdn']; if ($search_basedn != '' && substr($search_basedn, -1) != ',') { $search_basedn .= ','; } $search_basedn .= $this->options['basedn']; // attributes $searchAttributes = $this->options['attributes']; // make functions params array $func_params = array($this->conn_id, $search_basedn, $filter, $searchAttributes); // search function to use $func_name = $this->_scope2function($this->options['userscope']); $this->log("Searching with {$func_name} and filter {$filter} in {$search_basedn}", AUTH_LOG_DEBUG); // search if (($result_id = @call_user_func_array($func_name, $func_params)) === false) { $this->log('User not found', AUTH_LOG_DEBUG); } elseif (@ldap_count_entries($this->conn_id, $result_id) >= 1) { // did we get some possible results? $this->log('User(s) found', AUTH_LOG_DEBUG); $first = true; $entry_id = null; do { // then get the user dn if ($first) { $entry_id = @ldap_first_entry($this->conn_id, $result_id); $first = false; } else { $entry_id = @ldap_next_entry($this->conn_id, $entry_id); if ($entry_id === false) { break; } } $user_dn = @ldap_get_dn($this->conn_id, $entry_id); // as the dn is not fetched as an attribute, we save it anyway if (is_array($searchAttributes) && in_array('dn', $searchAttributes)) { $this->log('Saving DN to AuthData', AUTH_LOG_DEBUG); $this->_auth_obj->setAuthData('dn', $user_dn); } // fetch attributes if ($attributes = @ldap_get_attributes($this->conn_id, $entry_id)) { if (is_array($attributes) && isset($attributes['count']) && $attributes['count'] > 0) { // ldap_get_attributes() returns a specific multi dimensional array // format containing all the attributes and where each array starts // with a 'count' element providing the number of attributes in the // entry, or the number of values for attribute. For compatibility // reasons, it remains the default format returned by LDAP container // setAuthData(). // The code below optionally returns attributes in another format, // more compliant with other Auth containers, where each attribute // element are directly set in the 'authData' list. This option is // enabled by setting 'attrformat' to // 'AUTH' in the 'options' array. // eg. $this->options['attrformat'] = 'AUTH' if (strtoupper($this->options['attrformat']) == 'AUTH') { $this->log('Saving attributes to Auth data in AUTH format', AUTH_LOG_DEBUG); unset($attributes['count']); foreach ($attributes as $attributeName => $attributeValue) { if (is_int($attributeName)) { continue; } if (is_array($attributeValue) && isset($attributeValue['count'])) { unset($attributeValue['count']); } if (count($attributeValue) <= 1) { $attributeValue = $attributeValue[0]; } $this->log('Storing additional field: ' . $attributeName, AUTH_LOG_DEBUG); $this->_auth_obj->setAuthData($attributeName, $attributeValue); } } else { $this->log('Saving attributes to Auth data in LDAP format', AUTH_LOG_DEBUG); $this->_auth_obj->setAuthData('attributes', $attributes); } } } @ldap_free_result($result_id); // need to catch an empty password as openldap seems to return TRUE // if anonymous binding is allowed if ($password != "") { $this->log("Bind as {$user_dn}", AUTH_LOG_DEBUG); // try binding as this user with the supplied password if (@ldap_bind($this->conn_id, $user_dn, $password)) { $this->log('Bind successful', AUTH_LOG_DEBUG); // check group if appropiate if (strlen($this->options['group'])) { // decide whether memberattr value is a dn or the username $this->log('Checking group membership', AUTH_LOG_DEBUG); $return = $this->checkGroup($this->options['memberisdn'] ? $user_dn : $username); $this->_disconnect(); return $return; } else { $this->log('Authenticated', AUTH_LOG_DEBUG); $this->_disconnect(); return true; // user authenticated } // checkGroup } // bind } // non-empty password } while ($this->options['try_all'] == true); // interate through entries } // get results // default $this->log('NOT authenticated!', AUTH_LOG_DEBUG); $this->_disconnect(); return false; }
/** * Retrieve the immediate children DNs of the given $parentDn * * This method is used in recursive methods like {@see delete()} * or {@see copy()} * * @param string|Dn $parentDn * @throws Exception\LdapException * @return array of DNs */ protected function getChildrenDns($parentDn) { if ($parentDn instanceof Dn) { $parentDn = $parentDn->toString(); } $children = array(); ErrorHandler::start(E_WARNING); $search = ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn')); for ($entry = ldap_first_entry($this->getResource(), $search); $entry !== false; $entry = ldap_next_entry($this->getResource(), $entry)) { $childDn = ldap_get_dn($this->getResource(), $entry); if ($childDn === false) { ErrorHandler::stop(); throw new Exception\LdapException($this, 'getting dn'); } $children[] = $childDn; } ldap_free_result($search); ErrorHandler::stop(); return $children; }
/** * Get the next entry in the searchresult. * * This will return a valid Net_LDAP2_Entry object or false, so * you can use this method to easily iterate over the entries inside * a while loop. * * @return Net_LDAP2_Entry|false Reference to Net_LDAP2_Entry object or false */ public function &shiftEntry() { if ($this->count() == 0) { $false = false; return $false; } if (is_null($this->_entry)) { $this->_entry = @ldap_first_entry($this->_link, $this->_search); $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry); if ($entry instanceof Net_LDAP2_Error) { $entry = false; } } else { if (!($this->_entry = @ldap_next_entry($this->_link, $this->_entry))) { $false = false; return $false; } $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry); if ($entry instanceof Net_LDAP2_Error) { $entry = false; } } return $entry; }
/** * Recursively process the groups the given member distinguished name * belongs to, adding them to the already processed groups array. * * @param string $memberdn distinguished name to search * @param array reference &$membergroups array with already found * groups, where we'll put the newly found * groups. */ protected function ldap_find_user_groups_recursively($memberdn, &$membergroups) { $result = @ldap_read($this->ldapconnection, $memberdn, '(objectClass=*)', array($this->get_config('group_memberofattribute'))); if (!$result) { return; } if ($entry = ldap_first_entry($this->ldapconnection, $result)) { do { $attributes = ldap_get_attributes($this->ldapconnection, $entry); for ($j = 0; $j < $attributes['count']; $j++) { $groups = ldap_get_values_len($this->ldapconnection, $entry, $attributes[$j]); foreach ($groups as $key => $group) { if ($key === 'count') { // Skip the entries count continue; } if (!in_array($group, $membergroups)) { // Only push and recurse if we haven't 'seen' this group before // to prevent loops (MS Active Directory allows them!!). array_push($membergroups, $group); $this->ldap_find_user_groups_recursively($group, $membergroups); } } } } while ($entry = ldap_next_entry($this->ldapconnection, $entry)); } }