xref: /dokuwiki/lib/plugins/authad/auth.php (revision ce0feb5f5c38d0e698bd162105fbe61ceb27fca8)
1<?php
2use dokuwiki\Utf8\Sort;
3use dokuwiki\Logger;
4
5/**
6 * Active Directory authentication backend for DokuWiki
7 *
8 * This makes authentication with a Active Directory server much easier
9 * than when using the normal LDAP backend by utilizing the adLDAP library
10 *
11 * Usage:
12 *   Set DokuWiki's local.protected.php auth setting to read
13 *
14 *   $conf['authtype']       = 'authad';
15 *
16 *   $conf['plugin']['authad']['account_suffix']     = '@my.domain.org';
17 *   $conf['plugin']['authad']['base_dn']            = 'DC=my,DC=domain,DC=org';
18 *   $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
19 *
20 *   //optional:
21 *   $conf['plugin']['authad']['sso']                = 1;
22 *   $conf['plugin']['authad']['admin_username']     = 'root';
23 *   $conf['plugin']['authad']['admin_password']     = 'pass';
24 *   $conf['plugin']['authad']['real_primarygroup']  = 1;
25 *   $conf['plugin']['authad']['use_ssl']            = 1;
26 *   $conf['plugin']['authad']['use_tls']            = 1;
27 *   $conf['plugin']['authad']['debug']              = 1;
28 *   // warn user about expiring password this many days in advance:
29 *   $conf['plugin']['authad']['expirywarn']         = 5;
30 *
31 *   // get additional information to the userinfo array
32 *   // add a list of comma separated ldap contact fields.
33 *   $conf['plugin']['authad']['additional'] = 'field1,field2';
34 *
35 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
36 * @author  James Van Lommel <jamesvl@gmail.com>
37 * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
38 * @author  Andreas Gohr <andi@splitbrain.org>
39 * @author  Jan Schumann <js@schumann-it.com>
40 */
41class auth_plugin_authad extends DokuWiki_Auth_Plugin
42{
43
44    /**
45     * @var array hold connection data for a specific AD domain
46     */
47    protected $opts = array();
48
49    /**
50     * @var array open connections for each AD domain, as adLDAP objects
51     */
52    protected $adldap = array();
53
54    /**
55     * @var bool message state
56     */
57    protected $msgshown = false;
58
59    /**
60     * @var array user listing cache
61     */
62    protected $users = array();
63
64    /**
65     * @var array filter patterns for listing users
66     */
67    protected $pattern = array();
68
69    protected $grpsusers = array();
70
71    /**
72     * Constructor
73     */
74    public function __construct()
75    {
76        global $INPUT;
77        parent::__construct();
78
79        require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
80        require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php');
81
82        // we load the config early to modify it a bit here
83        $this->loadConfig();
84
85        // additional information fields
86        if (isset($this->conf['additional'])) {
87            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
88            $this->conf['additional'] = explode(',', $this->conf['additional']);
89        } else $this->conf['additional'] = array();
90
91        // ldap extension is needed
92        if (!function_exists('ldap_connect')) {
93            if ($this->conf['debug'])
94                msg("AD Auth: PHP LDAP extension not found.", -1);
95            $this->success = false;
96            return;
97        }
98
99        // Prepare SSO
100        if (!empty($INPUT->server->str('REMOTE_USER'))) {
101            // make sure the right encoding is used
102            if ($this->getConf('sso_charset')) {
103                $INPUT->server->set('REMOTE_USER', iconv($this->getConf('sso_charset'), 'UTF-8', $INPUT->server->str('REMOTE_USER')));
104            } elseif (!\dokuwiki\Utf8\Clean::isUtf8($INPUT->server->str('REMOTE_USER'))) {
105                $INPUT->server->set('REMOTE_USER', utf8_encode($INPUT->server->str('REMOTE_USER')));
106            }
107
108            // trust the incoming user
109            if ($this->conf['sso']) {
110                $INPUT->server->set('REMOTE_USER', $this->cleanUser($INPUT->server->str('REMOTE_USER')));
111
112                // we need to simulate a login
113                if (empty($_COOKIE[DOKU_COOKIE])) {
114                    $INPUT->set('u', $INPUT->server->str('REMOTE_USER'));
115                    $INPUT->set('p', 'sso_only');
116                }
117            }
118        }
119
120        // other can do's are changed in $this->_loadServerConfig() base on domain setup
121        $this->cando['modName'] = (bool)$this->conf['update_name'];
122        $this->cando['modMail'] = (bool)$this->conf['update_mail'];
123        $this->cando['getUserCount'] = true;
124    }
125
126    /**
127     * Load domain config on capability check
128     *
129     * @param string $cap
130     * @return bool
131     */
132    public function canDo($cap)
133    {
134        global $INPUT;
135        //capabilities depend on config, which may change depending on domain
136        $domain = $this->getUserDomain($INPUT->server->str('REMOTE_USER'));
137        $this->loadServerConfig($domain);
138        return parent::canDo($cap);
139    }
140
141    /**
142     * Check user+password [required auth function]
143     *
144     * Checks if the given user exists and the given
145     * plaintext password is correct by trying to bind
146     * to the LDAP server
147     *
148     * @author  James Van Lommel <james@nosq.com>
149     * @param string $user
150     * @param string $pass
151     * @return  bool
152     */
153    public function checkPass($user, $pass)
154    {
155        global $INPUT;
156        if ($INPUT->server->str('REMOTE_USER') == $user &&
157            $this->conf['sso']
158        ) return true;
159
160        $adldap = $this->initAdLdap($this->getUserDomain($user));
161        if (!$adldap) return false;
162
163        try {
164            return $adldap->authenticate($this->getUserName($user), $pass);
165        } catch (adLDAPException $e) {
166            // shouldn't really happen
167            return false;
168        }
169    }
170
171    /**
172     * Return user info [required auth function]
173     *
174     * Returns info about the given user needs to contain
175     * at least these fields:
176     *
177     * name    string  full name of the user
178     * mail    string  email address of the user
179     * grps    array   list of groups the user is in
180     *
181     * This AD specific function returns the following
182     * addional fields:
183     *
184     * dn         string    distinguished name (DN)
185     * uid        string    samaccountname
186     * lastpwd    int       timestamp of the date when the password was set
187     * expires    true      if the password expires
188     * expiresin  int       seconds until the password expires
189     * any fields specified in the 'additional' config option
190     *
191     * @author  James Van Lommel <james@nosq.com>
192     * @param string $user
193     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
194     * @return array
195     */
196    public function getUserData($user, $requireGroups = true)
197    {
198        global $conf;
199        global $lang;
200        global $ID;
201        global $INPUT;
202        $adldap = $this->initAdLdap($this->getUserDomain($user));
203        if (!$adldap) return array();
204
205        if ($user == '') return array();
206
207        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
208
209        // add additional fields to read
210        $fields = array_merge($fields, $this->conf['additional']);
211        $fields = array_unique($fields);
212        $fields = array_filter($fields);
213
214        //get info for given user
215        $result = $adldap->user()->info($this->getUserName($user), $fields);
216        if ($result == false) {
217            return array();
218        }
219
220        //general user info
221        $info = array();
222        $info['name'] = $result[0]['displayname'][0];
223        $info['mail'] = $result[0]['mail'][0];
224        $info['uid']  = $result[0]['samaccountname'][0];
225        $info['dn']   = $result[0]['dn'];
226        //last password set (Windows counts from January 1st 1601)
227        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
228        //will it expire?
229        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
230
231        // additional information
232        foreach ($this->conf['additional'] as $field) {
233            if (isset($result[0][strtolower($field)])) {
234                $info[$field] = $result[0][strtolower($field)][0];
235            }
236        }
237
238        // handle ActiveDirectory memberOf
239        $info['grps'] = $adldap->user()->groups($this->getUserName($user), (bool) $this->opts['recursive_groups']);
240
241        if (is_array($info['grps'])) {
242            foreach ($info['grps'] as $ndx => $group) {
243                $info['grps'][$ndx] = $this->cleanGroup($group);
244            }
245        }
246
247        // always add the default group to the list of groups
248        if (!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
249            $info['grps'][] = $conf['defaultgroup'];
250        }
251
252        // add the user's domain to the groups
253        $domain = $this->getUserDomain($user);
254        if ($domain && !in_array("domain-$domain", (array) $info['grps'])) {
255            $info['grps'][] = $this->cleanGroup("domain-$domain");
256        }
257
258        // check expiry time
259        if ($info['expires'] && $this->conf['expirywarn']) {
260            try {
261                $expiry = $adldap->user()->passwordExpiry($user);
262                if (is_array($expiry)) {
263                    $info['expiresat'] = $expiry['expiryts'];
264                    $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
265
266                    // if this is the current user, warn him (once per request only)
267                    if (($INPUT->server->str('REMOTE_USER') == $user) &&
268                        ($info['expiresin'] <= $this->conf['expirywarn']) &&
269                        !$this->msgshown
270                    ) {
271                        $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']);
272                        if ($this->canDo('modPass')) {
273                            $url = wl($ID, array('do'=> 'profile'));
274                            $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
275                        }
276                        msg($msg);
277                        $this->msgshown = true;
278                    }
279                }
280            } catch (adLDAPException $e) {
281                // ignore. should usually not happen
282            }
283        }
284
285        return $info;
286    }
287
288    /**
289     * Make AD group names usable by DokuWiki.
290     *
291     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
292     *
293     * @author  James Van Lommel (jamesvl@gmail.com)
294     * @param string $group
295     * @return string
296     */
297    public function cleanGroup($group)
298    {
299        $group = str_replace('\\', '', $group);
300        $group = str_replace('#', '', $group);
301        $group = preg_replace('[\s]', '_', $group);
302        $group = \dokuwiki\Utf8\PhpString::strtolower(trim($group));
303        return $group;
304    }
305
306    /**
307     * Sanitize user names
308     *
309     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
310     *
311     * @author Andreas Gohr <gohr@cosmocode.de>
312     * @param string $user
313     * @return string
314     */
315    public function cleanUser($user)
316    {
317        $domain = '';
318
319        // get NTLM or Kerberos domain part
320        list($dom, $user) = array_pad(explode('\\', $user, 2), 2, '');
321        if (!$user) $user = $dom;
322        if ($dom) $domain = $dom;
323        list($user, $dom) = array_pad(explode('@', $user, 2), 2, '');
324        if ($dom) $domain = $dom;
325
326        // clean up both
327        $domain = \dokuwiki\Utf8\PhpString::strtolower(trim($domain));
328        $user   = \dokuwiki\Utf8\PhpString::strtolower(trim($user));
329
330        // is this a known, valid domain or do we work without account suffix? if not discard
331        if ((!isset($this->conf[$domain]) || !is_array($this->conf[$domain])) &&
332            $this->conf['account_suffix'] !== '') {
333            $domain = '';
334        }
335
336        // reattach domain
337        if ($domain) $user = "$user@$domain";
338        return $user;
339    }
340
341    /**
342     * Most values in LDAP are case-insensitive
343     *
344     * @return bool
345     */
346    public function isCaseSensitive()
347    {
348        return false;
349    }
350
351    /**
352     * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
353     *
354     * @param array $filter
355     * @return string
356     */
357    protected function constructSearchString($filter)
358    {
359        if (!$filter) {
360            return '*';
361        }
362        $adldapUtils = new adLDAPUtils($this->initAdLdap(null));
363        $result = '*';
364        if (isset($filter['name'])) {
365            $result .= ')(displayname=*' . $adldapUtils->ldapSlashes($filter['name']) . '*';
366            unset($filter['name']);
367        }
368
369        if (isset($filter['user'])) {
370            $result .= ')(samAccountName=*' . $adldapUtils->ldapSlashes($filter['user']) . '*';
371            unset($filter['user']);
372        }
373
374        if (isset($filter['mail'])) {
375            $result .= ')(mail=*' . $adldapUtils->ldapSlashes($filter['mail']) . '*';
376            unset($filter['mail']);
377        }
378        return $result;
379    }
380
381    /**
382     * Return a count of the number of user which meet $filter criteria
383     *
384     * @param array $filter  $filter array of field/pattern pairs, empty array for no filter
385     * @return int number of users
386     */
387    public function getUserCount($filter = array())
388    {
389        $adldap = $this->initAdLdap(null);
390        if (!$adldap) {
391            Logger::debug("authad/auth.php getUserCount(): _adldap not set.");
392            return -1;
393        }
394        if ($filter == array()) {
395            $result = $adldap->user()->all();
396        } else {
397            $searchString = $this->constructSearchString($filter);
398            $result = $adldap->user()->all(false, $searchString);
399            if (isset($filter['grps'])) {
400                $this->users = array_fill_keys($result, false);
401                /** @var admin_plugin_usermanager $usermanager */
402                $usermanager = plugin_load("admin", "usermanager", false);
403                $usermanager->setLastdisabled(true);
404                if (!isset($this->grpsusers[$this->filterToString($filter)])) {
405                    $this->fillGroupUserArray($filter, $usermanager->getStart() + 3*$usermanager->getPagesize());
406                } elseif (count($this->grpsusers[$this->filterToString($filter)]) <
407                    $usermanager->getStart() + 3*$usermanager->getPagesize()
408                ) {
409                    $this->fillGroupUserArray(
410                        $filter,
411                        $usermanager->getStart() +
412                        3*$usermanager->getPagesize() -
413                        count($this->grpsusers[$this->filterToString($filter)])
414                    );
415                }
416                $result = $this->grpsusers[$this->filterToString($filter)];
417            } else {
418                /** @var admin_plugin_usermanager $usermanager */
419                $usermanager = plugin_load("admin", "usermanager", false);
420                $usermanager->setLastdisabled(false);
421            }
422        }
423
424        if (!$result) {
425            return 0;
426        }
427        return count($result);
428    }
429
430    /**
431     *
432     * create a unique string for each filter used with a group
433     *
434     * @param array $filter
435     * @return string
436     */
437    protected function filterToString($filter)
438    {
439        $result = '';
440        if (isset($filter['user'])) {
441            $result .= 'user-' . $filter['user'];
442        }
443        if (isset($filter['name'])) {
444            $result .= 'name-' . $filter['name'];
445        }
446        if (isset($filter['mail'])) {
447            $result .= 'mail-' . $filter['mail'];
448        }
449        if (isset($filter['grps'])) {
450            $result .= 'grps-' . $filter['grps'];
451        }
452        return $result;
453    }
454
455    /**
456     * Create an array of $numberOfAdds users passing a certain $filter, including belonging
457     * to a certain group and save them to a object-wide array. If the array
458     * already exists try to add $numberOfAdds further users to it.
459     *
460     * @param array $filter
461     * @param int $numberOfAdds additional number of users requested
462     * @return int number of Users actually add to Array
463     */
464    protected function fillGroupUserArray($filter, $numberOfAdds)
465    {
466        if (isset($this->grpsusers[$this->filterToString($filter)])) {
467            $actualstart = count($this->grpsusers[$this->filterToString($filter)]);
468        } else {
469            $this->grpsusers[$this->filterToString($filter)] = [];
470            $actualstart = 0;
471        }
472
473        $i=0;
474        $count = 0;
475        $this->constructPattern($filter);
476        foreach ($this->users as $user => &$info) {
477            if ($i++ < $actualstart) {
478                continue;
479            }
480            if ($info === false) {
481                $info = $this->getUserData($user);
482            }
483            if ($this->filter($user, $info)) {
484                $this->grpsusers[$this->filterToString($filter)][$user] = $info;
485                if (($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
486            }
487        }
488        return $count;
489    }
490
491    /**
492     * Bulk retrieval of user data
493     *
494     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
495     *
496     * @param   int $start index of first user to be returned
497     * @param   int $limit max number of users to be returned
498     * @param   array $filter array of field/pattern pairs, null for no filter
499     * @return array userinfo (refer getUserData for internal userinfo details)
500     */
501    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
502    {
503        $adldap = $this->initAdLdap(null);
504        if (!$adldap) return array();
505
506        //if (!$this->users) {
507            //get info for given user
508            $result = $adldap->user()->all(false, $this->constructSearchString($filter));
509            if (!$result) return array();
510            $this->users = array_fill_keys($result, false);
511        //}
512
513        $i     = 0;
514        $count = 0;
515        $result = array();
516
517        if (!isset($filter['grps'])) {
518            /** @var admin_plugin_usermanager $usermanager */
519            $usermanager = plugin_load("admin", "usermanager", false);
520            $usermanager->setLastdisabled(false);
521            $this->constructPattern($filter);
522            foreach ($this->users as $user => &$info) {
523                if ($i++ < $start) {
524                    continue;
525                }
526                if ($info === false) {
527                    $info = $this->getUserData($user);
528                }
529                $result[$user] = $info;
530                if (($limit > 0) && (++$count >= $limit)) break;
531            }
532        } else {
533            /** @var admin_plugin_usermanager $usermanager */
534            $usermanager = plugin_load("admin", "usermanager", false);
535            $usermanager->setLastdisabled(true);
536            if (!isset($this->grpsusers[$this->filterToString($filter)]) ||
537                count($this->grpsusers[$this->filterToString($filter)]) < ($start+$limit)
538            ) {
539                if(!isset($this->grpsusers[$this->filterToString($filter)])) {
540                    $this->grpsusers[$this->filterToString($filter)] = [];
541                }
542
543                $this->fillGroupUserArray(
544                    $filter,
545                    $start+$limit - count($this->grpsusers[$this->filterToString($filter)]) +1
546                );
547            }
548            if (!$this->grpsusers[$this->filterToString($filter)]) return array();
549            foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) {
550                if ($i++ < $start) {
551                    continue;
552                }
553                $result[$user] = $info;
554                if (($limit > 0) && (++$count >= $limit)) break;
555            }
556        }
557        return $result;
558    }
559
560    /**
561     * Modify user data
562     *
563     * @param   string $user      nick of the user to be changed
564     * @param   array  $changes   array of field/value pairs to be changed
565     * @return  bool
566     */
567    public function modifyUser($user, $changes)
568    {
569        $return = true;
570        $adldap = $this->initAdLdap($this->getUserDomain($user));
571        if (!$adldap) {
572            msg($this->getLang('connectfail'), -1);
573            return false;
574        }
575
576        // password changing
577        if (isset($changes['pass'])) {
578            try {
579                $return = $adldap->user()->password($this->getUserName($user), $changes['pass']);
580            } catch (adLDAPException $e) {
581                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
582                $return = false;
583            }
584            if (!$return) msg($this->getLang('passchangefail'), -1);
585        }
586
587        // changing user data
588        $adchanges = array();
589        if (isset($changes['name'])) {
590            // get first and last name
591            $parts                     = explode(' ', $changes['name']);
592            $adchanges['surname']      = array_pop($parts);
593            $adchanges['firstname']    = join(' ', $parts);
594            $adchanges['display_name'] = $changes['name'];
595        }
596        if (isset($changes['mail'])) {
597            $adchanges['email'] = $changes['mail'];
598        }
599        if (count($adchanges)) {
600            try {
601                $return = $return & $adldap->user()->modify($this->getUserName($user), $adchanges);
602            } catch (adLDAPException $e) {
603                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
604                $return = false;
605            }
606            if (!$return) msg($this->getLang('userchangefail'), -1);
607        }
608
609        return $return;
610    }
611
612    /**
613     * Initialize the AdLDAP library and connect to the server
614     *
615     * When you pass null as domain, it will reuse any existing domain.
616     * Eg. the one of the logged in user. It falls back to the default
617     * domain if no current one is available.
618     *
619     * @param string|null $domain The AD domain to use
620     * @return adLDAP|bool true if a connection was established
621     */
622    protected function initAdLdap($domain)
623    {
624        if (is_null($domain) && is_array($this->opts)) {
625            $domain = $this->opts['domain'];
626        }
627
628        $this->opts = $this->loadServerConfig((string) $domain);
629        if (isset($this->adldap[$domain])) return $this->adldap[$domain];
630
631        // connect
632        try {
633            $this->adldap[$domain] = new adLDAP($this->opts);
634            return $this->adldap[$domain];
635        } catch (Exception $e) {
636            if ($this->conf['debug']) {
637                msg('AD Auth: '.$e->getMessage(), -1);
638            }
639            $this->success         = false;
640            $this->adldap[$domain] = null;
641        }
642        return false;
643    }
644
645    /**
646     * Get the domain part from a user
647     *
648     * @param string $user
649     * @return string
650     */
651    public function getUserDomain($user)
652    {
653        list(, $domain) = array_pad(explode('@', $user, 2), 2, '');
654        return $domain;
655    }
656
657    /**
658     * Get the user part from a user
659     *
660     * When an account suffix is set, we strip the domain part from the user
661     *
662     * @param string $user
663     * @return string
664     */
665    public function getUserName($user)
666    {
667        if ($this->conf['account_suffix'] !== '') {
668            list($user) = explode('@', $user, 2);
669        }
670        return $user;
671    }
672
673    /**
674     * Fetch the configuration for the given AD domain
675     *
676     * @param string $domain current AD domain
677     * @return array
678     */
679    protected function loadServerConfig($domain)
680    {
681        // prepare adLDAP standard configuration
682        $opts = $this->conf;
683
684        $opts['domain'] = $domain;
685
686        // add possible domain specific configuration
687        if ($domain && is_array($this->conf[$domain])) foreach ($this->conf[$domain] as $key => $val) {
688            $opts[$key] = $val;
689        }
690
691        // handle multiple AD servers
692        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
693        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
694        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
695
696        // compatibility with old option name
697        if (empty($opts['admin_username']) && !empty($opts['ad_username'])) {
698            $opts['admin_username'] = $opts['ad_username'];
699        }
700        if (empty($opts['admin_password']) && !empty($opts['ad_password'])) {
701            $opts['admin_password'] = $opts['ad_password'];
702        }
703        $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate
704
705        // we can change the password if SSL is set
706        if ($opts['update_pass'] && ($opts['use_ssl'] || $opts['use_tls'])) {
707            $this->cando['modPass'] = true;
708        } else {
709            $this->cando['modPass'] = false;
710        }
711
712        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
713        if (empty($opts['admin_username'])) $opts['admin_username'] = null;
714        if (empty($opts['admin_password'])) $opts['admin_password'] = null;
715
716        // user listing needs admin priviledges
717        if (!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
718            $this->cando['getUsers'] = true;
719        } else {
720            $this->cando['getUsers'] = false;
721        }
722
723        return $opts;
724    }
725
726    /**
727     * Returns a list of configured domains
728     *
729     * The default domain has an empty string as key
730     *
731     * @return array associative array(key => domain)
732     */
733    public function getConfiguredDomains()
734    {
735        $domains = array();
736        if (empty($this->conf['account_suffix'])) return $domains; // not configured yet
737
738        // add default domain, using the name from account suffix
739        $domains[''] = ltrim($this->conf['account_suffix'], '@');
740
741        // find additional domains
742        foreach ($this->conf as $key => $val) {
743            if (is_array($val) && isset($val['account_suffix'])) {
744                $domains[$key] = ltrim($val['account_suffix'], '@');
745            }
746        }
747        Sort::ksort($domains);
748
749        return $domains;
750    }
751
752    /**
753     * Check provided user and userinfo for matching patterns
754     *
755     * The patterns are set up with $this->_constructPattern()
756     *
757     * @author Chris Smith <chris@jalakai.co.uk>
758     *
759     * @param string $user
760     * @param array  $info
761     * @return bool
762     */
763    protected function filter($user, $info)
764    {
765        foreach ($this->pattern as $item => $pattern) {
766            if ($item == 'user') {
767                if (!preg_match($pattern, $user)) return false;
768            } elseif ($item == 'grps') {
769                if (!count(preg_grep($pattern, $info['grps']))) return false;
770            } else {
771                if (!preg_match($pattern, $info[$item])) return false;
772            }
773        }
774        return true;
775    }
776
777    /**
778     * Create a pattern for $this->_filter()
779     *
780     * @author Chris Smith <chris@jalakai.co.uk>
781     *
782     * @param array $filter
783     */
784    protected function constructPattern($filter)
785    {
786        $this->pattern = array();
787        foreach ($filter as $item => $pattern) {
788            $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
789        }
790    }
791}
792