示例#1
0
function ldap_call($connection, $bind_user, $bind_pass, $filter)
{
    $ds = ldap_connect($connection);
    //echo $connection . $bind_user . $bind_pass . $filter ;
    //personal e-mails
    if ($ds) {
        $r = ldap_bind($ds, $bind_user, $bind_pass);
        //$filter="(|(mail= null)(objectCategory=group))";
        $sr = ldap_search($ds, "ou=LMC, dc=lamontanita, dc=local", $filter);
        ldap_sort($ds, $sr, "cn");
        $info = ldap_get_entries($ds, $sr);
        //echo $info["count"] . " results returned:<p>";
        echo "<table id='ldaptable' border=1><tr><th>Name</th><th>E-mail</th></tr>";
        for ($i = 0; $i < $info["count"]; $i++) {
            if ($info[$i]["mail"][0] != null) {
                echo "<td>" . $info[$i]["cn"][0] . "</td>";
                echo "<td>" . $info[$i]["mail"][0] . "</td></tr>";
            }
        }
        echo "</table>";
        return $info;
        ldap_close($ds);
    } else {
        echo "<h4>LDAP_CALL unable to connect to LDAP server</h4>";
    }
}
示例#2
0
 /**
 * Get all mozComPerson's from LDAP where
 * isManager=TRUE AND employeetype!=DISABLED
 *
 * @return array in the form:
 * Array(
 *  [morgamic@mozilla.com] => Array
 (
 [cn] => Mike Morgan
 [title] => Director of Web Development
 [bugzilla_email] => morgamic@gmail.com
 )
 *  , ...
 * )
 */
 public function employee_list($type = 'all')
 {
     $this->bind_as_user();
     $manager_list = null;
     $search_filter = null;
     switch (strtolower($type)) {
         case 'manager':
             $search_filter = '(&(objectClass=mozComPerson)(isManager=TRUE)(!(employeetype=DISABLED)))';
             break;
         case 'all':
         default:
             $search_filter = '(&(objectClass=mozComPerson)(!(employeetype=DISABLED)))';
             break;
     }
     $manager_search = $this->ldap_search($search_filter, array("mail", "employeetype", "bugzillaEmail", "cn", "title"));
     if ($manager_search) {
         ldap_sort($this->ds(), $manager_search, 'cn');
         $manager_list = ldap_get_entries($this->ds(), $manager_search);
     } else {
         kohana::log('error', "LDAP search failed using [{$this->ds()}, {$this->base_dn}, " . "{$search_filter}]" . "LDAP error:[" . ldap_error($this->ds) . "]");
     }
     $manager_list = $this->flatten_ldap_results($manager_list);
     $cleaned_list = array();
     foreach ($manager_list as $manager) {
         // ensure keys to keep out of isset?:;
         $manager = array_merge(array('cn' => null, 'title' => null, 'mail' => null, 'bugzillaemail' => null), $manager);
         if (!empty($manager['mail'])) {
             $bugzilla_email = !empty($manager['bugzillaemail']) ? $manager['bugzillaemail'] : $manager['mail'];
             $cleaned_list[$manager['mail']] = array('cn' => $manager['cn'] ? $manager['cn'] : null, 'title' => $manager['title'] ? $manager['title'] : null, 'bugzilla_email' => $bugzilla_email);
         }
     }
     return $cleaned_list;
 }
