xref: /dokuwiki/lib/plugins/authad/auth.php (revision 7910cbbbce7fd803f3ee4f458d5426eac51bfd89)
1f4476bd9SJan Schumann<?php
2f4476bd9SJan Schumann// must be run within Dokuwiki
3f4476bd9SJan Schumannif(!defined('DOKU_INC')) die();
4f4476bd9SJan Schumann
532fd494aSAndreas Gohrrequire_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
632fd494aSAndreas Gohr
7f4476bd9SJan Schumann/**
8f4476bd9SJan Schumann * Active Directory authentication backend for DokuWiki
9f4476bd9SJan Schumann *
10f4476bd9SJan Schumann * This makes authentication with a Active Directory server much easier
11f4476bd9SJan Schumann * than when using the normal LDAP backend by utilizing the adLDAP library
12f4476bd9SJan Schumann *
13f4476bd9SJan Schumann * Usage:
14f4476bd9SJan Schumann *   Set DokuWiki's local.protected.php auth setting to read
15f4476bd9SJan Schumann *
16f4476bd9SJan Schumann *   $conf['authtype']       = 'authad';
17f4476bd9SJan Schumann *
1832fd494aSAndreas Gohr *   $conf['plugin']['authad']['account_suffix']     = '@my.domain.org';
1932fd494aSAndreas Gohr *   $conf['plugin']['authad']['base_dn']            = 'DC=my,DC=domain,DC=org';
2032fd494aSAndreas Gohr *   $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
21f4476bd9SJan Schumann *
22f4476bd9SJan Schumann *   //optional:
2332fd494aSAndreas Gohr *   $conf['plugin']['authad']['sso']                = 1;
243002d731SAndreas Gohr *   $conf['plugin']['authad']['admin_username']     = 'root';
253002d731SAndreas Gohr *   $conf['plugin']['authad']['admin_password']     = 'pass';
2632fd494aSAndreas Gohr *   $conf['plugin']['authad']['real_primarygroup']  = 1;
2732fd494aSAndreas Gohr *   $conf['plugin']['authad']['use_ssl']            = 1;
2832fd494aSAndreas Gohr *   $conf['plugin']['authad']['use_tls']            = 1;
2932fd494aSAndreas Gohr *   $conf['plugin']['authad']['debug']              = 1;
3093a7873eSAndreas Gohr *   // warn user about expiring password this many days in advance:
3132fd494aSAndreas Gohr *   $conf['plugin']['authad']['expirywarn']         = 5;
32f4476bd9SJan Schumann *
33f4476bd9SJan Schumann *   // get additional information to the userinfo array
34f4476bd9SJan Schumann *   // add a list of comma separated ldap contact fields.
35f4476bd9SJan Schumann *   $conf['plugin']['authad']['additional'] = 'field1,field2';
36f4476bd9SJan Schumann *
37f4476bd9SJan Schumann * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
38f4476bd9SJan Schumann * @author  James Van Lommel <jamesvl@gmail.com>
39f4476bd9SJan Schumann * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
40f4476bd9SJan Schumann * @author  Andreas Gohr <andi@splitbrain.org>
41f4476bd9SJan Schumann * @author  Jan Schumann <js@schumann-it.com>
42f4476bd9SJan Schumann */
4393a7873eSAndreas Gohrclass auth_plugin_authad extends DokuWiki_Auth_Plugin {
4432fd494aSAndreas Gohr
4593a7873eSAndreas Gohr    /**
4693a7873eSAndreas Gohr     * @var array hold connection data for a specific AD domain
4793a7873eSAndreas Gohr     */
4893a7873eSAndreas Gohr    protected $opts = array();
4932fd494aSAndreas Gohr
5093a7873eSAndreas Gohr    /**
5193a7873eSAndreas Gohr     * @var array open connections for each AD domain, as adLDAP objects
5293a7873eSAndreas Gohr     */
5393a7873eSAndreas Gohr    protected $adldap = array();
5493a7873eSAndreas Gohr
5593a7873eSAndreas Gohr    /**
5693a7873eSAndreas Gohr     * @var bool message state
5793a7873eSAndreas Gohr     */
5893a7873eSAndreas Gohr    protected $msgshown = false;
5993a7873eSAndreas Gohr
6093a7873eSAndreas Gohr    /**
6193a7873eSAndreas Gohr     * @var array user listing cache
6293a7873eSAndreas Gohr     */
6393a7873eSAndreas Gohr    protected $users = array();
6493a7873eSAndreas Gohr
6593a7873eSAndreas Gohr    /**
6693a7873eSAndreas Gohr     * @var array filter patterns for listing users
6793a7873eSAndreas Gohr     */
6893a7873eSAndreas Gohr    protected $_pattern = array();
69f4476bd9SJan Schumann
70c52f6cd2SMichael Große    protected $_actualstart = 0;
71c52f6cd2SMichael Große
72c52f6cd2SMichael Große    protected $_grpsusers = array();
73c52f6cd2SMichael Große
74f4476bd9SJan Schumann    /**
75f4476bd9SJan Schumann     * Constructor
76f4476bd9SJan Schumann     */
7793a7873eSAndreas Gohr    public function __construct() {
7800d58927SMichael Hamann        global $INPUT;
79454d868bSAndreas Gohr        parent::__construct();
80454d868bSAndreas Gohr
8132fd494aSAndreas Gohr        // we load the config early to modify it a bit here
8232fd494aSAndreas Gohr        $this->loadConfig();
83f4476bd9SJan Schumann
84f4476bd9SJan Schumann        // additional information fields
8532fd494aSAndreas Gohr        if(isset($this->conf['additional'])) {
8632fd494aSAndreas Gohr            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
8732fd494aSAndreas Gohr            $this->conf['additional'] = explode(',', $this->conf['additional']);
8832fd494aSAndreas Gohr        } else $this->conf['additional'] = array();
89f4476bd9SJan Schumann
90f4476bd9SJan Schumann        // ldap extension is needed
91f4476bd9SJan Schumann        if(!function_exists('ldap_connect')) {
9232fd494aSAndreas Gohr            if($this->conf['debug'])
93f4476bd9SJan Schumann                msg("AD Auth: PHP LDAP extension not found.", -1);
94f4476bd9SJan Schumann            $this->success = false;
95f4476bd9SJan Schumann            return;
96f4476bd9SJan Schumann        }
97f4476bd9SJan Schumann
98f4476bd9SJan Schumann        // Prepare SSO
99d34a2a38SAndreas Gohr        if(!empty($_SERVER['REMOTE_USER'])) {
100d34a2a38SAndreas Gohr
101d34a2a38SAndreas Gohr            // make sure the right encoding is used
102d34a2a38SAndreas Gohr            if($this->getConf('sso_charset')) {
103d34a2a38SAndreas Gohr                $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
104d34a2a38SAndreas Gohr            } elseif(!utf8_check($_SERVER['REMOTE_USER'])) {
10593a7873eSAndreas Gohr                $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
10693a7873eSAndreas Gohr            }
107d34a2a38SAndreas Gohr
108d34a2a38SAndreas Gohr            // trust the incoming user
109d34a2a38SAndreas Gohr            if($this->conf['sso']) {
11093a7873eSAndreas Gohr                $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
111f4476bd9SJan Schumann
112f4476bd9SJan Schumann                // we need to simulate a login
113f4476bd9SJan Schumann                if(empty($_COOKIE[DOKU_COOKIE])) {
11400d58927SMichael Hamann                    $INPUT->set('u', $_SERVER['REMOTE_USER']);
11500d58927SMichael Hamann                    $INPUT->set('p', 'sso_only');
116f4476bd9SJan Schumann                }
117f4476bd9SJan Schumann            }
118d34a2a38SAndreas Gohr        }
119f4476bd9SJan Schumann
12093a7873eSAndreas Gohr        // other can do's are changed in $this->_loadServerConfig() base on domain setup
121f4476bd9SJan Schumann        $this->cando['modName'] = true;
122f4476bd9SJan Schumann        $this->cando['modMail'] = true;
12325f80763SMichael Große        $this->cando['getUserCount'] = true;
124f4476bd9SJan Schumann    }
125f4476bd9SJan Schumann
126f4476bd9SJan Schumann    /**
127a154806fSAndreas Gohr     * Load domain config on capability check
128a154806fSAndreas Gohr     *
129a154806fSAndreas Gohr     * @param string $cap
130a154806fSAndreas Gohr     * @return bool
131a154806fSAndreas Gohr     */
132a154806fSAndreas Gohr    public function canDo($cap) {
133a154806fSAndreas Gohr        //capabilities depend on config, which may change depending on domain
134a154806fSAndreas Gohr        $domain = $this->_userDomain($_SERVER['REMOTE_USER']);
135a154806fSAndreas Gohr        $this->_loadServerConfig($domain);
136a154806fSAndreas Gohr        return parent::canDo($cap);
137a154806fSAndreas Gohr    }
138a154806fSAndreas Gohr
139a154806fSAndreas Gohr    /**
140f4476bd9SJan Schumann     * Check user+password [required auth function]
141f4476bd9SJan Schumann     *
142f4476bd9SJan Schumann     * Checks if the given user exists and the given
143f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
144f4476bd9SJan Schumann     * to the LDAP server
145f4476bd9SJan Schumann     *
146f4476bd9SJan Schumann     * @author  James Van Lommel <james@nosq.com>
14793a7873eSAndreas Gohr     * @param string $user
14893a7873eSAndreas Gohr     * @param string $pass
149f4476bd9SJan Schumann     * @return  bool
150f4476bd9SJan Schumann     */
15193a7873eSAndreas Gohr    public function checkPass($user, $pass) {
152f4476bd9SJan Schumann        if($_SERVER['REMOTE_USER'] &&
153f4476bd9SJan Schumann            $_SERVER['REMOTE_USER'] == $user &&
15432fd494aSAndreas Gohr            $this->conf['sso']
15593a7873eSAndreas Gohr        ) return true;
156f4476bd9SJan Schumann
15793a7873eSAndreas Gohr        $adldap = $this->_adldap($this->_userDomain($user));
15893a7873eSAndreas Gohr        if(!$adldap) return false;
15993a7873eSAndreas Gohr
16093a7873eSAndreas Gohr        return $adldap->authenticate($this->_userName($user), $pass);
161f4476bd9SJan Schumann    }
162f4476bd9SJan Schumann
163f4476bd9SJan Schumann    /**
164f4476bd9SJan Schumann     * Return user info [required auth function]
165f4476bd9SJan Schumann     *
166f4476bd9SJan Schumann     * Returns info about the given user needs to contain
167f4476bd9SJan Schumann     * at least these fields:
168f4476bd9SJan Schumann     *
169f4476bd9SJan Schumann     * name    string  full name of the user
170f4476bd9SJan Schumann     * mail    string  email address of the user
171f4476bd9SJan Schumann     * grps    array   list of groups the user is in
172f4476bd9SJan Schumann     *
17393a7873eSAndreas Gohr     * This AD specific function returns the following
174f4476bd9SJan Schumann     * addional fields:
175f4476bd9SJan Schumann     *
176f4476bd9SJan Schumann     * dn         string    distinguished name (DN)
17793a7873eSAndreas Gohr     * uid        string    samaccountname
17893a7873eSAndreas Gohr     * lastpwd    int       timestamp of the date when the password was set
17993a7873eSAndreas Gohr     * expires    true      if the password expires
18093a7873eSAndreas Gohr     * expiresin  int       seconds until the password expires
18193a7873eSAndreas Gohr     * any fields specified in the 'additional' config option
182f4476bd9SJan Schumann     *
183f4476bd9SJan Schumann     * @author  James Van Lommel <james@nosq.com>
18493a7873eSAndreas Gohr     * @param string $user
1852046a654SChristopher Smith     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
18693a7873eSAndreas Gohr     * @return array
187f4476bd9SJan Schumann     */
1882046a654SChristopher Smith    public function getUserData($user, $requireGroups=true) {
189f4476bd9SJan Schumann        global $conf;
19093a7873eSAndreas Gohr        global $lang;
19193a7873eSAndreas Gohr        global $ID;
19293a7873eSAndreas Gohr        $adldap = $this->_adldap($this->_userDomain($user));
19393a7873eSAndreas Gohr        if(!$adldap) return false;
194f4476bd9SJan Schumann
19593a7873eSAndreas Gohr        if($user == '') return array();
19693a7873eSAndreas Gohr
19793a7873eSAndreas Gohr        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
198f4476bd9SJan Schumann
199f4476bd9SJan Schumann        // add additional fields to read
20032fd494aSAndreas Gohr        $fields = array_merge($fields, $this->conf['additional']);
201f4476bd9SJan Schumann        $fields = array_unique($fields);
20214642325SAndreas Gohr        $fields = array_filter($fields);
203f4476bd9SJan Schumann
204f4476bd9SJan Schumann        //get info for given user
20532fd494aSAndreas Gohr        $result = $adldap->user()->info($this->_userName($user), $fields);
20693a7873eSAndreas Gohr        if($result == false){
20793a7873eSAndreas Gohr            return array();
20893a7873eSAndreas Gohr        }
20993a7873eSAndreas Gohr
210f4476bd9SJan Schumann        //general user info
21159bc3b48SGerrit Uitslag        $info = array();
212f4476bd9SJan Schumann        $info['name'] = $result[0]['displayname'][0];
213f4476bd9SJan Schumann        $info['mail'] = $result[0]['mail'][0];
214f4476bd9SJan Schumann        $info['uid']  = $result[0]['samaccountname'][0];
215f4476bd9SJan Schumann        $info['dn']   = $result[0]['dn'];
21693a7873eSAndreas Gohr        //last password set (Windows counts from January 1st 1601)
21793a7873eSAndreas Gohr        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
21893a7873eSAndreas Gohr        //will it expire?
21993a7873eSAndreas Gohr        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
220f4476bd9SJan Schumann
221f4476bd9SJan Schumann        // additional information
22232fd494aSAndreas Gohr        foreach($this->conf['additional'] as $field) {
223f4476bd9SJan Schumann            if(isset($result[0][strtolower($field)])) {
224f4476bd9SJan Schumann                $info[$field] = $result[0][strtolower($field)][0];
225f4476bd9SJan Schumann            }
226f4476bd9SJan Schumann        }
227f4476bd9SJan Schumann
228f4476bd9SJan Schumann        // handle ActiveDirectory memberOf
22932fd494aSAndreas Gohr        $info['grps'] = $adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']);
230f4476bd9SJan Schumann
231f4476bd9SJan Schumann        if(is_array($info['grps'])) {
232f4476bd9SJan Schumann            foreach($info['grps'] as $ndx => $group) {
233f4476bd9SJan Schumann                $info['grps'][$ndx] = $this->cleanGroup($group);
234f4476bd9SJan Schumann            }
235f4476bd9SJan Schumann        }
236f4476bd9SJan Schumann
237f4476bd9SJan Schumann        // always add the default group to the list of groups
238f4476bd9SJan Schumann        if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
239f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
240f4476bd9SJan Schumann        }
241f4476bd9SJan Schumann
24293a7873eSAndreas Gohr        // add the user's domain to the groups
24393a7873eSAndreas Gohr        $domain = $this->_userDomain($user);
24493a7873eSAndreas Gohr        if($domain && !in_array("domain-$domain", (array) $info['grps'])) {
24593a7873eSAndreas Gohr            $info['grps'][] = $this->cleanGroup("domain-$domain");
24693a7873eSAndreas Gohr        }
24793a7873eSAndreas Gohr
24893a7873eSAndreas Gohr        // check expiry time
24932fd494aSAndreas Gohr        if($info['expires'] && $this->conf['expirywarn']){
2501e52e72aSAndreas Gohr            $expiry = $adldap->user()->passwordExpiry($user);
2511e52e72aSAndreas Gohr            if(is_array($expiry)){
2521e52e72aSAndreas Gohr                $info['expiresat'] = $expiry['expiryts'];
2531e52e72aSAndreas Gohr                $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
25493a7873eSAndreas Gohr
25593a7873eSAndreas Gohr                // if this is the current user, warn him (once per request only)
25693a7873eSAndreas Gohr                if(($_SERVER['REMOTE_USER'] == $user) &&
2571e52e72aSAndreas Gohr                    ($info['expiresin'] <= $this->conf['expirywarn']) &&
25893a7873eSAndreas Gohr                    !$this->msgshown
25993a7873eSAndreas Gohr                ) {
2601e52e72aSAndreas Gohr                    $msg = sprintf($lang['authpwdexpire'], $info['expiresin']);
26193a7873eSAndreas Gohr                    if($this->canDo('modPass')) {
26293a7873eSAndreas Gohr                        $url = wl($ID, array('do'=> 'profile'));
26393a7873eSAndreas Gohr                        $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
26493a7873eSAndreas Gohr                    }
26593a7873eSAndreas Gohr                    msg($msg);
26693a7873eSAndreas Gohr                    $this->msgshown = true;
26793a7873eSAndreas Gohr                }
26893a7873eSAndreas Gohr            }
2691e52e72aSAndreas Gohr        }
27093a7873eSAndreas Gohr
271f4476bd9SJan Schumann        return $info;
272f4476bd9SJan Schumann    }
273f4476bd9SJan Schumann
274f4476bd9SJan Schumann    /**
275f4476bd9SJan Schumann     * Make AD group names usable by DokuWiki.
276f4476bd9SJan Schumann     *
277f4476bd9SJan Schumann     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
278f4476bd9SJan Schumann     *
279f4476bd9SJan Schumann     * @author  James Van Lommel (jamesvl@gmail.com)
28093a7873eSAndreas Gohr     * @param string $group
28193a7873eSAndreas Gohr     * @return string
282f4476bd9SJan Schumann     */
28393a7873eSAndreas Gohr    public function cleanGroup($group) {
28493a7873eSAndreas Gohr        $group = str_replace('\\', '', $group);
28593a7873eSAndreas Gohr        $group = str_replace('#', '', $group);
28693a7873eSAndreas Gohr        $group = preg_replace('[\s]', '_', $group);
28793a7873eSAndreas Gohr        $group = utf8_strtolower(trim($group));
28893a7873eSAndreas Gohr        return $group;
289f4476bd9SJan Schumann    }
290f4476bd9SJan Schumann
291f4476bd9SJan Schumann    /**
292f4476bd9SJan Schumann     * Sanitize user names
29393a7873eSAndreas Gohr     *
29493a7873eSAndreas Gohr     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
29593a7873eSAndreas Gohr     *
29693a7873eSAndreas Gohr     * @author Andreas Gohr <gohr@cosmocode.de>
29793a7873eSAndreas Gohr     * @param string $user
29893a7873eSAndreas Gohr     * @return string
299f4476bd9SJan Schumann     */
30093a7873eSAndreas Gohr    public function cleanUser($user) {
30193a7873eSAndreas Gohr        $domain = '';
30293a7873eSAndreas Gohr
30393a7873eSAndreas Gohr        // get NTLM or Kerberos domain part
30493a7873eSAndreas Gohr        list($dom, $user) = explode('\\', $user, 2);
30593a7873eSAndreas Gohr        if(!$user) $user = $dom;
30693a7873eSAndreas Gohr        if($dom) $domain = $dom;
30793a7873eSAndreas Gohr        list($user, $dom) = explode('@', $user, 2);
30893a7873eSAndreas Gohr        if($dom) $domain = $dom;
30993a7873eSAndreas Gohr
31093a7873eSAndreas Gohr        // clean up both
31193a7873eSAndreas Gohr        $domain = utf8_strtolower(trim($domain));
31293a7873eSAndreas Gohr        $user   = utf8_strtolower(trim($user));
31393a7873eSAndreas Gohr
31493a7873eSAndreas Gohr        // is this a known, valid domain? if not discard
31532fd494aSAndreas Gohr        if(!is_array($this->conf[$domain])) {
31693a7873eSAndreas Gohr            $domain = '';
31793a7873eSAndreas Gohr        }
31893a7873eSAndreas Gohr
31993a7873eSAndreas Gohr        // reattach domain
32093a7873eSAndreas Gohr        if($domain) $user = "$user@$domain";
32193a7873eSAndreas Gohr        return $user;
322f4476bd9SJan Schumann    }
323f4476bd9SJan Schumann
324f4476bd9SJan Schumann    /**
325f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
32693a7873eSAndreas Gohr     *
32793a7873eSAndreas Gohr     * @return bool
328f4476bd9SJan Schumann     */
32993a7873eSAndreas Gohr    public function isCaseSensitive() {
330f4476bd9SJan Schumann        return false;
331f4476bd9SJan Schumann    }
332f4476bd9SJan Schumann
3336fcf992cSMichael Große    /**
334*7910cbbbSMichael Große     * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
335*7910cbbbSMichael Große     *
3366fcf992cSMichael Große     * @param array $filter
3376fcf992cSMichael Große     * @return string
3386fcf992cSMichael Große     */
33967a31a83SMichael Große    protected function _constructSearchString($filter){
34067a31a83SMichael Große        if (!$filter){
34167a31a83SMichael Große            return '*';
34267a31a83SMichael Große        }
34367a31a83SMichael Große        $result = '*';
34467a31a83SMichael Große        if (isset($filter['name'])) {
34567a31a83SMichael Große            $result .= ')(displayname=*' . $filter['name'] . '*';
34667a31a83SMichael Große            unset($filter['name']);
34767a31a83SMichael Große        }
348*7910cbbbSMichael Große
34967a31a83SMichael Große        if (isset($filter['user'])) {
35067a31a83SMichael Große            $result .= ')(samAccountName=*' . $filter['user'] . '*';
35167a31a83SMichael Große            unset($filter['user']);
35267a31a83SMichael Große        }
35367a31a83SMichael Große
35467a31a83SMichael Große        if (isset($filter['mail'])) {
35567a31a83SMichael Große            $result .= ')(mail=*' . $filter['mail'] . '*';
35667a31a83SMichael Große            unset($filter['mail']);
35767a31a83SMichael Große        }
35867a31a83SMichael Große        return $result;
35967a31a83SMichael Große    }
36067a31a83SMichael Große
361f4476bd9SJan Schumann    /**
362*7910cbbbSMichael Große     * Return a count of the number of user which meet $filter criteria
363*7910cbbbSMichael Große     *
364*7910cbbbSMichael Große     * @param array $filter  $filter array of field/pattern pairs, empty array for no filter
365*7910cbbbSMichael Große     * @return int number of users
36625f80763SMichael Große     */
36725f80763SMichael Große    public function getUserCount($filter = array()) {
3686fcf992cSMichael Große        $adldap = $this->_adldap(null);
3696fcf992cSMichael Große        if(!$adldap) {
3706fcf992cSMichael Große            dbglog("authad/auth.php getUserCount(): _adldap not set.");
3716fcf992cSMichael Große            return -1;
3726fcf992cSMichael Große        }
37367a31a83SMichael Große        if ($filter == array()) {
37425f80763SMichael Große            $result = $adldap->user()->all();
37567a31a83SMichael Große        } else {
37667a31a83SMichael Große            $searchString = $this->_constructSearchString($filter);
37767a31a83SMichael Große            $result = $adldap->user()->all(false, $searchString);
378c52f6cd2SMichael Große            if (isset($filter['grps'])) {
379c52f6cd2SMichael Große                $this->users = array_fill_keys($result, false);
380c52f6cd2SMichael Große                $usermanager = plugin_load("admin", "usermanager", false);
381462e9e37SMichael Große                $usermanager->setLastdisabled(true);
382c52f6cd2SMichael Große                if (!isset($this->_grpsusers[$this->_filterToString($filter)])){
383c52f6cd2SMichael Große                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize());
3846fcf992cSMichael Große                } elseif (count($this->_grpsusers[$this->_filterToString($filter)]) < $usermanager->getStart() + 3*$usermanager->getPagesize()) {
385c52f6cd2SMichael Große                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize() - count($this->_grpsusers[$this->_filterToString($filter)]));
386c52f6cd2SMichael Große                }
387c52f6cd2SMichael Große                $result = $this->_grpsusers[$this->_filterToString($filter)];
388462e9e37SMichael Große            } else {
389462e9e37SMichael Große                $usermanager = plugin_load("admin", "usermanager", false);
390462e9e37SMichael Große                $usermanager->setLastdisabled(false);
391c52f6cd2SMichael Große            }
39267a31a83SMichael Große
39367a31a83SMichael Große        }
39467a31a83SMichael Große
39525f80763SMichael Große        if (!$result) {
3966fcf992cSMichael Große            return 0;
39725f80763SMichael Große        }
39825f80763SMichael Große        return count($result);
39925f80763SMichael Große    }
40025f80763SMichael Große
4016fcf992cSMichael Große    /**
4026fcf992cSMichael Große     *
4036fcf992cSMichael Große     * create a unique string for each filter used with a group
4046fcf992cSMichael Große     *
4056fcf992cSMichael Große     * @param array $filter
4066fcf992cSMichael Große     * @return string
4076fcf992cSMichael Große     */
408c52f6cd2SMichael Große    protected function _filterToString ($filter) {
409c52f6cd2SMichael Große        $result = '';
410c52f6cd2SMichael Große        if (isset($filter['user'])) {
411c52f6cd2SMichael Große            $result .= 'user-' . $filter['user'];
412c52f6cd2SMichael Große        }
413c52f6cd2SMichael Große        if (isset($filter['name'])) {
414c52f6cd2SMichael Große            $result .= 'name-' . $filter['name'];
415c52f6cd2SMichael Große        }
416c52f6cd2SMichael Große        if (isset($filter['mail'])) {
417c52f6cd2SMichael Große            $result .= 'mail-' . $filter['mail'];
418c52f6cd2SMichael Große        }
419c52f6cd2SMichael Große        if (isset($filter['grps'])) {
420c52f6cd2SMichael Große            $result .= 'grps-' . $filter['grps'];
421c52f6cd2SMichael Große        }
422c52f6cd2SMichael Große        return $result;
423c52f6cd2SMichael Große    }
424c52f6cd2SMichael Große
4256fcf992cSMichael Große    /**
426*7910cbbbSMichael Große     * Create an array of $numberOfAdds users passing a certain $filter, including belonging
427*7910cbbbSMichael Große     * to a certain group and save them to a object-wide array. If the array
428*7910cbbbSMichael Große     * already exists try to add $numberOfAdds further users to it.
429*7910cbbbSMichael Große     *
4306fcf992cSMichael Große     * @param array $filter
4316fcf992cSMichael Große     * @param int $numberOfAdds additional number of users requested
4326fcf992cSMichael Große     * @return int number of Users actually add to Array
4336fcf992cSMichael Große     */
434c52f6cd2SMichael Große    protected function _fillGroupUserArray($filter, $numberOfAdds){
435c52f6cd2SMichael Große        $this->_grpsusers[$this->_filterToString($filter)];
436c52f6cd2SMichael Große        $i = 0;
437c52f6cd2SMichael Große        $count = 0;
438c52f6cd2SMichael Große        $this->_constructPattern($filter);
439c52f6cd2SMichael Große        foreach ($this->users as $user => &$info) {
440c52f6cd2SMichael Große            if($i++ < $this->_actualstart) {
441c52f6cd2SMichael Große                continue;
442c52f6cd2SMichael Große            }
443c52f6cd2SMichael Große            if($info === false) {
444c52f6cd2SMichael Große                $info = $this->getUserData($user);
445c52f6cd2SMichael Große            }
446c52f6cd2SMichael Große            if($this->_filter($user, $info)) {
447c52f6cd2SMichael Große                $this->_grpsusers[$this->_filterToString($filter)][$user] = $info;
448c52f6cd2SMichael Große                if(($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
449c52f6cd2SMichael Große            }
450c52f6cd2SMichael Große        }
451c52f6cd2SMichael Große        $this->_actualstart = $i;
452c52f6cd2SMichael Große        return $count;
453c52f6cd2SMichael Große    }
454c52f6cd2SMichael Große
45525f80763SMichael Große    /**
456f4476bd9SJan Schumann     * Bulk retrieval of user data
457f4476bd9SJan Schumann     *
458f4476bd9SJan Schumann     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
459253d4b48SGerrit Uitslag     *
46093a7873eSAndreas Gohr     * @param   int $start index of first user to be returned
46193a7873eSAndreas Gohr     * @param   int $limit max number of users to be returned
46293a7873eSAndreas Gohr     * @param   array $filter array of field/pattern pairs, null for no filter
46393a7873eSAndreas Gohr     * @return array userinfo (refer getUserData for internal userinfo details)
464f4476bd9SJan Schumann     */
465c52f6cd2SMichael Große    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
46693a7873eSAndreas Gohr        $adldap = $this->_adldap(null);
46793a7873eSAndreas Gohr        if(!$adldap) return false;
468f4476bd9SJan Schumann
4690ba750c0SAndreas Gohr        if(!$this->users) {
470f4476bd9SJan Schumann            //get info for given user
47167a31a83SMichael Große            $result = $adldap->user()->all(false, $this->_constructSearchString($filter));
472f4476bd9SJan Schumann            if (!$result) return array();
473f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
474f4476bd9SJan Schumann        }
475f4476bd9SJan Schumann
476f4476bd9SJan Schumann        $i     = 0;
477f4476bd9SJan Schumann        $count = 0;
478f4476bd9SJan Schumann        $result = array();
479f4476bd9SJan Schumann
480c52f6cd2SMichael Große        if (!isset($filter['grps'])) {
481462e9e37SMichael Große            $usermanager = plugin_load("admin", "usermanager", false);
482462e9e37SMichael Große            $usermanager->setLastdisabled(false);
4836fcf992cSMichael Große            $this->_constructPattern($filter);
484f4476bd9SJan Schumann            foreach($this->users as $user => &$info) {
485f4476bd9SJan Schumann                if($i++ < $start) {
486f4476bd9SJan Schumann                    continue;
487f4476bd9SJan Schumann                }
488f4476bd9SJan Schumann                if($info === false) {
489f4476bd9SJan Schumann                    $info = $this->getUserData($user);
490f4476bd9SJan Schumann                }
491f4476bd9SJan Schumann                $result[$user] = $info;
4929a2c73e8SAndreas Gohr                if(($limit > 0) && (++$count >= $limit)) break;
493f4476bd9SJan Schumann            }
494c52f6cd2SMichael Große        } else {
495462e9e37SMichael Große            $usermanager = plugin_load("admin", "usermanager", false);
496462e9e37SMichael Große            $usermanager->setLastdisabled(true);
497c52f6cd2SMichael Große            if (!isset($this->_grpsusers[$this->_filterToString($filter)]) || count($this->_grpsusers[$this->_filterToString($filter)]) < ($start+$limit)) {
498c52f6cd2SMichael Große                $this->_fillGroupUserArray($filter,$start+$limit - count($this->_grpsusers[$this->_filterToString($filter)]) +1);
499c52f6cd2SMichael Große            }
5006fcf992cSMichael Große            if (!$this->_grpsusers[$this->_filterToString($filter)]) return false;
501c52f6cd2SMichael Große            foreach($this->_grpsusers[$this->_filterToString($filter)] as $user => &$info) {
502c52f6cd2SMichael Große                if($i++ < $start) {
503c52f6cd2SMichael Große                    continue;
504c52f6cd2SMichael Große                }
505c52f6cd2SMichael Große                $result[$user] = $info;
506c52f6cd2SMichael Große                if(($limit > 0) && (++$count >= $limit)) break;
507c52f6cd2SMichael Große            }
508c52f6cd2SMichael Große
509c52f6cd2SMichael Große        }
510f4476bd9SJan Schumann        return $result;
511f4476bd9SJan Schumann    }
512f4476bd9SJan Schumann
513f4476bd9SJan Schumann    /**
514f4476bd9SJan Schumann     * Modify user data
515f4476bd9SJan Schumann     *
51693a7873eSAndreas Gohr     * @param   string $user      nick of the user to be changed
51793a7873eSAndreas Gohr     * @param   array  $changes   array of field/value pairs to be changed
518f4476bd9SJan Schumann     * @return  bool
519f4476bd9SJan Schumann     */
52093a7873eSAndreas Gohr    public function modifyUser($user, $changes) {
521f4476bd9SJan Schumann        $return = true;
52293a7873eSAndreas Gohr        $adldap = $this->_adldap($this->_userDomain($user));
52393a7873eSAndreas Gohr        if(!$adldap) return false;
524f4476bd9SJan Schumann
525f4476bd9SJan Schumann        // password changing
526f4476bd9SJan Schumann        if(isset($changes['pass'])) {
527f4476bd9SJan Schumann            try {
52832fd494aSAndreas Gohr                $return = $adldap->user()->password($this->_userName($user),$changes['pass']);
529f4476bd9SJan Schumann            } catch (adLDAPException $e) {
53032fd494aSAndreas Gohr                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
531f4476bd9SJan Schumann                $return = false;
532f4476bd9SJan Schumann            }
533f4476bd9SJan Schumann            if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1);
534f4476bd9SJan Schumann        }
535f4476bd9SJan Schumann
536f4476bd9SJan Schumann        // changing user data
537f4476bd9SJan Schumann        $adchanges = array();
538f4476bd9SJan Schumann        if(isset($changes['name'])) {
539f4476bd9SJan Schumann            // get first and last name
540f4476bd9SJan Schumann            $parts                     = explode(' ', $changes['name']);
541f4476bd9SJan Schumann            $adchanges['surname']      = array_pop($parts);
542f4476bd9SJan Schumann            $adchanges['firstname']    = join(' ', $parts);
543f4476bd9SJan Schumann            $adchanges['display_name'] = $changes['name'];
544f4476bd9SJan Schumann        }
545f4476bd9SJan Schumann        if(isset($changes['mail'])) {
546f4476bd9SJan Schumann            $adchanges['email'] = $changes['mail'];
547f4476bd9SJan Schumann        }
548f4476bd9SJan Schumann        if(count($adchanges)) {
549f4476bd9SJan Schumann            try {
55032fd494aSAndreas Gohr                $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges);
551f4476bd9SJan Schumann            } catch (adLDAPException $e) {
55232fd494aSAndreas Gohr                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
553f4476bd9SJan Schumann                $return = false;
554f4476bd9SJan Schumann            }
555f4476bd9SJan Schumann        }
556f4476bd9SJan Schumann
557f4476bd9SJan Schumann        return $return;
558f4476bd9SJan Schumann    }
559f4476bd9SJan Schumann
560f4476bd9SJan Schumann    /**
561f4476bd9SJan Schumann     * Initialize the AdLDAP library and connect to the server
56293a7873eSAndreas Gohr     *
56393a7873eSAndreas Gohr     * When you pass null as domain, it will reuse any existing domain.
56493a7873eSAndreas Gohr     * Eg. the one of the logged in user. It falls back to the default
56593a7873eSAndreas Gohr     * domain if no current one is available.
56693a7873eSAndreas Gohr     *
56793a7873eSAndreas Gohr     * @param string|null $domain The AD domain to use
56893a7873eSAndreas Gohr     * @return adLDAP|bool true if a connection was established
569f4476bd9SJan Schumann     */
57093a7873eSAndreas Gohr    protected function _adldap($domain) {
57193a7873eSAndreas Gohr        if(is_null($domain) && is_array($this->opts)) {
57293a7873eSAndreas Gohr            $domain = $this->opts['domain'];
57393a7873eSAndreas Gohr        }
57493a7873eSAndreas Gohr
57593a7873eSAndreas Gohr        $this->opts = $this->_loadServerConfig((string) $domain);
57693a7873eSAndreas Gohr        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
577f4476bd9SJan Schumann
578f4476bd9SJan Schumann        // connect
579f4476bd9SJan Schumann        try {
58093a7873eSAndreas Gohr            $this->adldap[$domain] = new adLDAP($this->opts);
58193a7873eSAndreas Gohr            return $this->adldap[$domain];
582f4476bd9SJan Schumann        } catch(adLDAPException $e) {
58332fd494aSAndreas Gohr            if($this->conf['debug']) {
584f4476bd9SJan Schumann                msg('AD Auth: '.$e->getMessage(), -1);
585f4476bd9SJan Schumann            }
586f4476bd9SJan Schumann            $this->success         = false;
58793a7873eSAndreas Gohr            $this->adldap[$domain] = null;
588f4476bd9SJan Schumann        }
589f4476bd9SJan Schumann        return false;
590f4476bd9SJan Schumann    }
591f4476bd9SJan Schumann
592f4476bd9SJan Schumann    /**
59393a7873eSAndreas Gohr     * Get the domain part from a user
594f4476bd9SJan Schumann     *
595253d4b48SGerrit Uitslag     * @param string $user
59693a7873eSAndreas Gohr     * @return string
597f4476bd9SJan Schumann     */
59893a7873eSAndreas Gohr    public function _userDomain($user) {
59993a7873eSAndreas Gohr        list(, $domain) = explode('@', $user, 2);
60093a7873eSAndreas Gohr        return $domain;
601f4476bd9SJan Schumann    }
602f4476bd9SJan Schumann
60393a7873eSAndreas Gohr    /**
60493a7873eSAndreas Gohr     * Get the user part from a user
60593a7873eSAndreas Gohr     *
606253d4b48SGerrit Uitslag     * @param string $user
60793a7873eSAndreas Gohr     * @return string
60893a7873eSAndreas Gohr     */
60993a7873eSAndreas Gohr    public function _userName($user) {
61093a7873eSAndreas Gohr        list($name) = explode('@', $user, 2);
61193a7873eSAndreas Gohr        return $name;
61293a7873eSAndreas Gohr    }
61393a7873eSAndreas Gohr
61493a7873eSAndreas Gohr    /**
61593a7873eSAndreas Gohr     * Fetch the configuration for the given AD domain
61693a7873eSAndreas Gohr     *
61793a7873eSAndreas Gohr     * @param string $domain current AD domain
61893a7873eSAndreas Gohr     * @return array
61993a7873eSAndreas Gohr     */
62093a7873eSAndreas Gohr    protected function _loadServerConfig($domain) {
62193a7873eSAndreas Gohr        // prepare adLDAP standard configuration
62232fd494aSAndreas Gohr        $opts = $this->conf;
62393a7873eSAndreas Gohr
62493a7873eSAndreas Gohr        $opts['domain'] = $domain;
62593a7873eSAndreas Gohr
62693a7873eSAndreas Gohr        // add possible domain specific configuration
62732fd494aSAndreas Gohr        if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) {
62893a7873eSAndreas Gohr            $opts[$key] = $val;
62993a7873eSAndreas Gohr        }
63093a7873eSAndreas Gohr
63193a7873eSAndreas Gohr        // handle multiple AD servers
63293a7873eSAndreas Gohr        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
63393a7873eSAndreas Gohr        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
63493a7873eSAndreas Gohr        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
63593a7873eSAndreas Gohr
6368257d713SAndreas Gohr        // compatibility with old option name
6378257d713SAndreas Gohr        if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username'];
6388257d713SAndreas Gohr        if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password'];
6398257d713SAndreas Gohr
64093a7873eSAndreas Gohr        // we can change the password if SSL is set
64193a7873eSAndreas Gohr        if($opts['use_ssl'] || $opts['use_tls']) {
64293a7873eSAndreas Gohr            $this->cando['modPass'] = true;
64393a7873eSAndreas Gohr        } else {
64493a7873eSAndreas Gohr            $this->cando['modPass'] = false;
64593a7873eSAndreas Gohr        }
64693a7873eSAndreas Gohr
64712d195abSAndreas Gohr        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
64812d195abSAndreas Gohr        if(empty($opts['admin_username'])) $opts['admin_username'] = null;
64912d195abSAndreas Gohr        if(empty($opts['admin_password'])) $opts['admin_password'] = null;
65012d195abSAndreas Gohr
65112d195abSAndreas Gohr        // user listing needs admin priviledges
6528257d713SAndreas Gohr        if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
65393a7873eSAndreas Gohr            $this->cando['getUsers'] = true;
65493a7873eSAndreas Gohr        } else {
6551b228d28SKlap-in            $this->cando['getUsers'] = false;
65693a7873eSAndreas Gohr        }
65793a7873eSAndreas Gohr
65893a7873eSAndreas Gohr        return $opts;
65993a7873eSAndreas Gohr    }
66093a7873eSAndreas Gohr
66193a7873eSAndreas Gohr    /**
662741b8a48SAndreas Gohr     * Returns a list of configured domains
663741b8a48SAndreas Gohr     *
664741b8a48SAndreas Gohr     * The default domain has an empty string as key
665741b8a48SAndreas Gohr     *
666741b8a48SAndreas Gohr     * @return array associative array(key => domain)
667741b8a48SAndreas Gohr     */
668741b8a48SAndreas Gohr    public function _getConfiguredDomains() {
669741b8a48SAndreas Gohr        $domains = array();
670741b8a48SAndreas Gohr        if(empty($this->conf['account_suffix'])) return $domains; // not configured yet
671741b8a48SAndreas Gohr
672741b8a48SAndreas Gohr        // add default domain, using the name from account suffix
673741b8a48SAndreas Gohr        $domains[''] = ltrim($this->conf['account_suffix'], '@');
674741b8a48SAndreas Gohr
675741b8a48SAndreas Gohr        // find additional domains
676741b8a48SAndreas Gohr        foreach($this->conf as $key => $val) {
677741b8a48SAndreas Gohr            if(is_array($val) && isset($val['account_suffix'])) {
678741b8a48SAndreas Gohr                $domains[$key] = ltrim($val['account_suffix'], '@');
679741b8a48SAndreas Gohr            }
680741b8a48SAndreas Gohr        }
681741b8a48SAndreas Gohr        ksort($domains);
682741b8a48SAndreas Gohr
683741b8a48SAndreas Gohr        return $domains;
684741b8a48SAndreas Gohr    }
685741b8a48SAndreas Gohr
686741b8a48SAndreas Gohr    /**
68793a7873eSAndreas Gohr     * Check provided user and userinfo for matching patterns
68893a7873eSAndreas Gohr     *
68993a7873eSAndreas Gohr     * The patterns are set up with $this->_constructPattern()
69093a7873eSAndreas Gohr     *
69193a7873eSAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
692253d4b48SGerrit Uitslag     *
69393a7873eSAndreas Gohr     * @param string $user
69493a7873eSAndreas Gohr     * @param array  $info
69593a7873eSAndreas Gohr     * @return bool
69693a7873eSAndreas Gohr     */
69793a7873eSAndreas Gohr    protected function _filter($user, $info) {
69893a7873eSAndreas Gohr        foreach($this->_pattern as $item => $pattern) {
69993a7873eSAndreas Gohr            if($item == 'user') {
70093a7873eSAndreas Gohr                if(!preg_match($pattern, $user)) return false;
70193a7873eSAndreas Gohr            } else if($item == 'grps') {
70293a7873eSAndreas Gohr                if(!count(preg_grep($pattern, $info['grps']))) return false;
70393a7873eSAndreas Gohr            } else {
70493a7873eSAndreas Gohr                if(!preg_match($pattern, $info[$item])) return false;
70593a7873eSAndreas Gohr            }
70693a7873eSAndreas Gohr        }
70793a7873eSAndreas Gohr        return true;
70893a7873eSAndreas Gohr    }
70993a7873eSAndreas Gohr
71093a7873eSAndreas Gohr    /**
71193a7873eSAndreas Gohr     * Create a pattern for $this->_filter()
71293a7873eSAndreas Gohr     *
71393a7873eSAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
714253d4b48SGerrit Uitslag     *
71593a7873eSAndreas Gohr     * @param array $filter
71693a7873eSAndreas Gohr     */
71793a7873eSAndreas Gohr    protected function _constructPattern($filter) {
718f4476bd9SJan Schumann        $this->_pattern = array();
719f4476bd9SJan Schumann        foreach($filter as $item => $pattern) {
720f4476bd9SJan Schumann            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
721f4476bd9SJan Schumann        }
722f4476bd9SJan Schumann    }
723f4476bd9SJan Schumann}
724