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