コード例 #1
2
ファイル: ldap.php プロジェクト: DarneoStudio/bitrix
 function _RootDSE($filtr)
 {
     $sr = ldap_read($this->conn, '', 'objectClass=*', array($filtr), 0);
     //$sr = ldap_read($this->conn, '', 'objectClass=*');
     $entry = ldap_first_entry($this->conn, $sr);
     $attributes = ldap_get_attributes($this->conn, $entry);
     $values = false;
     if ($attributes['count'] > 0) {
         $values = @ldap_get_values_len($this->conn, $entry, $filtr);
     }
     return $values;
 }
コード例 #2
0
ファイル: auth.php プロジェクト: BestianRU/AD-LDAP-Auth
function xldap_user_group_check($ldap, $userdn, $groupdn, $recurs_count = 16)
{
    if ($recurs_count <= 0) {
        return FALSE;
    }
    $attributes = array('memberof');
    $result = ldap_read($ldap, $userdn, '(objectclass=*)', $attributes);
    if ($result === FALSE) {
        return FALSE;
    }
    $entries = ldap_get_entries($ldap, $result);
    if ($entries['count'] <= 0) {
        return FALSE;
    }
    if (empty($entries[0]['memberof'])) {
        return FALSE;
    } else {
        for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
            if ($entries[0]['memberof'][$i] == $groupdn) {
                return TRUE;
            } else {
                if ($recurs_count > 1) {
                    if (xldap_user_group_check($ldap, $entries[0]['memberof'][$i], $groupdn, $recurs_count - 1)) {
                        return TRUE;
                    }
                }
            }
        }
    }
    return FALSE;
}
コード例 #3
0
ファイル: get_cn.php プロジェクト: rkulan007/tableau-portal
function get_ldap_cn($user, $debug = 0)
{
    try {
        if (!($ds = get_ldap_connection())) {
            throw new Exception('Unable to connect to LDAP Server');
        }
        $dn = "mail={$user}, o=com, dc=mozilla";
        //the object itself instead of the top search level as in ldap_search
        $filter = "(objectclass=inetOrgPerson)";
        // this command requires some filter
        $justthese = array("cn");
        //the attributes to pull, which is much more efficient than pulling all attributes if you don't do this
        if (!($sr = ldap_read($ds, $dn, $filter, $justthese))) {
            throw new Exception('Incorrect Username or filter');
        }
        if (!($entry = ldap_get_entries($ds, $sr))) {
            throw new Exception('Unable to find LDAP entry for ' . $user);
        }
        if ($debug != 0) {
            echo $entry[0]["cn"][0] . " is the name in LDAP for " . $user;
        }
        ldap_close($ds);
        return $entry[0]["cn"][0];
    } catch (Exception $e) {
        echo 'Oops! I countered the following error: ', $e->getMessage(), "\n";
    }
}
コード例 #4
0
ファイル: access.php プロジェクト: noci2012/owncloud
 /**
  * @brief reads a given attribute for an LDAP record identified by a DN
  * @param $dn the record in question
  * @param $attr the attribute that shall be retrieved
  * @returns the values in an array on success, false otherwise
  *
  * Reads an attribute from an LDAP entry
  */
 public function readAttribute($dn, $attr)
 {
     if (!$this->checkConnection()) {
         \OCP\Util::writeLog('user_ldap', 'No LDAP Connector assigned, access impossible for readAttribute.', \OCP\Util::WARN);
         return false;
     }
     $cr = $this->connection->getConnectionResource();
     if (!is_resource($cr)) {
         //LDAP not available
         \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
         return false;
     }
     $rr = @ldap_read($cr, $dn, 'objectClass=*', array($attr));
     if (!is_resource($rr)) {
         \OCP\Util::writeLog('user_ldap', 'readAttribute ' . $attr . ' failed for DN ' . $dn, \OCP\Util::DEBUG);
         //in case an error occurs , e.g. object does not exist
         return false;
     }
     $er = ldap_first_entry($cr, $rr);
     //LDAP attributes are not case sensitive
     $result = \OCP\Util::mb_array_change_key_case(ldap_get_attributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
     $attr = mb_strtolower($attr, 'UTF-8');
     if (isset($result[$attr]) && $result[$attr]['count'] > 0) {
         $values = array();
         for ($i = 0; $i < $result[$attr]['count']; $i++) {
             $values[] = $this->resemblesDN($attr) ? $this->sanitizeDN($result[$attr][$i]) : $result[$attr][$i];
         }
         return $values;
     }
     \OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, \OCP\Util::DEBUG);
     return false;
 }
コード例 #5
0
ファイル: user.inc.php プロジェクト: tmaex/useradmin
 public static function readUser($ldapconn, $dn)
 {
     $search = ldap_read($ldapconn, $dn, USER::FILTER_USERS, array("cn", "mail", "displayName", "sn", "givenName", "memberOf"));
     if (ldap_count_entries($ldapconn, $search) > 0) {
         $entry = ldap_first_entry($ldapconn, $search);
         return User::readFromLdapEntry($ldapconn, $entry);
     }
 }
コード例 #6
0
ファイル: LibLdap.php プロジェクト: dittertp/libldap
 /**
  * @param string $dn         the dn to read
  * @param string $filter     the filter
  * @param array  $attributes the attributes to be returned
  *
  * @return array
  * @throws \Exception
  */
 public function readEntry($dn, $filter, array $attributes)
 {
     $result = @ldap_read($this->connection, $dn, $filter, $attributes);
     if ($result === false) {
         throw new \Exception("invalid bla");
     }
     $entries = ldap_get_entries($this->connection, $result);
     return $entries;
 }