示例#3
0
function change_pass($user, $new_pass)
{
    global $config;
    global $ldap_connection;
    get_ldap_connection($config['user'], $config['pass']);
    if ($ldap_connection) {
        $filter = "(sAMAccountName={$user})";
        $result = ldap_search($ldap_connection, $config['domain_dn'], $filter);
        ldap_sort($ldap_connection, $result, "sn");
        $info = ldap_get_entries($ldap_connection, $result);
        $isLocked = $info[0]["lockoutTime"];
        if ($isLocked > 0) {
            return msg('account_locked');
        }
        $userDn = $info[0]["distinguishedname"][0];
        $userdata["unicodePwd"] = iconv("UTF-8", "UTF-16LE", '"' . $new_pass . '"');
        $result = ldap_mod_replace($ldap_connection, $userDn, $userdata);
        if (!$result) {
            return msg(ldap_error($ldap_connection));
        }
    } else {
        return msg("wrong_admin");
    }
    close_ldap_connection();
    return "";
}
示例#4
0
文件: Ldap.php 项目: Jazzee/Jazzee
 /**
  * Parse the LDAP search results into a nice array
  *
  * @param resource $searchResult
  * @return array
  */
 protected function parseSearchResult($searchResult)
 {
     $result = array();
     ldap_sort($this->_directoryServer, $searchResult, $this->_controller->getConfig()->getLdapFirstNameAttribute());
     ldap_sort($this->_directoryServer, $searchResult, $this->_controller->getConfig()->getLdapLastNameAttribute());
     if (ldap_count_entries($this->_directoryServer, $searchResult)) {
         $entries = ldap_get_entries($this->_directoryServer, $searchResult);
         for ($i = 0; $i < $entries["count"]; $i++) {
             $arr = array('userName' => '', 'firstName' => '', 'lastName' => '', 'emailAddress' => '');
             if (!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapUsernameAttribute())][0])) {
                 $arr['userName'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapUsernameAttribute())][0];
             }
             if (!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapFirstNameAttribute())][0])) {
                 $arr['firstName'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapFirstNameAttribute())][0];
             }
             if (!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapLastNameAttribute())][0])) {
                 $arr['lastName'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapLastNameAttribute())][0];
             }
             if (!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapEmailAddressAttribute())][0])) {
                 $arr['emailAddress'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapEmailAddressAttribute())][0];
             }
             $result[] = $arr;
         }
     }
     return $result;
 }
示例#5
0
 public function query_users($filter, $base = '', $attributes = NULL)
 {
     $attributes = $attributes ? $attributes : $this->fields;
     $search = ldap_search($this->ldapconn, $base, $filter, $attributes);
     ldap_sort($this->ldapconn, $search, $this->conf["ldap_sort_order"] ? $this->conf["ldap_sort_order"] : "sn");
     return ldap_get_entries($this->ldapconn, $search);
 }
示例#6
0
function AssistedLDAPSearch($ldapc, $ldap_base, $search_string, $search_limit, $sort_string)
{
    // Searching...
    $search_result = ldap_search($ldapc, $ldap_base, $search_string, $search_limit);
    // Let's see if you could make it
    if (!$search_result) {
        echo '<div class="error">' . _("An error has ocurred while the system was performing a search: ") . ldap_error($ldapc) . '.<br /><br /><a href="javascript:history.back(1);">' . _("Back") . '</a></div>';
        include "../themes/{$app_theme}/footer.php";
        die;
    }
    // Sorting the result by cn
    $search_sort = ldap_sort($ldapc, $search_result, $sort_string);
    // Let's see if you could make it
    if (!$search_sort) {
        echo '<div class="error">' . _("There was an error organizing the LDAP search results: ") . ldap_error($ldapc) . '.<br /><br /><a href="javascript:history.back(1);">' . _("Back") . '</a></div>';
        include "../themes/{$app_theme}/footer.php";
        die;
    }
    // Getting the all the entries
    $search_entries = ldap_get_entries($ldapc, $search_result);
    // Let's see if you could make it
    if (!$search_entries) {
        echo '<div class="error">' . _("There was an error retrieving the LDAP search results: ") . ldap_error($ldapc) . '.<br /><br /><a href="javascript:history.back(1);">' . _("Back") . '</a></div>';
        include "../themes/{$app_theme}/footer.php";
        die;
    }
    return $search_entries;
}
示例#7
0
 public function sort($key)
 {
     if (ldap_sort($this->handler, $this->result, $key) === false) {
         throw new LdapException(sprintf("Error while sorting results on key '%s'.", $key), $this->handler);
     }
     return $this;
 }
