xref: /dokuwiki/lib/plugins/authad/auth.php (revision 0489c64b7de1b71fdd124114dd18525156f26327)
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 $actualstart = 0;
69
70    protected $grpsusers = array();
71
72    /**
73     * Constructor
74     */
75    public function __construct()
76    {
77        global $INPUT;
78        parent::__construct();
79
80        require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
81        require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php');
82
83        // we load the config early to modify it a bit here
84        $this->loadConfig();
85
86        // additional information fields
87        if (isset($this->conf['additional'])) {
88            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
89            $this->conf['additional'] = explode(',', $this->conf['additional']);
90        } else $this->conf['additional'] = array();
91
92        // ldap extension is needed
93        if (!function_exists('ldap_connect')) {
94            if ($this->conf['debug'])
95                msg("AD Auth: PHP LDAP extension not found.", -1);
96            $this->success = false;
97            return;
98        }
99
100        // Prepare SSO
101        if (!empty($_SERVER['REMOTE_USER'])) {
102            // make sure the right encoding is used
103            if ($this->getConf('sso_charset')) {
104                $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
105            } elseif (!\dokuwiki\Utf8\Clean::isUtf8($_SERVER['REMOTE_USER'])) {
106                $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
107            }
108
109            // trust the incoming user
110            if ($this->conf['sso']) {
111                $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
112
113                // we need to simulate a login
114                if (empty($_COOKIE[DOKU_COOKIE])) {
115                    $INPUT->set('u', $_SERVER['REMOTE_USER']);
116                    $INPUT->set('p', 'sso_only');
117                }
118            }
119        }
120
121        // other can do's are changed in $this->_loadServerConfig() base on domain setup
122        $this->cando['modName'] = (bool)$this->conf['update_name'];
123        $this->cando['modMail'] = (bool)$this->conf['update_mail'];
124        $this->cando['getUserCount'] = true;
125    }
126
127    /**
128     * Load domain config on capability check
129     *
130     * @param string $cap
131     * @return bool
132     */
133    public function canDo($cap)
134    {
135        //capabilities depend on config, which may change depending on domain
136        $domain = $this->getUserDomain($_SERVER['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        if ($_SERVER['REMOTE_USER'] &&
156            $_SERVER['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        $adldap = $this->initAdLdap($this->getUserDomain($user));
202        if (!$adldap) return array();
203
204        if ($user == '') return array();
205
206        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
207
208        // add additional fields to read
209        $fields = array_merge($fields, $this->conf['additional']);
210        $fields = array_unique($fields);
211        $fields = array_filter($fields);
212
213        //get info for given user
214        $result = $adldap->user()->info($this->getUserName($user), $fields);
215        if ($result == false) {
216            return array();
217        }
218
219        //general user info
220        $info = array();
221        $info['name'] = $result[0]['displayname'][0];
222        $info['mail'] = $result[0]['mail'][0];
223        $info['uid']  = $result[0]['samaccountname'][0];
224        $info['dn']   = $result[0]['dn'];
225        //last password set (Windows counts from January 1st 1601)
226        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
227        //will it expire?
228        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
229
230        // additional information
231        foreach ($this->conf['additional'] as $field) {
232            if (isset($result[0][strtolower($field)])) {
233                $info[$field] = $result[0][strtolower($field)][0];
234            }
235        }
236
237        // handle ActiveDirectory memberOf
238        $info['grps'] = $adldap->user()->groups($this->getUserName($user), (bool) $this->opts['recursive_groups']);
239
240        if (is_array($info['grps'])) {
241            foreach ($info['grps'] as $ndx => $group) {
242                $info['grps'][$ndx] = $this->cleanGroup($group);
243            }
244        }
245
246        // always add the default group to the list of groups
247        if (!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
248            $info['grps'][] = $conf['defaultgroup'];
249        }
250
251        // add the user's domain to the groups
252        $domain = $this->getUserDomain($user);
253        if ($domain && !in_array("domain-$domain", (array) $info['grps'])) {
254            $info['grps'][] = $this->cleanGroup("domain-$domain");
255        }
256
257        // check expiry time
258        if ($info['expires'] && $this->conf['expirywarn']) {
259            try {
260                $expiry = $adldap->user()->passwordExpiry($user);
261                if (is_array($expiry)) {
262                    $info['expiresat'] = $expiry['expiryts'];
263                    $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
264
265                    // if this is the current user, warn him (once per request only)
266                    if (($_SERVER['REMOTE_USER'] == $user) &&
267                        ($info['expiresin'] <= $this->conf['expirywarn']) &&
268                        !$this->msgshown
269                    ) {
270                        $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']);
271                        if ($this->canDo('modPass')) {
272                            $url = wl($ID, array('do'=> 'profile'));
273                            $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
274                        }
275                        msg($msg);
276                        $this->msgshown = true;
277                    }
278                }
279            } catch (adLDAPException $e) {
280                // ignore. should usually not happen
281            }
282        }
283
284        return $info;
285    }
286
287    /**
288     * Make AD group names usable by DokuWiki.
289     *
290     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
291     *
292     * @author  James Van Lommel (jamesvl@gmail.com)
293     * @param string $group
294     * @return string
295     */
296    public function cleanGroup($group)
297    {
298        $group = str_replace('\\', '', $group);
299        $group = str_replace('#', '', $group);
300        $group = preg_replace('[\s]', '_', $group);
301        $group = \dokuwiki\Utf8\PhpString::strtolower(trim($group));
302        return $group;
303    }
304
305    /**
306     * Sanitize user names
307     *
308     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
309     *
310     * @author Andreas Gohr <gohr@cosmocode.de>
311     * @param string $user
312     * @return string
313     */
314    public function cleanUser($user)
315    {
316        $domain = '';
317
318        // get NTLM or Kerberos domain part
319        list($dom, $user) = explode('\\', $user, 2);
320        if (!$user) $user = $dom;
321        if ($dom) $domain = $dom;
322        list($user, $dom) = explode('@', $user, 2);
323        if ($dom) $domain = $dom;
324
325        // clean up both
326        $domain = \dokuwiki\Utf8\PhpString::strtolower(trim($domain));
327        $user   = \dokuwiki\Utf8\PhpString::strtolower(trim($user));
328
329        // is this a known, valid domain or do we work without account suffix? if not discard
330        if (!is_array($this->conf[$domain]) && $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            dbglog("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        $this->grpsusers[$this->filterToString($filter)];
465        $i = 0;
466        $count = 0;
467        $this->constructPattern($filter);
468        foreach ($this->users as $user => &$info) {
469            if ($i++ < $this->actualstart) {
470                continue;
471            }
472            if ($info === false) {
473                $info = $this->getUserData($user);
474            }
475            if ($this->filter($user, $info)) {
476                $this->grpsusers[$this->filterToString($filter)][$user] = $info;
477                if (($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
478            }
479        }
480        $this->actualstart = $i;
481        return $count;
482    }
483
484    /**
485     * Bulk retrieval of user data
486     *
487     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
488     *
489     * @param   int $start index of first user to be returned
490     * @param   int $limit max number of users to be returned
491     * @param   array $filter array of field/pattern pairs, null for no filter
492     * @return array userinfo (refer getUserData for internal userinfo details)
493     */
494    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
495    {
496        $adldap = $this->initAdLdap(null);
497        if (!$adldap) return array();
498
499        if (!$this->users) {
500            //get info for given user
501            $result = $adldap->user()->all(false, $this->constructSearchString($filter));
502            if (!$result) return array();
503            $this->users = array_fill_keys($result, false);
504        }
505
506        $i     = 0;
507        $count = 0;
508        $result = array();
509
510        if (!isset($filter['grps'])) {
511            /** @var admin_plugin_usermanager $usermanager */
512            $usermanager = plugin_load("admin", "usermanager", false);
513            $usermanager->setLastdisabled(false);
514            $this->constructPattern($filter);
515            foreach ($this->users as $user => &$info) {
516                if ($i++ < $start) {
517                    continue;
518                }
519                if ($info === false) {
520                    $info = $this->getUserData($user);
521                }
522                $result[$user] = $info;
523                if (($limit > 0) && (++$count >= $limit)) break;
524            }
525        } else {
526            /** @var admin_plugin_usermanager $usermanager */
527            $usermanager = plugin_load("admin", "usermanager", false);
528            $usermanager->setLastdisabled(true);
529            if (!isset($this->grpsusers[$this->filterToString($filter)]) ||
530                count($this->grpsusers[$this->filterToString($filter)]) < ($start+$limit)
531            ) {
532                $this->fillGroupUserArray(
533                    $filter,
534                    $start+$limit - count($this->grpsusers[$this->filterToString($filter)]) +1
535                );
536            }
537            if (!$this->grpsusers[$this->filterToString($filter)]) return array();
538            foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) {
539                if ($i++ < $start) {
540                    continue;
541                }
542                $result[$user] = $info;
543                if (($limit > 0) && (++$count >= $limit)) break;
544            }
545        }
546        return $result;
547    }
548
549    /**
550     * Modify user data
551     *
552     * @param   string $user      nick of the user to be changed
553     * @param   array  $changes   array of field/value pairs to be changed
554     * @return  bool
555     */
556    public function modifyUser($user, $changes)
557    {
558        $return = true;
559        $adldap = $this->initAdLdap($this->getUserDomain($user));
560        if (!$adldap) {
561            msg($this->getLang('connectfail'), -1);
562            return false;
563        }
564
565        // password changing
566        if (isset($changes['pass'])) {
567            try {
568                $return = $adldap->user()->password($this->getUserName($user), $changes['pass']);
569            } catch (adLDAPException $e) {
570                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
571                $return = false;
572            }
573            if (!$return) msg($this->getLang('passchangefail'), -1);
574        }
575
576        // changing user data
577        $adchanges = array();
578        if (isset($changes['name'])) {
579            // get first and last name
580            $parts                     = explode(' ', $changes['name']);
581            $adchanges['surname']      = array_pop($parts);
582            $adchanges['firstname']    = join(' ', $parts);
583            $adchanges['display_name'] = $changes['name'];
584        }
585        if (isset($changes['mail'])) {
586            $adchanges['email'] = $changes['mail'];
587        }
588        if (count($adchanges)) {
589            try {
590                $return = $return & $adldap->user()->modify($this->getUserName($user), $adchanges);
591            } catch (adLDAPException $e) {
592                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
593                $return = false;
594            }
595            if (!$return) msg($this->getLang('userchangefail'), -1);
596        }
597
598        return $return;
599    }
600
601    /**
602     * Initialize the AdLDAP library and connect to the server
603     *
604     * When you pass null as domain, it will reuse any existing domain.
605     * Eg. the one of the logged in user. It falls back to the default
606     * domain if no current one is available.
607     *
608     * @param string|null $domain The AD domain to use
609     * @return adLDAP|bool true if a connection was established
610     */
611    protected function initAdLdap($domain)
612    {
613        if (is_null($domain) && is_array($this->opts)) {
614            $domain = $this->opts['domain'];
615        }
616
617        $this->opts = $this->loadServerConfig((string) $domain);
618        if (isset($this->adldap[$domain])) return $this->adldap[$domain];
619
620        // connect
621        try {
622            $this->adldap[$domain] = new adLDAP($this->opts);
623            return $this->adldap[$domain];
624        } catch (Exception $e) {
625            if ($this->conf['debug']) {
626                msg('AD Auth: '.$e->getMessage(), -1);
627            }
628            $this->success         = false;
629            $this->adldap[$domain] = null;
630        }
631        return false;
632    }
633
634    /**
635     * Get the domain part from a user
636     *
637     * @param string $user
638     * @return string
639     */
640    public function getUserDomain($user)
641    {
642        list(, $domain) = explode('@', $user, 2);
643        return $domain;
644    }
645
646    /**
647     * Get the user part from a user
648     *
649     * When an account suffix is set, we strip the domain part from the user
650     *
651     * @param string $user
652     * @return string
653     */
654    public function getUserName($user)
655    {
656        if ($this->conf['account_suffix'] !== '') {
657            list($user) = explode('@', $user, 2);
658        }
659        return $user;
660    }
661
662    /**
663     * Fetch the configuration for the given AD domain
664     *
665     * @param string $domain current AD domain
666     * @return array
667     */
668    protected function loadServerConfig($domain)
669    {
670        // prepare adLDAP standard configuration
671        $opts = $this->conf;
672
673        $opts['domain'] = $domain;
674
675        // add possible domain specific configuration
676        if ($domain && is_array($this->conf[$domain])) foreach ($this->conf[$domain] as $key => $val) {
677            $opts[$key] = $val;
678        }
679
680        // handle multiple AD servers
681        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
682        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
683        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
684
685        // compatibility with old option name
686        if (empty($opts['admin_username']) && !empty($opts['ad_username'])) {
687            $opts['admin_username'] = $opts['ad_username'];
688        }
689        if (empty($opts['admin_password']) && !empty($opts['ad_password'])) {
690            $opts['admin_password'] = $opts['ad_password'];
691        }
692        $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate
693
694        // we can change the password if SSL is set
695        if ($opts['use_ssl'] || $opts['use_tls']) {
696            $this->cando['modPass'] = true;
697        } else {
698            $this->cando['modPass'] = false;
699        }
700
701        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
702        if (empty($opts['admin_username'])) $opts['admin_username'] = null;
703        if (empty($opts['admin_password'])) $opts['admin_password'] = null;
704
705        // user listing needs admin priviledges
706        if (!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
707            $this->cando['getUsers'] = true;
708        } else {
709            $this->cando['getUsers'] = false;
710        }
711
712        return $opts;
713    }
714
715    /**
716     * Returns a list of configured domains
717     *
718     * The default domain has an empty string as key
719     *
720     * @return array associative array(key => domain)
721     */
722    public function getConfiguredDomains()
723    {
724        $domains = array();
725        if (empty($this->conf['account_suffix'])) return $domains; // not configured yet
726
727        // add default domain, using the name from account suffix
728        $domains[''] = ltrim($this->conf['account_suffix'], '@');
729
730        // find additional domains
731        foreach ($this->conf as $key => $val) {
732            if (is_array($val) && isset($val['account_suffix'])) {
733                $domains[$key] = ltrim($val['account_suffix'], '@');
734            }
735        }
736        Sort::ksort($domains);
737
738        return $domains;
739    }
740
741    /**
742     * Check provided user and userinfo for matching patterns
743     *
744     * The patterns are set up with $this->_constructPattern()
745     *
746     * @author Chris Smith <chris@jalakai.co.uk>
747     *
748     * @param string $user
749     * @param array  $info
750     * @return bool
751     */
752    protected function filter($user, $info)
753    {
754        foreach ($this->pattern as $item => $pattern) {
755            if ($item == 'user') {
756                if (!preg_match($pattern, $user)) return false;
757            } elseif ($item == 'grps') {
758                if (!count(preg_grep($pattern, $info['grps']))) return false;
759            } else {
760                if (!preg_match($pattern, $info[$item])) return false;
761            }
762        }
763        return true;
764    }
765
766    /**
767     * Create a pattern for $this->_filter()
768     *
769     * @author Chris Smith <chris@jalakai.co.uk>
770     *
771     * @param array $filter
772     */
773    protected function constructPattern($filter)
774    {
775        $this->pattern = array();
776        foreach ($filter as $item => $pattern) {
777            $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
778        }
779    }
780}
781