コード例 #7
0
ファイル: ldap.class.php プロジェクト: rokett/ldapHelper
 /**
  * Get Root DSE
  *
  * @param	array	Attributes to return.  By default all attributes will be returned
  * @return	array	Requested attributes
  */
 protected function getRootDse($attributes = null)
 {
     if ($attributes === null) {
         $result = ldap_read($this->connection, NULL, 'objectClass=*');
     } else {
         $result = ldap_read($this->connection, NULL, 'objectClass=*', $attributes);
     }
     $entries = ldap_get_entries($this->connection, $result);
     return $entries;
 }
コード例 #8
0
ファイル: ldap-functions.php プロジェクト: ddrmoscow/queXS
function ldap_search_withScope($ds, $basedn, $filter, $attrlist, $scope)
{
    if ($scope == "base") {
        $search = ldap_read($ds, $basedn, $filter, $attrlist);
    } elseif ($scope == "one") {
        $search = ldap_list($ds, $basedn, $filter, $attrlist);
    } elseif ($scope == "sub") {
        $search = ldap_search($ds, $basedn, $filter, $attrlist);
    }
    return $search;
}
コード例 #9
0
ファイル: OpenLdap.php プロジェクト: rajeshpillai/df-adldap
 /**
  * Reads all objects.
  *
  * @return array
  */
 public function getUserInfo()
 {
     if ($this->authenticated) {
         if (empty($this->userData)) {
             $rs = ldap_read($this->connection, $this->dn, "(objectclass=*)");
             $this->userData = ldap_get_entries($this->connection, $rs);
         }
         return $this->userData;
     }
     return [];
 }
コード例 #10
0
ファイル: access.php プロジェクト: CDN-Sparks/owncloud
 /**
  * @brief reads a given attribute for an LDAP record identified by a DN
  * @param $dn the record in question
  * @param $attr the attribute that shall be retrieved
  *        if empty, just check the record's existence
  * @returns an array of values on success or an empty
  *          array if $attr is empty, false otherwise
  *
  * Reads an attribute from an LDAP entry or check if entry exists
  */
 public function readAttribute($dn, $attr, $filter = 'objectClass=*')
 {
     if (!$this->checkConnection()) {
         \OCP\Util::writeLog('user_ldap', 'No LDAP Connector assigned, access impossible for readAttribute.', \OCP\Util::WARN);
         return false;
     }
     $cr = $this->connection->getConnectionResource();
     if (!is_resource($cr)) {
         //LDAP not available
         \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
         return false;
     }
     $dn = $this->DNasBaseParameter($dn);
     $rr = @ldap_read($cr, $dn, $filter, array($attr));
     if (!is_resource($rr)) {
         if (!empty($attr)) {
             //do not throw this message on userExists check, irritates
             \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
         }
         //in case an error occurs , e.g. object does not exist
         return false;
     }
     if (empty($attr)) {
         \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
         return array();
     }
     $er = ldap_first_entry($cr, $rr);
     if (!is_resource($er)) {
         //did not match the filter, return false
         return false;
     }
     //LDAP attributes are not case sensitive
     $result = \OCP\Util::mb_array_change_key_case(ldap_get_attributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
     $attr = mb_strtolower($attr, 'UTF-8');
     if (isset($result[$attr]) && $result[$attr]['count'] > 0) {
         $values = array();
         for ($i = 0; $i < $result[$attr]['count']; $i++) {
             if ($this->resemblesDN($attr)) {
                 $values[] = $this->sanitizeDN($result[$attr][$i]);
             } elseif (strtolower($attr) == 'objectguid' || strtolower($attr) == 'guid') {
                 $values[] = $this->convertObjectGUID2Str($result[$attr][$i]);
             } else {
                 $values[] = $result[$attr][$i];
             }
         }
         return $values;
     }
     \OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, \OCP\Util::DEBUG);
     return false;
 }