示例#8
0
function query_users($ldapconn, $filter, $base = '', $attributes, $sort = null)
{
    $adapter = new MozillaSearchAdapter();
    $conf = $adapter->conf();
    $search = ldap_search($ldapconn, $base, $filter, $attributes);
    ldap_sort($ldapconn, $search, $sort || $conf["ldap_sort_order"] || "sn");
    return ldap_get_entries($ldapconn, $search);
}
示例#9
0
 public function getSearchEntries()
 {
     if ($this->ldapConnection && $this->searchResult && $this->maxEntriesToGet >= $this->numEntries) {
         ldap_sort($this->ldapConnection, $this->searchResult, 'sn');
         return ldap_get_entries($this->ldapConnection, $this->searchResult);
     } else {
         return false;
     }
 }
示例#10
0
 public function testAuth()
 {
     $adServer = "ldap://10.249.99.50:3268";
     $ldap = ldap_connect($adServer);
     $username = '******';
     //$_POST['username'];
     $password = '******';
     //$_POST['password'];
     echo " " . $username . " " . $password . "<br>";
     if ($username != "" && $password != "") {
         $ldaprdn = 'egat' . "\\" . $username;
         ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
         ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
         $bind = @ldap_bind($ldap, $ldaprdn, $password);
         if ($bind) {
             // session_start();
             $filter = "(sAMAccountName={$username})";
             $result = ldap_search($ldap, "dc=egat,dc=local", $filter);
             ldap_sort($ldap, $result, "sn");
             $info = ldap_get_entries($ldap, $result);
             Log::info("count->" . $info["count"]);
             $attributes = ['mail', 'cn', 'c', 'st', 'title', 'description', 'postofficebox', 'physicaldeliveryofficename', 'telephonenumber', 'distinguishedname', 'info', 'memberof', 'department', 'company'];
             for ($i = 0; $i < $info["count"]; $i++) {
                 if ($info['count'] > 1) {
                     break;
                 }
                 //  $userlogon= $info[$i]["givenname"][0] ." " . $info[$i]["sn"][0] ." (" . $info[$i]["samaccountname"][0] .")";
                 Log::info("givenname->" . $info[$i]["givenname"][0]);
                 //Log::info("sn->".$info[$i]["sn"][0]);
                 Log::info("samaccountname->" . $info[$i]["samaccountname"][0]);
                 for ($j = 0; $j < sizeof($attributes); $j++) {
                     Log::info($j + 1 . " [" . $attributes[$j] . "]->" . $info[$i][$attributes[$j]][0]);
                 }
                 //Log::info("givenname->".$info[$i]); // for show attributes
                 /*
                 $_SESSION['name']=$info[$i]["givenname"][0];
                 $_SESSION['sn']=$info[$i]["sn"][0];
                 $_SESSION['id']=$info[$i]["samaccountname"][0];
                 */
                 //echo '<pre>';
                 //var_dump($info);
                 // echo '</pre>';
                 //$userDn = $info[$i]["distinguishedname"][0];
                 //header( "location: index.php" );
                 // exit(0);
             }
             @ldap_close($ldap);
         } else {
             //  $userlogon="Invalid";
             //header( "location: index.php" );
         }
     } else {
         //$userlogon="Invalid";
         //header( "location: index.php" );
     }
 }
示例#11
0
 function findAll($attribute = 'uid', $value = '*', $baseDn = 'ou=People,dc=example,dc=com')
 {
     $r = ldap_search($this->ds, $baseDn, $attribute . '=' . $value);
     if ($r) {
         //if the result contains entries with surnames,
         //sort by surname:
         ldap_sort($this->ds, $r, "sn");
         return ldap_get_entries($this->ds, $r);
     }
 }
示例#12
0
 function findLargestUidNumber()
 {
     $r = ldap_search($this->ds, $this->baseDn, 'uidnumber=*');
     if ($r) {
         // there must be a better way to get the largest uidnumber, but I can't find a way to reverse sort.
         ldap_sort($this->ds, $r, "uidnumber");
         $result = ldap_get_entries($this->ds, $r);
         $count = $result['count'];
         $biguid = $result[$count - 1]['uidnumber'][0];
         return $biguid;
     }
     return null;
 }
