示例#1
0
function search_uidspip ($filter,$ldap_server, $ldap_port, $dn) {
  global  $ldap_grp_attr;
  
  // LDAP attributs
  $ldap_grp_attr = array (
    "cn",
    "memberuid"  );

  $ds = @ldap_connect ( $ldap_server, $ldap_port );
  if ( $ds ) {
    $r = @ldap_bind ( $ds ); // Bind anonyme
    if ($r) {
      $result=@ldap_list ($ds, $dn["groups"], $filter, $ldap_grp_attr);
      if ($result) {
        $info = ldap_get_entries( $ds, $result );
        if ($info["count"]) {
          // Stockage des logins des membres des classes
          //  dans le tableau $ret
          $init=0;
          for ($loop=0; $loop < $info["count"]; $loop++) {
            $group=split ("[\_\]",$info[$loop]["cn"][0],2);
            for ( $i = 0; $i < $info[$loop]["memberuid"]["count"]; $i++ ) {
              $ret[$init]["uid"] = $info[$loop]["memberuid"][$i];
              $ret[$init]["cat"] = $group[0];
              $init++;
            }
          }
        }
        ldap_free_result ( $result );
      }
    } 
    @ldap_close ( $ds );
  } 
  return $ret;
}
示例#2
0
 public function getAllUsers()
 {
     // Settings for LDAP
     if ($this->container->hasParameter('ldap_host')) {
         $ldapHostname = $this->container->getParameter("ldap_host");
         $ldapPort = $this->container->getParameter("ldap_port");
         $ldapVersion = $this->container->getParameter("ldap_version");
         $baseDn = $this->container->getParameter("ldap_user_base_dn");
         $nameAttribute = $this->container->getParameter("ldap_user_name_attribute");
         $filter = "(" . $nameAttribute . "=*)";
         $connection = @ldap_connect($ldapHostname, $ldapPort);
         ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldapVersion);
         $ldapListRequest = ldap_list($connection, $baseDn, $filter);
         // or throw exeption('Unable to list. LdapError: ' . ldap_error($ldapConnection));
         $ldapUserList = ldap_get_entries($connection, $ldapListRequest);
     }
     // Settings for local user database
     $repo = $this->getDoctrine()->getRepository('FOMUserBundle:User');
     $users = $repo->findAll();
     $all = array();
     if ($this->container->hasParameter('ldap_host')) {
         // Add Users from LDAP
         foreach ($ldapUserList as $ldapUser) {
             $user = new \stdClass();
             $user->getUsername = $ldapUser[$nameAttribute][0];
             $all[] = $user;
         }
     }
     // Add Mapbenderusers from database
     foreach ($users as $user) {
         $all[] = $user;
     }
     return $all;
 }
示例#3
0
文件: LDAP.php 项目: nasaa0528/core
 /**
  * search ldap tree
  * @param $filter ldap filter string to use
  * @param string $ldap_scope scope either one or tree
  * @return array|bool result list or false on errors
  */
 private function search($filter, $ldap_scope = "tree")
 {
     $result = false;
     if ($this->ldapHandle != null) {
         // if we're looking at multple dn's, split and combine output
         foreach (explode(";", $this->baseSearchDN) as $baseDN) {
             if ($ldap_scope == "one") {
                 $sr = @ldap_list($this->ldapHandle, $baseDN, $filter, $this->ldapSearchAttr);
             } else {
                 $sr = @ldap_search($this->ldapHandle, $baseDN, $filter, $this->ldapSearchAttr);
             }
             if ($sr !== false) {
                 $info = @ldap_get_entries($this->ldapHandle, $sr);
                 if ($info !== false) {
                     if ($result === false) {
                         $result = array();
                         $result['count'] = 0;
                     }
                     for ($i = 0; $i < $info["count"]; $i++) {
                         $result['count']++;
                         $result[] = $info[$i];
                     }
                 }
             }
         }
     }
     return $result;
 }
