xref: /dokuwiki/lib/plugins/authad/auth.php (revision 485f8f3546a5eb52d71fdffe1a54b8e0f06cd4cf)
1f4476bd9SJan Schumann<?php
2d4f83172SAndreas Gohr
38553d24dSAndreas Gohruse dokuwiki\Extension\AuthPlugin;
4ab9790caSAndreas Gohruse dokuwiki\Utf8\Clean;
5*485f8f35SAndreas Gohruse dokuwiki\Utf8\Conversion;
6ab9790caSAndreas Gohruse dokuwiki\Utf8\PhpString;
70489c64bSMoisés Braga Ribeirouse dokuwiki\Utf8\Sort;
831667ec6SAndreas Gohruse dokuwiki\Logger;
931667ec6SAndreas Gohr
10f4476bd9SJan Schumann/**
11f4476bd9SJan Schumann * Active Directory authentication backend for DokuWiki
12f4476bd9SJan Schumann *
13f4476bd9SJan Schumann * This makes authentication with a Active Directory server much easier
14f4476bd9SJan Schumann * than when using the normal LDAP backend by utilizing the adLDAP library
15f4476bd9SJan Schumann *
16f4476bd9SJan Schumann * Usage:
17f4476bd9SJan Schumann *   Set DokuWiki's local.protected.php auth setting to read
18f4476bd9SJan Schumann *
19f4476bd9SJan Schumann *   $conf['authtype']       = 'authad';
20f4476bd9SJan Schumann *
2132fd494aSAndreas Gohr *   $conf['plugin']['authad']['account_suffix']     = '@my.domain.org';
2232fd494aSAndreas Gohr *   $conf['plugin']['authad']['base_dn']            = 'DC=my,DC=domain,DC=org';
2332fd494aSAndreas Gohr *   $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
24f4476bd9SJan Schumann *
25f4476bd9SJan Schumann *   //optional:
2632fd494aSAndreas Gohr *   $conf['plugin']['authad']['sso']                = 1;
273002d731SAndreas Gohr *   $conf['plugin']['authad']['admin_username']     = 'root';
283002d731SAndreas Gohr *   $conf['plugin']['authad']['admin_password']     = 'pass';
2932fd494aSAndreas Gohr *   $conf['plugin']['authad']['real_primarygroup']  = 1;
3032fd494aSAndreas Gohr *   $conf['plugin']['authad']['use_ssl']            = 1;
3132fd494aSAndreas Gohr *   $conf['plugin']['authad']['use_tls']            = 1;
3232fd494aSAndreas Gohr *   $conf['plugin']['authad']['debug']              = 1;
3393a7873eSAndreas Gohr *   // warn user about expiring password this many days in advance:
3432fd494aSAndreas Gohr *   $conf['plugin']['authad']['expirywarn']         = 5;
35f4476bd9SJan Schumann *
36f4476bd9SJan Schumann *   // get additional information to the userinfo array
37f4476bd9SJan Schumann *   // add a list of comma separated ldap contact fields.
38f4476bd9SJan Schumann *   $conf['plugin']['authad']['additional'] = 'field1,field2';
39f4476bd9SJan Schumann *
40f4476bd9SJan Schumann * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
41f4476bd9SJan Schumann * @author  James Van Lommel <jamesvl@gmail.com>
42f4476bd9SJan Schumann * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
43f4476bd9SJan Schumann * @author  Andreas Gohr <andi@splitbrain.org>
44f4476bd9SJan Schumann * @author  Jan Schumann <js@schumann-it.com>
45f4476bd9SJan Schumann */
468553d24dSAndreas Gohrclass auth_plugin_authad extends AuthPlugin
47a4337320SAndreas Gohr{
4893a7873eSAndreas Gohr    /**
4993a7873eSAndreas Gohr     * @var array hold connection data for a specific AD domain
5093a7873eSAndreas Gohr     */
51ab9790caSAndreas Gohr    protected $opts = [];
5232fd494aSAndreas Gohr
5393a7873eSAndreas Gohr    /**
5493a7873eSAndreas Gohr     * @var array open connections for each AD domain, as adLDAP objects
5593a7873eSAndreas Gohr     */
56ab9790caSAndreas Gohr    protected $adldap = [];
5793a7873eSAndreas Gohr
5893a7873eSAndreas Gohr    /**
5993a7873eSAndreas Gohr     * @var bool message state
6093a7873eSAndreas Gohr     */
6193a7873eSAndreas Gohr    protected $msgshown = false;
6293a7873eSAndreas Gohr
6393a7873eSAndreas Gohr    /**
6493a7873eSAndreas Gohr     * @var array user listing cache
6593a7873eSAndreas Gohr     */
66ab9790caSAndreas Gohr    protected $users = [];
6793a7873eSAndreas Gohr
6893a7873eSAndreas Gohr    /**
6993a7873eSAndreas Gohr     * @var array filter patterns for listing users
7093a7873eSAndreas Gohr     */
71ab9790caSAndreas Gohr    protected $pattern = [];
72f4476bd9SJan Schumann
73ab9790caSAndreas Gohr    protected $grpsusers = [];
74c52f6cd2SMichael Große
75f4476bd9SJan Schumann    /**
76f4476bd9SJan Schumann     * Constructor
77f4476bd9SJan Schumann     */
78a4337320SAndreas Gohr    public function __construct()
79a4337320SAndreas Gohr    {
8000d58927SMichael Hamann        global $INPUT;
81454d868bSAndreas Gohr        parent::__construct();
82454d868bSAndreas Gohr
83a4337320SAndreas Gohr        require_once(DOKU_PLUGIN . 'authad/adLDAP/adLDAP.php');
84a4337320SAndreas Gohr        require_once(DOKU_PLUGIN . 'authad/adLDAP/classes/adLDAPUtils.php');
85a4337320SAndreas Gohr
8632fd494aSAndreas Gohr        // we load the config early to modify it a bit here
8732fd494aSAndreas Gohr        $this->loadConfig();
88f4476bd9SJan Schumann
89f4476bd9SJan Schumann        // additional information fields
9032fd494aSAndreas Gohr        if (isset($this->conf['additional'])) {
9132fd494aSAndreas Gohr            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
9232fd494aSAndreas Gohr            $this->conf['additional'] = explode(',', $this->conf['additional']);
93ab9790caSAndreas Gohr        } else $this->conf['additional'] = [];
94f4476bd9SJan Schumann
95f4476bd9SJan Schumann        // ldap extension is needed
96f4476bd9SJan Schumann        if (!function_exists('ldap_connect')) {
9732fd494aSAndreas Gohr            if ($this->conf['debug'])
98f4476bd9SJan Schumann                msg("AD Auth: PHP LDAP extension not found.", -1);
99f4476bd9SJan Schumann            $this->success = false;
100f4476bd9SJan Schumann            return;
101f4476bd9SJan Schumann        }
102f4476bd9SJan Schumann
103f4476bd9SJan Schumann        // Prepare SSO
1041d5848a6Sfiwswe        if (!empty($INPUT->server->str('REMOTE_USER'))) {
105d34a2a38SAndreas Gohr            // make sure the right encoding is used
106d34a2a38SAndreas Gohr            if ($this->getConf('sso_charset')) {
107dccd6b2bSAndreas Gohr                $INPUT->server->set(
108dccd6b2bSAndreas Gohr                    'REMOTE_USER',
109dccd6b2bSAndreas Gohr                    iconv($this->getConf('sso_charset'), 'UTF-8', $INPUT->server->str('REMOTE_USER'))
110dccd6b2bSAndreas Gohr                );
111ab9790caSAndreas Gohr            } elseif (!Clean::isUtf8($INPUT->server->str('REMOTE_USER'))) {
112*485f8f35SAndreas Gohr                $INPUT->server->set('REMOTE_USER', Conversion::fromLatin1($INPUT->server->str('REMOTE_USER')));
11393a7873eSAndreas Gohr            }
114d34a2a38SAndreas Gohr
115d34a2a38SAndreas Gohr            // trust the incoming user
116d34a2a38SAndreas Gohr            if ($this->conf['sso']) {
1171d5848a6Sfiwswe                $INPUT->server->set('REMOTE_USER', $this->cleanUser($INPUT->server->str('REMOTE_USER')));
118f4476bd9SJan Schumann
119f4476bd9SJan Schumann                // we need to simulate a login
120f4476bd9SJan Schumann                if (empty($_COOKIE[DOKU_COOKIE])) {
1211d5848a6Sfiwswe                    $INPUT->set('u', $INPUT->server->str('REMOTE_USER'));
12200d58927SMichael Hamann                    $INPUT->set('p', 'sso_only');
123f4476bd9SJan Schumann                }
124f4476bd9SJan Schumann            }
125d34a2a38SAndreas Gohr        }
126f4476bd9SJan Schumann
12793a7873eSAndreas Gohr        // other can do's are changed in $this->_loadServerConfig() base on domain setup
128bb30445dSMichael Wilmes        $this->cando['modName'] = (bool)$this->conf['update_name'];
129bb30445dSMichael Wilmes        $this->cando['modMail'] = (bool)$this->conf['update_mail'];
13025f80763SMichael Große        $this->cando['getUserCount'] = true;
131f4476bd9SJan Schumann    }
132f4476bd9SJan Schumann
133f4476bd9SJan Schumann    /**
134a154806fSAndreas Gohr     * Load domain config on capability check
135a154806fSAndreas Gohr     *
136a154806fSAndreas Gohr     * @param string $cap
137a154806fSAndreas Gohr     * @return bool
138a154806fSAndreas Gohr     */
139a4337320SAndreas Gohr    public function canDo($cap)
140a4337320SAndreas Gohr    {
1411d5848a6Sfiwswe        global $INPUT;
142a154806fSAndreas Gohr        //capabilities depend on config, which may change depending on domain
1431d5848a6Sfiwswe        $domain = $this->getUserDomain($INPUT->server->str('REMOTE_USER'));
144a4337320SAndreas Gohr        $this->loadServerConfig($domain);
145a154806fSAndreas Gohr        return parent::canDo($cap);
146a154806fSAndreas Gohr    }
147a154806fSAndreas Gohr
148a154806fSAndreas Gohr    /**
149f4476bd9SJan Schumann     * Check user+password [required auth function]
150f4476bd9SJan Schumann     *
151f4476bd9SJan Schumann     * Checks if the given user exists and the given
152f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
153f4476bd9SJan Schumann     * to the LDAP server
154f4476bd9SJan Schumann     *
155f4476bd9SJan Schumann     * @author  James Van Lommel <james@nosq.com>
15693a7873eSAndreas Gohr     * @param string $user
15793a7873eSAndreas Gohr     * @param string $pass
158f4476bd9SJan Schumann     * @return  bool
159f4476bd9SJan Schumann     */
160a4337320SAndreas Gohr    public function checkPass($user, $pass)
161a4337320SAndreas Gohr    {
1621d5848a6Sfiwswe        global $INPUT;
1637d34963bSAndreas Gohr        if (
1647d34963bSAndreas Gohr            $INPUT->server->str('REMOTE_USER') == $user &&
16532fd494aSAndreas Gohr            $this->conf['sso']
16693a7873eSAndreas Gohr        ) return true;
167f4476bd9SJan Schumann
168a4337320SAndreas Gohr        $adldap = $this->initAdLdap($this->getUserDomain($user));
16993a7873eSAndreas Gohr        if (!$adldap) return false;
17093a7873eSAndreas Gohr
171a4337320SAndreas Gohr        try {
172a4337320SAndreas Gohr            return $adldap->authenticate($this->getUserName($user), $pass);
173093fe67eSAndreas Gohr        } catch (adLDAPException) {
174a4337320SAndreas Gohr            // shouldn't really happen
175a4337320SAndreas Gohr            return false;
176a4337320SAndreas Gohr        }
177f4476bd9SJan Schumann    }
178f4476bd9SJan Schumann
179f4476bd9SJan Schumann    /**
180f4476bd9SJan Schumann     * Return user info [required auth function]
181f4476bd9SJan Schumann     *
182f4476bd9SJan Schumann     * Returns info about the given user needs to contain
183f4476bd9SJan Schumann     * at least these fields:
184f4476bd9SJan Schumann     *
185f4476bd9SJan Schumann     * name    string  full name of the user
186f4476bd9SJan Schumann     * mail    string  email address of the user
187f4476bd9SJan Schumann     * grps    array   list of groups the user is in
188f4476bd9SJan Schumann     *
18993a7873eSAndreas Gohr     * This AD specific function returns the following
190f4476bd9SJan Schumann     * addional fields:
191f4476bd9SJan Schumann     *
192f4476bd9SJan Schumann     * dn         string    distinguished name (DN)
19393a7873eSAndreas Gohr     * uid        string    samaccountname
19493a7873eSAndreas Gohr     * lastpwd    int       timestamp of the date when the password was set
19593a7873eSAndreas Gohr     * expires    true      if the password expires
19693a7873eSAndreas Gohr     * expiresin  int       seconds until the password expires
19793a7873eSAndreas Gohr     * any fields specified in the 'additional' config option
198f4476bd9SJan Schumann     *
199f4476bd9SJan Schumann     * @author  James Van Lommel <james@nosq.com>
20093a7873eSAndreas Gohr     * @param string $user
2012046a654SChristopher Smith     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
202a0d03045Sfiwswe     * @return array|false
203f4476bd9SJan Schumann     */
204a4337320SAndreas Gohr    public function getUserData($user, $requireGroups = true)
205a4337320SAndreas Gohr    {
206f4476bd9SJan Schumann        global $conf;
20793a7873eSAndreas Gohr        global $lang;
20893a7873eSAndreas Gohr        global $ID;
2091d5848a6Sfiwswe        global $INPUT;
210a4337320SAndreas Gohr        $adldap = $this->initAdLdap($this->getUserDomain($user));
211a0d03045Sfiwswe        if (!$adldap) return false;
212a0d03045Sfiwswe        if ($user == '') return false;
21393a7873eSAndreas Gohr
214ab9790caSAndreas Gohr        $fields = ['mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol'];
215f4476bd9SJan Schumann
216f4476bd9SJan Schumann        // add additional fields to read
21732fd494aSAndreas Gohr        $fields = array_merge($fields, $this->conf['additional']);
218f4476bd9SJan Schumann        $fields = array_unique($fields);
21914642325SAndreas Gohr        $fields = array_filter($fields);
220f4476bd9SJan Schumann
221f4476bd9SJan Schumann        //get info for given user
222a4337320SAndreas Gohr        $result = $adldap->user()->info($this->getUserName($user), $fields);
22393a7873eSAndreas Gohr        if ($result == false) {
224a0d03045Sfiwswe            return false;
22593a7873eSAndreas Gohr        }
22693a7873eSAndreas Gohr
227f4476bd9SJan Schumann        //general user info
228ab9790caSAndreas Gohr        $info = [];
229f4476bd9SJan Schumann        $info['name'] = $result[0]['displayname'][0];
230f4476bd9SJan Schumann        $info['mail'] = $result[0]['mail'][0];
231f4476bd9SJan Schumann        $info['uid']  = $result[0]['samaccountname'][0];
232f4476bd9SJan Schumann        $info['dn']   = $result[0]['dn'];
23393a7873eSAndreas Gohr        //last password set (Windows counts from January 1st 1601)
234ab9790caSAndreas Gohr        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10_000_000 - 11_644_473_600;
23593a7873eSAndreas Gohr        //will it expire?
23693a7873eSAndreas Gohr        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
237f4476bd9SJan Schumann
238f4476bd9SJan Schumann        // additional information
23932fd494aSAndreas Gohr        foreach ($this->conf['additional'] as $field) {
240f4476bd9SJan Schumann            if (isset($result[0][strtolower($field)])) {
241f4476bd9SJan Schumann                $info[$field] = $result[0][strtolower($field)][0];
242f4476bd9SJan Schumann            }
243f4476bd9SJan Schumann        }
244f4476bd9SJan Schumann
245f4476bd9SJan Schumann        // handle ActiveDirectory memberOf
246a4337320SAndreas Gohr        $info['grps'] = $adldap->user()->groups($this->getUserName($user), (bool) $this->opts['recursive_groups']);
247f4476bd9SJan Schumann
248f4476bd9SJan Schumann        if (is_array($info['grps'])) {
249f4476bd9SJan Schumann            foreach ($info['grps'] as $ndx => $group) {
250f4476bd9SJan Schumann                $info['grps'][$ndx] = $this->cleanGroup($group);
251f4476bd9SJan Schumann            }
252a0d03045Sfiwswe        } else {
253a0d03045Sfiwswe            $info['grps'] = [];
254f4476bd9SJan Schumann        }
255f4476bd9SJan Schumann
256f4476bd9SJan Schumann        // always add the default group to the list of groups
257a0d03045Sfiwswe        if (!in_array($conf['defaultgroup'], $info['grps'])) {
258f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
259f4476bd9SJan Schumann        }
260f4476bd9SJan Schumann
26193a7873eSAndreas Gohr        // add the user's domain to the groups
262a4337320SAndreas Gohr        $domain = $this->getUserDomain($user);
263bf9be0e3SAndreas Gohr        if ($domain && !in_array("domain-$domain", $info['grps'])) {
26493a7873eSAndreas Gohr            $info['grps'][] = $this->cleanGroup("domain-$domain");
26593a7873eSAndreas Gohr        }
26693a7873eSAndreas Gohr
26793a7873eSAndreas Gohr        // check expiry time
26832fd494aSAndreas Gohr        if ($info['expires'] && $this->conf['expirywarn']) {
269a4337320SAndreas Gohr            try {
2701e52e72aSAndreas Gohr                $expiry = $adldap->user()->passwordExpiry($user);
2711e52e72aSAndreas Gohr                if (is_array($expiry)) {
2721e52e72aSAndreas Gohr                    $info['expiresat'] = $expiry['expiryts'];
2731e52e72aSAndreas Gohr                    $info['expiresin'] = round(($info['expiresat'] - time()) / (24 * 60 * 60));
27493a7873eSAndreas Gohr
27593a7873eSAndreas Gohr                    // if this is the current user, warn him (once per request only)
2767d34963bSAndreas Gohr                    if (
2777d34963bSAndreas Gohr                        ($INPUT->server->str('REMOTE_USER') == $user) &&
2781e52e72aSAndreas Gohr                        ($info['expiresin'] <= $this->conf['expirywarn']) &&
27993a7873eSAndreas Gohr                        !$this->msgshown
28093a7873eSAndreas Gohr                    ) {
2815b795a65SPatrick Brown                        $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']);
28293a7873eSAndreas Gohr                        if ($this->canDo('modPass')) {
283ab9790caSAndreas Gohr                            $url = wl($ID, ['do' => 'profile']);
28493a7873eSAndreas Gohr                            $msg .= ' <a href="' . $url . '">' . $lang['btn_profile'] . '</a>';
28593a7873eSAndreas Gohr                        }
28693a7873eSAndreas Gohr                        msg($msg);
28793a7873eSAndreas Gohr                        $this->msgshown = true;
28893a7873eSAndreas Gohr                    }
28993a7873eSAndreas Gohr                }
290093fe67eSAndreas Gohr            } catch (adLDAPException) {
291a4337320SAndreas Gohr                // ignore. should usually not happen
292a4337320SAndreas Gohr            }
2931e52e72aSAndreas Gohr        }
29493a7873eSAndreas Gohr
295f4476bd9SJan Schumann        return $info;
296f4476bd9SJan Schumann    }
297f4476bd9SJan Schumann
298f4476bd9SJan Schumann    /**
299f4476bd9SJan Schumann     * Make AD group names usable by DokuWiki.
300f4476bd9SJan Schumann     *
301f4476bd9SJan Schumann     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
302f4476bd9SJan Schumann     *
303f4476bd9SJan Schumann     * @author  James Van Lommel (jamesvl@gmail.com)
30493a7873eSAndreas Gohr     * @param string $group
30593a7873eSAndreas Gohr     * @return string
306f4476bd9SJan Schumann     */
307a4337320SAndreas Gohr    public function cleanGroup($group)
308a4337320SAndreas Gohr    {
30993a7873eSAndreas Gohr        $group = str_replace('\\', '', $group);
31093a7873eSAndreas Gohr        $group = str_replace('#', '', $group);
31193a7873eSAndreas Gohr        $group = preg_replace('[\s]', '_', $group);
312ab9790caSAndreas Gohr        $group = PhpString::strtolower(trim($group));
31393a7873eSAndreas Gohr        return $group;
314f4476bd9SJan Schumann    }
315f4476bd9SJan Schumann
316f4476bd9SJan Schumann    /**
317f4476bd9SJan Schumann     * Sanitize user names
31893a7873eSAndreas Gohr     *
31993a7873eSAndreas Gohr     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
32093a7873eSAndreas Gohr     *
32193a7873eSAndreas Gohr     * @author Andreas Gohr <gohr@cosmocode.de>
32293a7873eSAndreas Gohr     * @param string $user
32393a7873eSAndreas Gohr     * @return string
324f4476bd9SJan Schumann     */
325a4337320SAndreas Gohr    public function cleanUser($user)
326a4337320SAndreas Gohr    {
32793a7873eSAndreas Gohr        $domain = '';
32893a7873eSAndreas Gohr
32993a7873eSAndreas Gohr        // get NTLM or Kerberos domain part
330ab9790caSAndreas Gohr        [$dom, $user] = sexplode('\\', $user, 2, '');
33193a7873eSAndreas Gohr        if (!$user) $user = $dom;
33293a7873eSAndreas Gohr        if ($dom) $domain = $dom;
333ab9790caSAndreas Gohr        [$user, $dom] = sexplode('@', $user, 2, '');
33493a7873eSAndreas Gohr        if ($dom) $domain = $dom;
33593a7873eSAndreas Gohr
33693a7873eSAndreas Gohr        // clean up both
337ab9790caSAndreas Gohr        $domain = PhpString::strtolower(trim($domain));
338ab9790caSAndreas Gohr        $user   = PhpString::strtolower(trim($user));
33993a7873eSAndreas Gohr
340916ef7cfSAndreas Gohr        // is this a known, valid domain or do we work without account suffix? if not discard
3417d34963bSAndreas Gohr        if (
3427d34963bSAndreas Gohr            (!isset($this->conf[$domain]) || !is_array($this->conf[$domain])) &&
3437d34963bSAndreas Gohr            $this->conf['account_suffix'] !== ''
3447d34963bSAndreas Gohr        ) {
34593a7873eSAndreas Gohr            $domain = '';
34693a7873eSAndreas Gohr        }
34793a7873eSAndreas Gohr
34893a7873eSAndreas Gohr        // reattach domain
34993a7873eSAndreas Gohr        if ($domain) $user = "$user@$domain";
35093a7873eSAndreas Gohr        return $user;
351f4476bd9SJan Schumann    }
352f4476bd9SJan Schumann
353f4476bd9SJan Schumann    /**
354f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
35593a7873eSAndreas Gohr     *
35693a7873eSAndreas Gohr     * @return bool
357f4476bd9SJan Schumann     */
358a4337320SAndreas Gohr    public function isCaseSensitive()
359a4337320SAndreas Gohr    {
360f4476bd9SJan Schumann        return false;
361f4476bd9SJan Schumann    }
362f4476bd9SJan Schumann
3636fcf992cSMichael Große    /**
3647910cbbbSMichael Große     * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
3657910cbbbSMichael Große     *
3666fcf992cSMichael Große     * @param array $filter
3676fcf992cSMichael Große     * @return string
3686fcf992cSMichael Große     */
369a4337320SAndreas Gohr    protected function constructSearchString($filter)
370a4337320SAndreas Gohr    {
37167a31a83SMichael Große        if (!$filter) {
37267a31a83SMichael Große            return '*';
37367a31a83SMichael Große        }
374a4337320SAndreas Gohr        $adldapUtils = new adLDAPUtils($this->initAdLdap(null));
37567a31a83SMichael Große        $result = '*';
37667a31a83SMichael Große        if (isset($filter['name'])) {
37707aec029SMichael Große            $result .= ')(displayname=*' . $adldapUtils->ldapSlashes($filter['name']) . '*';
37867a31a83SMichael Große            unset($filter['name']);
37967a31a83SMichael Große        }
3807910cbbbSMichael Große
38167a31a83SMichael Große        if (isset($filter['user'])) {
38207aec029SMichael Große            $result .= ')(samAccountName=*' . $adldapUtils->ldapSlashes($filter['user']) . '*';
38367a31a83SMichael Große            unset($filter['user']);
38467a31a83SMichael Große        }
38567a31a83SMichael Große
38667a31a83SMichael Große        if (isset($filter['mail'])) {
38707aec029SMichael Große            $result .= ')(mail=*' . $adldapUtils->ldapSlashes($filter['mail']) . '*';
38867a31a83SMichael Große            unset($filter['mail']);
38967a31a83SMichael Große        }
39067a31a83SMichael Große        return $result;
39167a31a83SMichael Große    }
39267a31a83SMichael Große
393f4476bd9SJan Schumann    /**
3947910cbbbSMichael Große     * Return a count of the number of user which meet $filter criteria
3957910cbbbSMichael Große     *
3967910cbbbSMichael Große     * @param array $filter  $filter array of field/pattern pairs, empty array for no filter
3977910cbbbSMichael Große     * @return int number of users
39825f80763SMichael Große     */
399ab9790caSAndreas Gohr    public function getUserCount($filter = [])
400a4337320SAndreas Gohr    {
401a4337320SAndreas Gohr        $adldap = $this->initAdLdap(null);
4026fcf992cSMichael Große        if (!$adldap) {
40331667ec6SAndreas Gohr            Logger::debug("authad/auth.php getUserCount(): _adldap not set.");
4046fcf992cSMichael Große            return -1;
4056fcf992cSMichael Große        }
406ab9790caSAndreas Gohr        if ($filter == []) {
40725f80763SMichael Große            $result = $adldap->user()->all();
40867a31a83SMichael Große        } else {
409a4337320SAndreas Gohr            $searchString = $this->constructSearchString($filter);
41067a31a83SMichael Große            $result = $adldap->user()->all(false, $searchString);
411c52f6cd2SMichael Große            if (isset($filter['grps'])) {
412c52f6cd2SMichael Große                $this->users = array_fill_keys($result, false);
413a4337320SAndreas Gohr                /** @var admin_plugin_usermanager $usermanager */
414c52f6cd2SMichael Große                $usermanager = plugin_load("admin", "usermanager", false);
415462e9e37SMichael Große                $usermanager->setLastdisabled(true);
416a4337320SAndreas Gohr                if (!isset($this->grpsusers[$this->filterToString($filter)])) {
417a4337320SAndreas Gohr                    $this->fillGroupUserArray($filter, $usermanager->getStart() + 3 * $usermanager->getPagesize());
4187d34963bSAndreas Gohr                } elseif (
4197d34963bSAndreas Gohr                    count($this->grpsusers[$this->filterToString($filter)]) <
42064159a61SAndreas Gohr                    $usermanager->getStart() + 3 * $usermanager->getPagesize()
42164159a61SAndreas Gohr                ) {
422a4337320SAndreas Gohr                    $this->fillGroupUserArray(
42364159a61SAndreas Gohr                        $filter,
42464159a61SAndreas Gohr                        $usermanager->getStart() +
42564159a61SAndreas Gohr                        3 * $usermanager->getPagesize() -
426a4337320SAndreas Gohr                        count($this->grpsusers[$this->filterToString($filter)])
42764159a61SAndreas Gohr                    );
428c52f6cd2SMichael Große                }
429a4337320SAndreas Gohr                $result = $this->grpsusers[$this->filterToString($filter)];
430462e9e37SMichael Große            } else {
431a4337320SAndreas Gohr                /** @var admin_plugin_usermanager $usermanager */
432462e9e37SMichael Große                $usermanager = plugin_load("admin", "usermanager", false);
433462e9e37SMichael Große                $usermanager->setLastdisabled(false);
434c52f6cd2SMichael Große            }
43567a31a83SMichael Große        }
43667a31a83SMichael Große
43725f80763SMichael Große        if (!$result) {
4386fcf992cSMichael Große            return 0;
43925f80763SMichael Große        }
44025f80763SMichael Große        return count($result);
44125f80763SMichael Große    }
44225f80763SMichael Große
4436fcf992cSMichael Große    /**
4446fcf992cSMichael Große     *
4456fcf992cSMichael Große     * create a unique string for each filter used with a group
4466fcf992cSMichael Große     *
4476fcf992cSMichael Große     * @param array $filter
4486fcf992cSMichael Große     * @return string
4496fcf992cSMichael Große     */
450a4337320SAndreas Gohr    protected function filterToString($filter)
451a4337320SAndreas Gohr    {
452c52f6cd2SMichael Große        $result = '';
453c52f6cd2SMichael Große        if (isset($filter['user'])) {
454c52f6cd2SMichael Große            $result .= 'user-' . $filter['user'];
455c52f6cd2SMichael Große        }
456c52f6cd2SMichael Große        if (isset($filter['name'])) {
457c52f6cd2SMichael Große            $result .= 'name-' . $filter['name'];
458c52f6cd2SMichael Große        }
459c52f6cd2SMichael Große        if (isset($filter['mail'])) {
460c52f6cd2SMichael Große            $result .= 'mail-' . $filter['mail'];
461c52f6cd2SMichael Große        }
462c52f6cd2SMichael Große        if (isset($filter['grps'])) {
463c52f6cd2SMichael Große            $result .= 'grps-' . $filter['grps'];
464c52f6cd2SMichael Große        }
465c52f6cd2SMichael Große        return $result;
466c52f6cd2SMichael Große    }
467c52f6cd2SMichael Große
4686fcf992cSMichael Große    /**
4697910cbbbSMichael Große     * Create an array of $numberOfAdds users passing a certain $filter, including belonging
4707910cbbbSMichael Große     * to a certain group and save them to a object-wide array. If the array
4717910cbbbSMichael Große     * already exists try to add $numberOfAdds further users to it.
4727910cbbbSMichael Große     *
4736fcf992cSMichael Große     * @param array $filter
4746fcf992cSMichael Große     * @param int $numberOfAdds additional number of users requested
4756fcf992cSMichael Große     * @return int number of Users actually add to Array
4766fcf992cSMichael Große     */
477a4337320SAndreas Gohr    protected function fillGroupUserArray($filter, $numberOfAdds)
478a4337320SAndreas Gohr    {
479fdd649a2SAndreas Gohr        if (isset($this->grpsusers[$this->filterToString($filter)])) {
480fdd649a2SAndreas Gohr            $actualstart = count($this->grpsusers[$this->filterToString($filter)]);
481fdd649a2SAndreas Gohr        } else {
482fdd649a2SAndreas Gohr            $this->grpsusers[$this->filterToString($filter)] = [];
483fdd649a2SAndreas Gohr            $actualstart = 0;
484fdd649a2SAndreas Gohr        }
485fdd649a2SAndreas Gohr
486c52f6cd2SMichael Große        $i = 0;
487c52f6cd2SMichael Große        $count = 0;
488a4337320SAndreas Gohr        $this->constructPattern($filter);
489c52f6cd2SMichael Große        foreach ($this->users as $user => &$info) {
490fdd649a2SAndreas Gohr            if ($i++ < $actualstart) {
491c52f6cd2SMichael Große                continue;
492c52f6cd2SMichael Große            }
493c52f6cd2SMichael Große            if ($info === false) {
494c52f6cd2SMichael Große                $info = $this->getUserData($user);
495c52f6cd2SMichael Große            }
496a4337320SAndreas Gohr            if ($this->filter($user, $info)) {
497a4337320SAndreas Gohr                $this->grpsusers[$this->filterToString($filter)][$user] = $info;
498c52f6cd2SMichael Große                if (($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
499c52f6cd2SMichael Große            }
500c52f6cd2SMichael Große        }
501c52f6cd2SMichael Große        return $count;
502c52f6cd2SMichael Große    }
503c52f6cd2SMichael Große
50425f80763SMichael Große    /**
505f4476bd9SJan Schumann     * Bulk retrieval of user data
506f4476bd9SJan Schumann     *
507f4476bd9SJan Schumann     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
508253d4b48SGerrit Uitslag     *
50993a7873eSAndreas Gohr     * @param   int $start index of first user to be returned
51093a7873eSAndreas Gohr     * @param   int $limit max number of users to be returned
51193a7873eSAndreas Gohr     * @param   array $filter array of field/pattern pairs, null for no filter
51293a7873eSAndreas Gohr     * @return array userinfo (refer getUserData for internal userinfo details)
513f4476bd9SJan Schumann     */
514ab9790caSAndreas Gohr    public function retrieveUsers($start = 0, $limit = 0, $filter = [])
515a4337320SAndreas Gohr    {
516a4337320SAndreas Gohr        $adldap = $this->initAdLdap(null);
517ab9790caSAndreas Gohr        if (!$adldap) return [];
518f4476bd9SJan Schumann
519fdd649a2SAndreas Gohr        //if (!$this->users) {
520f4476bd9SJan Schumann            //get info for given user
521a4337320SAndreas Gohr            $result = $adldap->user()->all(false, $this->constructSearchString($filter));
522ab9790caSAndreas Gohr            if (!$result) return [];
523f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
524fdd649a2SAndreas Gohr        //}
525f4476bd9SJan Schumann
526f4476bd9SJan Schumann        $i     = 0;
527f4476bd9SJan Schumann        $count = 0;
528ab9790caSAndreas Gohr        $result = [];
529f4476bd9SJan Schumann
530c52f6cd2SMichael Große        if (!isset($filter['grps'])) {
531a4337320SAndreas Gohr            /** @var admin_plugin_usermanager $usermanager */
532462e9e37SMichael Große            $usermanager = plugin_load("admin", "usermanager", false);
533462e9e37SMichael Große            $usermanager->setLastdisabled(false);
534a4337320SAndreas Gohr            $this->constructPattern($filter);
535f4476bd9SJan Schumann            foreach ($this->users as $user => &$info) {
536f4476bd9SJan Schumann                if ($i++ < $start) {
537f4476bd9SJan Schumann                    continue;
538f4476bd9SJan Schumann                }
539f4476bd9SJan Schumann                if ($info === false) {
540f4476bd9SJan Schumann                    $info = $this->getUserData($user);
541f4476bd9SJan Schumann                }
542f4476bd9SJan Schumann                $result[$user] = $info;
5439a2c73e8SAndreas Gohr                if (($limit > 0) && (++$count >= $limit)) break;
544f4476bd9SJan Schumann            }
545c52f6cd2SMichael Große        } else {
546a4337320SAndreas Gohr            /** @var admin_plugin_usermanager $usermanager */
547462e9e37SMichael Große            $usermanager = plugin_load("admin", "usermanager", false);
548462e9e37SMichael Große            $usermanager->setLastdisabled(true);
5497d34963bSAndreas Gohr            if (
5507d34963bSAndreas Gohr                !isset($this->grpsusers[$this->filterToString($filter)]) ||
551a4337320SAndreas Gohr                count($this->grpsusers[$this->filterToString($filter)]) < ($start + $limit)
55264159a61SAndreas Gohr            ) {
553fdd649a2SAndreas Gohr                if (!isset($this->grpsusers[$this->filterToString($filter)])) {
554fdd649a2SAndreas Gohr                    $this->grpsusers[$this->filterToString($filter)] = [];
555fdd649a2SAndreas Gohr                }
556fdd649a2SAndreas Gohr
557a4337320SAndreas Gohr                $this->fillGroupUserArray(
55864159a61SAndreas Gohr                    $filter,
559a4337320SAndreas Gohr                    $start + $limit - count($this->grpsusers[$this->filterToString($filter)]) + 1
56064159a61SAndreas Gohr                );
561c52f6cd2SMichael Große            }
562ab9790caSAndreas Gohr            if (!$this->grpsusers[$this->filterToString($filter)]) return [];
563a4337320SAndreas Gohr            foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) {
564c52f6cd2SMichael Große                if ($i++ < $start) {
565c52f6cd2SMichael Große                    continue;
566c52f6cd2SMichael Große                }
567c52f6cd2SMichael Große                $result[$user] = $info;
568c52f6cd2SMichael Große                if (($limit > 0) && (++$count >= $limit)) break;
569c52f6cd2SMichael Große            }
570c52f6cd2SMichael Große        }
571f4476bd9SJan Schumann        return $result;
572f4476bd9SJan Schumann    }
573f4476bd9SJan Schumann
574f4476bd9SJan Schumann    /**
575f4476bd9SJan Schumann     * Modify user data
576f4476bd9SJan Schumann     *
57793a7873eSAndreas Gohr     * @param   string $user      nick of the user to be changed
57893a7873eSAndreas Gohr     * @param   array  $changes   array of field/value pairs to be changed
579f4476bd9SJan Schumann     * @return  bool
580f4476bd9SJan Schumann     */
581a4337320SAndreas Gohr    public function modifyUser($user, $changes)
582a4337320SAndreas Gohr    {
583f4476bd9SJan Schumann        $return = true;
584a4337320SAndreas Gohr        $adldap = $this->initAdLdap($this->getUserDomain($user));
5858f03c311SPatrick Brown        if (!$adldap) {
5868f03c311SPatrick Brown            msg($this->getLang('connectfail'), -1);
5878f03c311SPatrick Brown            return false;
5888f03c311SPatrick Brown        }
589f4476bd9SJan Schumann
590f4476bd9SJan Schumann        // password changing
591f4476bd9SJan Schumann        if (isset($changes['pass'])) {
592f4476bd9SJan Schumann            try {
593a4337320SAndreas Gohr                $return = $adldap->user()->password($this->getUserName($user), $changes['pass']);
594f4476bd9SJan Schumann            } catch (adLDAPException $e) {
59532fd494aSAndreas Gohr                if ($this->conf['debug']) msg('AD Auth: ' . $e->getMessage(), -1);
596f4476bd9SJan Schumann                $return = false;
597f4476bd9SJan Schumann            }
5988f03c311SPatrick Brown            if (!$return) msg($this->getLang('passchangefail'), -1);
599f4476bd9SJan Schumann        }
600f4476bd9SJan Schumann
601f4476bd9SJan Schumann        // changing user data
602ab9790caSAndreas Gohr        $adchanges = [];
603f4476bd9SJan Schumann        if (isset($changes['name'])) {
604f4476bd9SJan Schumann            // get first and last name
605f4476bd9SJan Schumann            $parts                     = explode(' ', $changes['name']);
606f4476bd9SJan Schumann            $adchanges['surname']      = array_pop($parts);
607ab9790caSAndreas Gohr            $adchanges['firstname']    = implode(' ', $parts);
608f4476bd9SJan Schumann            $adchanges['display_name'] = $changes['name'];
609f4476bd9SJan Schumann        }
610f4476bd9SJan Schumann        if (isset($changes['mail'])) {
611f4476bd9SJan Schumann            $adchanges['email'] = $changes['mail'];
612f4476bd9SJan Schumann        }
613ab9790caSAndreas Gohr        if ($adchanges !== []) {
614f4476bd9SJan Schumann            try {
615ab9790caSAndreas Gohr                $return &= $adldap->user()->modify($this->getUserName($user), $adchanges);
616f4476bd9SJan Schumann            } catch (adLDAPException $e) {
61732fd494aSAndreas Gohr                if ($this->conf['debug']) msg('AD Auth: ' . $e->getMessage(), -1);
618f4476bd9SJan Schumann                $return = false;
619f4476bd9SJan Schumann            }
6208f03c311SPatrick Brown            if (!$return) msg($this->getLang('userchangefail'), -1);
621f4476bd9SJan Schumann        }
622f4476bd9SJan Schumann
623f4476bd9SJan Schumann        return $return;
624f4476bd9SJan Schumann    }
625f4476bd9SJan Schumann
626f4476bd9SJan Schumann    /**
627f4476bd9SJan Schumann     * Initialize the AdLDAP library and connect to the server
62893a7873eSAndreas Gohr     *
62993a7873eSAndreas Gohr     * When you pass null as domain, it will reuse any existing domain.
63093a7873eSAndreas Gohr     * Eg. the one of the logged in user. It falls back to the default
63193a7873eSAndreas Gohr     * domain if no current one is available.
63293a7873eSAndreas Gohr     *
63393a7873eSAndreas Gohr     * @param string|null $domain The AD domain to use
63493a7873eSAndreas Gohr     * @return adLDAP|bool true if a connection was established
635f4476bd9SJan Schumann     */
636a4337320SAndreas Gohr    protected function initAdLdap($domain)
637a4337320SAndreas Gohr    {
63893a7873eSAndreas Gohr        if (is_null($domain) && is_array($this->opts)) {
63993a7873eSAndreas Gohr            $domain = $this->opts['domain'];
64093a7873eSAndreas Gohr        }
64193a7873eSAndreas Gohr
642a4337320SAndreas Gohr        $this->opts = $this->loadServerConfig((string) $domain);
64393a7873eSAndreas Gohr        if (isset($this->adldap[$domain])) return $this->adldap[$domain];
644f4476bd9SJan Schumann
645f4476bd9SJan Schumann        // connect
646f4476bd9SJan Schumann        try {
64793a7873eSAndreas Gohr            $this->adldap[$domain] = new adLDAP($this->opts);
64893a7873eSAndreas Gohr            return $this->adldap[$domain];
649a4337320SAndreas Gohr        } catch (Exception $e) {
65032fd494aSAndreas Gohr            if ($this->conf['debug']) {
651f4476bd9SJan Schumann                msg('AD Auth: ' . $e->getMessage(), -1);
652f4476bd9SJan Schumann            }
653f4476bd9SJan Schumann            $this->success         = false;
65493a7873eSAndreas Gohr            $this->adldap[$domain] = null;
655f4476bd9SJan Schumann        }
656f4476bd9SJan Schumann        return false;
657f4476bd9SJan Schumann    }
658f4476bd9SJan Schumann
659f4476bd9SJan Schumann    /**
66093a7873eSAndreas Gohr     * Get the domain part from a user
661f4476bd9SJan Schumann     *
662253d4b48SGerrit Uitslag     * @param string $user
66393a7873eSAndreas Gohr     * @return string
664f4476bd9SJan Schumann     */
665a4337320SAndreas Gohr    public function getUserDomain($user)
666a4337320SAndreas Gohr    {
667ab9790caSAndreas Gohr        [, $domain] = sexplode('@', $user, 2, '');
66893a7873eSAndreas Gohr        return $domain;
669f4476bd9SJan Schumann    }
670f4476bd9SJan Schumann
67193a7873eSAndreas Gohr    /**
67293a7873eSAndreas Gohr     * Get the user part from a user
67393a7873eSAndreas Gohr     *
674916ef7cfSAndreas Gohr     * When an account suffix is set, we strip the domain part from the user
675916ef7cfSAndreas Gohr     *
676253d4b48SGerrit Uitslag     * @param string $user
67793a7873eSAndreas Gohr     * @return string
67893a7873eSAndreas Gohr     */
679a4337320SAndreas Gohr    public function getUserName($user)
680a4337320SAndreas Gohr    {
681916ef7cfSAndreas Gohr        if ($this->conf['account_suffix'] !== '') {
682ab9790caSAndreas Gohr            [$user] = explode('@', $user, 2);
683916ef7cfSAndreas Gohr        }
684916ef7cfSAndreas Gohr        return $user;
68593a7873eSAndreas Gohr    }
68693a7873eSAndreas Gohr
68793a7873eSAndreas Gohr    /**
68893a7873eSAndreas Gohr     * Fetch the configuration for the given AD domain
68993a7873eSAndreas Gohr     *
69093a7873eSAndreas Gohr     * @param string $domain current AD domain
69193a7873eSAndreas Gohr     * @return array
69293a7873eSAndreas Gohr     */
693a4337320SAndreas Gohr    protected function loadServerConfig($domain)
694a4337320SAndreas Gohr    {
69593a7873eSAndreas Gohr        // prepare adLDAP standard configuration
69632fd494aSAndreas Gohr        $opts = $this->conf;
69793a7873eSAndreas Gohr
69893a7873eSAndreas Gohr        $opts['domain'] = $domain;
69993a7873eSAndreas Gohr
70093a7873eSAndreas Gohr        // add possible domain specific configuration
70172203f2cSAndreas Gohr        if ($domain && is_array($this->conf[$domain] ?? '')) foreach ($this->conf[$domain] as $key => $val) {
70293a7873eSAndreas Gohr            $opts[$key] = $val;
70393a7873eSAndreas Gohr        }
70493a7873eSAndreas Gohr
70593a7873eSAndreas Gohr        // handle multiple AD servers
70693a7873eSAndreas Gohr        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
707093fe67eSAndreas Gohr        $opts['domain_controllers'] = array_map(trim(...), $opts['domain_controllers']);
70893a7873eSAndreas Gohr        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
70993a7873eSAndreas Gohr
7108257d713SAndreas Gohr        // compatibility with old option name
71164159a61SAndreas Gohr        if (empty($opts['admin_username']) && !empty($opts['ad_username'])) {
71264159a61SAndreas Gohr            $opts['admin_username'] = $opts['ad_username'];
71364159a61SAndreas Gohr        }
71464159a61SAndreas Gohr        if (empty($opts['admin_password']) && !empty($opts['ad_password'])) {
71564159a61SAndreas Gohr            $opts['admin_password'] = $opts['ad_password'];
71664159a61SAndreas Gohr        }
717342753d2SAndreas Gohr        $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate
7188257d713SAndreas Gohr
71993a7873eSAndreas Gohr        // we can change the password if SSL is set
720a847f473Spluto00987        if ($opts['update_pass'] && ($opts['use_ssl'] || $opts['use_tls'])) {
72193a7873eSAndreas Gohr            $this->cando['modPass'] = true;
72293a7873eSAndreas Gohr        } else {
72393a7873eSAndreas Gohr            $this->cando['modPass'] = false;
72493a7873eSAndreas Gohr        }
72593a7873eSAndreas Gohr
72612d195abSAndreas Gohr        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
72712d195abSAndreas Gohr        if (empty($opts['admin_username'])) $opts['admin_username'] = null;
72812d195abSAndreas Gohr        if (empty($opts['admin_password'])) $opts['admin_password'] = null;
72912d195abSAndreas Gohr
73012d195abSAndreas Gohr        // user listing needs admin priviledges
7318257d713SAndreas Gohr        if (!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
73293a7873eSAndreas Gohr            $this->cando['getUsers'] = true;
73393a7873eSAndreas Gohr        } else {
7341b228d28SKlap-in            $this->cando['getUsers'] = false;
73593a7873eSAndreas Gohr        }
73693a7873eSAndreas Gohr
73793a7873eSAndreas Gohr        return $opts;
73893a7873eSAndreas Gohr    }
73993a7873eSAndreas Gohr
74093a7873eSAndreas Gohr    /**
741741b8a48SAndreas Gohr     * Returns a list of configured domains
742741b8a48SAndreas Gohr     *
743741b8a48SAndreas Gohr     * The default domain has an empty string as key
744741b8a48SAndreas Gohr     *
745741b8a48SAndreas Gohr     * @return array associative array(key => domain)
746741b8a48SAndreas Gohr     */
747a4337320SAndreas Gohr    public function getConfiguredDomains()
748a4337320SAndreas Gohr    {
749ab9790caSAndreas Gohr        $domains = [];
750741b8a48SAndreas Gohr        if (empty($this->conf['account_suffix'])) return $domains; // not configured yet
751741b8a48SAndreas Gohr
752741b8a48SAndreas Gohr        // add default domain, using the name from account suffix
753741b8a48SAndreas Gohr        $domains[''] = ltrim($this->conf['account_suffix'], '@');
754741b8a48SAndreas Gohr
755741b8a48SAndreas Gohr        // find additional domains
756741b8a48SAndreas Gohr        foreach ($this->conf as $key => $val) {
757741b8a48SAndreas Gohr            if (is_array($val) && isset($val['account_suffix'])) {
758741b8a48SAndreas Gohr                $domains[$key] = ltrim($val['account_suffix'], '@');
759741b8a48SAndreas Gohr            }
760741b8a48SAndreas Gohr        }
7610489c64bSMoisés Braga Ribeiro        Sort::ksort($domains);
762741b8a48SAndreas Gohr
763741b8a48SAndreas Gohr        return $domains;
764741b8a48SAndreas Gohr    }
765741b8a48SAndreas Gohr
766741b8a48SAndreas Gohr    /**
76793a7873eSAndreas Gohr     * Check provided user and userinfo for matching patterns
76893a7873eSAndreas Gohr     *
76993a7873eSAndreas Gohr     * The patterns are set up with $this->_constructPattern()
77093a7873eSAndreas Gohr     *
77193a7873eSAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
772253d4b48SGerrit Uitslag     *
77393a7873eSAndreas Gohr     * @param string $user
77493a7873eSAndreas Gohr     * @param array  $info
77593a7873eSAndreas Gohr     * @return bool
77693a7873eSAndreas Gohr     */
777a4337320SAndreas Gohr    protected function filter($user, $info)
778a4337320SAndreas Gohr    {
779a4337320SAndreas Gohr        foreach ($this->pattern as $item => $pattern) {
78093a7873eSAndreas Gohr            if ($item == 'user') {
78193a7873eSAndreas Gohr                if (!preg_match($pattern, $user)) return false;
78293a7873eSAndreas Gohr            } elseif ($item == 'grps') {
78393a7873eSAndreas Gohr                if (!count(preg_grep($pattern, $info['grps']))) return false;
784ab9790caSAndreas Gohr            } elseif (!preg_match($pattern, $info[$item])) {
785ab9790caSAndreas Gohr                return false;
78693a7873eSAndreas Gohr            }
78793a7873eSAndreas Gohr        }
78893a7873eSAndreas Gohr        return true;
78993a7873eSAndreas Gohr    }
79093a7873eSAndreas Gohr
79193a7873eSAndreas Gohr    /**
79293a7873eSAndreas Gohr     * Create a pattern for $this->_filter()
79393a7873eSAndreas Gohr     *
79493a7873eSAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
795253d4b48SGerrit Uitslag     *
79693a7873eSAndreas Gohr     * @param array $filter
79793a7873eSAndreas Gohr     */
798a4337320SAndreas Gohr    protected function constructPattern($filter)
799a4337320SAndreas Gohr    {
800ab9790caSAndreas Gohr        $this->pattern = [];
801f4476bd9SJan Schumann        foreach ($filter as $item => $pattern) {
802a4337320SAndreas Gohr            $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
803f4476bd9SJan Schumann        }
804f4476bd9SJan Schumann    }
805f4476bd9SJan Schumann}
806