示例#13
0
 /**
  * {@inheritdoc}
  */
 public function listUsers()
 {
     if (null === $this->ldapRes) {
         $this->connect();
     }
     $result = ldap_search($this->ldapRes, $this->baseDn, "(mail=*)", array("mail", "uid", "dn"));
     ldap_sort($this->ldapRes, $result, 'mail');
     $entries = ldap_get_entries($this->ldapRes, $result);
     $users = array();
     for ($i = 0; $i < $entries['count']; $i++) {
         $users[] = array('email' => $entries[$i]['mail'][0], 'username' => $entries[$i]['uid'][0]);
     }
     return $users;
 }
示例#14
0
 public function find($uri, $justthese = false, $criteria = false)
 {
     $map = Config::get($uri['concept'], 'OpenLDAP.mapping');
     if (!isset($criteria["limit"])) {
         $criteria["limit"] = $this->limit;
     }
     $sr = @ldap_search($this->con, $this->config['context'], self::parseCriteria($criteria, $map), self::parseJustthese($justthese, $map), 0, $criteria["limit"]);
     if (!$sr) {
         return false;
     }
     if (isset($criteria["order"])) {
         ldap_sort($this->con, $sr, $criteria["order"]);
     }
     return self::_formatEntries(ldap_get_entries($this->con, $sr), $map);
 }
示例#15
0
 private function getUser($user)
 {
     if (isset($this->dsPointer)) {
         $attributes = array('dn', 'givenName', 'sn', 'mail', 'samaccountname', 'memberof');
         $query = ldap_search($this->dsPointer, $this->baseDN, "(samaccountname=" . $user . ")", $attributes);
         if ($query) {
             ldap_sort($this->dsPointer, $query, 'sn');
             $result = ldap_get_entries($this->dsPointer, $query);
             return $result;
         } else {
             return null;
         }
     } else {
         return null;
     }
 }
示例#16
0
 /**
  * Perform an LDAP search. Mimics Cake's DBO behaviour
  *
  * @param $filters mixed
  * @param $attributes array List of attributes to return
  * @param $order string Attribute to order results by
  * @param $limit integer Maximum number of records to return
  * @param $deep boolean False to search only the BASE_DN level
  * @return array Returns an array of matches or FALSE if nothing is found
  */
 function findAll($filters = null, $attributes = array(), $order = null, $limit = 0, $deep = true)
 {
     $filter = is_array($filters) ? $this->conditionKeysToString($filters) : $filters;
     $function = $deep ? 'ldap_search' : 'ldap_list';
     $search = $function($this->ds, $this->base, $filter, $attributes, 0, $limit);
     if ($search) {
         if ($order) {
             ldap_sort($this->ds, $search, $order);
         }
         $entries = ldap_get_entries($this->ds, $search);
         $count = array_shift($entries);
         if ($count > 0) {
             return $entries;
         }
     }
     return false;
 }
示例#17
0
 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;
 }
示例#18
0
 /**
  * Generic LDAP search
  *
  * @author Alessandro De Zorzi <*****@*****.**>
  *
  * @todo add attrsonly, sizelimit, timelimit
  *
  * @param string $base_dn
  * @param string $filter
  * @param array $attributes
  * @return array $entries
  **/
 static function phamm_search($base_dn, $filter, $attributes = null, $sort = null)
 {
     global $connect;
     // Do a LDAP search
     if (isset($attributes)) {
         $search = ldap_search($connect, $base_dn, $filter, $attributes);
     } else {
         $search = ldap_search($connect, $base_dn, $filter);
     }
     // Order the results if possible
     if (version_compare(phpversion(), "4.2.0", ">=")) {
         ldap_sort($connect, $search, $sort);
     }
     // Get entries
     $entries = ldap_get_entries($connect, $search);
     // Free the memory
     ldap_free_result($search);
     // Return the entry
     return $entries;
 }
