xref: /dokuwiki/lib/plugins/authldap/auth.php (revision 67723447f02824ff2df7daa0f1f97d8b289c5d7a)
1f4476bd9SJan Schumann<?php
2f4476bd9SJan Schumann// must be run within Dokuwiki
3f4476bd9SJan Schumannif(!defined('DOKU_INC')) die();
4f4476bd9SJan Schumann
5f4476bd9SJan Schumann/**
6f4476bd9SJan Schumann * LDAP authentication backend
7f4476bd9SJan Schumann *
8f4476bd9SJan Schumann * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
9f4476bd9SJan Schumann * @author    Andreas Gohr <andi@splitbrain.org>
10f4476bd9SJan Schumann * @author    Chris Smith <chris@jalakaic.co.uk>
11f4476bd9SJan Schumann * @author    Jan Schumann <js@schumann-it.com>
12f4476bd9SJan Schumann */
1393a7873eSAndreas Gohrclass auth_plugin_authldap extends DokuWiki_Auth_Plugin {
1470e4a085SAndreas Gohr    /* @var resource $con holds the LDAP connection*/
1570e4a085SAndreas Gohr    protected $con = null;
1670e4a085SAndreas Gohr
1770e4a085SAndreas Gohr    /* @var int $bound What type of connection does already exist? */
1870e4a085SAndreas Gohr    protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
1970e4a085SAndreas Gohr
2070e4a085SAndreas Gohr    /* @var array $users User data cache */
2170e4a085SAndreas Gohr    protected $users = null;
2270e4a085SAndreas Gohr
2370e4a085SAndreas Gohr    /* @var array $_pattern User filter pattern */
2470e4a085SAndreas Gohr    protected $_pattern = null;
25f4476bd9SJan Schumann
26f4476bd9SJan Schumann    /**
27f4476bd9SJan Schumann     * Constructor
28f4476bd9SJan Schumann     */
2970e4a085SAndreas Gohr    public function __construct() {
30454d868bSAndreas Gohr        parent::__construct();
31454d868bSAndreas Gohr
32f4476bd9SJan Schumann        // ldap extension is needed
33f4476bd9SJan Schumann        if(!function_exists('ldap_connect')) {
3470e4a085SAndreas Gohr            $this->_debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
35f4476bd9SJan Schumann            $this->success = false;
36f4476bd9SJan Schumann            return;
37f4476bd9SJan Schumann        }
38f4476bd9SJan Schumann
3906da270eSAxel Angel        // Add the capabilities to change the password
4006da270eSAxel Angel        $this->cando['modPass'] = true;
41f4476bd9SJan Schumann    }
42f4476bd9SJan Schumann
43f4476bd9SJan Schumann    /**
44f4476bd9SJan Schumann     * Check user+password
45f4476bd9SJan Schumann     *
46f4476bd9SJan Schumann     * Checks if the given user exists and the given
47f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
48f4476bd9SJan Schumann     * to the LDAP server
49f4476bd9SJan Schumann     *
50f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
5170e4a085SAndreas Gohr     * @param string $user
5270e4a085SAndreas Gohr     * @param string $pass
53f4476bd9SJan Schumann     * @return  bool
54f4476bd9SJan Schumann     */
5570e4a085SAndreas Gohr    public function checkPass($user, $pass) {
56f4476bd9SJan Schumann        // reject empty password
57f4476bd9SJan Schumann        if(empty($pass)) return false;
58f4476bd9SJan Schumann        if(!$this->_openLDAP()) return false;
59f4476bd9SJan Schumann
60f4476bd9SJan Schumann        // indirect user bind
6170e4a085SAndreas Gohr        if($this->getConf('binddn') && $this->getConf('bindpw')) {
62f4476bd9SJan Schumann            // use superuser credentials
6370e4a085SAndreas Gohr            if(!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))) {
6470e4a085SAndreas Gohr                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
65f4476bd9SJan Schumann                return false;
66f4476bd9SJan Schumann            }
67f4476bd9SJan Schumann            $this->bound = 2;
6870e4a085SAndreas Gohr        } else if($this->getConf('binddn') &&
6970e4a085SAndreas Gohr            $this->getConf('usertree') &&
7070e4a085SAndreas Gohr            $this->getConf('userfilter')
7170e4a085SAndreas Gohr        ) {
72f4476bd9SJan Schumann            // special bind string
7370e4a085SAndreas Gohr            $dn = $this->_makeFilter(
7470e4a085SAndreas Gohr                $this->getConf('binddn'),
7570e4a085SAndreas Gohr                array('user'=> $user, 'server'=> $this->getConf('server'))
7670e4a085SAndreas Gohr            );
77f4476bd9SJan Schumann
7870e4a085SAndreas Gohr        } else if(strpos($this->getConf('usertree'), '%{user}')) {
79f4476bd9SJan Schumann            // direct user bind
8070e4a085SAndreas Gohr            $dn = $this->_makeFilter(
8170e4a085SAndreas Gohr                $this->getConf('usertree'),
8270e4a085SAndreas Gohr                array('user'=> $user, 'server'=> $this->getConf('server'))
8370e4a085SAndreas Gohr            );
84f4476bd9SJan Schumann
85f4476bd9SJan Schumann        } else {
86f4476bd9SJan Schumann            // Anonymous bind
87f4476bd9SJan Schumann            if(!@ldap_bind($this->con)) {
88f4476bd9SJan Schumann                msg("LDAP: can not bind anonymously", -1);
8970e4a085SAndreas Gohr                $this->_debug('LDAP anonymous bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
90f4476bd9SJan Schumann                return false;
91f4476bd9SJan Schumann            }
92f4476bd9SJan Schumann        }
93f4476bd9SJan Schumann
94f4476bd9SJan Schumann        // Try to bind to with the dn if we have one.
95f4476bd9SJan Schumann        if(!empty($dn)) {
96f4476bd9SJan Schumann            // User/Password bind
97f4476bd9SJan Schumann            if(!@ldap_bind($this->con, $dn, $pass)) {
9870e4a085SAndreas Gohr                $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
9970e4a085SAndreas Gohr                $this->_debug('LDAP user dn bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
100f4476bd9SJan Schumann                return false;
101f4476bd9SJan Schumann            }
102f4476bd9SJan Schumann            $this->bound = 1;
103f4476bd9SJan Schumann            return true;
104f4476bd9SJan Schumann        } else {
105f4476bd9SJan Schumann            // See if we can find the user
106f4476bd9SJan Schumann            $info = $this->getUserData($user, true);
107f4476bd9SJan Schumann            if(empty($info['dn'])) {
108f4476bd9SJan Schumann                return false;
109f4476bd9SJan Schumann            } else {
110f4476bd9SJan Schumann                $dn = $info['dn'];
111f4476bd9SJan Schumann            }
112f4476bd9SJan Schumann
113f4476bd9SJan Schumann            // Try to bind with the dn provided
114f4476bd9SJan Schumann            if(!@ldap_bind($this->con, $dn, $pass)) {
11570e4a085SAndreas Gohr                $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
11670e4a085SAndreas Gohr                $this->_debug('LDAP user bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
117f4476bd9SJan Schumann                return false;
118f4476bd9SJan Schumann            }
119f4476bd9SJan Schumann            $this->bound = 1;
120f4476bd9SJan Schumann            return true;
121f4476bd9SJan Schumann        }
122f4476bd9SJan Schumann    }
123f4476bd9SJan Schumann
124f4476bd9SJan Schumann    /**
125f4476bd9SJan Schumann     * Return user info
126f4476bd9SJan Schumann     *
127f4476bd9SJan Schumann     * Returns info about the given user needs to contain
128f4476bd9SJan Schumann     * at least these fields:
129f4476bd9SJan Schumann     *
130f4476bd9SJan Schumann     * name string  full name of the user
131f4476bd9SJan Schumann     * mail string  email addres of the user
132f4476bd9SJan Schumann     * grps array   list of groups the user is in
133f4476bd9SJan Schumann     *
134f4476bd9SJan Schumann     * This LDAP specific function returns the following
135f4476bd9SJan Schumann     * addional fields:
136f4476bd9SJan Schumann     *
137f4476bd9SJan Schumann     * dn     string  distinguished name (DN)
138f4476bd9SJan Schumann     * uid    string  Posix User ID
139f4476bd9SJan Schumann     * inbind bool    for internal use - avoid loop in binding
140f4476bd9SJan Schumann     *
141f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
142f4476bd9SJan Schumann     * @author  Trouble
143f4476bd9SJan Schumann     * @author  Dan Allen <dan.j.allen@gmail.com>
144f4476bd9SJan Schumann     * @author  <evaldas.auryla@pheur.org>
145f4476bd9SJan Schumann     * @author  Stephane Chazelas <stephane.chazelas@emerson.com>
1463e23f03eSSteScho     * @author  Steffen Schoch <schoch@dsb.net>
14770e4a085SAndreas Gohr     *
14870e4a085SAndreas Gohr     * @param   string $user
14970e4a085SAndreas Gohr     * @param   bool   $inbind authldap specific, true if in bind phase
150f4476bd9SJan Schumann     * @return  array containing user data or false
151f4476bd9SJan Schumann     */
15270e4a085SAndreas Gohr    public function getUserData($user, $inbind = false) {
153f4476bd9SJan Schumann        global $conf;
154f4476bd9SJan Schumann        if(!$this->_openLDAP()) return false;
155f4476bd9SJan Schumann
156f4476bd9SJan Schumann        // force superuser bind if wanted and not bound as superuser yet
15770e4a085SAndreas Gohr        if($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
158f4476bd9SJan Schumann            // use superuser credentials
15970e4a085SAndreas Gohr            if(!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))) {
16070e4a085SAndreas Gohr                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
161f4476bd9SJan Schumann                return false;
162f4476bd9SJan Schumann            }
163f4476bd9SJan Schumann            $this->bound = 2;
164f4476bd9SJan Schumann        } elseif($this->bound == 0 && !$inbind) {
165f4476bd9SJan Schumann            // in some cases getUserData is called outside the authentication workflow
166f4476bd9SJan Schumann            // eg. for sending email notification on subscribed pages. This data might not
167f4476bd9SJan Schumann            // be accessible anonymously, so we try to rebind the current user here
168f4476bd9SJan Schumann            list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
169f4476bd9SJan Schumann            if($loginuser && $loginpass) {
170b4304655SMichael Hamann                $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
171f4476bd9SJan Schumann                $this->checkPass($loginuser, $loginpass);
172f4476bd9SJan Schumann            }
173f4476bd9SJan Schumann        }
174f4476bd9SJan Schumann
175f4476bd9SJan Schumann        $info['user']   = $user;
17670e4a085SAndreas Gohr        $info['server'] = $this->getConf('server');
177f4476bd9SJan Schumann
178f4476bd9SJan Schumann        //get info for given user
17970e4a085SAndreas Gohr        $base = $this->_makeFilter($this->getConf('usertree'), $info);
18070e4a085SAndreas Gohr        if($this->getConf('userfilter')) {
18170e4a085SAndreas Gohr            $filter = $this->_makeFilter($this->getConf('userfilter'), $info);
182f4476bd9SJan Schumann        } else {
183f4476bd9SJan Schumann            $filter = "(ObjectClass=*)";
184f4476bd9SJan Schumann        }
185f4476bd9SJan Schumann
18670e4a085SAndreas Gohr        $sr     = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('userscope'));
187f4476bd9SJan Schumann        $result = @ldap_get_entries($this->con, $sr);
18870e4a085SAndreas Gohr        $this->_debug('LDAP user search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
18970e4a085SAndreas Gohr        $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__);
190f4476bd9SJan Schumann
191f4476bd9SJan Schumann        // Don't accept more or less than one response
192f4476bd9SJan Schumann        if(!is_array($result) || $result['count'] != 1) {
193f4476bd9SJan Schumann            return false; //user not found
194f4476bd9SJan Schumann        }
195f4476bd9SJan Schumann
196f4476bd9SJan Schumann        $user_result = $result[0];
197f4476bd9SJan Schumann        ldap_free_result($sr);
198f4476bd9SJan Schumann
199f4476bd9SJan Schumann        // general user info
200f4476bd9SJan Schumann        $info['dn']   = $user_result['dn'];
201f4476bd9SJan Schumann        $info['gid']  = $user_result['gidnumber'][0];
202f4476bd9SJan Schumann        $info['mail'] = $user_result['mail'][0];
203f4476bd9SJan Schumann        $info['name'] = $user_result['cn'][0];
204f4476bd9SJan Schumann        $info['grps'] = array();
205f4476bd9SJan Schumann
206f4476bd9SJan Schumann        // overwrite if other attribs are specified.
20770e4a085SAndreas Gohr        if(is_array($this->getConf('mapping'))) {
20870e4a085SAndreas Gohr            foreach($this->getConf('mapping') as $localkey => $key) {
209f4476bd9SJan Schumann                if(is_array($key)) {
210f4476bd9SJan Schumann                    // use regexp to clean up user_result
211f4476bd9SJan Schumann                    list($key, $regexp) = each($key);
2124f11d93dSGerrit Uitslag                    if($user_result[$key]) foreach($user_result[$key] as $grpkey => $grp) {
2134f11d93dSGerrit Uitslag                        if($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
214f4476bd9SJan Schumann                            if($localkey == 'grps') {
215f4476bd9SJan Schumann                                $info[$localkey][] = $match[1];
216f4476bd9SJan Schumann                            } else {
217f4476bd9SJan Schumann                                $info[$localkey] = $match[1];
218f4476bd9SJan Schumann                            }
219f4476bd9SJan Schumann                        }
220f4476bd9SJan Schumann                    }
221f4476bd9SJan Schumann                } else {
222f4476bd9SJan Schumann                    $info[$localkey] = $user_result[$key][0];
223f4476bd9SJan Schumann                }
224f4476bd9SJan Schumann            }
225f4476bd9SJan Schumann        }
226f4476bd9SJan Schumann        $user_result = array_merge($info, $user_result);
227f4476bd9SJan Schumann
228f4476bd9SJan Schumann        //get groups for given user if grouptree is given
22970e4a085SAndreas Gohr        if($this->getConf('grouptree') || $this->getConf('groupfilter')) {
23070e4a085SAndreas Gohr            $base   = $this->_makeFilter($this->getConf('grouptree'), $user_result);
23170e4a085SAndreas Gohr            $filter = $this->_makeFilter($this->getConf('groupfilter'), $user_result);
23270e4a085SAndreas Gohr            $sr     = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('groupscope'), array($this->getConf('groupkey')));
23370e4a085SAndreas Gohr            $this->_debug('LDAP group search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
23470e4a085SAndreas Gohr            $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__);
23570e4a085SAndreas Gohr
236f4476bd9SJan Schumann            if(!$sr) {
237f4476bd9SJan Schumann                msg("LDAP: Reading group memberships failed", -1);
238f4476bd9SJan Schumann                return false;
239f4476bd9SJan Schumann            }
240f4476bd9SJan Schumann            $result = ldap_get_entries($this->con, $sr);
241f4476bd9SJan Schumann            ldap_free_result($sr);
242f4476bd9SJan Schumann
243f4476bd9SJan Schumann            if(is_array($result)) foreach($result as $grp) {
2449f72d639SAndreas Gohr                if(!empty($grp[$this->getConf('groupkey')])) {
2459f72d639SAndreas Gohr                    $group = $grp[$this->getConf('groupkey')];
2469f72d639SAndreas Gohr                    if(is_array($group)){
2479f72d639SAndreas Gohr                        $group = $group[0];
2489f72d639SAndreas Gohr                    } else {
2499f72d639SAndreas Gohr                        $this->_debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
2509f72d639SAndreas Gohr                    }
2519f72d639SAndreas Gohr                    if($group === '') continue;
2529f72d639SAndreas Gohr
2539f72d639SAndreas Gohr                    $this->_debug('LDAP usergroup: '.htmlspecialchars($group), 0, __LINE__, __FILE__);
2549f72d639SAndreas Gohr                    $info['grps'][] = $group;
255f4476bd9SJan Schumann                }
256f4476bd9SJan Schumann            }
257f4476bd9SJan Schumann        }
258f4476bd9SJan Schumann
259f4476bd9SJan Schumann        // always add the default group to the list of groups
26004e4890dSAndreas Gohr        if(!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) {
261f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
262f4476bd9SJan Schumann        }
263f4476bd9SJan Schumann        return $info;
264f4476bd9SJan Schumann    }
265f4476bd9SJan Schumann
266f4476bd9SJan Schumann    /**
26706da270eSAxel Angel     * Definition of the function modifyUser in order to modify the password
26806da270eSAxel Angel     */
26906da270eSAxel Angel
27006da270eSAxel Angel    function modifyUser($user,$changes){
27106da270eSAxel Angel
27206da270eSAxel Angel        // open the connection to the ldap
27306da270eSAxel Angel        if(!$this->_openLDAP()){
27406da270eSAxel Angel            msg('LDAP cannot connect: '. htmlspecialchars(ldap_error($this->con)));
27506da270eSAxel Angel            return false;
27606da270eSAxel Angel        }
27706da270eSAxel Angel
27806da270eSAxel Angel        // find the information about the user, in particular the "dn"
27906da270eSAxel Angel        $info = $this->getUserData($user,true);
28006da270eSAxel Angel        if(empty($info['dn'])) {
28106da270eSAxel Angel            msg('LDAP cannot find your user dn: '. htmlspecialchars($info['dn']));
28206da270eSAxel Angel            return false;
28306da270eSAxel Angel        } else {
28406da270eSAxel Angel            $dn = $info['dn'];
28506da270eSAxel Angel        }
28606da270eSAxel Angel
28706da270eSAxel Angel        // find the new password and encrypt it whit SSHA
28806da270eSAxel Angel        if(empty($changes['pass'])) {
28906da270eSAxel Angel            msg('The new password is not allow because it\'s empty');
29006da270eSAxel Angel            return false;
29106da270eSAxel Angel        }
29206da270eSAxel Angel
29306da270eSAxel Angel        // find the old password of the user
29406da270eSAxel Angel        list($loginuser,$loginsticky,$loginpass) = auth_getCookie();
295719c6730SAxel Angel        if ($loginuser !== null) { // the user is currently logged in
296719c6730SAxel Angel            $secret = auth_cookiesalt(!$sticky, true);
29706da270eSAxel Angel            $pass   = auth_decrypt($loginpass, $secret);
29806da270eSAxel Angel
29906da270eSAxel Angel            // bind with the ldap
30006da270eSAxel Angel            if(!@ldap_bind($this->con, $dn, $pass)){
30106da270eSAxel Angel                msg('LDAP user bind failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
30206da270eSAxel Angel                return false;
30306da270eSAxel Angel            }
304719c6730SAxel Angel        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
305719c6730SAxel Angel            // we are changing the password on behalf of the user (eg: forgotten password)
306719c6730SAxel Angel            // bind with the superuser ldap
307719c6730SAxel Angel            if (!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))){
308719c6730SAxel Angel                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
309719c6730SAxel Angel                return false;
310719c6730SAxel Angel            }
311719c6730SAxel Angel        }
312719c6730SAxel Angel        else {
313719c6730SAxel Angel            return false; // no otherway
314719c6730SAxel Angel        }
31506da270eSAxel Angel
316*67723447SAxel Angel        // Generate the salted hashed password for LDAP
317*67723447SAxel Angel        $phash = new PassHash();
318*67723447SAxel Angel        $hash = $phash->hash_ssha($changes['pass']);
319*67723447SAxel Angel
32006da270eSAxel Angel        // change the password
32106da270eSAxel Angel        if(!@ldap_mod_replace($this->con, $dn,array('userpassword' => $hash))){
32206da270eSAxel Angel            msg('LDAP mod replace failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)));
32306da270eSAxel Angel            return false;
32406da270eSAxel Angel        }
32506da270eSAxel Angel
32606da270eSAxel Angel        return true;
32706da270eSAxel Angel    }
32806da270eSAxel Angel
32906da270eSAxel Angel    /**
330f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
33170e4a085SAndreas Gohr     *
33270e4a085SAndreas Gohr     * @return bool
333f4476bd9SJan Schumann     */
33470e4a085SAndreas Gohr    public function isCaseSensitive() {
335f4476bd9SJan Schumann        return false;
336f4476bd9SJan Schumann    }
337f4476bd9SJan Schumann
338f4476bd9SJan Schumann    /**
339f4476bd9SJan Schumann     * Bulk retrieval of user data
340f4476bd9SJan Schumann     *
341f4476bd9SJan Schumann     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
34270e4a085SAndreas Gohr     * @param   int   $start     index of first user to be returned
34370e4a085SAndreas Gohr     * @param   int   $limit     max number of users to be returned
34470e4a085SAndreas Gohr     * @param   array $filter  array of field/pattern pairs, null for no filter
345f4476bd9SJan Schumann     * @return  array of userinfo (refer getUserData for internal userinfo details)
346f4476bd9SJan Schumann     */
3479a2c73e8SAndreas Gohr    function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
348f4476bd9SJan Schumann        if(!$this->_openLDAP()) return false;
349f4476bd9SJan Schumann
35070e4a085SAndreas Gohr        if(is_null($this->users)) {
351f4476bd9SJan Schumann            // Perform the search and grab all their details
35270e4a085SAndreas Gohr            if($this->getConf('userfilter')) {
35370e4a085SAndreas Gohr                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
354f4476bd9SJan Schumann            } else {
355f4476bd9SJan Schumann                $all_filter = "(ObjectClass=*)";
356f4476bd9SJan Schumann            }
35770e4a085SAndreas Gohr            $sr          = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
358f4476bd9SJan Schumann            $entries     = ldap_get_entries($this->con, $sr);
359f4476bd9SJan Schumann            $users_array = array();
360f4476bd9SJan Schumann            for($i = 0; $i < $entries["count"]; $i++) {
361f4476bd9SJan Schumann                array_push($users_array, $entries[$i]["uid"][0]);
362f4476bd9SJan Schumann            }
363f4476bd9SJan Schumann            asort($users_array);
364f4476bd9SJan Schumann            $result = $users_array;
365f4476bd9SJan Schumann            if(!$result) return array();
366f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
367f4476bd9SJan Schumann        }
368f4476bd9SJan Schumann        $i     = 0;
369f4476bd9SJan Schumann        $count = 0;
370f4476bd9SJan Schumann        $this->_constructPattern($filter);
371f4476bd9SJan Schumann        $result = array();
372f4476bd9SJan Schumann
373f4476bd9SJan Schumann        foreach($this->users as $user => &$info) {
374f4476bd9SJan Schumann            if($i++ < $start) {
375f4476bd9SJan Schumann                continue;
376f4476bd9SJan Schumann            }
377f4476bd9SJan Schumann            if($info === false) {
378f4476bd9SJan Schumann                $info = $this->getUserData($user);
379f4476bd9SJan Schumann            }
380f4476bd9SJan Schumann            if($this->_filter($user, $info)) {
381f4476bd9SJan Schumann                $result[$user] = $info;
3829a2c73e8SAndreas Gohr                if(($limit > 0) && (++$count >= $limit)) break;
383f4476bd9SJan Schumann            }
384f4476bd9SJan Schumann        }
385f4476bd9SJan Schumann        return $result;
386f4476bd9SJan Schumann    }
387f4476bd9SJan Schumann
388f4476bd9SJan Schumann    /**
389f4476bd9SJan Schumann     * Make LDAP filter strings.
390f4476bd9SJan Schumann     *
391f4476bd9SJan Schumann     * Used by auth_getUserData to make the filter
392f4476bd9SJan Schumann     * strings for grouptree and groupfilter
393f4476bd9SJan Schumann     *
394f4476bd9SJan Schumann     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
39570e4a085SAndreas Gohr     * @param   string $filter ldap search filter with placeholders
39670e4a085SAndreas Gohr     * @param   array  $placeholders placeholders to fill in
397f4476bd9SJan Schumann     * @return  string
398f4476bd9SJan Schumann     */
39970e4a085SAndreas Gohr    protected function _makeFilter($filter, $placeholders) {
400f4476bd9SJan Schumann        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
401f4476bd9SJan Schumann        //replace each match
402f4476bd9SJan Schumann        foreach($matches[1] as $match) {
403f4476bd9SJan Schumann            //take first element if array
404f4476bd9SJan Schumann            if(is_array($placeholders[$match])) {
405f4476bd9SJan Schumann                $value = $placeholders[$match][0];
406f4476bd9SJan Schumann            } else {
407f4476bd9SJan Schumann                $value = $placeholders[$match];
408f4476bd9SJan Schumann            }
409f4476bd9SJan Schumann            $value  = $this->_filterEscape($value);
410f4476bd9SJan Schumann            $filter = str_replace('%{'.$match.'}', $value, $filter);
411f4476bd9SJan Schumann        }
412f4476bd9SJan Schumann        return $filter;
413f4476bd9SJan Schumann    }
414f4476bd9SJan Schumann
415f4476bd9SJan Schumann    /**
41670e4a085SAndreas Gohr     * return true if $user + $info match $filter criteria, false otherwise
417f4476bd9SJan Schumann     *
418f4476bd9SJan Schumann     * @author Chris Smith <chris@jalakai.co.uk>
41970e4a085SAndreas Gohr     *
42070e4a085SAndreas Gohr     * @param  string $user the user's login name
42170e4a085SAndreas Gohr     * @param  array  $info the user's userinfo array
42270e4a085SAndreas Gohr     * @return bool
423f4476bd9SJan Schumann     */
42470e4a085SAndreas Gohr    protected  function _filter($user, $info) {
425f4476bd9SJan Schumann        foreach($this->_pattern as $item => $pattern) {
426f4476bd9SJan Schumann            if($item == 'user') {
42770e4a085SAndreas Gohr                if(!preg_match($pattern, $user)) return false;
428f4476bd9SJan Schumann            } else if($item == 'grps') {
42970e4a085SAndreas Gohr                if(!count(preg_grep($pattern, $info['grps']))) return false;
430f4476bd9SJan Schumann            } else {
43170e4a085SAndreas Gohr                if(!preg_match($pattern, $info[$item])) return false;
432f4476bd9SJan Schumann            }
433f4476bd9SJan Schumann        }
43470e4a085SAndreas Gohr        return true;
435f4476bd9SJan Schumann    }
436f4476bd9SJan Schumann
43770e4a085SAndreas Gohr    /**
43870e4a085SAndreas Gohr     * Set the filter pattern
43970e4a085SAndreas Gohr     *
44070e4a085SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
44170e4a085SAndreas Gohr     *
44270e4a085SAndreas Gohr     * @param $filter
44370e4a085SAndreas Gohr     * @return void
44470e4a085SAndreas Gohr     */
44570e4a085SAndreas Gohr    protected function _constructPattern($filter) {
446f4476bd9SJan Schumann        $this->_pattern = array();
447f4476bd9SJan Schumann        foreach($filter as $item => $pattern) {
448f4476bd9SJan Schumann            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
449f4476bd9SJan Schumann        }
450f4476bd9SJan Schumann    }
451f4476bd9SJan Schumann
452f4476bd9SJan Schumann    /**
453f4476bd9SJan Schumann     * Escape a string to be used in a LDAP filter
454f4476bd9SJan Schumann     *
455f4476bd9SJan Schumann     * Ported from Perl's Net::LDAP::Util escape_filter_value
456f4476bd9SJan Schumann     *
457f4476bd9SJan Schumann     * @author Andreas Gohr
45870e4a085SAndreas Gohr     * @param  string $string
45970e4a085SAndreas Gohr     * @return string
460f4476bd9SJan Schumann     */
46170e4a085SAndreas Gohr    protected function _filterEscape($string) {
46270e4a085SAndreas Gohr        return preg_replace(
46370e4a085SAndreas Gohr            '/([\x00-\x1F\*\(\)\\\\])/e',
464f4476bd9SJan Schumann            '"\\\\\".join("",unpack("H2","$1"))',
46570e4a085SAndreas Gohr            $string
46670e4a085SAndreas Gohr        );
467f4476bd9SJan Schumann    }
468f4476bd9SJan Schumann
469f4476bd9SJan Schumann    /**
470f4476bd9SJan Schumann     * Opens a connection to the configured LDAP server and sets the wanted
471f4476bd9SJan Schumann     * option on the connection
472f4476bd9SJan Schumann     *
473f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
474f4476bd9SJan Schumann     */
47570e4a085SAndreas Gohr    protected function _openLDAP() {
476f4476bd9SJan Schumann        if($this->con) return true; // connection already established
477f4476bd9SJan Schumann
478f4476bd9SJan Schumann        $this->bound = 0;
479f4476bd9SJan Schumann
48070e4a085SAndreas Gohr        $port    = $this->getConf('port');
48193a7873eSAndreas Gohr        $bound   = false;
48270e4a085SAndreas Gohr        $servers = explode(',', $this->getConf('server'));
48393a7873eSAndreas Gohr        foreach($servers as $server) {
48493a7873eSAndreas Gohr            $server    = trim($server);
48593a7873eSAndreas Gohr            $this->con = @ldap_connect($server, $port);
486f4476bd9SJan Schumann            if(!$this->con) {
48793a7873eSAndreas Gohr                continue;
488f4476bd9SJan Schumann            }
489f4476bd9SJan Schumann
49093a7873eSAndreas Gohr            /*
49193a7873eSAndreas Gohr             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
49293a7873eSAndreas Gohr             * not actually connect but just initializes the connecting parameters. The actual
49393a7873eSAndreas Gohr             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
49493a7873eSAndreas Gohr             *
49593a7873eSAndreas Gohr             * So we should try to bind to server in order to check its availability.
49693a7873eSAndreas Gohr             */
49793a7873eSAndreas Gohr
498f4476bd9SJan Schumann            //set protocol version and dependend options
49970e4a085SAndreas Gohr            if($this->getConf('version')) {
50070e4a085SAndreas Gohr                if(!@ldap_set_option(
50170e4a085SAndreas Gohr                    $this->con, LDAP_OPT_PROTOCOL_VERSION,
50270e4a085SAndreas Gohr                    $this->getConf('version')
50370e4a085SAndreas Gohr                )
50470e4a085SAndreas Gohr                ) {
50570e4a085SAndreas Gohr                    msg('Setting LDAP Protocol version '.$this->getConf('version').' failed', -1);
50670e4a085SAndreas Gohr                    $this->_debug('LDAP version set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
507f4476bd9SJan Schumann                } else {
508f4476bd9SJan Schumann                    //use TLS (needs version 3)
50970e4a085SAndreas Gohr                    if($this->getConf('starttls')) {
510f4476bd9SJan Schumann                        if(!@ldap_start_tls($this->con)) {
511f4476bd9SJan Schumann                            msg('Starting TLS failed', -1);
51270e4a085SAndreas Gohr                            $this->_debug('LDAP TLS set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
513f4476bd9SJan Schumann                        }
514f4476bd9SJan Schumann                    }
515f4476bd9SJan Schumann                    // needs version 3
51670e4a085SAndreas Gohr                    if($this->getConf('referrals')) {
51770e4a085SAndreas Gohr                        if(!@ldap_set_option(
51870e4a085SAndreas Gohr                            $this->con, LDAP_OPT_REFERRALS,
51970e4a085SAndreas Gohr                            $this->getConf('referrals')
52070e4a085SAndreas Gohr                        )
52170e4a085SAndreas Gohr                        ) {
522f4476bd9SJan Schumann                            msg('Setting LDAP referrals to off failed', -1);
52370e4a085SAndreas Gohr                            $this->_debug('LDAP referal set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
524f4476bd9SJan Schumann                        }
525f4476bd9SJan Schumann                    }
526f4476bd9SJan Schumann                }
527f4476bd9SJan Schumann            }
528f4476bd9SJan Schumann
529f4476bd9SJan Schumann            //set deref mode
53070e4a085SAndreas Gohr            if($this->getConf('deref')) {
53170e4a085SAndreas Gohr                if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
53270e4a085SAndreas Gohr                    msg('Setting LDAP Deref mode '.$this->getConf('deref').' failed', -1);
53370e4a085SAndreas Gohr                    $this->_debug('LDAP deref set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
534f4476bd9SJan Schumann                }
535f4476bd9SJan Schumann            }
53693a7873eSAndreas Gohr            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
53793a7873eSAndreas Gohr            if(defined('LDAP_OPT_NETWORK_TIMEOUT')) {
53893a7873eSAndreas Gohr                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
53993a7873eSAndreas Gohr            }
540a426a6cdSAndreas Gohr
541a426a6cdSAndreas Gohr            if($this->getConf('binddn') && $this->getConf('bindpw')) {
542a426a6cdSAndreas Gohr                $bound = @ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'));
543a426a6cdSAndreas Gohr                $this->bound = 2;
544a426a6cdSAndreas Gohr            } else {
54593a7873eSAndreas Gohr                $bound = @ldap_bind($this->con);
546a426a6cdSAndreas Gohr            }
54793a7873eSAndreas Gohr            if($bound) {
54893a7873eSAndreas Gohr                break;
54993a7873eSAndreas Gohr            }
55093a7873eSAndreas Gohr        }
55193a7873eSAndreas Gohr
55293a7873eSAndreas Gohr        if(!$bound) {
55393a7873eSAndreas Gohr            msg("LDAP: couldn't connect to LDAP server", -1);
55493a7873eSAndreas Gohr            return false;
55593a7873eSAndreas Gohr        }
55693a7873eSAndreas Gohr
55770e4a085SAndreas Gohr        $this->cando['getUsers'] = true;
558f4476bd9SJan Schumann        return true;
559f4476bd9SJan Schumann    }
560f4476bd9SJan Schumann
561f4476bd9SJan Schumann    /**
562f4476bd9SJan Schumann     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
563f4476bd9SJan Schumann     *
564f4476bd9SJan Schumann     * @author Andreas Gohr <andi@splitbrain.org>
56570e4a085SAndreas Gohr     * @param resource $link_identifier
56670e4a085SAndreas Gohr     * @param string   $base_dn
56770e4a085SAndreas Gohr     * @param string   $filter
56870e4a085SAndreas Gohr     * @param string   $scope can be 'base', 'one' or 'sub'
56970e4a085SAndreas Gohr     * @param null     $attributes
57070e4a085SAndreas Gohr     * @param int      $attrsonly
57170e4a085SAndreas Gohr     * @param int      $sizelimit
57270e4a085SAndreas Gohr     * @param int      $timelimit
57370e4a085SAndreas Gohr     * @param int      $deref
57470e4a085SAndreas Gohr     * @return resource
575f4476bd9SJan Schumann     */
57670e4a085SAndreas Gohr    protected function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null,
577e7fbe189SAndreas Gohr                         $attrsonly = 0, $sizelimit = 0) {
578f4476bd9SJan Schumann        if(is_null($attributes)) $attributes = array();
579f4476bd9SJan Schumann
580f4476bd9SJan Schumann        if($scope == 'base') {
58170e4a085SAndreas Gohr            return @ldap_read(
58270e4a085SAndreas Gohr                $link_identifier, $base_dn, $filter, $attributes,
583e7fbe189SAndreas Gohr                $attrsonly, $sizelimit
58470e4a085SAndreas Gohr            );
585f4476bd9SJan Schumann        } elseif($scope == 'one') {
58670e4a085SAndreas Gohr            return @ldap_list(
58770e4a085SAndreas Gohr                $link_identifier, $base_dn, $filter, $attributes,
588e7fbe189SAndreas Gohr                $attrsonly, $sizelimit
58970e4a085SAndreas Gohr            );
590f4476bd9SJan Schumann        } else {
59170e4a085SAndreas Gohr            return @ldap_search(
59270e4a085SAndreas Gohr                $link_identifier, $base_dn, $filter, $attributes,
593e7fbe189SAndreas Gohr                $attrsonly, $sizelimit
59470e4a085SAndreas Gohr            );
595f4476bd9SJan Schumann        }
596f4476bd9SJan Schumann    }
59770e4a085SAndreas Gohr
59870e4a085SAndreas Gohr    /**
59970e4a085SAndreas Gohr     * Wrapper around msg() but outputs only when debug is enabled
60070e4a085SAndreas Gohr     *
60170e4a085SAndreas Gohr     * @param string $message
60270e4a085SAndreas Gohr     * @param int    $err
60370e4a085SAndreas Gohr     * @param int    $line
60470e4a085SAndreas Gohr     * @param string $file
60570e4a085SAndreas Gohr     * @return void
60670e4a085SAndreas Gohr     */
60770e4a085SAndreas Gohr    protected function _debug($message, $err, $line, $file) {
60870e4a085SAndreas Gohr        if(!$this->getConf('debug')) return;
60970e4a085SAndreas Gohr        msg($message, $err, $line, $file);
61070e4a085SAndreas Gohr    }
61170e4a085SAndreas Gohr
612f4476bd9SJan Schumann}
613