コード例 #11
0
ファイル: etape_ldap3.php プロジェクト: JLuc/SPIP
function install_etape_ldap3_dist()
{
    $adresse_ldap = _request('adresse_ldap');
    $login_ldap = _request('login_ldap');
    $pass_ldap = _request('pass_ldap');
    $port_ldap = _request('port_ldap');
    $base_ldap_text = defined('_INSTALL_BASE_LDAP') ? _INSTALL_BASE_LDAP : "ou=users, dc=mon-domaine, dc=com";
    echo install_debut_html('AUTO', ' onload="document.getElementById(\'suivant\').focus();return false;"');
    echo info_etape(_T('info_chemin_acces_1'), info_progression_etape(3, 'etape_ldap', 'install/')), _T('info_chemin_acces_2');
    $ldap_link = @ldap_connect("{$adresse_ldap}", "{$port_ldap}");
    if ($ldap_link) {
        @ldap_bind($ldap_link, "{$login_ldap}", "{$pass_ldap}");
        $result = @ldap_read($ldap_link, "", "objectclass=*", array("namingContexts"));
        $info = @ldap_get_entries($ldap_link, $result);
        @ldap_close($ldap_link);
    }
    $checked = false;
    $res = '';
    if (is_array($info) and $info["count"] > 0) {
        $res .= "<p>" . _T('info_selection_chemin_acces') . "</p>";
        $res .= "<ul>";
        $n = 0;
        for ($i = 0; $i < $info["count"]; $i++) {
            $names = $info[$i]["namingcontexts"];
            if (is_array($names)) {
                for ($j = 0; $j < $names["count"]; $j++) {
                    $n++;
                    $res .= "<li><input name=\"base_ldap\" value=\"" . spip_htmlspecialchars($names[$j]) . "\" type='radio' id='tab{$n}'";
                    if (!$checked) {
                        $res .= " checked=\"checked\"";
                        $checked = true;
                    }
                    $res .= " />";
                    $res .= "<label for='tab{$n}'>" . spip_htmlspecialchars($names[$j]) . "</label></li>\n";
                }
            }
        }
        $res .= "</ul>";
        $res .= _T('info_ou') . " ";
    }
    $res .= "<br />\n<input name=\"base_ldap\" value=\"\" type='radio' id='manuel'";
    if (!$checked) {
        $res .= " checked=\"checked\"";
        $checked = true;
    }
    $res .= " />" . "\n<label for='manuel'>" . _T('entree_chemin_acces') . "</label> " . "\n<fieldset>" . "<input type='text' name='base_ldap_text' class='text' value=\"{$base_ldap_text}\" size='40' />" . "\n</fieldset>" . "\n<input type='hidden' name='etape' value='ldap4' />" . install_propager(array('adresse_ldap', 'port_ldap', 'login_ldap', 'pass_ldap', 'protocole_ldap', 'tls_ldap')) . bouton_suivant();
    echo generer_form_ecrire('install', $res);
    echo install_fin_html();
}
コード例 #12
0
 public function ReadEntry($dn, $attribs)
 {
     //foreach($attribs as &$attrib)
     //	$attrib = strtolower($attrib);
     $filter = '(objectclass=*)';
     $sr = ldap_read($this->con, $dn, $filter, $attribs);
     if ($sr === false) {
         return false;
     }
     $entry = ldap_get_entries($this->con, $sr);
     if ($entry === false) {
         return false;
     }
     return $entry;
 }
コード例 #13
0
 public function getUserAttributes()
 {
     $fname_tag = qa_opt('ldap_login_fname');
     $sname_tag = qa_opt('ldap_login_sname');
     $mail_tag = qa_opt('ldap_login_mail');
     $filter = qa_opt('ldap_login_filter');
     $attributes = array('dn', $fname_tag, $sname_tag, $mail_tag);
     // The DN is known so just use it to read attributes
     $read = ldap_read($this->con, $this->dn, $filter, $attributes);
     $data = ldap_get_entries($this->con, $read);
     $fname = $data[0][strtolower($fname_tag)][0];
     $sname = $data[0][strtolower($sname_tag)][0];
     $mail = $data[0][strtolower($mail_tag)][0];
     return array($fname, $sname, $mail, $this->authenticatedUser);
 }
コード例 #14
0
ファイル: ldap.php プロジェクト: btalayminaei/DGSecurity
 public function read($dn = NULL)
 {
     $dn = $dn ? $dn : $this->dn;
     # default to self
     $attrs = array('givenname', 'surname', 'displayname', 'title', 'mail', 'mobile', 'telephonenumber', 'uid');
     $result = ldap_read($this->conn, $dn, $this->filter, $attrs);
     if (!$result) {
         throw new LDAPAuthError();
     }
     $entries = ldap_get_entries($this->conn, $result);
     if ($entries === false) {
         throw new LDAPAuthError();
     }
     return $this->flatten($entries[0]);
 }
コード例 #15
0
 private function getUserAttributesByDn($userDn)
 {
     $query = @ldap_read($this->ldapConnection, $userDn, "(objectClass=*)", array_values($this->config->s('LdapVootStorage')->s('attributeMapping')->toArray()));
     if (false === $query) {
         throw new VootStorageException("ldap_error", "directory query for user failed");
     }
     $entry = @ldap_first_entry($this->ldapConnection, $query);
     if (false === $entry) {
         throw new VootStorageException("not_found", "user not found");
     }
     $attributes = @ldap_get_attributes($this->ldapConnection, $entry);
     if (false === $attributes) {
         throw new VootStorageException("ldap_error", "unable to get user attributes");
     }
     $filteredAttributes = $this->filterAttributes($attributes);
     return $filteredAttributes;
 }
コード例 #16
0
ファイル: CatalogAdapter.php プロジェクト: cjvaz/expressomail
 protected function getUserLdapPhoto($contactID)
 {
     $ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
     $justthese = array("dn", 'jpegPhoto', 'givenName', 'sn');
     $this->getLdapCatalog()->ldapConnect(true);
     $ds = $this->getLdapCatalog()->ds;
     if ($ds) {
         $resource = @ldap_read($ds, $contactID, "phpgwaccounttype=u");
         $n_entries = @ldap_count_entries($ds, $resource);
         if ($n_entries == 1) {
             $first_entry = ldap_first_entry($ds, $resource);
             $obj = ldap_get_attributes($ds, $first_entry);
             if ($obj['jpegPhoto']) {
                 return ldap_get_values_len($ds, $first_entry, "jpegPhoto");
             }
         }
     }
     return false;
 }
