summaryrefslogtreecommitdiff
path: root/platform/www/lib/plugins/authad/auth.php
blob: 27a6b229e607d796a938d091cec3ebed1441cbf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
<?php

/**
 * Active Directory authentication backend for DokuWiki
 *
 * This makes authentication with a Active Directory server much easier
 * than when using the normal LDAP backend by utilizing the adLDAP library
 *
 * Usage:
 *   Set DokuWiki's local.protected.php auth setting to read
 *
 *   $conf['authtype']       = 'authad';
 *
 *   $conf['plugin']['authad']['account_suffix']     = '@my.domain.org';
 *   $conf['plugin']['authad']['base_dn']            = 'DC=my,DC=domain,DC=org';
 *   $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
 *
 *   //optional:
 *   $conf['plugin']['authad']['sso']                = 1;
 *   $conf['plugin']['authad']['admin_username']     = 'root';
 *   $conf['plugin']['authad']['admin_password']     = 'pass';
 *   $conf['plugin']['authad']['real_primarygroup']  = 1;
 *   $conf['plugin']['authad']['use_ssl']            = 1;
 *   $conf['plugin']['authad']['use_tls']            = 1;
 *   $conf['plugin']['authad']['debug']              = 1;
 *   // warn user about expiring password this many days in advance:
 *   $conf['plugin']['authad']['expirywarn']         = 5;
 *
 *   // get additional information to the userinfo array
 *   // add a list of comma separated ldap contact fields.
 *   $conf['plugin']['authad']['additional'] = 'field1,field2';
 *
 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author  James Van Lommel <jamesvl@gmail.com>
 * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
 * @author  Andreas Gohr <andi@splitbrain.org>
 * @author  Jan Schumann <js@schumann-it.com>
 */
class auth_plugin_authad extends DokuWiki_Auth_Plugin
{

    /**
     * @var array hold connection data for a specific AD domain
     */
    protected $opts = array();

    /**
     * @var array open connections for each AD domain, as adLDAP objects
     */
    protected $adldap = array();

    /**
     * @var bool message state
     */
    protected $msgshown = false;

    /**
     * @var array user listing cache
     */
    protected $users = array();

    /**
     * @var array filter patterns for listing users
     */
    protected $pattern = array();

    protected $grpsusers = array();

    /**
     * Constructor
     */
    public function __construct()
    {
        global $INPUT;
        parent::__construct();

        require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
        require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php');

        // we load the config early to modify it a bit here
        $this->loadConfig();

        // additional information fields
        if (isset($this->conf['additional'])) {
            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
            $this->conf['additional'] = explode(',', $this->conf['additional']);
        } else $this->conf['additional'] = array();

        // ldap extension is needed
        if (!function_exists('ldap_connect')) {
            if ($this->conf['debug'])
                msg("AD Auth: PHP LDAP extension not found.", -1);
            $this->success = false;
            return;
        }

        // Prepare SSO
        if (!empty($_SERVER['REMOTE_USER'])) {
            // make sure the right encoding is used
            if ($this->getConf('sso_charset')) {
                $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
            } elseif (!\dokuwiki\Utf8\Clean::isUtf8($_SERVER['REMOTE_USER'])) {
                $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
            }

            // trust the incoming user
            if ($this->conf['sso']) {
                $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);

                // we need to simulate a login
                if (empty($_COOKIE[DOKU_COOKIE])) {
                    $INPUT->set('u', $_SERVER['REMOTE_USER']);
                    $INPUT->set('p', 'sso_only');
                }
            }
        }