示例#19
0
function change_pass($username)
{
    global $LDAPHOST, $LDAPPORT, $ldap, $LDAPADMIN, $LDAPADMINPASS, $LDAPDATAFIELD, $LDAPLOCALDOMAIN, $LDAPDOMAIN;
    if ($ldap) {
        $bind = @ldap_bind($ldap, $LDAPADMIN . "@" . $LDAPLOCALDOMAIN, $LDAPADMINPASS);
        if (!$bind) {
            @ldap_close($ldap);
            die('<p class="message">Your password is incorrect, please try again 
            <a href=javascript:history.back()>click here</a><br>');
        }
        $filter = "(sAMAccountName={$username})";
        $results = ldap_search($ldap, $LDAPDOMAIN, $filter);
        ldap_sort($ldap, $results, "sn");
        $info = ldap_get_entries($ldap, $results);
        if ($info['count'] < 1) {
            @ldap_close($ldap);
            die('<p class="message">Error occurred, please verify your user , <a href="javascript:history.back()">Go Back</a>');
        }
        $dn = $info[0]["dn"];
        $stored_mail = $info[0][$LDAPDATAFIELD][0] or die('<p class="message">We could not get your info, please contact Support!');
        $newPassw = genPassword("xxx0yY0yY");
        $mailPass = $newPassw;
        $newPassword = "******"{$newPassw}\"";
        $len = strlen($newPassword);
        $newPass = "";
        for ($i = 0; $i < $len; $i++) {
            $newPass .= "{$newPassword[$i]}";
        }
        $newPassword = $newPass;
        $data_new["unicodePwd"][] = $newPassword;
        if (ldap_mod_replace($ldap, $dn, $data_new)) {
            return array(true, $stored_mail, $mailPass);
        } else {
            return array(false, 100, 100);
        }
        return array(true, $stored_mail, $mailPass);
    } else {
        return array(false, 0, 0);
    }
    // function
}
示例#20
0
 public function ValidarLDAP($user, $pass)
 {
     $adServer = "ldap://ad.ifxcorp.com/";
     $ldap = ldap_connect($adServer);
     $ldaprdn = 'ifxcorp' . "\\" . $user;
     ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
     $bind = @ldap_bind($ldap, $ldaprdn, $pass);
     if ($bind) {
         $filter = "(sAMAccountName={$user})";
         $result = ldap_search($ldap, "dc=ifxcorp,dc=com", $filter);
         ldap_sort($ldap, $result, "sn");
         $info = ldap_get_entries($ldap, $result);
         $validar_grupo = $this->ValidarGrupo($info);
         return $validar_grupo;
         @ldap_close($ldap);
     } else {
         return "ERROR_LOGIN";
     }
     return $info;
 }
示例#21
0
 protected function busqueda($base, $filtro, $atributos, $limite = 499, $ordenar = false)
 {
     try {
         if (!($busquedaLdap = ldap_search($this->conexionLdap, $base, $filtro, $atributos, 0, $limite))) {
             throw new ErrorException(ldap_error($this->conexionLdap));
         }
         if ($ordenar) {
             ldap_sort($this->conexionLdap, $busquedaLdap, $filtro[0]);
         }
         // La función muere en el momento que un throw es invocado. Así las cosas
         // TODO: Básicamente, debo quitar esto lo más pronto posible.
         // Esta operación a estas alturas no representa un error, pero si debe cortar muchas cosas
         if (!($datos = $this->iterarEntradas($busquedaLdap, $atributos))) {
             throw new ErrorException('La busqueda no devuelve entradas');
         }
         return $datos;
         // Hacemos la verdadera iteracion
     } catch (ErrorException $e) {
         $this->configurarErrorLdap('Error en búsqueda', $e->getMessage());
         return FALSE;
     }
 }
示例#22
0
function listeNomService()
{
    $ds = ldap_connect(LDAP_SERVEUR, LDAP_PORT) or die("error");
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    $FiltreSearch = "(&(objectclass=group)(SAMAccountName=Service*))";
    $justthese = array('samaccountName', 'cn');
    if ($ds) {
        // on s'authentifie en tant que super-utilisateur
        $r = ldap_bind($ds, LDAP_USER, LDAP_PASS);
        $sr = ldap_search($ds, LDAP_BASE_DN, $FiltreSearch, $justthese);
        ldap_sort($ds, $sr, "SAMAccountName");
        $infoLDAP = ldap_get_entries($ds, $sr);
        //echo ldap_count_entries($ds,$sr);
        $services = array();
        for ($i = 0; $i < ldap_count_entries($ds, $sr); $i++) {
            $services[] = $infoLDAP[$i]['cn'][0];
            //echo "<br>".$infoLDAP[$i]['cn'][0];
        }
        ldap_close($ds);
    } else {
        echo "Impossible de se connecter au serveur LDAP";
    }
    return $services;
}
示例#23
0
 /**
  * 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);
 }
示例#24
0
 /**
  * @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);
 }
示例#25
0
 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;
 }
示例#26
0
文件: Ldap.php 项目: Rovak/zf2
 /**
  * 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
  * - sizelimit
  * - timelimit
  *
  * @param  string|Filter\AbstractFilter|array $filter
  * @param  string|Dn|null                     $basedn
  * @param  integer                            $scope
  * @param  array                              $attributes
  * @param  string|null                        $sort
  * @param  string|null                        $collectionClass
  * @param  integer                            $sizelimit
  * @param  integer                            $timelimit
  * @return Collection
  * @throws Exception\LdapException
  */
 public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array(), $sort = null, $collectionClass = null, $sizelimit = 0, $timelimit = 0)
 {
     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;
                 case 'sizelimit':
                 case 'timelimit':
                     ${$key} = (int) $value;
                     break;
             }
         }
     }
     if ($basedn === null) {
         $basedn = $this->getBaseDn();
     } elseif ($basedn instanceof Dn) {
         $basedn = $basedn->toString();
     }
     if ($filter instanceof Filter\AbstractFilter) {
         $filter = $filter->toString();
     }
     $resource = $this->getResource();
     ErrorHandler::start(E_WARNING);
     switch ($scope) {
         case self::SEARCH_SCOPE_ONE:
             $search = ldap_list($resource, $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
             break;
         case self::SEARCH_SCOPE_BASE:
             $search = ldap_read($resource, $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
             break;
         case self::SEARCH_SCOPE_SUB:
         default:
             $search = ldap_search($resource, $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
             break;
     }
     ErrorHandler::stop();
     if ($search === false) {
         throw new Exception\LdapException($this, 'searching: ' . $filter);
     }
     if ($sort !== null && is_string($sort)) {
         ErrorHandler::start(E_WARNING);
         $isSorted = ldap_sort($this->getResource(), $search, $sort);
         ErrorHandler::stop();
         if ($isSorted === false) {
             throw new Exception\LdapException($this, 'sorting: ' . $sort);
         }
     }
     $iterator = new Collection\DefaultIterator($this, $search);
     return $this->createCollection($iterator, $collectionClass);
 }
示例#27
0
 public function getUserEntries($login = null, $countOnly = false, $offset = -1, $limit = -1, $regexpOnSearchAttr = false)
 {
     if ($login == null) {
         $filter = $this->ldapFilter;
     } else {
         if ($regexpOnSearchAttr && !empty($this->options["LDAP_SEARCHUSER_ATTR"])) {
             $searchAttr = $this->options["LDAP_SEARCHUSER_ATTR"];
             $searchAttrArray = explode(",", $searchAttr);
         }
         if (isset($searchAttrArray)) {
             if (count($searchAttrArray) > 1) {
                 $searchAttrFilter = "(|";
                 foreach ($searchAttrArray as $attr) {
                     $searchAttrFilter .= "(" . $attr . "=" . $login . ")";
                 }
                 $searchAttrFilter .= ")";
             } else {
                 $searchAttrFilter = "(" . $searchAttrArray[0] . "=" . $login . ")";
             }
         } else {
             $searchAttrFilter = "(" . $this->ldapUserAttr . "=" . $login . ")";
         }
         if ($this->ldapFilter == "") {
             $filter = $searchAttrFilter;
         } else {
             $filter = "(&" . $this->ldapFilter . $searchAttrFilter . ")";
         }
     }
     if (empty($filter)) {
         if (!empty($this->dynamicFilter)) {
             $filter = $this->dynamicFilter;
         } else {
             $filter = $this->ldapUserAttr . "=*";
         }
     } else {
         if (!empty($this->dynamicFilter)) {
             $filter = "(&(" . $this->dynamicFilter . ")" . $filter . ")";
         }
     }
     if ($this->ldapconn == null) {
         $this->startConnexion();
     }
     $conn = array();
     if (is_array($this->ldapDN)) {
         foreach ($this->ldapDN as $dn) {
             $conn[] = $this->ldapconn;
         }
     } else {
         $conn = array($this->ldapconn);
     }
     $expected = array($this->ldapUserAttr);
     if ($login != null && (!empty($this->customParamsMapping) || !empty($this->paramsMapping))) {
         if (!empty($this->customParamsMapping)) {
             $expected = array_merge($expected, array_keys($this->customParamsMapping));
         }
         if (!empty($this->paramsMapping)) {
             $keys = array();
             foreach ($this->paramsMapping as $param) {
                 $keys[] = $param["MAPPING_LDAP_PARAM"];
             }
             $expected = array_merge($expected, $keys);
         }
     }
     if (is_array($this->dynamicExpected)) {
         $expected = array_merge($expected, $this->dynamicExpected);
     }
     foreach ($conn as $dn => $ldapc) {
         if (!$ldapc) {
             unset($conn[$dn]);
         }
     }
     if (count($conn) < 1) {
         return array("count" => 0);
     }
     //$ret = ldap_search($conn,$this->ldapDN,$filter, $expected);
     $cookie = '';
     if (empty($this->pageSize) || !is_numeric($this->pageSize)) {
         $this->pageSize = 500;
     }
     $allEntries = array("count" => 0);
     $isSupportPagedResult = function_exists("ldap_control_paged_result") && function_exists("ldap_control_paged_result_response");
     $gotAllEntries = false;
     $index = 0;
     //Update progress bar in CLI mode
     $isListAll = $offset == -1 && $limit == -1 && is_null($login) && $regexpOnSearchAttr && php_sapi_name() == "cli";
     if ($isListAll) {
         $total = $this->getCountFromCache();
         $progressBar = new AJXP_ProgressBarCLI();
         $progressBar->init($index, $total["count"], "Get ldap users");
     }
     do {
         if ($isSupportPagedResult) {
             ldap_control_paged_result($this->ldapconn, $this->pageSize, false, $cookie);
         }
         $ret = ldap_search($conn, $this->ldapDN, $filter, $expected, 0, 0);
         if ($ret === false) {
             break;
         }
         foreach ($ret as $i => $resourceResult) {
             if ($resourceResult === false) {
                 continue;
             }
             if ($countOnly) {
                 $allEntries["count"] += ldap_count_entries($conn[$i], $resourceResult);
                 continue;
             }
             if ($limit != -1) {
                 //usort($entries, array($this, "userSortFunction"));
                 ldap_sort($conn[$i], $resourceResult, $this->ldapUserAttr);
             }
             $entries = ldap_get_entries($conn[$i], $resourceResult);
             // for better performance
             if (is_array($entries) && $offset != -1 && $limit != -1 && $index + $this->pageSize < $offset) {
                 $index += $this->pageSize;
                 continue;
             }
             if (!empty($entries["count"])) {
                 $allEntries["count"] += $entries["count"];
                 unset($entries["count"]);
                 foreach ($entries as $entry) {
                     if ($offset != -1 && $index < $offset) {
                         $index++;
                         continue;
                     }
                     // fake memberOf
                     if ($this->fakeAttrMemberOf && method_exists($this, "fakeMemberOf") && in_array(strtolower("memberof"), array_map("strtolower", $expected))) {
                         if ($this->attrMemberInGroup) {
                             $uid = $entry["dn"];
                         } else {
                             $uidWithEqual = explode(",", $entry["dn"]);
                             $uidShort = explode("=", $uidWithEqual[0]);
                             $uid = $uidShort[1];
                         }
                         $strldap = "(&" . $this->ldapGFilter . "(" . $this->fakeAttrMemberOf . "=" . $uid . "))";
                         $this->fakeMemberOf($conn, $this->ldapGDN, $strldap, array("cn"), $entry);
                     }
                     $allEntries[] = $entry;
                     $index++;
                     //Update progress bar in CLI mode
                     if (isset($progressBar)) {
                         $progressBar->update($index);
                     }
                     if ($offset != -1 && $limit != -1 && $index > $offset + $limit) {
                         break;
                     }
                 }
                 if ($index > $offset + $limit && $limit != -1 && $offset != -1) {
                     $gotAllEntries = true;
                 }
             }
         }
         if ($isSupportPagedResult) {
             foreach ($ret as $element) {
                 if (is_resource($element)) {
                     @ldap_control_paged_result_response($this->ldapconn, $element, $cookie);
                 }
             }
         }
     } while ($cookie !== null && $cookie != '' && $isSupportPagedResult && !$gotAllEntries);
     // reset paged_result for other activities (otherwise we will experience ldap error)
     if ($isSupportPagedResult) {
         ldap_control_paged_result($this->ldapconn, 0);
     }
     return $allEntries;
 }
示例#28
0
 /**
  * List the current set of contact records
  *
  * @param  array  List of cols to show
  * @param  int    Only return this number of records
  * @return array  Indexed list of contact records, each a hash array
  */
 function list_records($cols = null, $subset = 0)
 {
     // add general filter to query
     if (!empty($this->prop['filter']) && empty($this->filter)) {
         $filter = $this->prop['filter'];
         $this->set_search_set($filter);
     }
     // exec LDAP search if no result resource is stored
     if ($this->conn && !$this->ldap_result) {
         $this->_exec_search();
     }
     // count contacts for this user
     $this->result = $this->count();
     // we have a search result resource
     if ($this->ldap_result && $this->result->count > 0) {
         if ($this->sort_col && $this->prop['scope'] !== 'base') {
             ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
         }
         $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
         $last_row = $this->result->first + $this->page_size;
         $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
         $entries = ldap_get_entries($this->conn, $this->ldap_result);
         for ($i = $start_row; $i < min($entries['count'], $last_row); $i++) {
             $this->result->add($this->_ldap2result($entries[$i]));
         }
     }
     return $this->result;
 }
示例#29
0
$ldaptree = "dc=dorfketal,dc=local";
$ldaprdn = 'dorfketal' . "\\" . 'mspladmin';
$group = array();
// connect
$ldapconn = ldap_connect($ldapserver, 389) or die("Could not connect to LDAP server.");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
if ($ldapconn) {
    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass) or die("Error trying to bind: " . ldap_error($ldapconn));
    // verify binding
    if ($ldapbind) {
        $query = "(&(objectCategory=user))";
        //$query="(&(objectcategory=group)(name=ASC))";
        $result = ldap_search($ldapconn, $ldaptree, $query) or die("Error in search query: " . ldap_error($ldapconn));
        ldap_sort($ldapconn, $result, "objectCategory");
        $data = ldap_get_entries($ldapconn, $result);
        for ($i = 0; $i < $data[count]; $i++) {
            /*  echo "<pre>";
                print_r($data);
                exit;*/
            //$groupNameTemp=$data[$i][displayname][0];
            //$groupNameTemp=$data[$i][title][0];
            //$group[$i]=array('GroupName'=> $groupNameTemp);
            $group[$i]['name'] = $data[$i][displayname][0];
            $group[$i]['user_name'] = $data[$i][samaccountname][0];
            $group[$i]['mail'] = $data[$i][mail][0];
            /*$group[$i]['department'] = $data[$i][department][0];        
              $group[$i]['proxyaddress'] = $data[$i][proxyaddress][0];
              $group[$i]['mail'] = $data[$i][mail][0];
              $group[$i]['position'] = $data[$i][title][0];
<?php

require "connect.inc";
$link = ldap_connect_and_bind($host, $port, $user, $passwd, $protocol_version);
insert_dummy_data($link, $base);
ldap_add($link, "cn=userC,{$base}", array("objectclass" => "person", "cn" => "userC", "sn" => "zzz", "userPassword" => "oops", "description" => "a user"));
ldap_add($link, "cn=userD,{$base}", array("objectclass" => "person", "cn" => "userD", "sn" => "aaa", "userPassword" => "oops", "description" => "another user"));
ldap_add($link, "cn=userE,{$base}", array("objectclass" => "person", "cn" => "userE", "sn" => "a", "userPassword" => "oops", "description" => "yet another user"));
$result = ldap_search($link, "{$base}", "(objectclass=person)", array("sn", "description"));
var_dump(ldap_sort($link, $result, "description"), ldap_get_entries($link, $result));
?>
===DONE===