示例#4
0
function is_prof($login)
{
    global $ldap_server, $ldap_port, $dn;
    global $error;
    $error = "";
    $filter = "(&(cn=profs*)(memberUid={$login}))";
    $ldap_groups_attr = array("cn", "memberUid");
    /*-----------------------------------------------------*/
    $ds = @ldap_connect($ldap_server, $ldap_port);
    if ($ds) {
        $r = @ldap_bind($ds);
        if (!$r) {
            $error = "Echec du bind anonyme";
        } else {
            // Recherche du groupe d'appartenance de l'utilisateur connecte
            $result = @ldap_list($ds, $dn["groups"], $filter, $ldap_groups_attr);
            if ($result) {
                $info = @ldap_get_entries($ds, $result);
                if ($info["count"]) {
                    $is_prof = true;
                } else {
                    $is_prof = false;
                }
            }
        }
    }
    @ldap_unbind($ds);
    @ldap_close($ds);
    return $is_prof;
}
 private function getOrganizations()
 {
     // Common functions
     $common = new common();
     // Ldap Connections
     $ldap = $common->ldapConnect($this->ldap_host, $this->ldap_root_dn, $this->ldap_root_pw);
     if ($ldap) {
         $filter = "objectClass=organizationalUnit";
         $justthese = array("ou");
         $search = ldap_list($ldap, $this->ldap_context, $filter, $justthese);
         $entry = ldap_get_entries($ldap, $search);
     }
     if ($entry['count'] > 0) {
         foreach ($entry as $tmp) {
             if ($tmp['ou'][0] != "") {
                 $result_ou[] = $tmp['ou'][0];
             }
         }
     } else {
         $result_ou[] = $this->ldap_context;
     }
     natcasesort($result_ou);
     ldap_close($ldap);
     return $result_ou ? $result_ou : '';
 }
function searchonelevel($ldap, $base, $filter, $attrs, $minresults = 1, $maxresults = 999999)
{
    $results = ldap_list($ldap, $base, $filter, $attrs);
    $results or ldapdie($ldap, "ldap_list()");
    $entries = ldap_get_entries($ldap, $results);
    $entries or ldapdie($ldap, "ldap_get_entries()");
    $entries["count"] <= $maxresults or ldapdie($ldap, "More than {$maxresults} object(s) match \"{$filter}\"");
    $entries["count"] >= $minresults or ldapdie($ldap, "Could not find {$minresults} object(s) matching \"{$filter}\"");
    return $entries;
}
示例#7
0
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;
}
示例#8
0
 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;
 }
示例#9
0
function my_people_get_variables ($serveur,$port,$Dn)
{
  $ldap_server=$serveur;
  $ldap_port=$port;
  $dn=$Dn;
  global $error;
  $error="";
  // LDAP attribute
 
  $ldap_group_attr = array (
    "cn",
    "memberuid",
    "description",  // Description du groupe
  );

  $ds = @ldap_connect ( $ldap_server, $ldap_port );
  if ( $ds ) {
    $r = @ldap_bind ( $ds ); // Bind anonyme
    if ($r) {
       
        // Recherche des groupes d'appartenance dans la branche Groups
        
        $filter = "(&(objectclass=posixGroup))";
        $result = @ldap_list ( $ds, $dn["groups"], $filter, $ldap_group_attr );
        if ($result) {
          $info = @ldap_get_entries ( $ds, $result );
          if ( $info["count"]) {
            for ($loop=0; $loop<$info["count"];$loop++) {
              //if ($info[$loop]["member"][0] == "") $typegr="posixGroup"; else $typegr="groupOfNames";
              $typegr="posixGroup";
              $ret_group[$loop] = array (
                "cn"           => $info[$loop]["cn"][0],
                //"owner"        => $info[$loop]["owner"][0],
                "description"  => utf8_decode($info[$loop]["description"][0]),
                "type" => $typegr
              );
            }
            usort($ret_group, "cmp_cn");
          }
          @ldap_free_result ( $result );
       }
       // Fin recherche des groupes
    } else {
      $error = "Echec du bind anonyme";
    }
    @ldap_close ( $ds );
  } else {
    $error = "Erreur de connection au serveur LDAP";
  }
 return array( $ret_group);
}
示例#10
0
 /**
  * @return boolean
  * @param ResourceBundle $connection
  * @param string $connection
  * @param boolean $recursive
  */
 public function deleteRecord($connection, $dn, $recursive = false)
 {
     if ($recursive == false) {
         return ldap_delete($connection, $dn);
     } else {
         $sr = ldap_list($connection, $dn, "ObjectClass=*", array(""));
         $info = ldap_get_entries($connection, $sr);
         for ($i = 0; $i < $info['count']; $i++) {
             $result = myldap_delete($connection, $info[$i]['dn'], $recursive);
             if (!$result) {
                 return $result;
             }
         }
         return ldap_delete($connection, $dn);
     }
 }