コード例 #17
0
ファイル: group.inc.php プロジェクト: tmaex/useradmin
 public function loadUsers()
 {
     $search = ldap_read($this->ldapconn, $this->dn, Group::FILTER_GROUPS, array("member"));
     if (ldap_count_entries($this->ldapconn, $search) > 0) {
         $entry = ldap_first_entry($this->ldapconn, $search);
         $att = ldap_get_attributes($this->ldapconn, $entry);
         if (isset($att['member'])) {
             $this->members = [];
             for ($i = 0; $i < $att['member']['count']; $i++) {
                 $dn = $att['member'][$i];
                 if ($dn != DUMMY_USER_DN) {
                     $this->members[] = User::readUser($this->ldapconn, $dn);
                 }
             }
         } else {
             $this->members = [];
         }
     }
 }
コード例 #18
0
ファイル: Duser_ldap.php プロジェクト: Anon215/filebin
 public function login($username, $password)
 {
     $CI =& get_instance();
     $config = $CI->config->item("auth_ldap");
     if ($username == "" || $password == "") {
         return false;
     }
     $ds = ldap_connect($config['host'], $config['port']);
     if ($ds === false) {
         return false;
     }
     switch ($config["scope"]) {
         case "base":
             $r = ldap_read($ds, $config['basedn'], $config["username_field"] . '=' . $username);
             break;
         case "one":
             $r = ldap_list($ds, $config['basedn'], $config["username_field"] . '=' . $username);
             break;
         case "subtree":
             $r = ldap_search($ds, $config['basedn'], $config["username_field"] . '=' . $username);
             break;
         default:
             throw new \exceptions\ApiException("libraries/duser/ldap/invalid-ldap-scope", "Invalid LDAP scope");
     }
     if ($r === false) {
         return false;
     }
     foreach ($config["options"] as $key => $value) {
         if (ldap_set_option($ds, $key, $value) === false) {
             return false;
         }
     }
     $result = ldap_get_entries($ds, $r);
     if ($result === false || !isset($result[0])) {
         return false;
     }
     // ignore errors from ldap_bind as it will throw an error if the password is incorrect
     if (@ldap_bind($ds, $result[0]['dn'], $password)) {
         ldap_unbind($ds);
         return array("username" => $result[0][$config["username_field"]][0], "userid" => $result[0][$config["userid_field"]][0]);
     }
     return false;
 }
コード例 #19
0
 protected function retrieveResponse()
 {
     $response = $this->initResponse();
     $response->setCode($this->errorNo);
     $response->setResponseError($this->errorMsg);
     if (!$this->filter) {
         return $response;
     }
     $ds = $this->connectToServer();
     if (!$ds) {
         $response->setResponseError("Could not connect to LDAP server");
         return $response;
     }
     if ($this->adminDN) {
         if (!ldap_bind($ds, $this->adminDN, $this->adminPassword)) {
             Kurogo::log(LOG_WARNING, "Error binding to LDAP Server {$this->host} for {$this->adminDN}: " . ldap_error($ds), 'data');
             $response->setResponseError("Could not connect to LDAP server");
             return $response;
         }
     }
     // suppress warnings on non-dev servers
     // about searches that go over the result limit
     if (!$this->debugMode) {
         $error_reporting = ini_get('error_reporting');
         error_reporting($error_reporting & ~E_WARNING);
     }
     if ($this->filter instanceof LDAPFilter) {
         $result = @ldap_search($ds, $this->searchBase, strval($this->filter), $this->getAttributes(), 0, 0, $this->searchTimelimit);
     } else {
         $result = @ldap_read($ds, $this->filter, "(objectclass=*)", $this->getAttributes(), 0, 0, $this->readTimelimit);
     }
     $error_code = ldap_errno($ds);
     $response->setResponse($result);
     $response->setCode($error_code);
     $response->setContext('ldap', $ds);
     if ($error_code) {
         $response->setResponseError($this->generateErrorMessage($error_code));
     }
     if (!$this->debugMode) {
         error_reporting($error_reporting);
     }
     return $response;
 }
コード例 #20
0
ファイル: libldap.php プロジェクト: pl0o0f/nedi-puppet
/**
 * Function that try to load from LDAP the user information...
 *
 * @param $ldap_connection ldap connection descriptor
 * @param $ldap_method LDAP method
 * @param $userdn Basedn of the user
 * @param $login User Login
 */
function getFromLDAP($ldap_connection, $userdn, $login)
{
    global $fields, $ldapsrv, $ldapmap;
    if ($ldap_connection) {
        $fields = array('ldap_login' => $ldapsrv[5], 'ldap_field_email' => $ldapmap[6], 'ldap_field_realname' => 'sn', 'ldap_field_firstname' => 'givenname', 'ldap_field_phone' => $ldapmap[7], 'ldap_field_title' => 'title');
        $fields = array_filter($fields);
        $f = array_values($fields);
        $sr = @ldap_read($ldap_connection, $userdn, "objectClass=*", $f);
        $v = ldap_get_entries($ldap_connection, $sr);
        if (!is_array($v) || count($v) == 0) {
            return false;
        }
        foreach ($fields as $k => $e) {
            if (empty($v[0][$e][0])) {
                switch ($k) {
                    case "title":
                    case "type":
                    default:
                        $fields[$k] = "";
                        //	break;
                }
            } else {
                switch ($k) {
                    case "language":
                    case "title":
                    case "type":
                    default:
                        if (!empty($v[0][$e][0])) {
                            $fields[$k] = addslashes($v[0][$e][0]);
                        } else {
                            $fields[$k] = "";
                            //	    break;
                        }
                }
            }
            $stringData = "Field {$fields[$k]} = ({$v['0']}[{$e}][0]\n";
            fwrite($fh, $stringData);
        }
        return true;
    }
    return false;
}
コード例 #21
0
ファイル: Manager.php プロジェクト: mangati/php-ldap
 /**
  * Get the LDAP entry by DN
  * @param  string $dn
  * @param  array  $attributes
  * @return Entry
  */
 public function get($dn, array $attributes = [])
 {
     $this->checkConnection();
     $resource = $this->conn->getResource();
     $filter = "(objectclass=*)";
     $search = @ldap_read($resource, $dn, $filter, $attributes);
     if ($search === false) {
         ErrorHandler::throwException($this->conn);
     }
     $result = @ldap_get_entries($resource, $search);
     if ($result === false) {
         ErrorHandler::throwException($this->conn);
     }
     $entry = null;
     if ($result['count'] > 0) {
         $row = $result[0];
         $entry = $this->parseArray($row);
     }
     return $entry;
 }