        // other can do's are changed in $this->_loadServerConfig() base on domain setup
        $this->cando['modName'] = (bool)$this->conf['update_name'];
        $this->cando['modMail'] = (bool)$this->conf['update_mail'];
        $this->cando['getUserCount'] = true;
    }

    /**
     * Load domain config on capability check
     *
     * @param string $cap
     * @return bool
     */
    public function canDo($cap)
    {
        //capabilities depend on config, which may change depending on domain
        $domain = $this->getUserDomain($_SERVER['REMOTE_USER']);
        $this->loadServerConfig($domain);
        return parent::canDo($cap);
    }

    /**
     * Check user+password [required auth function]
     *
     * Checks if the given user exists and the given
     * plaintext password is correct by trying to bind
     * to the LDAP server
     *
     * @author  James Van Lommel <james@nosq.com>
     * @param string $user
     * @param string $pass
     * @return  bool
     */
    public function checkPass($user, $pass)
    {
        if ($_SERVER['REMOTE_USER'] &&
            $_SERVER['REMOTE_USER'] == $user &&
            $this->conf['sso']
        ) return true;

        $adldap = $this->initAdLdap($this->getUserDomain($user));
        if (!$adldap) return false;

        try {
            return $adldap->authenticate($this->getUserName($user), $pass);
        } catch (adLDAPException $e) {
            // shouldn't really happen
            return false;
        }
    }

    /**
     * Return user info [required auth function]
     *
     * Returns info about the given user needs to contain
     * at least these fields:
     *
     * name    string  full name of the user
     * mail    string  email address of the user
     * grps    array   list of groups the user is in
     *
     * This AD specific function returns the following
     * addional fields:
     *
     * dn         string    distinguished name (DN)
     * uid        string    samaccountname
     * lastpwd    int       timestamp of the date when the password was set
     * expires    true      if the password expires
     * expiresin  int       seconds until the password expires
     * any fields specified in the 'additional' config option
     *
     * @author  James Van Lommel <james@nosq.com>
     * @param string $user
     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
     * @return array
     */
    public function getUserData($user, $requireGroups = true)
    {
        global $conf;
        global $lang;
        global $ID;
        $adldap = $this->initAdLdap($this->getUserDomain($user));
        if (!$adldap) return array();

        if ($user == '') return array();

        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');

        // add additional fields to read
        $fields = array_merge($fields, $this->conf['additional']);
        $fields = array_unique($fields);
        $fields = array_filter($fields);

        //get info for given user
        $result = $adldap->user()->info($this->getUserName($user), $fields);
        if ($result == false) {
            return array();
        }

        //general user info
        $info = array();
        $info['name'] = $result[0]['displayname'][0];
        $info['mail'] = $result[0]['mail'][0];
        $info['uid']  = $result[0]['samaccountname'][0];
        $info['dn']   = $result[0]['dn'];
        //last password set (Windows counts from January 1st 1601)
        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
        //will it expire?
        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD

        // additional information
        foreach ($this->conf['additional'] as $field) {
            if (isset($result[0][strtolower($field)])) {
                $info[$field] = $result[0][strtolower($field)][0];
            }
        }

        // handle ActiveDirectory memberOf
        $info['grps'] = $adldap->user()->groups($this->getUserName($user), (bool) $this->opts['recursive_groups']);

        if (is_array($info['grps'])) {
            foreach ($info['grps'] as $ndx => $group) {
                $info['grps'][$ndx] = $this->cleanGroup($group);
            }
        }

        // always add the default group to the list of groups
        if (!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
            $info['grps'][] = $conf['defaultgroup'];
        }

        // add the user's domain to the groups
        $domain = $this->getUserDomain($user);
        if ($domain && !in_array("domain-$domain", (array) $info['grps'])) {
            $info['grps'][] = $this->cleanGroup("domain-$domain");
        }

        // check expiry time
        if ($info['expires'] && $this->conf['expirywarn']) {
            try {
                $expiry = $adldap->user()->passwordExpiry($user);
                if (is_array($expiry)) {
                    $info['expiresat'] = $expiry['expiryts'];
                    $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));

                    // if this is the current user, warn him (once per request only)
                    if (($_SERVER['REMOTE_USER'] == $user) &&
                        ($info['expiresin'] <= $this->conf['expirywarn']) &&
                        !$this->msgshown
                    ) {
                        $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']);
                        if ($this->canDo('modPass')) {
                            $url = wl($ID, array('do'=> 'profile'));
                            $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
                        }
                        msg($msg);
                        $this->msgshown = true;
                    }
                }
            } catch (adLDAPException $e) {
                // ignore. should usually not happen
            }
        }

        return $info;
    }

    /**
     * Make AD group names usable by DokuWiki.
     *
     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
     *
     * @author  James Van Lommel (jamesvl@gmail.com)
     * @param string $group
     * @return string
     */
    public function cleanGroup($group)
    {
        $group = str_replace('\\', '', $group);
        $group = str_replace('#', '', $group);
        $group = preg_replace('[\s]', '_', $group);
        $group = \dokuwiki\Utf8\PhpString::strtolower(trim($group));
        return $group;
    }

    /**
     * Sanitize user names
     *
     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
     *
     * @author Andreas Gohr <gohr@cosmocode.de>
     * @param string $user
     * @return string
     */
    public function cleanUser($user)
    {
        $domain = '';

        // get NTLM or Kerberos domain part
        list($dom, $user) = explode('\\', $user, 2);
        if (!$user) $user = $dom;
        if ($dom) $domain = $dom;
        list($user, $dom) = explode('@', $user, 2);
        if ($dom) $domain = $dom;

        // clean up both
        $domain = \dokuwiki\Utf8\PhpString::strtolower(trim($domain));
        $user   = \dokuwiki\Utf8\PhpString::strtolower(trim($user));

        // is this a known, valid domain or do we work without account suffix? if not discard
        if (!is_array($this->conf[$domain]) && $this->conf['account_suffix'] !== '') {
            $domain = '';
        }

        // reattach domain
        if ($domain) $user = "$user@$domain";
        return $user;
    }

    /**
     * Most values in LDAP are case-insensitive
     *
     * @return bool
     */
    public function isCaseSensitive()
    {
        return false;
    }

    /**
     * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
     *
     * @param array $filter
     * @return string
     */
    protected function constructSearchString($filter)
    {
        if (!$filter) {
            return '*';
        }
        $adldapUtils = new adLDAPUtils($this->initAdLdap(null));
        $result = '*';
        if (isset($filter['name'])) {
            $result .= ')(displayname=*' . $adldapUtils->ldapSlashes($filter['name']) . '*';
            unset($filter['name']);
        }

        if (isset($filter['user'])) {
            $result .= ')(samAccountName=*' . $adldapUtils->ldapSlashes($filter['user']) . '*';
            unset($filter['user']);
        }

        if (isset($filter['mail'])) {
            $result .= ')(mail=*' . $adldapUtils->ldapSlashes($filter['mail']) . '*';
            unset($filter['mail']);
        }
        return $result;
    }

    /**
     * Return a count of the number of user which meet $filter criteria
     *
     * @param array $filter  $filter array of field/pattern pairs, empty array for no filter
     * @return int number of users
     */
    public function getUserCount($filter = array())
    {
        $adldap = $this->initAdLdap(null);
        if (!$adldap) {
            dbglog("authad/auth.php getUserCount(): _adldap not set.");
            return -1;
        }
        if ($filter == array()) {
            $result = $adldap->user()->all();
        } else {
            $searchString = $this->constructSearchString($filter);
            $result = $adldap->user()->all(false, $searchString);
            if (isset($filter['grps'])) {
                $this->users = array_fill_keys($result, false);
                /** @var admin_plugin_usermanager $usermanager */
                $usermanager = plugin_load("admin", "usermanager", false);
                $usermanager->setLastdisabled(true);
                if (!isset($this->grpsusers[$this->filterToString($filter)])) {
                    $this->fillGroupUserArray($filter, $usermanager->getStart() + 3*$usermanager->getPagesize());
                } elseif (count($this->grpsusers[$this->filterToString($filter)]) <
                    $usermanager->getStart() + 3*$usermanager->getPagesize()
                ) {
                    $this->fillGroupUserArray(
                        $filter,
                        $usermanager->getStart() +
                        3*$usermanager->getPagesize() -
                        count($this->grpsusers[$this->filterToString($filter)])
                    );
                }
                $result = $this->grpsusers[$this->filterToString($filter)];
            } else {
                /** @var admin_plugin_usermanager $usermanager */
                $usermanager = plugin_load("admin", "usermanager", false);
                $usermanager->setLastdisabled(false);
            }
        }

        if (!$result) {
            return 0;
        }
        return count($result);
    }

    /**
     *
     * create a unique string for each filter used with a group
     *
     * @param array $filter
     * @return string
     */
    protected function filterToString($filter)
    {
        $result = '';
        if (isset($filter['user'])) {
            $result .= 'user-' . $filter['user'];
        }
        if (isset($filter['name'])) {
            $result .= 'name-' . $filter['name'];
        }
        if (isset($filter['mail'])) {
            $result .= 'mail-' . $filter['mail'];
        }
        if (isset($filter['grps'])) {
            $result .= 'grps-' . $filter['grps'];
        }
        return $result;
    }

    /**
     * Create an array of $numberOfAdds users passing a certain $filter, including belonging
     * to a certain group and save them to a object-wide array. If the array
     * already exists try to add $numberOfAdds further users to it.
     *
     * @param array $filter
     * @param int $numberOfAdds additional number of users requested
     * @return int number of Users actually add to Array
     */
    protected function fillGroupUserArray($filter, $numberOfAdds)
    {
        if (isset($this->grpsusers[$this->filterToString($filter)])) {
            $actualstart = count($this->grpsusers[$this->filterToString($filter)]);
        } else {
            $this->grpsusers[$this->filterToString($filter)] = [];
            $actualstart = 0;
        }

        $i=0;
        $count = 0;
        $this->constructPattern($filter);
        foreach ($this->users as $user => &$info) {
            if ($i++ < $actualstart) {
                continue;
            }
            if ($info === false) {
                $info = $this->getUserData($user);
            }
            if ($this->filter($user, $info)) {
                $this->grpsusers[$this->filterToString($filter)][$user] = $info;
                if (($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
            }
        }
        return $count;
    }

    /**
     * Bulk retrieval of user data
     *
     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
     *
     * @param   int $start index of first user to be returned
     * @param   int $limit max number of users to be returned
     * @param   array $filter array of field/pattern pairs, null for no filter
     * @return array userinfo (refer getUserData for internal userinfo details)
     */
    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
    {
        $adldap = $this->initAdLdap(null);
        if (!$adldap) return array();

        //if (!$this->users) {
            //get info for given user
            $result = $adldap->user()->all(false, $this->constructSearchString($filter));
            if (!$result) return array();
            $this->users = array_fill_keys($result, false);
        //}

        $i     = 0;
        $count = 0;
        $result = array();

        if (!isset($filter['grps'])) {
            /** @var admin_plugin_usermanager $usermanager */
            $usermanager = plugin_load("admin", "usermanager", false);
            $usermanager->setLastdisabled(false);
            $this->constructPattern($filter);
            foreach ($this->users as $user => &$info) {
                if ($i++ < $start) {
                    continue;
                }
                if ($info === false) {
                    $info = $this->getUserData($user);
                }
                $result[$user] = $info;
                if (($limit > 0) && (++$count >= $limit)) break;
            }
        } else {
            /** @var admin_plugin_usermanager $usermanager */
            $usermanager = plugin_load("admin", "usermanager", false);
            $usermanager->setLastdisabled(true);
            if (!isset($this->grpsusers[$this->filterToString($filter)]) ||
                count($this->grpsusers[$this->filterToString($filter)]) < ($start+$limit)
            ) {
                if(!isset($this->grpsusers[$this->filterToString($filter)])) {
                    $this->grpsusers[$this->filterToString($filter)] = [];
                }

                $this->fillGroupUserArray(
                    $filter,
                    $start+$limit - count($this->grpsusers[$this->filterToString($filter)]) +1
                );
            }
            if (!$this->grpsusers[$this->filterToString($filter)]) return array();
            foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) {
                if ($i++ < $start) {
                    continue;
                }
                $result[$user] = $info;
                if (($limit > 0) && (++$count >= $limit)) break;
            }
        }
        return $result;
    }

    /**
     * Modify user data
     *
     * @param   string $user      nick of the user to be changed
     * @param   array  $changes   array of field/value pairs to be changed
     * @return  bool
     */
    public function modifyUser($user, $changes)
    {
        $return = true;
        $adldap = $this->initAdLdap($this->getUserDomain($user));
        if (!$adldap) {
            msg($this->getLang('connectfail'), -1);
            return false;
        }

        // password changing
        if (isset($changes['pass'])) {
            try {
                $return = $adldap->user()->password($this->getUserName($user), $changes['pass']);
            } catch (adLDAPException $e) {
                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
                $return = false;
            }
            if (!$return) msg($this->getLang('passchangefail'), -1);
        }

        // changing user data
        $adchanges = array();
        if (isset($changes['name'])) {
            // get first and last name
            $parts                     = explode(' ', $changes['name']);
            $adchanges['surname']      = array_pop($parts);
            $adchanges['firstname']    = join(' ', $parts);
            $adchanges['display_name'] = $changes['name'];
        }
        if (isset($changes['mail'])) {
            $adchanges['email'] = $changes['mail'];
        }
        if (count($adchanges)) {
            try {
                $return = $return & $adldap->user()->modify($this->getUserName($user), $adchanges);
            } catch (adLDAPException $e) {
                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
                $return = false;
            }
            if (!$return) msg($this->getLang('userchangefail'), -1);
        }

        return $return;
    }

    /**
     * Initialize the AdLDAP library and connect to the server
     *
     * When you pass null as domain, it will reuse any existing domain.
     * Eg. the one of the logged in user. It falls back to the default
     * domain if no current one is available.
     *
     * @param string|null $domain The AD domain to use
     * @return adLDAP|bool true if a connection was established
     */
    protected function initAdLdap($domain)
    {
        if (is_null($domain) && is_array($this->opts)) {
            $domain = $this->opts['domain'];
        }

        $this->opts = $this->loadServerConfig((string) $domain);
        if (isset($this->adldap[$domain])) return $this->adldap[$domain];

        // connect
        try {
            $this->adldap[$domain] = new adLDAP($this->opts);
            return $this->adldap[$domain];
        } catch (Exception $e) {
            if ($this->conf['debug']) {
                msg('AD Auth: '.$e->getMessage(), -1);
            }
            $this->success         = false;
            $this->adldap[$domain] = null;
        }
        return false;
    }

    /**
     * Get the domain part from a user
     *
     * @param string $user
     * @return string
     */
    public function getUserDomain($user)
    {
        list(, $domain) = explode('@', $user, 2);
        return $domain;
    }

    /**
     * Get the user part from a user
     *
     * When an account suffix is set, we strip the domain part from the user
     *
     * @param string $user
     * @return string
     */
    public function getUserName($user)
    {
        if ($this->conf['account_suffix'] !== '') {
            list($user) = explode('@', $user, 2);
        }
        return $user;
    }

    /**
     * Fetch the configuration for the given AD domain
     *
     * @param string $domain current AD domain
     * @return array
     */
    protected function loadServerConfig($domain)
    {
        // prepare adLDAP standard configuration
        $opts = $this->conf;

        $opts['domain'] = $domain;

        // add possible domain specific configuration
        if ($domain && is_array($this->conf[$domain])) foreach ($this->conf[$domain] as $key => $val) {
            $opts[$key] = $val;
        }

        // handle multiple AD servers
        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);

        // compatibility with old option name
        if (empty($opts['admin_username']) && !empty($opts['ad_username'])) {
            $opts['admin_username'] = $opts['ad_username'];
        }
        if (empty($opts['admin_password']) && !empty($opts['ad_password'])) {
            $opts['admin_password'] = $opts['ad_password'];
        }
        $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate

        // we can change the password if SSL is set
        if ($opts['use_ssl'] || $opts['use_tls']) {
            $this->cando['modPass'] = true;
        } else {
            $this->cando['modPass'] = false;
        }

        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
        if (empty($opts['admin_username'])) $opts['admin_username'] = null;
        if (empty($opts['admin_password'])) $opts['admin_password'] = null;

        // user listing needs admin priviledges
        if (!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
            $this->cando['getUsers'] = true;
        } else {
            $this->cando['getUsers'] = false;
        }

        return $opts;
    }

    /**
     * Returns a list of configured domains
     *
     * The default domain has an empty string as key
     *
     * @return array associative array(key => domain)
     */
    public function getConfiguredDomains()
    {
        $domains = array();
        if (empty($this->conf['account_suffix'])) return $domains; // not configured yet

        // add default domain, using the name from account suffix
        $domains[''] = ltrim($this->conf['account_suffix'], '@');

        // find additional domains
        foreach ($this->conf as $key => $val) {
            if (is_array($val) && isset($val['account_suffix'])) {
                $domains[$key] = ltrim($val['account_suffix'], '@');
            }
        }
        ksort($domains);

        return $domains;
    }

    /**
     * Check provided user and userinfo for matching patterns
     *
     * The patterns are set up with $this->_constructPattern()
     *
     * @author Chris Smith <chris@jalakai.co.uk>
     *
     * @param string $user
     * @param array  $info
     * @return bool
     */
    protected function filter($user, $info)
    {
        foreach ($this->pattern as $item => $pattern) {
            if ($item == 'user') {
                if (!preg_match($pattern, $user)) return false;
            } elseif ($item == 'grps') {
                if (!count(preg_grep($pattern, $info['grps']))) return false;
            } else {
                if (!preg_match($pattern, $info[$item])) return false;
            }
        }
        return true;
    }

    /**
     * Create a pattern for $this->_filter()
     *
     * @author Chris Smith <chris@jalakai.co.uk>
     *
     * @param array $filter
     */
    protected function constructPattern($filter)
    {
        $this->pattern = array();
        foreach ($filter as $item => $pattern) {
            $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
        }
    }
}