示例#11
0
 /**
  * suppression d'entrees OpenLDAP
  * recursivite possible
  */
 function lda_del($ldapconn, $dn, $recursive = FALSE)
 {
     if ($recursive == FALSE) {
         return ldap_delete($ldapconn, $dn);
     } else {
         $sr = ldap_list($ldapconn, $dn, "ObjectClass=*");
         $info = ldap_get_entries($ldapconn, $sr);
         for ($i = 0; $i < $info['count']; $i++) {
             $result = lda_del($ldapconn, $info[$i]['dn'], $recursive);
             if (!$result) {
                 return $result;
             }
         }
         return ldap_delete($ldapconn, $dn);
     }
 }
示例#12
0
 public function search($base, $depth, $filter, $attrs = array('cn'))
 {
     $attrs = array_values(array_unique($attrs));
     if ($depth == 'one') {
         if (($data = ldap_list($this->ldap, $base, $filter, $attrs)) === FALSE) {
             throw new LDAPException('ldap_list() failed', $this->ldap);
         }
     } else {
         if (($data = ldap_search($this->ldap, $base, $filter, $attrs)) === FALSE) {
             throw new LDAPException('ldap_search() failed', $this->ldap);
         }
     }
     if (($result = ldap_get_entries($this->ldap, $data)) === FALSE) {
         throw new LDAPException('ldap_get_entries() failed', $this->ldap);
     }
     return $result;
 }
示例#13
0
文件: Ldap.php 项目: mharj/ldap
 public function query(LdapQuery $query)
 {
     set_error_handler($this->eh);
     switch ($query->scope) {
         case LDAP_SCOPE_SUBTREE:
             $sr = ldap_search($this->ds, $query->base, $query->filter, $query->attrs, 0, $query->sizeLimit, $query->timeLimit, $query->deref);
             break;
         case LDAP_SCOPE_ONELEVEL:
             $sr = ldap_list($this->ds, $query->base, $query->filter, $query->attrs, 0, $query->sizeLimit, $query->timeLimit, $query->deref);
             break;
         case LDAP_SCOPE_BASE:
             $sr = ldap_read($this->ds, $query->base, $query->filter, $query->attrs, 0, $query->sizeLimit, $query->timeLimit, $query->deref);
             break;
         default:
             throw new LdapException("Unknown query scope");
     }
     restore_error_handler();
     return new LdapEntries($this->ds, $sr);
 }
示例#14
0
 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;
 }