コード例 #22
0
 /**
  * Validates a username and password over ldap
  *
  * @param string $username
  * @param string $password
  * @return bool
  */
 public function validateUserPassExternal($username, $password)
 {
     /* create ldap connection */
     $conn = ldap_connect(BAIKAL_DAV_LDAP_URI);
     if (!$conn) {
         return false;
     }
     if (!ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3)) {
         return false;
     }
     /* bind with user 
      * error_handler have to change, because a failed bind raises an error
      * this raise a secuity issue because in the stack trace is the password of user readable
      */
     $arr = explode('@', $username, 2);
     $dn = str_replace('%n', $username, BAIKAL_DAV_LDAP_DN_TEMPLATE);
     $dn = str_replace('%u', $arr[0], $dn);
     if (isset($arr[1])) {
         $dn = str_replace('%d', $arr[1], $dn);
     }
     set_error_handler("\\Baikal\\Core\\LDAPUserBindAuth::exception_error_handler");
     $bind = ldap_bind($conn, $dn, $password);
     restore_error_handler();
     if (!$bind) {
         ldap_close($conn);
         return false;
     }
     /* read displayname and email from user */
     $this->accountValues = array();
     $sr = ldap_read($conn, $dn, '(objectclass=*)', array(BAIKAL_DAV_LDAP_DISPLAYNAME_ATTR, BAIKAL_DAV_LDAP_EMAIL_ATTR));
     $entry = ldap_get_entries($conn, $sr);
     if (isset($entry[0][BAIKAL_DAV_LDAP_DISPLAYNAME_ATTR][0])) {
         $this->accountValues['displayname'] = $entry[0][BAIKAL_DAV_LDAP_DISPLAYNAME_ATTR][0];
     }
     if (isset($entry[0][BAIKAL_DAV_LDAP_EMAIL_ATTR][0])) {
         $this->accountValues['email'] = $entry[0][BAIKAL_DAV_LDAP_EMAIL_ATTR][0];
     }
     /* close */
     ldap_close($conn);
     return true;
 }
コード例 #23
0
ファイル: Ldap.php プロジェクト: glial/glial
 public function checkGroupEx($ad, $userdn, $groupdn)
 {
     $attributes = array('memberof');
     $result = ldap_read($ad, $userdn, '(objectclass=*)', $attributes);
     if ($result === FALSE) {
         return FALSE;
     }
     $entries = ldap_get_entries($ad, $result);
     if ($entries['count'] <= 0) {
         return FALSE;
     }
     if (empty($entries[0]['memberof'])) {
         return FALSE;
     } else {
         for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
             if ($entries[0]['memberof'][$i] == $groupdn) {
                 return TRUE;
             } elseif (self::checkGroupEx($ad, $entries[0]['memberof'][$i], $groupdn)) {
                 return TRUE;
             }
         }
     }
     return FALSE;
 }
コード例 #24
0
ファイル: Ldap.php プロジェクト: jpbender/mage_virtual
 /**
  * A global LDAP search routine for finding information.
  *
  * Options can be either passed as single parameters according to the
  * method signature or as an array with one or more of the following keys
  * - filter
  * - baseDn
  * - scope
  * - attributes
  * - sort
  * - collectionClass
  *
  * @param  string|Zend_Ldap_Filter_Abstract|array $filter
  * @param  string|Zend_Ldap_Dn|null               $basedn
  * @param  integer                                $scope
  * @param  array                                  $attributes
  * @param  string|null                            $sort
  * @param  string|null                            $collectionClass
  * @return Zend_Ldap_Collection
  * @throws Zend_Ldap_Exception
  */
 public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array(), $sort = null, $collectionClass = null)
 {
     if (is_array($filter)) {
         $options = array_change_key_case($filter, CASE_LOWER);
         foreach ($options as $key => $value) {
             switch ($key) {
                 case 'filter':
                 case 'basedn':
                 case 'scope':
                 case 'sort':
                     ${$key} = $value;
                     break;
                 case 'attributes':
                     if (is_array($value)) {
                         $attributes = $value;
                     }
                     break;
                 case 'collectionclass':
                     $collectionClass = $value;
                     break;
             }
         }
     }
     if ($basedn === null) {
         $basedn = $this->getBaseDn();
     } else {
         if ($basedn instanceof Zend_Ldap_Dn) {
             $basedn = $basedn->toString();
         }
     }
     if ($filter instanceof Zend_Ldap_Filter_Abstract) {
         $filter = $filter->toString();
     }
     switch ($scope) {
         case self::SEARCH_SCOPE_ONE:
             $search = @ldap_list($this->getResource(), $basedn, $filter, $attributes);
             break;
         case self::SEARCH_SCOPE_BASE:
             $search = @ldap_read($this->getResource(), $basedn, $filter, $attributes);
             break;
         case self::SEARCH_SCOPE_SUB:
         default:
             $search = @ldap_search($this->getResource(), $basedn, $filter, $attributes);
             break;
     }
     if ($search === false) {
         /**
          * @see Zend_Ldap_Exception
          */
         #require_once 'Zend/Ldap/Exception.php';
         throw new Zend_Ldap_Exception($this, 'searching: ' . $filter);
     }
     if (!is_null($sort) && is_string($sort)) {
         $isSorted = @ldap_sort($this->getResource(), $search, $sort);
         if ($isSorted === false) {
             /**
              * @see Zend_Ldap_Exception
              */
             #require_once 'Zend/Ldap/Exception.php';
             throw new Zend_Ldap_Exception($this, 'sorting: ' . $sort);
         }
     }
     /**
      * Zend_Ldap_Collection_Iterator_Default
      */
     #require_once 'Zend/Ldap/Collection/Iterator/Default.php';
     $iterator = new Zend_Ldap_Collection_Iterator_Default($this, $search);
     return $this->_createCollection($iterator, $collectionClass);
 }
