xref: /dokuwiki/lib/plugins/authad/auth.php (revision 342753d2c30febfa5363dabecbfd03ee1344cc54)
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');
607aec029SMichael Großerequire_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php');
732fd494aSAndreas Gohr
8f4476bd9SJan Schumann/**
9f4476bd9SJan Schumann * Active Directory authentication backend for DokuWiki
10f4476bd9SJan Schumann *
11f4476bd9SJan Schumann * This makes authentication with a Active Directory server much easier
12f4476bd9SJan Schumann * than when using the normal LDAP backend by utilizing the adLDAP library
13f4476bd9SJan Schumann *
14f4476bd9SJan Schumann * Usage:
15f4476bd9SJan Schumann *   Set DokuWiki's local.protected.php auth setting to read
16f4476bd9SJan Schumann *
17f4476bd9SJan Schumann *   $conf['authtype']       = 'authad';
18f4476bd9SJan Schumann *
1932fd494aSAndreas Gohr *   $conf['plugin']['authad']['account_suffix']     = '@my.domain.org';
2032fd494aSAndreas Gohr *   $conf['plugin']['authad']['base_dn']            = 'DC=my,DC=domain,DC=org';
2132fd494aSAndreas Gohr *   $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
22f4476bd9SJan Schumann *
23f4476bd9SJan Schumann *   //optional:
2432fd494aSAndreas Gohr *   $conf['plugin']['authad']['sso']                = 1;
253002d731SAndreas Gohr *   $conf['plugin']['authad']['admin_username']     = 'root';
263002d731SAndreas Gohr *   $conf['plugin']['authad']['admin_password']     = 'pass';
2732fd494aSAndreas Gohr *   $conf['plugin']['authad']['real_primarygroup']  = 1;
2832fd494aSAndreas Gohr *   $conf['plugin']['authad']['use_ssl']            = 1;
2932fd494aSAndreas Gohr *   $conf['plugin']['authad']['use_tls']            = 1;
3032fd494aSAndreas Gohr *   $conf['plugin']['authad']['debug']              = 1;
3193a7873eSAndreas Gohr *   // warn user about expiring password this many days in advance:
3232fd494aSAndreas Gohr *   $conf['plugin']['authad']['expirywarn']         = 5;
33f4476bd9SJan Schumann *
34f4476bd9SJan Schumann *   // get additional information to the userinfo array
35f4476bd9SJan Schumann *   // add a list of comma separated ldap contact fields.
36f4476bd9SJan Schumann *   $conf['plugin']['authad']['additional'] = 'field1,field2';
37f4476bd9SJan Schumann *
38f4476bd9SJan Schumann * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
39f4476bd9SJan Schumann * @author  James Van Lommel <jamesvl@gmail.com>
40f4476bd9SJan Schumann * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
41f4476bd9SJan Schumann * @author  Andreas Gohr <andi@splitbrain.org>
42f4476bd9SJan Schumann * @author  Jan Schumann <js@schumann-it.com>
43f4476bd9SJan Schumann */
4493a7873eSAndreas Gohrclass auth_plugin_authad extends DokuWiki_Auth_Plugin {
4532fd494aSAndreas Gohr
4693a7873eSAndreas Gohr    /**
4793a7873eSAndreas Gohr     * @var array hold connection data for a specific AD domain
4893a7873eSAndreas Gohr     */
4993a7873eSAndreas Gohr    protected $opts = array();
5032fd494aSAndreas Gohr
5193a7873eSAndreas Gohr    /**
5293a7873eSAndreas Gohr     * @var array open connections for each AD domain, as adLDAP objects
5393a7873eSAndreas Gohr     */
5493a7873eSAndreas Gohr    protected $adldap = array();
5593a7873eSAndreas Gohr
5693a7873eSAndreas Gohr    /**
5793a7873eSAndreas Gohr     * @var bool message state
5893a7873eSAndreas Gohr     */
5993a7873eSAndreas Gohr    protected $msgshown = false;
6093a7873eSAndreas Gohr
6193a7873eSAndreas Gohr    /**
6293a7873eSAndreas Gohr     * @var array user listing cache
6393a7873eSAndreas Gohr     */
6493a7873eSAndreas Gohr    protected $users = array();
6593a7873eSAndreas Gohr
6693a7873eSAndreas Gohr    /**
6793a7873eSAndreas Gohr     * @var array filter patterns for listing users
6893a7873eSAndreas Gohr     */
6993a7873eSAndreas Gohr    protected $_pattern = array();
70f4476bd9SJan Schumann
71c52f6cd2SMichael Große    protected $_actualstart = 0;
72c52f6cd2SMichael Große
73c52f6cd2SMichael Große    protected $_grpsusers = array();
74c52f6cd2SMichael Große
75f4476bd9SJan Schumann    /**
76f4476bd9SJan Schumann     * Constructor
77f4476bd9SJan Schumann     */
7893a7873eSAndreas Gohr    public function __construct() {
7900d58927SMichael Hamann        global $INPUT;
80454d868bSAndreas Gohr        parent::__construct();
81454d868bSAndreas Gohr
8232fd494aSAndreas Gohr        // we load the config early to modify it a bit here
8332fd494aSAndreas Gohr        $this->loadConfig();
84f4476bd9SJan Schumann
85f4476bd9SJan Schumann        // additional information fields
8632fd494aSAndreas Gohr        if(isset($this->conf['additional'])) {
8732fd494aSAndreas Gohr            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
8832fd494aSAndreas Gohr            $this->conf['additional'] = explode(',', $this->conf['additional']);
8932fd494aSAndreas Gohr        } else $this->conf['additional'] = array();
90f4476bd9SJan Schumann
91f4476bd9SJan Schumann        // ldap extension is needed
92f4476bd9SJan Schumann        if(!function_exists('ldap_connect')) {
9332fd494aSAndreas Gohr            if($this->conf['debug'])
94f4476bd9SJan Schumann                msg("AD Auth: PHP LDAP extension not found.", -1);
95f4476bd9SJan Schumann            $this->success = false;
96f4476bd9SJan Schumann            return;
97f4476bd9SJan Schumann        }
98f4476bd9SJan Schumann
99f4476bd9SJan Schumann        // Prepare SSO
100d34a2a38SAndreas Gohr        if(!empty($_SERVER['REMOTE_USER'])) {
101d34a2a38SAndreas Gohr
102d34a2a38SAndreas Gohr            // make sure the right encoding is used
103d34a2a38SAndreas Gohr            if($this->getConf('sso_charset')) {
104d34a2a38SAndreas Gohr                $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
105d34a2a38SAndreas Gohr            } elseif(!utf8_check($_SERVER['REMOTE_USER'])) {
10693a7873eSAndreas Gohr                $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
10793a7873eSAndreas Gohr            }
108d34a2a38SAndreas Gohr
109d34a2a38SAndreas Gohr            // trust the incoming user
110d34a2a38SAndreas Gohr            if($this->conf['sso']) {
11193a7873eSAndreas Gohr                $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
112f4476bd9SJan Schumann
113f4476bd9SJan Schumann                // we need to simulate a login
114f4476bd9SJan Schumann                if(empty($_COOKIE[DOKU_COOKIE])) {
11500d58927SMichael Hamann                    $INPUT->set('u', $_SERVER['REMOTE_USER']);
11600d58927SMichael Hamann                    $INPUT->set('p', 'sso_only');
117f4476bd9SJan Schumann                }
118f4476bd9SJan Schumann            }
119d34a2a38SAndreas Gohr        }
120f4476bd9SJan Schumann
12193a7873eSAndreas Gohr        // other can do's are changed in $this->_loadServerConfig() base on domain setup
122bb30445dSMichael Wilmes        $this->cando['modName'] = (bool)$this->conf['update_name'];
123bb30445dSMichael Wilmes        $this->cando['modMail'] = (bool)$this->conf['update_mail'];
12425f80763SMichael Große        $this->cando['getUserCount'] = true;
125f4476bd9SJan Schumann    }
126f4476bd9SJan Schumann
127f4476bd9SJan Schumann    /**
128a154806fSAndreas Gohr     * Load domain config on capability check
129a154806fSAndreas Gohr     *
130a154806fSAndreas Gohr     * @param string $cap
131a154806fSAndreas Gohr     * @return bool
132a154806fSAndreas Gohr     */
133a154806fSAndreas Gohr    public function canDo($cap) {
134a154806fSAndreas Gohr        //capabilities depend on config, which may change depending on domain
135a154806fSAndreas Gohr        $domain = $this->_userDomain($_SERVER['REMOTE_USER']);
136a154806fSAndreas Gohr        $this->_loadServerConfig($domain);
137a154806fSAndreas Gohr        return parent::canDo($cap);
138a154806fSAndreas Gohr    }
139a154806fSAndreas Gohr
140a154806fSAndreas Gohr    /**
141f4476bd9SJan Schumann     * Check user+password [required auth function]
142f4476bd9SJan Schumann     *
143f4476bd9SJan Schumann     * Checks if the given user exists and the given
144f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
145f4476bd9SJan Schumann     * to the LDAP server
146f4476bd9SJan Schumann     *
147f4476bd9SJan Schumann     * @author  James Van Lommel <james@nosq.com>
14893a7873eSAndreas Gohr     * @param string $user
14993a7873eSAndreas Gohr     * @param string $pass
150f4476bd9SJan Schumann     * @return  bool
151f4476bd9SJan Schumann     */
15293a7873eSAndreas Gohr    public function checkPass($user, $pass) {
153f4476bd9SJan Schumann        if($_SERVER['REMOTE_USER'] &&
154f4476bd9SJan Schumann            $_SERVER['REMOTE_USER'] == $user &&
15532fd494aSAndreas Gohr            $this->conf['sso']
15693a7873eSAndreas Gohr        ) return true;
157f4476bd9SJan Schumann
15893a7873eSAndreas Gohr        $adldap = $this->_adldap($this->_userDomain($user));
15993a7873eSAndreas Gohr        if(!$adldap) return false;
16093a7873eSAndreas Gohr
16193a7873eSAndreas Gohr        return $adldap->authenticate($this->_userName($user), $pass);
162f4476bd9SJan Schumann    }
163f4476bd9SJan Schumann
164f4476bd9SJan Schumann    /**
165f4476bd9SJan Schumann     * Return user info [required auth function]
166f4476bd9SJan Schumann     *
167f4476bd9SJan Schumann     * Returns info about the given user needs to contain
168f4476bd9SJan Schumann     * at least these fields:
169f4476bd9SJan Schumann     *
170f4476bd9SJan Schumann     * name    string  full name of the user
171f4476bd9SJan Schumann     * mail    string  email address of the user
172f4476bd9SJan Schumann     * grps    array   list of groups the user is in
173f4476bd9SJan Schumann     *
17493a7873eSAndreas Gohr     * This AD specific function returns the following
175f4476bd9SJan Schumann     * addional fields:
176f4476bd9SJan Schumann     *
177f4476bd9SJan Schumann     * dn         string    distinguished name (DN)
17893a7873eSAndreas Gohr     * uid        string    samaccountname
17993a7873eSAndreas Gohr     * lastpwd    int       timestamp of the date when the password was set
18093a7873eSAndreas Gohr     * expires    true      if the password expires
18193a7873eSAndreas Gohr     * expiresin  int       seconds until the password expires
18293a7873eSAndreas Gohr     * any fields specified in the 'additional' config option
183f4476bd9SJan Schumann     *
184f4476bd9SJan Schumann     * @author  James Van Lommel <james@nosq.com>
18593a7873eSAndreas Gohr     * @param string $user
1862046a654SChristopher Smith     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
18793a7873eSAndreas Gohr     * @return array
188f4476bd9SJan Schumann     */
1892046a654SChristopher Smith    public function getUserData($user, $requireGroups=true) {
190f4476bd9SJan Schumann        global $conf;
19193a7873eSAndreas Gohr        global $lang;
19293a7873eSAndreas Gohr        global $ID;
19393a7873eSAndreas Gohr        $adldap = $this->_adldap($this->_userDomain($user));
19493a7873eSAndreas Gohr        if(!$adldap) return false;
195f4476bd9SJan Schumann
19693a7873eSAndreas Gohr        if($user == '') return array();
19793a7873eSAndreas Gohr
19893a7873eSAndreas Gohr        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
199f4476bd9SJan Schumann
200f4476bd9SJan Schumann        // add additional fields to read
20132fd494aSAndreas Gohr        $fields = array_merge($fields, $this->conf['additional']);
202f4476bd9SJan Schumann        $fields = array_unique($fields);
20314642325SAndreas Gohr        $fields = array_filter($fields);
204f4476bd9SJan Schumann
205f4476bd9SJan Schumann        //get info for given user
20632fd494aSAndreas Gohr        $result = $adldap->user()->info($this->_userName($user), $fields);
20793a7873eSAndreas Gohr        if($result == false){
20893a7873eSAndreas Gohr            return array();
20993a7873eSAndreas Gohr        }
21093a7873eSAndreas Gohr
211f4476bd9SJan Schumann        //general user info
21259bc3b48SGerrit Uitslag        $info = array();
213f4476bd9SJan Schumann        $info['name'] = $result[0]['displayname'][0];
214f4476bd9SJan Schumann        $info['mail'] = $result[0]['mail'][0];
215f4476bd9SJan Schumann        $info['uid']  = $result[0]['samaccountname'][0];
216f4476bd9SJan Schumann        $info['dn']   = $result[0]['dn'];
21793a7873eSAndreas Gohr        //last password set (Windows counts from January 1st 1601)
21893a7873eSAndreas Gohr        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
21993a7873eSAndreas Gohr        //will it expire?
22093a7873eSAndreas Gohr        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
221f4476bd9SJan Schumann
222f4476bd9SJan Schumann        // additional information
22332fd494aSAndreas Gohr        foreach($this->conf['additional'] as $field) {
224f4476bd9SJan Schumann            if(isset($result[0][strtolower($field)])) {
225f4476bd9SJan Schumann                $info[$field] = $result[0][strtolower($field)][0];
226f4476bd9SJan Schumann            }
227f4476bd9SJan Schumann        }
228f4476bd9SJan Schumann
229f4476bd9SJan Schumann        // handle ActiveDirectory memberOf
23032fd494aSAndreas Gohr        $info['grps'] = $adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']);
231f4476bd9SJan Schumann
232f4476bd9SJan Schumann        if(is_array($info['grps'])) {
233f4476bd9SJan Schumann            foreach($info['grps'] as $ndx => $group) {
234f4476bd9SJan Schumann                $info['grps'][$ndx] = $this->cleanGroup($group);
235f4476bd9SJan Schumann            }
236f4476bd9SJan Schumann        }
237f4476bd9SJan Schumann
238f4476bd9SJan Schumann        // always add the default group to the list of groups
239f4476bd9SJan Schumann        if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
240f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
241f4476bd9SJan Schumann        }
242f4476bd9SJan Schumann
24393a7873eSAndreas Gohr        // add the user's domain to the groups
24493a7873eSAndreas Gohr        $domain = $this->_userDomain($user);
24593a7873eSAndreas Gohr        if($domain && !in_array("domain-$domain", (array) $info['grps'])) {
24693a7873eSAndreas Gohr            $info['grps'][] = $this->cleanGroup("domain-$domain");
24793a7873eSAndreas Gohr        }
24893a7873eSAndreas Gohr
24993a7873eSAndreas Gohr        // check expiry time
25032fd494aSAndreas Gohr        if($info['expires'] && $this->conf['expirywarn']){
2511e52e72aSAndreas Gohr            $expiry = $adldap->user()->passwordExpiry($user);
2521e52e72aSAndreas Gohr            if(is_array($expiry)){
2531e52e72aSAndreas Gohr                $info['expiresat'] = $expiry['expiryts'];
2541e52e72aSAndreas Gohr                $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
25593a7873eSAndreas Gohr
25693a7873eSAndreas Gohr                // if this is the current user, warn him (once per request only)
25793a7873eSAndreas Gohr                if(($_SERVER['REMOTE_USER'] == $user) &&
2581e52e72aSAndreas Gohr                    ($info['expiresin'] <= $this->conf['expirywarn']) &&
25993a7873eSAndreas Gohr                    !$this->msgshown
26093a7873eSAndreas Gohr                ) {
2615b795a65SPatrick Brown                    $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']);
26293a7873eSAndreas Gohr                    if($this->canDo('modPass')) {
26393a7873eSAndreas Gohr                        $url = wl($ID, array('do'=> 'profile'));
26493a7873eSAndreas Gohr                        $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
26593a7873eSAndreas Gohr                    }
26693a7873eSAndreas Gohr                    msg($msg);
26793a7873eSAndreas Gohr                    $this->msgshown = true;
26893a7873eSAndreas Gohr                }
26993a7873eSAndreas Gohr            }
2701e52e72aSAndreas Gohr        }
27193a7873eSAndreas Gohr
272f4476bd9SJan Schumann        return $info;
273f4476bd9SJan Schumann    }
274f4476bd9SJan Schumann
275f4476bd9SJan Schumann    /**
276f4476bd9SJan Schumann     * Make AD group names usable by DokuWiki.
277f4476bd9SJan Schumann     *
278f4476bd9SJan Schumann     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
279f4476bd9SJan Schumann     *
280f4476bd9SJan Schumann     * @author  James Van Lommel (jamesvl@gmail.com)
28193a7873eSAndreas Gohr     * @param string $group
28293a7873eSAndreas Gohr     * @return string
283f4476bd9SJan Schumann     */
28493a7873eSAndreas Gohr    public function cleanGroup($group) {
28593a7873eSAndreas Gohr        $group = str_replace('\\', '', $group);
28693a7873eSAndreas Gohr        $group = str_replace('#', '', $group);
28793a7873eSAndreas Gohr        $group = preg_replace('[\s]', '_', $group);
28893a7873eSAndreas Gohr        $group = utf8_strtolower(trim($group));
28993a7873eSAndreas Gohr        return $group;
290f4476bd9SJan Schumann    }
291f4476bd9SJan Schumann
292f4476bd9SJan Schumann    /**
293f4476bd9SJan Schumann     * Sanitize user names
29493a7873eSAndreas Gohr     *
29593a7873eSAndreas Gohr     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
29693a7873eSAndreas Gohr     *
29793a7873eSAndreas Gohr     * @author Andreas Gohr <gohr@cosmocode.de>
29893a7873eSAndreas Gohr     * @param string $user
29993a7873eSAndreas Gohr     * @return string
300f4476bd9SJan Schumann     */
30193a7873eSAndreas Gohr    public function cleanUser($user) {
30293a7873eSAndreas Gohr        $domain = '';
30393a7873eSAndreas Gohr
30493a7873eSAndreas Gohr        // get NTLM or Kerberos domain part
30593a7873eSAndreas Gohr        list($dom, $user) = explode('\\', $user, 2);
30693a7873eSAndreas Gohr        if(!$user) $user = $dom;
30793a7873eSAndreas Gohr        if($dom) $domain = $dom;
30893a7873eSAndreas Gohr        list($user, $dom) = explode('@', $user, 2);
30993a7873eSAndreas Gohr        if($dom) $domain = $dom;
31093a7873eSAndreas Gohr
31193a7873eSAndreas Gohr        // clean up both
31293a7873eSAndreas Gohr        $domain = utf8_strtolower(trim($domain));
31393a7873eSAndreas Gohr        $user   = utf8_strtolower(trim($user));
31493a7873eSAndreas Gohr
31593a7873eSAndreas Gohr        // is this a known, valid domain? if not discard
31632fd494aSAndreas Gohr        if(!is_array($this->conf[$domain])) {
31793a7873eSAndreas Gohr            $domain = '';
31893a7873eSAndreas Gohr        }
31993a7873eSAndreas Gohr
32093a7873eSAndreas Gohr        // reattach domain
32193a7873eSAndreas Gohr        if($domain) $user = "$user@$domain";
32293a7873eSAndreas Gohr        return $user;
323f4476bd9SJan Schumann    }
324f4476bd9SJan Schumann
325f4476bd9SJan Schumann    /**
326f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
32793a7873eSAndreas Gohr     *
32893a7873eSAndreas Gohr     * @return bool
329f4476bd9SJan Schumann     */
33093a7873eSAndreas Gohr    public function isCaseSensitive() {
331f4476bd9SJan Schumann        return false;
332f4476bd9SJan Schumann    }
333f4476bd9SJan Schumann
3346fcf992cSMichael Große    /**
3357910cbbbSMichael Große     * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
3367910cbbbSMichael Große     *
3376fcf992cSMichael Große     * @param array $filter
3386fcf992cSMichael Große     * @return string
3396fcf992cSMichael Große     */
34067a31a83SMichael Große    protected function _constructSearchString($filter){
34167a31a83SMichael Große        if (!$filter){
34267a31a83SMichael Große            return '*';
34367a31a83SMichael Große        }
34407aec029SMichael Große        $adldapUtils = new adLDAPUtils($this->_adldap(null));
34567a31a83SMichael Große        $result = '*';
34667a31a83SMichael Große        if (isset($filter['name'])) {
34707aec029SMichael Große            $result .= ')(displayname=*' . $adldapUtils->ldapSlashes($filter['name']) . '*';
34867a31a83SMichael Große            unset($filter['name']);
34967a31a83SMichael Große        }
3507910cbbbSMichael Große
35167a31a83SMichael Große        if (isset($filter['user'])) {
35207aec029SMichael Große            $result .= ')(samAccountName=*' . $adldapUtils->ldapSlashes($filter['user']) . '*';
35367a31a83SMichael Große            unset($filter['user']);
35467a31a83SMichael Große        }
35567a31a83SMichael Große
35667a31a83SMichael Große        if (isset($filter['mail'])) {
35707aec029SMichael Große            $result .= ')(mail=*' . $adldapUtils->ldapSlashes($filter['mail']) . '*';
35867a31a83SMichael Große            unset($filter['mail']);
35967a31a83SMichael Große        }
36067a31a83SMichael Große        return $result;
36167a31a83SMichael Große    }
36267a31a83SMichael Große
363f4476bd9SJan Schumann    /**
3647910cbbbSMichael Große     * Return a count of the number of user which meet $filter criteria
3657910cbbbSMichael Große     *
3667910cbbbSMichael Große     * @param array $filter  $filter array of field/pattern pairs, empty array for no filter
3677910cbbbSMichael Große     * @return int number of users
36825f80763SMichael Große     */
36925f80763SMichael Große    public function getUserCount($filter = array()) {
3706fcf992cSMichael Große        $adldap = $this->_adldap(null);
3716fcf992cSMichael Große        if(!$adldap) {
3726fcf992cSMichael Große            dbglog("authad/auth.php getUserCount(): _adldap not set.");
3736fcf992cSMichael Große            return -1;
3746fcf992cSMichael Große        }
37567a31a83SMichael Große        if ($filter == array()) {
37625f80763SMichael Große            $result = $adldap->user()->all();
37767a31a83SMichael Große        } else {
37867a31a83SMichael Große            $searchString = $this->_constructSearchString($filter);
37967a31a83SMichael Große            $result = $adldap->user()->all(false, $searchString);
380c52f6cd2SMichael Große            if (isset($filter['grps'])) {
381c52f6cd2SMichael Große                $this->users = array_fill_keys($result, false);
382c52f6cd2SMichael Große                $usermanager = plugin_load("admin", "usermanager", false);
383462e9e37SMichael Große                $usermanager->setLastdisabled(true);
384c52f6cd2SMichael Große                if (!isset($this->_grpsusers[$this->_filterToString($filter)])){
385c52f6cd2SMichael Große                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize());
3866fcf992cSMichael Große                } elseif (count($this->_grpsusers[$this->_filterToString($filter)]) < $usermanager->getStart() + 3*$usermanager->getPagesize()) {
387c52f6cd2SMichael Große                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize() - count($this->_grpsusers[$this->_filterToString($filter)]));
388c52f6cd2SMichael Große                }
389c52f6cd2SMichael Große                $result = $this->_grpsusers[$this->_filterToString($filter)];
390462e9e37SMichael Große            } else {
391462e9e37SMichael Große                $usermanager = plugin_load("admin", "usermanager", false);
392462e9e37SMichael Große                $usermanager->setLastdisabled(false);
393c52f6cd2SMichael Große            }
39467a31a83SMichael Große
39567a31a83SMichael Große        }
39667a31a83SMichael Große
39725f80763SMichael Große        if (!$result) {
3986fcf992cSMichael Große            return 0;
39925f80763SMichael Große        }
40025f80763SMichael Große        return count($result);
40125f80763SMichael Große    }
40225f80763SMichael Große
4036fcf992cSMichael Große    /**
4046fcf992cSMichael Große     *
4056fcf992cSMichael Große     * create a unique string for each filter used with a group
4066fcf992cSMichael Große     *
4076fcf992cSMichael Große     * @param array $filter
4086fcf992cSMichael Große     * @return string
4096fcf992cSMichael Große     */
410c52f6cd2SMichael Große    protected function _filterToString ($filter) {
411c52f6cd2SMichael Große        $result = '';
412c52f6cd2SMichael Große        if (isset($filter['user'])) {
413c52f6cd2SMichael Große            $result .= 'user-' . $filter['user'];
414c52f6cd2SMichael Große        }
415c52f6cd2SMichael Große        if (isset($filter['name'])) {
416c52f6cd2SMichael Große            $result .= 'name-' . $filter['name'];
417c52f6cd2SMichael Große        }
418c52f6cd2SMichael Große        if (isset($filter['mail'])) {
419c52f6cd2SMichael Große            $result .= 'mail-' . $filter['mail'];
420c52f6cd2SMichael Große        }
421c52f6cd2SMichael Große        if (isset($filter['grps'])) {
422c52f6cd2SMichael Große            $result .= 'grps-' . $filter['grps'];
423c52f6cd2SMichael Große        }
424c52f6cd2SMichael Große        return $result;
425c52f6cd2SMichael Große    }
426c52f6cd2SMichael Große
4276fcf992cSMichael Große    /**
4287910cbbbSMichael Große     * Create an array of $numberOfAdds users passing a certain $filter, including belonging
4297910cbbbSMichael Große     * to a certain group and save them to a object-wide array. If the array
4307910cbbbSMichael Große     * already exists try to add $numberOfAdds further users to it.
4317910cbbbSMichael Große     *
4326fcf992cSMichael Große     * @param array $filter
4336fcf992cSMichael Große     * @param int $numberOfAdds additional number of users requested
4346fcf992cSMichael Große     * @return int number of Users actually add to Array
4356fcf992cSMichael Große     */
436c52f6cd2SMichael Große    protected function _fillGroupUserArray($filter, $numberOfAdds){
437c52f6cd2SMichael Große        $this->_grpsusers[$this->_filterToString($filter)];
438c52f6cd2SMichael Große        $i = 0;
439c52f6cd2SMichael Große        $count = 0;
440c52f6cd2SMichael Große        $this->_constructPattern($filter);
441c52f6cd2SMichael Große        foreach ($this->users as $user => &$info) {
442c52f6cd2SMichael Große            if($i++ < $this->_actualstart) {
443c52f6cd2SMichael Große                continue;
444c52f6cd2SMichael Große            }
445c52f6cd2SMichael Große            if($info === false) {
446c52f6cd2SMichael Große                $info = $this->getUserData($user);
447c52f6cd2SMichael Große            }
448c52f6cd2SMichael Große            if($this->_filter($user, $info)) {
449c52f6cd2SMichael Große                $this->_grpsusers[$this->_filterToString($filter)][$user] = $info;
450c52f6cd2SMichael Große                if(($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
451c52f6cd2SMichael Große            }
452c52f6cd2SMichael Große        }
453c52f6cd2SMichael Große        $this->_actualstart = $i;
454c52f6cd2SMichael Große        return $count;
455c52f6cd2SMichael Große    }
456c52f6cd2SMichael Große
45725f80763SMichael Große    /**
458f4476bd9SJan Schumann     * Bulk retrieval of user data
459f4476bd9SJan Schumann     *
460f4476bd9SJan Schumann     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
461253d4b48SGerrit Uitslag     *
46293a7873eSAndreas Gohr     * @param   int $start index of first user to be returned
46393a7873eSAndreas Gohr     * @param   int $limit max number of users to be returned
46493a7873eSAndreas Gohr     * @param   array $filter array of field/pattern pairs, null for no filter
46593a7873eSAndreas Gohr     * @return array userinfo (refer getUserData for internal userinfo details)
466f4476bd9SJan Schumann     */
467c52f6cd2SMichael Große    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
46893a7873eSAndreas Gohr        $adldap = $this->_adldap(null);
46993a7873eSAndreas Gohr        if(!$adldap) return false;
470f4476bd9SJan Schumann
4710ba750c0SAndreas Gohr        if(!$this->users) {
472f4476bd9SJan Schumann            //get info for given user
47367a31a83SMichael Große            $result = $adldap->user()->all(false, $this->_constructSearchString($filter));
474f4476bd9SJan Schumann            if (!$result) return array();
475f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
476f4476bd9SJan Schumann        }
477f4476bd9SJan Schumann
478f4476bd9SJan Schumann        $i     = 0;
479f4476bd9SJan Schumann        $count = 0;
480f4476bd9SJan Schumann        $result = array();
481f4476bd9SJan Schumann
482c52f6cd2SMichael Große        if (!isset($filter['grps'])) {
483462e9e37SMichael Große            $usermanager = plugin_load("admin", "usermanager", false);
484462e9e37SMichael Große            $usermanager->setLastdisabled(false);
4856fcf992cSMichael Große            $this->_constructPattern($filter);
486f4476bd9SJan Schumann            foreach($this->users as $user => &$info) {
487f4476bd9SJan Schumann                if($i++ < $start) {
488f4476bd9SJan Schumann                    continue;
489f4476bd9SJan Schumann                }
490f4476bd9SJan Schumann                if($info === false) {
491f4476bd9SJan Schumann                    $info = $this->getUserData($user);
492f4476bd9SJan Schumann                }
493f4476bd9SJan Schumann                $result[$user] = $info;
4949a2c73e8SAndreas Gohr                if(($limit > 0) && (++$count >= $limit)) break;
495f4476bd9SJan Schumann            }
496c52f6cd2SMichael Große        } else {
497462e9e37SMichael Große            $usermanager = plugin_load("admin", "usermanager", false);
498462e9e37SMichael Große            $usermanager->setLastdisabled(true);
499c52f6cd2SMichael Große            if (!isset($this->_grpsusers[$this->_filterToString($filter)]) || count($this->_grpsusers[$this->_filterToString($filter)]) < ($start+$limit)) {
500c52f6cd2SMichael Große                $this->_fillGroupUserArray($filter,$start+$limit - count($this->_grpsusers[$this->_filterToString($filter)]) +1);
501c52f6cd2SMichael Große            }
5026fcf992cSMichael Große            if (!$this->_grpsusers[$this->_filterToString($filter)]) return false;
503c52f6cd2SMichael Große            foreach($this->_grpsusers[$this->_filterToString($filter)] as $user => &$info) {
504c52f6cd2SMichael Große                if($i++ < $start) {
505c52f6cd2SMichael Große                    continue;
506c52f6cd2SMichael Große                }
507c52f6cd2SMichael Große                $result[$user] = $info;
508c52f6cd2SMichael Große                if(($limit > 0) && (++$count >= $limit)) break;
509c52f6cd2SMichael Große            }
510c52f6cd2SMichael Große
511c52f6cd2SMichael Große        }
512f4476bd9SJan Schumann        return $result;
513f4476bd9SJan Schumann    }
514f4476bd9SJan Schumann
515f4476bd9SJan Schumann    /**
516f4476bd9SJan Schumann     * Modify user data
517f4476bd9SJan Schumann     *
51893a7873eSAndreas Gohr     * @param   string $user      nick of the user to be changed
51993a7873eSAndreas Gohr     * @param   array  $changes   array of field/value pairs to be changed
520f4476bd9SJan Schumann     * @return  bool
521f4476bd9SJan Schumann     */
52293a7873eSAndreas Gohr    public function modifyUser($user, $changes) {
523f4476bd9SJan Schumann        $return = true;
52493a7873eSAndreas Gohr        $adldap = $this->_adldap($this->_userDomain($user));
5258f03c311SPatrick Brown        if(!$adldap) {
5268f03c311SPatrick Brown            msg($this->getLang('connectfail'), -1);
5278f03c311SPatrick Brown            return false;
5288f03c311SPatrick Brown        }
529f4476bd9SJan Schumann
530f4476bd9SJan Schumann        // password changing
531f4476bd9SJan Schumann        if(isset($changes['pass'])) {
532f4476bd9SJan Schumann            try {
53332fd494aSAndreas Gohr                $return = $adldap->user()->password($this->_userName($user),$changes['pass']);
534f4476bd9SJan Schumann            } catch (adLDAPException $e) {
53532fd494aSAndreas Gohr                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
536f4476bd9SJan Schumann                $return = false;
537f4476bd9SJan Schumann            }
5388f03c311SPatrick Brown            if(!$return) msg($this->getLang('passchangefail'), -1);
539f4476bd9SJan Schumann        }
540f4476bd9SJan Schumann
541f4476bd9SJan Schumann        // changing user data
542f4476bd9SJan Schumann        $adchanges = array();
543f4476bd9SJan Schumann        if(isset($changes['name'])) {
544f4476bd9SJan Schumann            // get first and last name
545f4476bd9SJan Schumann            $parts                     = explode(' ', $changes['name']);
546f4476bd9SJan Schumann            $adchanges['surname']      = array_pop($parts);
547f4476bd9SJan Schumann            $adchanges['firstname']    = join(' ', $parts);
548f4476bd9SJan Schumann            $adchanges['display_name'] = $changes['name'];
549f4476bd9SJan Schumann        }
550f4476bd9SJan Schumann        if(isset($changes['mail'])) {
551f4476bd9SJan Schumann            $adchanges['email'] = $changes['mail'];
552f4476bd9SJan Schumann        }
553f4476bd9SJan Schumann        if(count($adchanges)) {
554f4476bd9SJan Schumann            try {
55532fd494aSAndreas Gohr                $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges);
556f4476bd9SJan Schumann            } catch (adLDAPException $e) {
55732fd494aSAndreas Gohr                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
558f4476bd9SJan Schumann                $return = false;
559f4476bd9SJan Schumann            }
5608f03c311SPatrick Brown            if(!$return) msg($this->getLang('userchangefail'), -1);
561f4476bd9SJan Schumann        }
562f4476bd9SJan Schumann
563f4476bd9SJan Schumann        return $return;
564f4476bd9SJan Schumann    }
565f4476bd9SJan Schumann
566f4476bd9SJan Schumann    /**
567f4476bd9SJan Schumann     * Initialize the AdLDAP library and connect to the server
56893a7873eSAndreas Gohr     *
56993a7873eSAndreas Gohr     * When you pass null as domain, it will reuse any existing domain.
57093a7873eSAndreas Gohr     * Eg. the one of the logged in user. It falls back to the default
57193a7873eSAndreas Gohr     * domain if no current one is available.
57293a7873eSAndreas Gohr     *
57393a7873eSAndreas Gohr     * @param string|null $domain The AD domain to use
57493a7873eSAndreas Gohr     * @return adLDAP|bool true if a connection was established
575f4476bd9SJan Schumann     */
57693a7873eSAndreas Gohr    protected function _adldap($domain) {
57793a7873eSAndreas Gohr        if(is_null($domain) && is_array($this->opts)) {
57893a7873eSAndreas Gohr            $domain = $this->opts['domain'];
57993a7873eSAndreas Gohr        }
58093a7873eSAndreas Gohr
58193a7873eSAndreas Gohr        $this->opts = $this->_loadServerConfig((string) $domain);
58293a7873eSAndreas Gohr        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
583f4476bd9SJan Schumann
584f4476bd9SJan Schumann        // connect
585f4476bd9SJan Schumann        try {
58693a7873eSAndreas Gohr            $this->adldap[$domain] = new adLDAP($this->opts);
58793a7873eSAndreas Gohr            return $this->adldap[$domain];
588f4476bd9SJan Schumann        } catch(adLDAPException $e) {
58932fd494aSAndreas Gohr            if($this->conf['debug']) {
590f4476bd9SJan Schumann                msg('AD Auth: '.$e->getMessage(), -1);
591f4476bd9SJan Schumann            }
592f4476bd9SJan Schumann            $this->success         = false;
59393a7873eSAndreas Gohr            $this->adldap[$domain] = null;
594f4476bd9SJan Schumann        }
595f4476bd9SJan Schumann        return false;
596f4476bd9SJan Schumann    }
597f4476bd9SJan Schumann
598f4476bd9SJan Schumann    /**
59993a7873eSAndreas Gohr     * Get the domain part from a user
600f4476bd9SJan Schumann     *
601253d4b48SGerrit Uitslag     * @param string $user
60293a7873eSAndreas Gohr     * @return string
603f4476bd9SJan Schumann     */
60493a7873eSAndreas Gohr    public function _userDomain($user) {
60593a7873eSAndreas Gohr        list(, $domain) = explode('@', $user, 2);
60693a7873eSAndreas Gohr        return $domain;
607f4476bd9SJan Schumann    }
608f4476bd9SJan Schumann
60993a7873eSAndreas Gohr    /**
61093a7873eSAndreas Gohr     * Get the user part from a user
61193a7873eSAndreas Gohr     *
612253d4b48SGerrit Uitslag     * @param string $user
61393a7873eSAndreas Gohr     * @return string
61493a7873eSAndreas Gohr     */
61593a7873eSAndreas Gohr    public function _userName($user) {
61693a7873eSAndreas Gohr        list($name) = explode('@', $user, 2);
61793a7873eSAndreas Gohr        return $name;
61893a7873eSAndreas Gohr    }
61993a7873eSAndreas Gohr
62093a7873eSAndreas Gohr    /**
62193a7873eSAndreas Gohr     * Fetch the configuration for the given AD domain
62293a7873eSAndreas Gohr     *
62393a7873eSAndreas Gohr     * @param string $domain current AD domain
62493a7873eSAndreas Gohr     * @return array
62593a7873eSAndreas Gohr     */
62693a7873eSAndreas Gohr    protected function _loadServerConfig($domain) {
62793a7873eSAndreas Gohr        // prepare adLDAP standard configuration
62832fd494aSAndreas Gohr        $opts = $this->conf;
62993a7873eSAndreas Gohr
63093a7873eSAndreas Gohr        $opts['domain'] = $domain;
63193a7873eSAndreas Gohr
63293a7873eSAndreas Gohr        // add possible domain specific configuration
63332fd494aSAndreas Gohr        if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) {
63493a7873eSAndreas Gohr            $opts[$key] = $val;
63593a7873eSAndreas Gohr        }
63693a7873eSAndreas Gohr
63793a7873eSAndreas Gohr        // handle multiple AD servers
63893a7873eSAndreas Gohr        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
63993a7873eSAndreas Gohr        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
64093a7873eSAndreas Gohr        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
64193a7873eSAndreas Gohr
6428257d713SAndreas Gohr        // compatibility with old option name
6438257d713SAndreas Gohr        if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username'];
6448257d713SAndreas Gohr        if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password'];
645*342753d2SAndreas Gohr        $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate
6468257d713SAndreas Gohr
64793a7873eSAndreas Gohr        // we can change the password if SSL is set
64893a7873eSAndreas Gohr        if($opts['use_ssl'] || $opts['use_tls']) {
64993a7873eSAndreas Gohr            $this->cando['modPass'] = true;
65093a7873eSAndreas Gohr        } else {
65193a7873eSAndreas Gohr            $this->cando['modPass'] = false;
65293a7873eSAndreas Gohr        }
65393a7873eSAndreas Gohr
65412d195abSAndreas Gohr        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
65512d195abSAndreas Gohr        if(empty($opts['admin_username'])) $opts['admin_username'] = null;
65612d195abSAndreas Gohr        if(empty($opts['admin_password'])) $opts['admin_password'] = null;
65712d195abSAndreas Gohr
65812d195abSAndreas Gohr        // user listing needs admin priviledges
6598257d713SAndreas Gohr        if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
66093a7873eSAndreas Gohr            $this->cando['getUsers'] = true;
66193a7873eSAndreas Gohr        } else {
6621b228d28SKlap-in            $this->cando['getUsers'] = false;
66393a7873eSAndreas Gohr        }
66493a7873eSAndreas Gohr
66593a7873eSAndreas Gohr        return $opts;
66693a7873eSAndreas Gohr    }
66793a7873eSAndreas Gohr
66893a7873eSAndreas Gohr    /**
669741b8a48SAndreas Gohr     * Returns a list of configured domains
670741b8a48SAndreas Gohr     *
671741b8a48SAndreas Gohr     * The default domain has an empty string as key
672741b8a48SAndreas Gohr     *
673741b8a48SAndreas Gohr     * @return array associative array(key => domain)
674741b8a48SAndreas Gohr     */
675741b8a48SAndreas Gohr    public function _getConfiguredDomains() {
676741b8a48SAndreas Gohr        $domains = array();
677741b8a48SAndreas Gohr        if(empty($this->conf['account_suffix'])) return $domains; // not configured yet
678741b8a48SAndreas Gohr
679741b8a48SAndreas Gohr        // add default domain, using the name from account suffix
680741b8a48SAndreas Gohr        $domains[''] = ltrim($this->conf['account_suffix'], '@');
681741b8a48SAndreas Gohr
682741b8a48SAndreas Gohr        // find additional domains
683741b8a48SAndreas Gohr        foreach($this->conf as $key => $val) {
684741b8a48SAndreas Gohr            if(is_array($val) && isset($val['account_suffix'])) {
685741b8a48SAndreas Gohr                $domains[$key] = ltrim($val['account_suffix'], '@');
686741b8a48SAndreas Gohr            }
687741b8a48SAndreas Gohr        }
688741b8a48SAndreas Gohr        ksort($domains);
689741b8a48SAndreas Gohr
690741b8a48SAndreas Gohr        return $domains;
691741b8a48SAndreas Gohr    }
692741b8a48SAndreas Gohr
693741b8a48SAndreas Gohr    /**
69493a7873eSAndreas Gohr     * Check provided user and userinfo for matching patterns
69593a7873eSAndreas Gohr     *
69693a7873eSAndreas Gohr     * The patterns are set up with $this->_constructPattern()
69793a7873eSAndreas Gohr     *
69893a7873eSAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
699253d4b48SGerrit Uitslag     *
70093a7873eSAndreas Gohr     * @param string $user
70193a7873eSAndreas Gohr     * @param array  $info
70293a7873eSAndreas Gohr     * @return bool
70393a7873eSAndreas Gohr     */
70493a7873eSAndreas Gohr    protected function _filter($user, $info) {
70593a7873eSAndreas Gohr        foreach($this->_pattern as $item => $pattern) {
70693a7873eSAndreas Gohr            if($item == 'user') {
70793a7873eSAndreas Gohr                if(!preg_match($pattern, $user)) return false;
70893a7873eSAndreas Gohr            } else if($item == 'grps') {
70993a7873eSAndreas Gohr                if(!count(preg_grep($pattern, $info['grps']))) return false;
71093a7873eSAndreas Gohr            } else {
71193a7873eSAndreas Gohr                if(!preg_match($pattern, $info[$item])) return false;
71293a7873eSAndreas Gohr            }
71393a7873eSAndreas Gohr        }
71493a7873eSAndreas Gohr        return true;
71593a7873eSAndreas Gohr    }
71693a7873eSAndreas Gohr
71793a7873eSAndreas Gohr    /**
71893a7873eSAndreas Gohr     * Create a pattern for $this->_filter()
71993a7873eSAndreas Gohr     *
72093a7873eSAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
721253d4b48SGerrit Uitslag     *
72293a7873eSAndreas Gohr     * @param array $filter
72393a7873eSAndreas Gohr     */
72493a7873eSAndreas Gohr    protected function _constructPattern($filter) {
725f4476bd9SJan Schumann        $this->_pattern = array();
726f4476bd9SJan Schumann        foreach($filter as $item => $pattern) {
727f4476bd9SJan Schumann            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
728f4476bd9SJan Schumann        }
729f4476bd9SJan Schumann    }
730f4476bd9SJan Schumann}
731