示例#15
0
function delete_ldap($dn, $connect, $recursive = false)
{
    if ($recursive == false) {
        if (!@ldap_delete($connect, $dn)) {
            echo "Deleting {$dn}...\n";
            echo "ERROR: ldap_delete \"{$dn}\"" . ldap_err2str(ldap_errno($connect)) . "\n";
            return false;
        }
    }
    $sr = @ldap_list($connect, $dn, "ObjectClass=*");
    if ($sr) {
        $info = @ldap_get_entries($connect, $sr);
        for ($i = 0; $i < $info['count']; $i++) {
            $result = delete_ldap($info[$i]['dn'], $connect, $recursive);
            if (!$result) {
                return $result;
            }
        }
        return delete_ldap($dn, $connect, false);
    }
}
示例#16
0
 /**
  * execute ldap query and return ldap records
  *
  * @param scope
  * @params see pagedLdapQuery $params
  *
  * @return array of ldap entries
  */
 function ldapQuery($scope, $params)
 {
     $this->connectAndBindIfNotAlready();
     switch ($scope) {
         case LDAP_SCOPE_SUBTREE:
             $result = @ldap_search($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'], $params['sizelimit'], $params['timelimit'], $params['deref']);
             if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
                 // false positive error thrown.  do not return result limit error when $sizelimit specified
             } elseif ($this->hasError()) {
                 watchdog('ldap_server', 'ldap_search() function error. LDAP Error: %message, ldap_search() parameters: %query', array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']), WATCHDOG_ERROR);
             }
             break;
         case LDAP_SCOPE_BASE:
             $result = @ldap_read($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'], $params['sizelimit'], $params['timelimit'], $params['deref']);
             if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
                 // false positive error thrown.  do not result limit error when $sizelimit specified
             } elseif ($this->hasError()) {
                 watchdog('ldap_server', 'ldap_read() function error.  LDAP Error: %message, ldap_read() parameters: %query', array('%message' => $this->errorMsg('ldap'), '%query' => @$params['query_display']), WATCHDOG_ERROR);
             }
             break;
         case LDAP_SCOPE_ONELEVEL:
             $result = @ldap_list($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'], $params['sizelimit'], $params['timelimit'], $params['deref']);
             if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
                 // false positive error thrown.  do not result limit error when $sizelimit specified
             } elseif ($this->hasError()) {
                 watchdog('ldap_server', 'ldap_list() function error. LDAP Error: %message, ldap_list() parameters: %query', array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']), WATCHDOG_ERROR);
             }
             break;
     }
     return $result;
 }
示例#17
0
    /** 
     * Validate the login using CAS
     */
    function validate_login($null, $username, $password)
    {
        if (!$this->cas_configured) {
            die('Error. Cas not configured and I was unable to redirect you to wp-login. Use define("WPCAS_BYPASS",true); in your wp-config.php
					to bypass wpCAS');
        }
        phpCAS::forceAuthentication();
        // might as well be paranoid
        if (!phpCAS::isAuthenticated()) {
            exit;
        }
        $username = phpCAS::getUser();
        $password = md5($username . 'wpCASAuth!"#$"!$!"%$#"%#$' . rand() . $this->generateRandomString(20));
        $user = get_user_by('login', $username);
        if ($user) {
            if (is_multisite()) {
                if ($this->canUserRegister($username) && !is_user_member_of_blog($user->ID, get_current_blog_id())) {
                    $nextrole = $this->canUserRegister($username);
                    add_user_to_blog(get_current_blog_id(), $user->ID, $nextrole);
                }
            }
            return $user;
        }
        /** Register a new user, if it is allowed */
        if ($user_role = $this->canUserRegister($username)) {
            $user_email = '';
            $email_registration = $this->settings['e-mail_registration'];
            //How does the site is configured to get the email?
            switch ($email_registration) {
                case 2:
                    //Using sufix
                    $user_email = $username . '@' . $this->settings['email_suffix'];
                    break;
                case 3:
                    //Using LDAP
                    /*fetch user email from ldap*/
                    $ds = ldap_connect($this->settings['ldap_server']);
                    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $this->settings['ldap_protocol']);
                    ldap_set_option($ds, LDAP_OPT_RESTART, TRUE);
                    $r = ldap_bind($ds, $this->settings['ldap_username_rdn'], $this->settings['ldap_password']);
                    $list = ldap_list($ds, $this->settings['ldap_basedn'], "uid={$username}");
                    if ($list !== FALSE) {
                        $result = ldap_get_entries($ds, $list);
                        if ($result['count'] > 0) {
                            $result = $result[0];
                            if (isset($result['mail']) && is_array($result['mail'])) {
                                $user_email = $result['mail'][0];
                            }
                            if (isset($result['displayname']) && is_array($result['displayname'])) {
                                $user_realname = $result['displayname'][0];
                                $exploded_name = explode(' ', $user_realname);
                                $firstname = $exploded_name[0];
                                $lastname = end($exploded_name);
                            }
                        }
                    }
                    break;
                default:
                    //No email predition
                    break;
            }
            $user_info = array();
            $user_info['user_pass'] = $password;
            $user_info['user_email'] = $user_email;
            $user_info['user_login'] = $username;
            $user_info['display_name'] = $user_realname;
            $user_info['first_name'] = $firstname;
            $user_info['last_name'] = $lastname;
            //Verify if we need to add user to a specified role
            if (!is_bool($user_role)) {
                $user_info['role'] = $user_role;
            }
            if (!is_wp_error(wp_insert_user($user_info))) {
                $send_user = !empty($user_info['user_email']);
                //False, if user has no email
                if (!isset($user_info['role']) && $this->settings['wait_mail']['send_user']) {
                    //If user has no role and is allowed to send wait mail to user
                    $this->processMailing(WPCAS_WAITACCESS_MAIL, $user_info, $send_user);
                } else {
                    if (!isset($user_info['role']) && !$this->settings['wait_mail']['send_user']) {
                        //Otherwise, if has no role and we don't want a wait for access mail, send the welcome mail
                        $this->processMailing(WPCAS_WELCOME_MAIL, $user_info, $send_user);
                    } else {
                        //In any other case, send a Welcome Mail
                        $this->processMailing(WPCAS_WELCOME_MAIL, $user_info, $send_user);
                    }
                }
                $user = get_user_by('login', $username);
                if (!isset($user_info['user_role'])) {
                    update_user_meta($user->ID, '_wpcas_waiting', true);
                }
                return $user;
            }
        } else {
            $caserror_file = get_template_directory() . '/cas_error.php';
            include file_exists($caserror_file) ? $caserror_file : "cas_error.php";
            exit;
        }
    }
示例#18
0
文件: Ldap.php 项目: Rovak/zf2
 /**
  * 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;
 }
示例#19
0
 /**
  * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
  *
  * @param  $scope string - can be 'base', 'one' or 'sub'
  * @author Andreas Gohr <*****@*****.**>
  */
 function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null, $attrsonly = 0, $sizelimit = 0, $timelimit = 0, $deref = LDAP_DEREF_NEVER)
 {
     if (is_null($attributes)) {
         $attributes = array();
     }
     if ($scope == 'base') {
         return @ldap_read($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
     } elseif ($scope == 'one') {
         return @ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
     } else {
         return @ldap_search($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
     }
 }
示例#20
0
 /**
  * @param $login
  * @return bool|Model\Organization
  */
 public function getOrga($login)
 {
     $infos = ldap_get_entries($this->connection, ldap_list($this->connection, 'ou=people,dc=utt,dc=fr', 'uid=' . $login));
     if (empty($infos[0]) || !isset($infos[0])) {
         return false;
     }
     return $this->mapOrga($infos[0]);
 }
示例#21
0
 function find_ext_enrolments($ldap_connection, $memberuid, $role)
 {
     /// role is a record from the mdl_role table
     /// return multidimentional array array with of courses (at least dn and idnumber)
     ///
     global $CFG;
     if (empty($memberuid)) {
         // No "idnumber" stored for this user, so no LDAP enrolments
         return array();
     }
     //default return value
     $courses = array();
     $this->enrol_ldap_bind($ldap_connection);
     //get all contexts and look for first matching user
     $ldap_contexts = explode(";", $CFG->{'enrol_ldap_contexts_role' . $role->id});
     // get all the fields we will want for the potential course creation
     // as they are light. don't get membership -- potentially a lot of data.
     $ldap_fields_wanted = array('dn', $CFG->enrol_ldap_course_idnumber);
     if (!empty($CFG->enrol_ldap_course_fullname)) {
         array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_fullname);
     }
     if (!empty($CFG->enrol_ldap_course_shortname)) {
         array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_shortname);
     }
     if (!empty($CFG->enrol_ldap_course_summary)) {
         array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_summary);
     }
     // define the search pattern
     $ldap_search_pattern = "(" . $CFG->{'enrol_ldap_memberattribute_role' . $role->id} . "=" . $memberuid . ")";
     if (!empty($CFG->enrol_ldap_objectclass)) {
         $ldap_search_pattern = '(&(objectclass=' . $CFG->enrol_ldap_objectclass . ')' . $ldap_search_pattern . ')';
     }
     foreach ($ldap_contexts as $context) {
         $context == trim($context);
         if (empty($context)) {
             continue;
             // next;
         }
         if ($CFG->enrol_ldap_search_sub) {
             //use ldap_search to find first user from subtree
             $ldap_result = ldap_search($ldap_connection, $context, $ldap_search_pattern, $ldap_fields_wanted);
         } else {
             //search only in this context
             $ldap_result = ldap_list($ldap_connection, $context, $ldap_search_pattern, $ldap_fields_wanted);
         }
         // check and push results
         $records = ldap_get_entries($ldap_connection, $ldap_result);
         // ldap libraries return an odd array, really. fix it:
         $flat_records = array();
         for ($c = 0; $c < $records['count']; $c++) {
             array_push($flat_records, $records["{$c}"]);
         }
         if (count($flat_records)) {
             $courses = array_merge($courses, $flat_records);
         }
     }
     return $courses;
 }