コード例 #25
0
<?php

/* 
 * server_info.php
 * Fetches and displays all information that it can from the specified server
 * 
 * Variables that come in as GET vars:
 *  - server_id
 */
require 'common.php';
$server_id = $_GET['server_id'];
$server_name = $servers[$server_id]['name'];
$ds = pla_ldap_connect($server_id) or pla_error("Could not connect or authenticate to LDAP server");
$r = @ldap_read($ds, '', 'objectClass=*', array('+'));
if (!$r) {
    pla_error("Could not fetch any information from the server");
}
$entry = @ldap_first_entry($ds, $r);
$attrs = @ldap_get_attributes($ds, $entry);
$count = @ldap_count_entries($ds, $r);
//echo "<pre>"; print_r( $attrs ); echo "</pre>";
include 'header.php';
?>

<h3 class="title">Server info for <?php 
echo htmlspecialchars($server_name);
?>
</h3>
<h3 class="subtitle">Server reports the following information about itself</h3>

<?php 
コード例 #26
0
ファイル: LDAP.php プロジェクト: danielkjfrog/docker
 /**
  * Search a given DN for attributes, and return the resulting associative
  * array.
  *
  * @param string $dn
  * The DN of an element.
  * @param string|array $attributes
  * The names of the attribute(s) to retrieve. Defaults to NULL; that is,
  * all available attributes. Note that this is not very effective.
  * @param int $maxsize
  * The maximum size of any attribute's value(s). If exceeded, the attribute
  * will not be returned.
  * @return array
  * The array of attributes and their values.
  * @see http://no.php.net/manual/en/function.ldap-read.php
  */
 public function getAttributes($dn, $attributes = NULL, $maxsize = NULL)
 {
     // Preparations, including a pretty debug message...
     $description = 'all attributes';
     if (is_array($attributes)) {
         $description = '\'' . join(',', $attributes) . '\'';
     } else {
         // Get all attributes...
         // TODO: Verify that this originally was the intended behaviour. Could $attributes be a string?
         $attributes = array();
     }
     SimpleSAML_Logger::debug('Library - LDAP getAttributes(): Getting ' . $description . ' from DN \'' . $dn . '\'');
     // Attempt to get attributes.
     // TODO: Should aliases be dereferenced?
     $result = @ldap_read($this->ldap, $dn, 'objectClass=*', $attributes, 0, 0, $this->timeout);
     if ($result === false) {
         throw $this->makeException('Library - LDAP getAttributes(): Failed to get attributes from DN \'' . $dn . '\'');
     }
     $entry = @ldap_first_entry($this->ldap, $result);
     if ($entry === false) {
         throw $this->makeException('Library - LDAP getAttributes(): Could not get first entry from DN \'' . $dn . '\'');
     }
     $attributes = @ldap_get_attributes($this->ldap, $entry);
     // Recycling $attributes... Possibly bad practice.
     if ($attributes === false) {
         throw $this->makeException('Library - LDAP getAttributes(): Could not get attributes of first entry from DN \'' . $dn . '\'');
     }
     // Parsing each found attribute into our result set.
     $result = array();
     // Recycling $result... Possibly bad practice.
     for ($i = 0; $i < $attributes['count']; $i++) {
         // Ignore attributes that exceed the maximum allowed size.
         $name = $attributes[$i];
         $attribute = $attributes[$name];
         // Deciding whether to base64 encode.
         $values = array();
         for ($j = 0; $j < $attribute['count']; $j++) {
             $value = $attribute[$j];
             if (!empty($maxsize) && strlen($value) >= $maxsize) {
                 // Ignoring and warning.
                 SimpleSAML_Logger::warning('Library - LDAP getAttributes(): Attribute \'' . $name . '\' exceeded maximum allowed size by ' + ($maxsize - strlen($value)));
                 continue;
             }
             // Base64 encode jpegPhoto.
             if (strtolower($name) === 'jpegphoto') {
                 $values[] = base64_encode($value);
             } else {
                 $values[] = $value;
             }
         }
         // Adding.
         $result[$name] = $values;
     }
     // We're done.
     SimpleSAML_Logger::debug('Library - LDAP getAttributes(): Found attributes \'(' . join(',', array_keys($result)) . ')\'');
     return $result;
 }
