xref: /plugin/pureldap/classes/ADClient.php (revision 1078ec268114f0851ebf8a4280d0599a5fccb7d5)
1<?php
2
3namespace dokuwiki\plugin\pureldap\classes;
4
5use FreeDSx\Ldap\Entry\Entries;
6use FreeDSx\Ldap\Entry\Entry;
7use FreeDSx\Ldap\Exception\OperationException;
8use FreeDSx\Ldap\Operations;
9use FreeDSx\Ldap\Search\Filters;
10
11class ADClient extends Client
12{
13
14    /** @inheritDoc */
15    public function getUser($username, $fetchgroups = true)
16    {
17        if (!$this->autoAuth()) return null;
18
19        $filter = Filters::and(
20            Filters::equal('objectClass', 'user'),
21            Filters::equal('userPrincipalName', $username)
22        );
23
24        try {
25            /** @var Entries $entries */
26            $entries = $this->ldap->search(Operations::search($filter));
27        } catch (OperationException $e) {
28            $this->debug($e);
29            return null;
30        }
31        if ($entries->count() !== 1) return null;
32        $entry = $entries->first();
33
34        return [
35            'user' => $username,
36            'name' => $this->attr2str($entry->get('DisplayName')) ?: $this->attr2str($entry->get('Name')),
37            'mail' => $this->attr2str($entry->get('mail')),
38            'dn' => $entry->getDn()->toString(),
39            'grps' => $this->getUserGroups($entry), // we always return groups because its currently inexpensive
40        ];
41    }
42
43    /**
44     * Get the list of groups the given user is member of
45     *
46     * This method currently does no LDAP queries and thus is inexpensive.
47     *
48     * @param Entry $userentry
49     * @return array
50     * @todo implement nested group memberships
51     */
52    protected function getUserGroups(Entry $userentry)
53    {
54        $groups = [$this->config['defaultgroup']]; // always add default
55
56        // we simply take the first CN= part of the group DN and return it as the group name
57        // this should be correct for ActiveDirectory and saves us additional LDAP queries
58        if ($userentry->has('memberOf')) {
59            foreach ($userentry->get('memberOf')->getValues() as $line) {
60                list($cn) = explode(',', $line, 2);
61                $groups[] = substr($cn, 3);
62            }
63        }
64
65        // resolving the primary group in AD is complicated but basically never needed
66        // http://support.microsoft.com/?kbid=321360
67        $gid = $userentry->get('primaryGroupID')->firstValue();
68        if ($gid == 513) {
69            $groups[] = 'Domain Users';
70        }
71
72        return $groups;
73    }
74}
75