示例#22
0
 /**
  * Performs a single level search on the current connection.
  *
  * @param string $dn
  * @param string $filter
  * @param array  $attributes
  *
  * @return mixed
  */
 public function listing($dn, $filter, array $attributes)
 {
     if ($this->suppressErrors) {
         return @ldap_list($this->getConnection(), $dn, $filter, $attributes);
     }
     return ldap_list($this->getConnection(), $dn, $filter, $attributes);
 }
 /**
  * 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;
 }
示例#24
0
 protected function recursive_delete($connection, $dn, $filter)
 {
     if ($res = ldap_list($connection, $dn, $filter, array('dn'))) {
         $info = ldap_get_entries($connection, $res);
         ldap_free_result($res);
         if ($info['count'] > 0) {
             if ($res = ldap_search($connection, "{$filter},{$dn}", 'cn=*', array('dn'))) {
                 $info = ldap_get_entries($connection, $res);
                 ldap_free_result($res);
                 foreach ($info as $i) {
                     if (isset($i['dn'])) {
                         ldap_delete($connection, $i['dn']);
                     }
                 }
             }
             if ($res = ldap_search($connection, "{$filter},{$dn}", 'ou=*', array('dn'))) {
                 $info = ldap_get_entries($connection, $res);
                 ldap_free_result($res);
                 foreach ($info as $i) {
                     if (isset($i['dn']) and $info[0]['dn'] != $i['dn']) {
                         ldap_delete($connection, $i['dn']);
                     }
                 }
             }
             ldap_delete($connection, "{$filter},{$dn}");
         }
     }
 }
示例#25
0
 public function is_phonebook_admin($ldapconn, $dn)
 {
     $search = ldap_list($ldapconn, "ou=groups, dc=mozilla", "(&(member={$dn})(cn=phonebook_admin))", array("cn"));
     $results = ldap_get_entries($ldapconn, $search);
     return $results["count"];
 }
示例#26
0
 /**
  * Performs a request against the LDAP server
  *
  * The type of request (and the corresponding PHP ldap function called)
  * depend on two additional parameters, added in respect to the
  * DB_common interface.
  *
  * @param string $filter text of the request to send to the LDAP server
  * @param string $action type of request to perform, defaults to search (ldap_search())
  * @param array $params array of additional parameters to pass to the PHP ldap function requested
  * @return result from ldap function or DB Error object if no result
  */
 function simpleQuery($filter, $action = null, $params = null)
 {
     if ($action === null) {
         $action = !empty($this->q_action) ? $this->q_action : $this->action;
     }
     if ($params === null) {
         $params = count($this->q_params) > 0 ? $this->q_params : array();
     }
     if (!$this->isManip($action)) {
         $base = $this->q_base ? $this->q_base : $this->base;
         $attributes = array();
         $attrsonly = 0;
         $sizelimit = 0;
         $timelimit = 0;
         $deref = LDAP_DEREF_NEVER;
         $sorting = '';
         $sorting_method = '';
         reset($params);
         while (list($k, $v) = each($params)) {
             if (isset(${$k})) {
                 ${$k} = $v;
             }
         }
         $this->sorting = $sorting;
         $this->sorting_method = $sorting_method;
         $this->attributes = $attributes;
         # double escape char for filter: '(o=Przedsi\C4\99biorstwo)' => '(o=Przedsi\\C4\\99biorstwo)'
         $filter = str_replace('\\', '\\\\', $filter);
         $this->last_query = $filter;
         if ($action == 'search') {
             $result = @ldap_search($this->connection, $base, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
         } else {
             if ($action == 'list') {
                 $result = @ldap_list($this->connection, $base, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
             } else {
                 if ($action == 'read') {
                     $result = @ldap_read($this->connection, $base, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
                 } else {
                     return $this->ldapRaiseError(DB_ERROR_UNKNOWN_LDAP_ACTION);
                 }
             }
         }
         if (!$result) {
             return $this->ldapRaiseError();
         }
     } else {
         # If first argument is an array, it contains the entry with DN.
         if (is_array($filter)) {
             $entry = $filter;
             $filter = $entry["dn"];
         } else {
             $entry = array();
         }
         unset($entry["dn"]);
         $attribute = '';
         $value = '';
         $newrdn = '';
         $newparent = '';
         $deleteoldrdn = false;
         reset($params);
         while (list($k, $v) = each($params)) {
             if (isset(${$k})) {
                 ${$k} = $v;
             }
         }
         $this->last_query = $filter;
         if ($action == 'add') {
             $result = @ldap_add($this->connection, $filter, $entry);
         } else {
             if ($action == 'compare') {
                 $result = @ldap_add($this->connection, $filter, $attribute, $value);
             } else {
                 if ($action == 'delete') {
                     $result = @ldap_delete($this->connection, $filter);
                 } else {
                     if ($action == 'modify') {
                         $result = @ldap_modify($this->connection, $filter, $entry);
                     } else {
                         if ($action == 'mod_add') {
                             $result = @ldap_mod_add($this->connection, $filter, $entry);
                         } else {
                             if ($action == 'mod_del') {
                                 $result = @ldap_mod_del($this->connection, $filter, $entry);
                             } else {
                                 if ($action == 'mod_replace') {
                                     $result = @ldap_mod_replace($this->connection, $filter, $entry);
                                 } else {
                                     if ($action == 'rename') {
                                         $result = @ldap_rename($this->connection, $filter, $newrdn, $newparent, $deleteoldrdn);
                                     } else {
                                         return $this->ldapRaiseError(DB_ERROR_UNKNOWN_LDAP_ACTION);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (!$result) {
             return $this->ldapRaiseError();
         }
     }
     $this->freeQuery();
     return $result;
 }
示例#27
0
/**
 * assigns all countries to the template
 */
function tpl_country()
{
    global $conf;
    global $LDAP_CON;
    global $smarty;
    if (!$conf['openxchange']) {
        return;
    }
    $country = array();
    $sr = ldap_list($LDAP_CON, $conf['publicbook'], "ObjectClass=OXUserObject", array("userCountry"));
    $result1 = ldap_get_binentries($LDAP_CON, $sr);
    //check users private addressbook
    if (!empty($_SESSION['ldapab']['binddn']) && $conf['privatebook']) {
        $sr = @ldap_list($LDAP_CON, $conf['privatebook'] . ',' . $_SESSION['ldapab']['binddn'], "ObjectClass=OXUserObject", array("userCountry"));
        $result2 = ldap_get_binentries($LDAP_CON, $sr);
    }
    $result = array_merge((array) $result1, (array) $result2);
    if (count($result)) {
        foreach ($result as $entry) {
            if (count($entry['userCountry'])) {
                foreach ($entry['userCountry'] as $c) {
                    array_push($country, $c);
                }
            }
        }
    }
    $country = array_unique($country);
    sort($country, SORT_STRING);
    $smarty->assign('country', $country);
}
示例#28
0
 /**
  * 
  * returns the distinct values of the target LDAP attribute
  * these will be the names of the synched Mahara groups
  * @returns array of string 
  */
 function get_attribute_distinct_values()
 {
     global $CFG, $DB;
     // only these groups will be synched
     if (!empty($this->config->group_synching_ldap_attribute_values)) {
         return $this->config->group_synching_ldap_attribute_values;
     }
     //build a filter to fetch all users having something in the target LDAP attribute
     $filter = '(' . $this->config['user_attribute'] . '=*)';
     if (!empty($this->config['objectclass'])) {
         $filter .= "&(" . $this->config['objectclass'] . "))";
     }
     $filter = '(&' . $filter . '(' . $this->config['group_synching_ldap_attribute_attribute'] . '=*))';
     if ($CFG->debug_ldap_groupes) {
         moodle_print_object('looking for ', $filter);
     }
     $ldapconnection = $this->ldap_connect();
     $ldap_contexts = explode(";", $this->config['contexts']);
     $matchings = array();
     foreach ($ldap_contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         if ($this->config['search_sub'] == 'yes') {
             // Use ldap_search to find first user from subtree
             $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->group_synching_ldap_attribute_attribute));
         } else {
             // Search only in this context
             $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->group_synching_ldap_attribute_attribute));
         }
         if (!$ldap_result) {
             continue;
         }
         // this API function returns all attributes as an array
         // wether they are single or multiple
         $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
         // Add found DISTINCT values to list
         for ($i = 0; $i < count($users); $i++) {
             $count = $users[$i][$this->config['group_synching_ldap_attribute_attribute']]['count'];
             for ($j = 0; $j < $count; $j++) {
                 /*
                    $value=  textlib::convert($users[$i][$this->config['group_synching_ldap_attribute_attribute']][$j],
                                 $this->config->ldapencoding, 'utf-8');
                 */
                 $value = $users[$i][$this->config['group_synching_ldap_attribute_attribute']][$j];
                 if (!in_array($value, $matchings)) {
                     array_push($matchings, $value);
                 }
             }
         }
     }
     ldap_close($ldapconnection);
     return $matchings;
 }
示例#29
0
 /**
  * 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;
 }
示例#30
0
 /**
  * Return multidimensional array with details of user courses (at
  * least dn and idnumber).
  *
  * @param string $memberuid user idnumber (without magic quotes).
  * @param object role is a record from the mdl_role table.
  * @return array
  */
 protected function find_ext_enrolments($memberuid, $role)
 {
     global $CFG;
     require_once $CFG->libdir . '/ldaplib.php';
     if (empty($memberuid)) {
         // No "idnumber" stored for this user, so no LDAP enrolments
         return array();
     }
     $ldap_contexts = trim($this->get_config('contexts_role' . $role->id));
     if (empty($ldap_contexts)) {
         // No role contexts, so no LDAP enrolments
         return array();
     }
     $extmemberuid = core_text::convert($memberuid, 'utf-8', $this->get_config('ldapencoding'));
     if ($this->get_config('memberattribute_isdn')) {
         if (!($extmemberuid = $this->ldap_find_userdn($extmemberuid))) {
             return array();
         }
     }
     $ldap_search_pattern = '';
     if ($this->get_config('nested_groups')) {
         $usergroups = $this->ldap_find_user_groups($extmemberuid);
         if (count($usergroups) > 0) {
             foreach ($usergroups as $group) {
                 $ldap_search_pattern .= '(' . $this->get_config('memberattribute_role' . $role->id) . '=' . $group . ')';
             }
         }
     }
     // Default return value
     $courses = array();
     // Get all the fields we will want for the potential course creation
     // as they are light. don't get membership -- potentially a lot of data.
     $ldap_fields_wanted = array('dn', $this->get_config('course_idnumber'));
     $fullname = $this->get_config('course_fullname');
     $shortname = $this->get_config('course_shortname');
     $summary = $this->get_config('course_summary');
     if (isset($fullname)) {
         array_push($ldap_fields_wanted, $fullname);
     }
     if (isset($shortname)) {
         array_push($ldap_fields_wanted, $shortname);
     }
     if (isset($summary)) {
         array_push($ldap_fields_wanted, $summary);
     }
     // Define the search pattern
     if (empty($ldap_search_pattern)) {
         $ldap_search_pattern = '(' . $this->get_config('memberattribute_role' . $role->id) . '=' . ldap_filter_addslashes($extmemberuid) . ')';
     } else {
         $ldap_search_pattern = '(|' . $ldap_search_pattern . '(' . $this->get_config('memberattribute_role' . $role->id) . '=' . ldap_filter_addslashes($extmemberuid) . ')' . ')';
     }
     $ldap_search_pattern = '(&' . $this->get_config('objectclass') . $ldap_search_pattern . ')';
     // Get all contexts and look for first matching user
     $ldap_contexts = explode(';', $ldap_contexts);
     $ldap_pagedresults = ldap_paged_results_supported($this->get_config('ldap_version'));
     foreach ($ldap_contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         $ldap_cookie = '';
         $flat_records = array();
         do {
             if ($ldap_pagedresults) {
                 ldap_control_paged_result($this->ldapconnection, $this->config->pagesize, true, $ldap_cookie);
             }
             if ($this->get_config('course_search_sub')) {
                 // Use ldap_search to find first user from subtree
                 $ldap_result = @ldap_search($this->ldapconnection, $context, $ldap_search_pattern, $ldap_fields_wanted);
             } else {
                 // Search only in this context
                 $ldap_result = @ldap_list($this->ldapconnection, $context, $ldap_search_pattern, $ldap_fields_wanted);
             }
             if (!$ldap_result) {
                 continue;
             }
             if ($ldap_pagedresults) {
                 ldap_control_paged_result_response($this->ldapconnection, $ldap_result, $ldap_cookie);
             }
             // Check and push results. ldap_get_entries() already
             // lowercases the attribute index, so there's no need to
             // use array_change_key_case() later.
             $records = ldap_get_entries($this->ldapconnection, $ldap_result);
             // LDAP libraries return an odd array, really. Fix it.
             for ($c = 0; $c < $records['count']; $c++) {
                 array_push($flat_records, $records[$c]);
             }
             // Free some mem
             unset($records);
         } while ($ldap_pagedresults && !empty($ldap_cookie));
         // If LDAP paged results were used, the current connection must be completely
         // closed and a new one created, to work without paged results from here on.
         if ($ldap_pagedresults) {
             $this->ldap_close();
             $this->ldap_connect();
         }
         if (count($flat_records)) {
             $courses = array_merge($courses, $flat_records);
         }
     }
     return $courses;
 }