コード例 #27
0
ファイル: ldap.php プロジェクト: WineWorld/joomlatrialcmbg
 /**
  * Read all or specified attributes of given dn
  *
  * @param   string  $dn  The DN of the object you want to read
  *
  * @return  mixed  array of attributes or -1 on error
  *
  * @since   12.1
  */
 public function read($dn)
 {
     $base = substr($dn, strpos($dn, ',') + 1);
     $cn = substr($dn, 0, strpos($dn, ','));
     $result = @ldap_read($this->_resource, $base, $cn);
     if ($result) {
         return @ldap_get_entries($this->_resource, $result);
     } else {
         return $result;
     }
 }
コード例 #28
0
ファイル: user.class.php プロジェクト: geldarr/hack-space
 /**
  * Function that try to load from LDAP the user information...
  *
  * @param $ldap_connection          ldap connection descriptor
  * @param $ldap_method              LDAP method
  * @param $userdn                   Basedn of the user
  * @param $login                    User Login
  * @param $import          boolean  true for import, false for update (true by default)
  *
  * @return boolean : true if found / false if not founded
  **/
 function getFromLDAP($ldap_connection, $ldap_method, $userdn, $login, $import = true)
 {
     global $DB, $CFG_GLPI;
     // we prevent some delay...
     if (empty($ldap_method["host"])) {
         return false;
     }
     if ($ldap_connection) {
         //Set all the search fields
         $this->fields['password'] = "";
         $fields = AuthLDAP::getSyncFields($ldap_method);
         //Hook to allow plugin to request more attributes from ldap
         $fields = Plugin::doHookFunction("retrieve_more_field_from_ldap", $fields);
         $fields = array_filter($fields);
         $f = array_values($fields);
         $sr = @ldap_read($ldap_connection, $userdn, "objectClass=*", $f);
         $v = AuthLDAP::get_entries_clean($ldap_connection, $sr);
         if (!is_array($v) || count($v) == 0 || empty($v[0][$fields['name']][0])) {
             return false;
         }
         //Store user's dn
         $this->fields['user_dn'] = addslashes($userdn);
         //Store date_sync
         $this->fields['date_sync'] = $_SESSION['glpi_currenttime'];
         // Empty array to ensure than syncDynamicEmails will be done
         $this->fields["_emails"] = array();
         foreach ($fields as $k => $e) {
             if (empty($v[0][$e][0])) {
                 switch ($k) {
                     case "language":
                         // Not set value : managed but user class
                         break;
                     case "usertitles_id":
                     case "usercategories_id":
                         $this->fields[$k] = 0;
                         break;
                     default:
                         $this->fields[$k] = "";
                 }
             } else {
                 switch ($k) {
                     case "email1":
                     case "email2":
                     case "email3":
                     case "email4":
                         // Manage multivaluable fields
                         if (!empty($v[0][$e])) {
                             foreach ($v[0][$e] as $km => $m) {
                                 if (!preg_match('/count/', $km)) {
                                     $this->fields["_emails"][] = addslashes($m);
                                 }
                             }
                             // Only get them once if duplicated
                             $this->fields["_emails"] = array_unique($this->fields["_emails"]);
                         }
                         break;
                     case "language":
                         $language = Config::getLanguage($v[0][$e][0]);
                         if ($language != '') {
                             $this->fields[$k] = $language;
                         }
                         break;
                     case "usertitles_id":
                         $this->fields[$k] = Dropdown::importExternal('UserTitle', addslashes($v[0][$e][0]));
                         break;
                     case "usercategories_id":
                         $this->fields[$k] = Dropdown::importExternal('UserCategory', addslashes($v[0][$e][0]));
                         break;
                     default:
                         if (!empty($v[0][$e][0])) {
                             $this->fields[$k] = addslashes($v[0][$e][0]);
                         } else {
                             $this->fields[$k] = "";
                         }
                 }
             }
         }
         // Empty array to ensure than syncLdapGroups will be done
         $this->fields["_groups"] = array();
         ///The groups are retrieved by looking into an ldap user object
         if ($ldap_method["group_search_type"] == 0 || $ldap_method["group_search_type"] == 2) {
             $this->getFromLDAPGroupVirtual($ldap_connection, $ldap_method, $userdn, $login);
         }
         ///The groups are retrived by looking into an ldap group object
         if ($ldap_method["group_search_type"] == 1 || $ldap_method["group_search_type"] == 2) {
             $this->getFromLDAPGroupDiscret($ldap_connection, $ldap_method, $userdn, $login);
         }
         ///Only process rules if working on the master database
         if (!$DB->isSlave()) {
             //Instanciate the affectation's rule
             $rule = new RuleRightCollection();
             //Process affectation rules :
             //we don't care about the function's return because all
             //the datas are stored in session temporary
             if (isset($this->fields["_groups"])) {
                 $groups = $this->fields["_groups"];
             } else {
                 $groups = array();
             }
             $this->fields = $rule->processAllRules($groups, Toolbox::stripslashes_deep($this->fields), array('type' => 'LDAP', 'ldap_server' => $ldap_method["id"], 'connection' => $ldap_connection, 'userdn' => $userdn));
             $this->fields['_ruleright_process'] = true;
             //If rule  action is ignore import
             if ($import && isset($this->fields["_stop_import"])) {
                 return false;
             }
             //or no rights found & do not import users with no rights
             if ($import && !$CFG_GLPI["use_noright_users_add"]) {
                 $ok = false;
                 if (isset($this->fields["_ldap_rules"]) && count($this->fields["_ldap_rules"])) {
                     if (isset($this->fields["_ldap_rules"]["rules_entities_rights"]) && count($this->fields["_ldap_rules"]["rules_entities_rights"])) {
                         $ok = true;
                     }
                     if (!$ok) {
                         $entity_count = 0;
                         $right_count = 0;
                         if (Profile::getDefault()) {
                             $right_count++;
                         }
                         if (isset($this->fields["_ldap_rules"]["rules_entities"])) {
                             $entity_count += count($this->fields["_ldap_rules"]["rules_entities"]);
                         }
                         if (isset($this->input["_ldap_rules"]["rules_rights"])) {
                             $right_count += count($this->fields["_ldap_rules"]["rules_rights"]);
                         }
                         if ($entity_count && $right_count) {
                             $ok = true;
                         }
                     }
                 }
                 if (!$ok) {
                     $this->fields["_stop_import"] = true;
                     return false;
                 }
             }
             // Add ldap result to data send to the hook
             $this->fields['_ldap_result'] = $v;
             $this->fields['_ldap_conn'] = $ldap_connection;
             //Hook to retrieve more information for ldap
             $this->fields = Plugin::doHookFunction("retrieve_more_data_from_ldap", $this->fields);
             unset($this->fields['_ldap_result']);
         }
         return true;
     }
     return false;
 }
