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