コード例 #29
0
 if ($etape == 2) {
     echo "<h2>" . $titre_ldap . "</h2>\n";
     echo "<h2>" . encode_message_utf8("Connexion à l'annuaire LDAP.") . "</h2>\n";
     // Connexion à l'annuaire
     $ds = grr_connect_ldap($adresse, $port, $login_ldap, $pwd_ldap, $use_tls);
     if ($ds) {
         $connexion_ok = 'yes';
     } else {
         $connexion_ok = 'no';
     }
     if ($connexion_ok == 'yes') {
         echo "<p>" . encode_message_utf8("<b>La connexion LDAP a réussi.</b></p>\n");
         echo "<form action=\"admin_config_ldap.php\" method=\"post\"><div>\n";
         // On lit toutes les infos (objectclass=*) dans le dossier
         // Retourne un identifiant de résultat ($result), ou bien FALSE en cas d'erreur.
         $result = ldap_read($ds, "", "objectclass=*", array("namingContexts"));
         $info = ldap_get_entries($ds, $result);
         // Retourne un tableau associatif multi-dimensionnel ou FALSE en cas d'erreur. :
         // $info["count"] = nombre d'entrées dans le résultat
         // $info[0] : sous-tableau renfermant les infos de la première entrée
         // $info[n]["dn"] : dn de la n-ième entrée du résultat
         // $info[n]["count"] : nombre d'attributs de la n-ième entrée
         // $info[n][m] : m-ième attribut de la n-ième entrée
         // info[n]["attribut"]["count"] : nombre de valeur de cet attribut pour la n-ième entrée
         // $info[n]["attribut"][m] : m-ième valeur de l'attribut pour la n-ième entrée
         $checked = false;
         if (is_array($info) && $info["count"] > 0) {
             echo encode_message_utf8("<p>Sélectionnez ci-dessous le chemin d'accès dans l'annuaire :</p>");
             $n = 0;
             for ($i = 0; $i < $info["count"]; $i++) {
                 $names[] = $info[$i]["dn"];
コード例 #30
0
 /**
  * Gets the indicated user details as well as the  role. worker function
  * @param string $username the user name
  * @oaram boolean $getRole Defaults to false
  * @param array $details of string.  The details we wish on the user.  Defaults to empty array
  * @returns array with indexed by the values of $details and values the corresponding detail
  */
 protected function _getUserInfo($username, $getRole = false, $details = array())
 {
     if (!$username || !($ldap = $this->getConnection())) {
         return false;
     }
     $return = array();
     $p_attrs = array();
     $p_attr_keys = array();
     //using array of keys b/c keys for attributes need to be numerically indeixed
     foreach ($details as $detail) {
         if (!array_key_exists($detail, $this->options['p_details'])) {
             continue;
         }
         $p_attrs[] = $this->options['p_details'][$detail];
         $p_attr_keys[] = $detail;
         $return[$detail] = null;
     }
     if (count($p_attrs) > 0 && ($r = @ldap_read($ldap, $this->getPeopleQry($username), 'cn=*', $p_attrs)) && ldap_count_entries($ldap, $r) == 1 && ($entry = @ldap_first_entry($ldap, $r))) {
         foreach ($p_attrs as $key => $attr) {
             $values = ldap_get_values($ldap, $entry, $attr);
             if (!is_array($values) || $values['count'] != 1) {
                 $return[$p_attr_keys[$key]] = null;
                 continue;
             }
             $return[$p_attr_keys[$key]] = $values[0];
         }
     }
     if ($getRole) {
         $return['role'] = null;
         if (($r = @ldap_list($ldap, $this->getRoleQry(), 'ou=' . self::ldap_escape($username), array('cn'))) && @ldap_count_entries($ldap, $r) == 1 && ($entry = @ldap_first_entry($ldap, $r))) {
             $values = ldap_get_values($ldap, $entry, 'cn');
             if ($values['count'] == 1) {
                 //sanity check
                 $return['role'] = $values[0];
             }
         }
     }
     return $return;
 }