Completed
Push — master ( 79a44e...273314 )
by Sean
02:15
created

LDAPService   F

Complexity

Total Complexity 147

Size/Duplication

Total Lines 920
Duplicated Lines 11.3 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 29
Bugs 3 Features 4
Metric Value
wmc 147
c 29
b 3
f 4
lcom 1
cbo 16
dl 104
loc 920
rs 1.263

28 Methods

Rating   Name   Duplication   Size   Complexity  
A get_cache() 0 7 1
A flush() 0 5 1
A setGateway() 0 4 1
A enabled() 0 5 1
A authenticate() 0 19 3
A getNodes() 0 17 4
C getGroups() 10 24 7
B getNestedGroups() 6 18 5
A getGroupByGUID() 10 10 4
A getGroupByDN() 10 10 4
B getUsers() 10 18 5
A getUserByGUID() 10 10 4
A getUserByDN() 10 10 4
A getUserByEmail() 10 10 4
A getUserByUsername() 10 10 4
A getUsernameByEmail() 0 9 2
A update() 0 4 1
A delete() 0 4 1
A move() 0 4 1
A add() 0 4 1
A getLDAPGroupMembers() 0 13 4
F updateMemberFromLDAP() 18 161 33
C updateGroupFromLDAP() 0 40 7
B createLDAPUser() 0 39 5
B updateLDAPFromMember() 0 55 9
F updateLDAPGroupsForMember() 0 87 20
B setPassword() 0 34 6
B deleteLDAPMember() 0 18 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like LDAPService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LDAPService, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Class LDAPService
4
 *
5
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
6
 * All other modules should access LDAP through this class.
7
 *
8
 * This class builds on top of LDAPGateway's detailed code by adding:
9
 * - caching
10
 * - data aggregation and restructuring from multiple lower-level calls
11
 * - error handling
12
 *
13
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
14
 */
15
class LDAPService extends Object implements Flushable
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
16
{
17
    /**
18
     * @var array
19
     */
20
    private static $dependencies = array(
0 ignored issues
show
Unused Code introduced by
The property $dependencies is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
21
        'gateway' => '%$LDAPGateway'
22
    );
23
24
    /**
25
     * If configured, only user objects within these locations will be exposed to this service.
26
     *
27
     * @var array
28
     * @config
29
     */
30
    private static $users_search_locations = array();
0 ignored issues
show
Unused Code introduced by
The property $users_search_locations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
31
32
    /**
33
     * If configured, only group objects within these locations will be exposed to this service.
34
     * @var array
35
     *
36
     * @config
37
     */
38
    private static $groups_search_locations = array();
0 ignored issues
show
Unused Code introduced by
The property $groups_search_locations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
39
40
    /**
41
     * @var array
42
     */
43
    private static $_cache_nested_groups = array();
44
45
    /**
46
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
47
     * be added to this group's membership when imported, regardless of any sort of group mappings.
48
     *
49
     * @var string
50
     * @config
51
     */
52
    private static $default_group;
0 ignored issues
show
Unused Code introduced by
The property $default_group is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
53
54
    /**
55
     * Get the cache objecgt used for LDAP results. Note that the default lifetime set here
56
     * is 8 hours, but you can change that by calling SS_Cache::set_lifetime('ldap', <lifetime in seconds>)
57
     *
58
     * @return Zend_Cache_Frontend
59
     */
60
    public static function get_cache()
61
    {
62
        return SS_Cache::factory('ldap', 'Output', array(
63
            'automatic_serialization' => true,
64
            'lifetime' => 28800
65
        ));
66
    }
67
68
    /**
69
     * Flushes out the LDAP results cache when flush=1 is called.
70
     */
71
    public static function flush()
72
    {
73
        $cache = self::get_cache();
74
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
75
    }
76
77
    /**
78
     * @var LDAPGateway
79
     */
80
    public $gateway;
81
82
    /**
83
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
84
     * @var LDAPGateway
85
     */
86
    public function setGateway($gateway)
87
    {
88
        $this->gateway = $gateway;
89
    }
90
91
    /**
92
     * Checkes whether or not the service is enabled.
93
     *
94
     * @return bool
95
     */
96
    public function enabled()
97
    {
98
        $options = Config::inst()->get('LDAPGateway', 'options');
99
        return !empty($options);
100
    }
101
102
    /**
103
     * Authenticate the given username and password with LDAP.
104
     *
105
     * @param string $username
106
     * @param string $password
107
     *
108
     * @return array
109
     */
110
    public function authenticate($username, $password)
111
    {
112
        $result = $this->gateway->authenticate($username, $password);
113
        $messages = $result->getMessages();
114
115
        // all messages beyond the first one are for debugging and
116
        // not suitable to display to the user.
117
        foreach ($messages as $i => $message) {
118
            if ($i > 0) {
119
                SS_Log::log(str_replace("\n", "\n  ", $message), SS_Log::DEBUG);
120
            }
121
        }
122
123
        return array(
124
            'success' => $result->getCode() === 1,
125
            'identity' => $result->getIdentity(),
126
            'message' => $messages[0] // first message is user readable, suitable for showing back to the login form
127
        );
128
    }
129
130
    /**
131
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
132
     *
133
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
134
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
135
     * @return array
136
     */
137
    public function getNodes($cached = true, $attributes = array())
138
    {
139
        $cache = self::get_cache();
140
        $results = $cache->load('nodes' . md5(implode('', $attributes)));
141
142
        if (!$results || !$cached) {
143
            $results = array();
144
            $records = $this->gateway->getNodes(null, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
145
            foreach ($records as $record) {
146
                $results[$record['dn']] = $record;
147
            }
148
149
            $cache->save($results);
150
        }
151
152
        return $results;
153
    }
154
155
    /**
156
     * Return all AD groups in configured search locations, including all nested groups.
157
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
158
     * to use the default baseDn defined in the connection.
159
     *
160
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
161
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
162
     * @param string $indexBy Attribute to use as an index.
163
     * @return array
164
     */
165
    public function getGroups($cached = true, $attributes = array(), $indexBy = 'dn')
166
    {
167
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
168
        $cache = self::get_cache();
169
        $results = $cache->load('groups' . md5(implode('', array_merge($searchLocations, $attributes))));
170
171
        if (!$results || !$cached) {
172
            $results = array();
173 View Code Duplication
            foreach ($searchLocations as $searchLocation) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
                $records = $this->gateway->getGroups($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
175
                if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
176
                    continue;
177
                }
178
179
                foreach ($records as $record) {
180
                    $results[$record[$indexBy]] = $record;
181
                }
182
            }
183
184
            $cache->save($results);
185
        }
186
187
        return $results;
188
    }
189
190
    /**
191
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
192
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
193
     *
194
     * @param string $dn
195
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
196
     * @return array
197
     */
198
    public function getNestedGroups($dn, $attributes = array())
199
    {
200
        if (isset(self::$_cache_nested_groups[$dn])) {
201
            return self::$_cache_nested_groups[$dn];
202
        }
203
204
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
205
        $results = array();
206 View Code Duplication
        foreach ($searchLocations as $searchLocation) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
207
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
208
            foreach ($records as $record) {
209
                $results[$record['dn']] = $record;
210
            }
211
        }
212
213
        self::$_cache_nested_groups[$dn] = $results;
214
        return $results;
215
    }
216
217
    /**
218
     * Get a particular AD group's data given a GUID.
219
     *
220
     * @param string $guid
221
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
222
     * @return array
223
     */
224 View Code Duplication
    public function getGroupByGUID($guid, $attributes = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225
    {
226
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
227
        foreach ($searchLocations as $searchLocation) {
228
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
229
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
230
                return $records[0];
231
            }
232
        }
233
    }
234
235
    /**
236
     * Get a particular AD group's data given a DN.
237
     *
238
     * @param string $dn
239
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
240
     * @return array
241
     */
242 View Code Duplication
    public function getGroupByDN($dn, $attributes = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
243
    {
244
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
245
        foreach ($searchLocations as $searchLocation) {
246
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
247
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
248
                return $records[0];
249
            }
250
        }
251
    }
252
253
    /**
254
     * Return all AD users in configured search locations, including all users in nested groups.
255
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
256
     * to use the default baseDn defined in the connection.
257
     *
258
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
259
     * @return array
260
     */
261
    public function getUsers($attributes = array())
262
    {
263
        $searchLocations = $this->config()->users_search_locations ?: array(null);
264
        $results = array();
265
266 View Code Duplication
        foreach ($searchLocations as $searchLocation) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
267
            $records = $this->gateway->getUsers($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
268
            if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
269
                continue;
270
            }
271
272
            foreach ($records as $record) {
273
                $results[$record['objectguid']] = $record;
274
            }
275
        }
276
277
        return $results;
278
    }
279
280
    /**
281
     * Get a specific AD user's data given a GUID.
282
     *
283
     * @param string $guid
284
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
285
     * @return array
286
     */
287 View Code Duplication
    public function getUserByGUID($guid, $attributes = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
    {
289
        $searchLocations = $this->config()->users_search_locations ?: array(null);
290
        foreach ($searchLocations as $searchLocation) {
291
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
292
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
293
                return $records[0];
294
            }
295
        }
296
    }
297
298
    /**
299
     * Get a specific AD user's data given a DN.
300
     *
301
     * @param string $dn
302
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
303
     *
304
     * @return array
305
     */
306 View Code Duplication
    public function getUserByDN($dn, $attributes = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
307
    {
308
        $searchLocations = $this->config()->users_search_locations ?: array(null);
309
        foreach ($searchLocations as $searchLocation) {
310
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
311
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
312
                return $records[0];
313
            }
314
        }
315
    }
316
317
    /**
318
     * Get a specific user's data given an email.
319
     *
320
     * @param string $email
321
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
322
     * @return array
323
     */
324 View Code Duplication
    public function getUserByEmail($email, $attributes = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
325
    {
326
        $searchLocations = $this->config()->users_search_locations ?: array(null);
327
        foreach ($searchLocations as $searchLocation) {
328
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
329
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
330
                return $records[0];
331
            }
332
        }
333
    }
334
335
    /**
336
     * Get a specific user's data given a username.
337
     *
338
     * @param string $username
339
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
340
     * @return array
341
     */
342 View Code Duplication
    public function getUserByUsername($username, $attributes = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
343
    {
344
        $searchLocations = $this->config()->users_search_locations ?: array(null);
345
        foreach ($searchLocations as $searchLocation) {
346
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
347
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
348
                return $records[0];
349
            }
350
        }
351
    }
352
353
    /**
354
     * Get a username for an email.
355
     *
356
     * @param string $email
357
     * @return string|null
358
     */
359
    public function getUsernameByEmail($email)
360
    {
361
        $data = $this->getUserByEmail($email);
362
        if (empty($data)) {
363
            return null;
364
        }
365
366
        return $this->gateway->getCanonicalUsername($data);
367
    }
368
369
    /**
370
     * Given a group DN, get the group membership data in LDAP.
371
     *
372
     * @param string $dn
373
     * @return array
374
     */
375
    public function getLDAPGroupMembers($dn)
376
    {
377
        $groupObj = Group::get()->filter('DN', $dn)->first();
378
        $groupData = $this->getGroupByGUID($groupObj->GUID);
379
        $members = !empty($groupData['member']) ? $groupData['member'] : array();
380
        // If a user belongs to a single group, this comes through as a string.
381
        // Normalise to a array so it's consistent.
382
        if ($members && is_string($members)) {
383
            $members = array($members);
384
        }
385
386
        return $members;
387
    }
388
389
    /**
390
     * Update the current Member record with data from LDAP.
391
     *
392
     * Constraints:
393
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
394
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
395
     *
396
     * @param Member
397
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
398
     *            If not given, the data will be looked up by the user's GUID.
399
     * @return bool
400
     */
401
    public function updateMemberFromLDAP(Member $member, $data = null)
402
    {
403
        if (!$this->enabled()) {
404
            return false;
405
        }
406
407
        if (!$member->GUID) {
408
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
409
            return false;
410
        }
411
412
        if (!$data) {
413
            $data = $this->getUserByGUID($member->GUID);
414
            if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
415
                SS_Log::log(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID), SS_Log::WARN);
416
                return false;
417
            }
418
        }
419
420
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
421
        $member->LastSynced = (string)SS_Datetime::now();
422
423
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
424
            if (!isset($data[$attribute])) {
425
                SS_Log::log(sprintf(
426
                    'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
427
                    $attribute,
428
                    $data['objectguid'],
429
                    $member->ID
430
                ), SS_Log::NOTICE);
431
432
                continue;
433
            }
434
435
            if ($attribute == 'thumbnailphoto') {
436
                $imageClass = $member->getRelationClass($field);
437
                if ($imageClass !== 'Image' && !is_subclass_of($imageClass, 'Image')) {
438
                    SS_Log::log(sprintf(
439
                        'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
440
                        $field
441
                    ), SS_Log::WARN);
442
443
                    continue;
444
                }
445
446
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
447
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
448
                $absPath = BASE_PATH . '/' . $path;
449
                if (!file_exists($absPath)) {
450
                    Filesystem::makeFolder($absPath);
451
                }
452
453
                // remove existing record if it exists
454
                $existingObj = $member->getComponent($field);
455
                if ($existingObj && $existingObj->exists()) {
456
                    $existingObj->delete();
457
                }
458
459
                // The image data is provided in raw binary.
460
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
461
                $record = new $imageClass();
462
                $record->Name = $filename;
463
                $record->Filename = $path . '/' . $filename;
464
                $record->write();
465
466
                $relationField = $field . 'ID';
467
                $member->{$relationField} = $record->ID;
468
            } else {
469
                $member->$field = $data[$attribute];
470
            }
471
        }
472
473
        // if a default group was configured, ensure the user is in that group
474
        if ($this->config()->default_group) {
475
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
476
            if (!($group && $group->exists())) {
477
                SS_Log::log(
478
                    sprintf(
479
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
480
                        $this->config()->default_group
481
                    ),
482
                    SS_Log::WARN
483
                );
484
            } else {
485
                $group->Members()->add($member, array(
486
                    'IsImportedFromLDAP' => '1'
487
                ));
488
            }
489
        }
490
491
        // this is to keep track of which groups the user gets mapped to
492
        // and we'll use that later to remove them from any groups that they're no longer mapped to
493
        $mappedGroupIDs = array();
494
495
        // ensure the user is in any mapped groups
496
        if (isset($data['memberof'])) {
497
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : array($data['memberof']);
498
            foreach ($ldapGroups as $groupDN) {
499
                foreach (LDAPGroupMapping::get() as $mapping) {
500
                    if (!$mapping->DN) {
501
                        SS_Log::log(
502
                            sprintf(
503
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
504
                                $mapping->ID
505
                            ),
506
                            SS_Log::WARN
507
                        );
508
                        continue;
509
                    }
510
511
                    // the user is a direct member of group with a mapping, add them to the SS group.
512 View Code Duplication
                    if ($mapping->DN == $groupDN) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
513
                        $group = $mapping->Group();
514
                        if ($group && $group->exists()) {
515
                            $group->Members()->add($member, array(
516
                                'IsImportedFromLDAP' => '1'
517
                            ));
518
                            $mappedGroupIDs[] = $mapping->GroupID;
519
                        }
520
                    }
521
522
                    // the user *might* be a member of a nested group provided the scope of the mapping
523
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
524
                    // to see if they are a member of one of those. If they are, add them to the SS group
525
                    if ($mapping->Scope == 'Subtree') {
526
                        $childGroups = $this->getNestedGroups($mapping->DN, array('dn'));
527
                        if (!$childGroups) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $childGroups of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
528
                            continue;
529
                        }
530
531
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
532 View Code Duplication
                            if ($childGroupDN == $groupDN) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
533
                                $group = $mapping->Group();
534
                                if ($group && $group->exists()) {
535
                                    $group->Members()->add($member, array(
536
                                        'IsImportedFromLDAP' => '1'
537
                                    ));
538
                                    $mappedGroupIDs[] = $mapping->GroupID;
539
                                }
540
                            }
541
                        }
542
                    }
543
                }
544
            }
545
        }
546
547
        // remove the user from any previously mapped groups, where the mapping has since been removed
548
        $groupRecords = DB::query(sprintf('SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s', $member->ID));
549
        foreach ($groupRecords as $groupRecord) {
550
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
551
                $group = Group::get()->byId($groupRecord['GroupID']);
552
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
553
                if ($group) {
554
                    $group->Members()->remove($member);
555
                }
556
            }
557
        }
558
        // This will throw an exception if there are two distinct GUIDs with the same email address.
559
        // We are happy with a raw 500 here at this stage.
560
        $member->write();
561
    }
562
563
    /**
564
     * Sync a specific Group by updating it with LDAP data.
565
     *
566
     * @param Group $group An existing Group or a new Group object
567
     * @param array $data LDAP group object data
568
     *
569
     * @return bool
570
     */
571
    public function updateGroupFromLDAP(Group $group, $data)
572
    {
573
        if (!$this->enabled()) {
574
            return false;
575
        }
576
577
        // Synchronise specific guaranteed fields.
578
        $group->Code = $data['samaccountname'];
579
        if (!empty($data['name'])) {
580
            $group->Title = $data['name'];
581
        } else {
582
            $group->Title = $data['samaccountname'];
583
        }
584
        if (!empty($data['description'])) {
585
            $group->Description = $data['description'];
586
        }
587
        $group->DN = $data['dn'];
588
        $group->LastSynced = (string)SS_Datetime::now();
589
        $group->write();
590
591
        // Mappings on this group are automatically maintained to contain just the group's DN.
592
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
593
        $hasCorrectMapping = false;
594
        foreach ($group->LDAPGroupMappings() as $mapping) {
595
            if ($mapping->DN === $data['dn']) {
596
                // This is the correct mapping we want to retain.
597
                $hasCorrectMapping = true;
598
            } else {
599
                $mapping->delete();
600
            }
601
        }
602
603
        // Second, if the main mapping was not found, add it in.
604
        if (!$hasCorrectMapping) {
605
            $mapping = new LDAPGroupMapping();
606
            $mapping->DN = $data['dn'];
0 ignored issues
show
Documentation introduced by
The property DN does not exist on object<LDAPGroupMapping>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
607
            $mapping->write();
608
            $group->LDAPGroupMappings()->add($mapping);
609
        }
610
    }
611
612
    /**
613
     * Creates a new LDAP user from the passed Member record.
614
     * Note that the Member record must have a non-empty Username field for this to work.
615
     *
616
     * @param Member $member
617
     */
618
    public function createLDAPUser(Member $member)
619
    {
620
        if (!$this->enabled()) {
621
            return;
622
        }
623
        if (empty($member->Username)) {
624
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
625
        }
626
627
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
628
        $member->Username = strtolower($member->Username);
629
630
        // Create user in LDAP using available information.
631
        $dn = sprintf('CN=%s,%s', $member->Username, LDAP_NEW_USERS_DN);
632
633
        try {
634
            $this->add($dn, array(
635
                'objectclass' => 'user',
636
                'cn' => $member->Username,
637
                'accountexpires' => '9223372036854775807',
638
                'useraccountcontrol' => '66048',
639
                'userprincipalname' => sprintf(
640
                    '%s@%s',
641
                    $member->Username,
642
                    $this->gateway->config()->options['accountDomainName']
643
                ),
644
            ));
645
        } catch (\Exception $e) {
646
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
647
        }
648
649
        $user = $this->getUserByUsername($member->Username);
650
        if (empty($user['objectguid'])) {
651
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
652
        }
653
654
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
655
        $member->GUID = $user['objectguid'];
656
    }
657
658
    /**
659
     * Update the Member data back to the corresponding LDAP user object.
660
     *
661
     * @param Member $member
662
     * @throws ValidationException
663
     */
664
    public function updateLDAPFromMember(Member $member)
665
    {
666
        if (!$this->enabled()) {
667
            return;
668
        }
669
        if (!$member->GUID) {
670
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
671
        }
672
673
        $data = $this->getUserByGUID($member->GUID);
674
        if (empty($data['objectguid'])) {
675
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
676
        }
677
678
        $dn = $data['distinguishedname'];
679
680
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
681
        $member->Username = strtolower($member->Username);
682
683
        try {
684
            // If the common name (cn) has changed, we need to ensure they've been moved
685
            // to the new DN, to avoid any clashes between user objects.
686
            if ($data['cn'] != $member->Username) {
687
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
688
                $this->move($dn, $newDn);
689
                $dn = $newDn;
690
            }
691
        } catch (\Exception $e) {
692
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
693
        }
694
695
        try {
696
            $attributes = array(
697
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
698
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
699
                'userprincipalname' => sprintf(
700
                    '%s@%s',
701
                    $member->Username,
702
                    $this->gateway->config()->options['accountDomainName']
703
                ),
704
            );
705
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
706
                $relationClass = $member->getRelationClass($field);
707
                if ($relationClass) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
708
                    // todo no support for writing back relations yet.
709
                } else {
710
                    $attributes[$attribute] = $member->$field;
711
                }
712
            }
713
714
            $this->update($dn, $attributes);
715
        } catch (\Exception $e) {
716
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
717
        }
718
    }
719
720
    /**
721
     * Ensure the user belongs to the correct groups in LDAP from their membership
722
     * to local LDAP mapped SilverStripe groups.
723
     *
724
     * This also removes them from LDAP groups if they've been taken out of one.
725
     * It will not affect group membership of non-mapped groups, so it will
726
     * not touch such internal AD groups like "Domain Users".
727
     *
728
     * @param Member $member
729
     */
730
    public function updateLDAPGroupsForMember(Member $member)
731
    {
732
        if (!$this->enabled()) {
733
            return;
734
        }
735
        if (!$member->GUID) {
736
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
737
        }
738
739
        $addGroups = array();
740
        $removeGroups = array();
741
742
        $user = $this->getUserByGUID($member->GUID);
743
        if (empty($user['objectguid'])) {
744
            throw new ValidationException('LDAP update failure: user missing GUID');
745
        }
746
747
        // If a user belongs to a single group, this comes through as a string.
748
        // Normalise to a array so it's consistent.
749
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : array();
750
        if ($existingGroups && is_string($existingGroups)) {
751
            $existingGroups = array($existingGroups);
752
        }
753
754
        foreach ($member->Groups() as $group) {
755
            if (!$group->GUID) {
756
                continue;
757
            }
758
759
            // mark this group as something we need to ensure the user belongs to in LDAP.
760
            $addGroups[] = $group->DN;
761
        }
762
763
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
764
        // see if the user should be removed from any of them.
765
        $remainingGroups = array_diff($existingGroups, $addGroups);
766
767
        foreach ($remainingGroups as $groupDn) {
768
            // We only want to be removing groups we have a local Group mapped to. Removing
769
            // membership for anything else would be bad!
770
            $group = Group::get()->filter('DN', $groupDn)->first();
771
            if (!$group || !$group->exists()) {
772
                continue;
773
            }
774
775
            // this group should be removed from the user's memberof attribute, as it's been removed.
776
            $removeGroups[] = $groupDn;
777
        }
778
779
        // go through the groups we want the user to be in and ensure they're in them.
780
        foreach ($addGroups as $groupDn) {
781
            $members = $this->getLDAPGroupMembers($groupDn);
782
783
            // this user is already in the group, no need to do anything.
784
            if (in_array($user['distinguishedname'], $members)) {
785
                continue;
786
            }
787
788
            $members[] = $user['distinguishedname'];
789
790
            try {
791
                $this->update($groupDn, array('member' => $members));
792
            } catch (\Exception $e) {
793
                throw new ValidationException('LDAP group membership add failure: '.$e->getMessage());
794
            }
795
        }
796
797
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
798
        foreach ($removeGroups as $groupDn) {
799
            $members = $this->getLDAPGroupMembers($groupDn);
800
801
            // remove the user from the members data.
802
            if (in_array($user['distinguishedname'], $members)) {
803
                foreach ($members as $i => $dn) {
804
                    if ($dn == $user['distinguishedname']) {
805
                        unset($members[$i]);
806
                    }
807
                }
808
            }
809
810
            try {
811
                $this->update($groupDn, array('member' => $members));
812
            } catch (\Exception $e) {
813
                throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage());
814
            }
815
        }
816
    }
817
818
    /**
819
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
820
     * password in the `unicodePwd` attribute.
821
     *
822
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
823
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
824
     *
825
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
826
     *
827
     * @param Member $member
828
     * @param string $password
829
     * @return ValidationResult
830
     * @throws Exception
831
     */
832
    public function setPassword(Member $member, $password)
833
    {
834
        $validationResult = ValidationResult::create(true);
835
        if (!$member->GUID) {
836
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
837
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
838
            return $validationResult;
839
        }
840
841
        $userData = $this->getUserByGUID($member->GUID);
842
        if (empty($userData['distinguishedname'])) {
843
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
844
            return $validationResult;
845
        }
846
847
        try {
848
            $this->update(
849
                $userData['distinguishedname'],
850
                array('unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password)))
851
            );
852
        } catch (Exception $e) {
853
            // Try to parse the exception to get the error message to display to user, eg:
854
            // Can't change password for Member.ID "13": 0x13 (Constraint violation; 0000052D: Constraint violation - check_password_restrictions: the password does not meet the complexity criteria!): updating: CN=User Name,OU=Users,DC=foo,DC=company,DC=com
855
            $pattern = '/^([^\s])*\s([^\;]*);\s([^\:]*):\s([^\:]*):\s([^\)]*)/i';
856
            if (preg_match($pattern, $e->getMessage(), $matches) && !empty($matches[5])) {
857
                $validationResult->error($matches[5]);
858
            } else {
859
                // Unparsable exception, an administrator should check the logs
860
                $validationResult->error(_t('LDAPAuthenticator.CANTCHANGEPASSWORD', 'We couldn\'t change your password, please contact an administrator.'));
861
            }
862
        }
863
864
        return $validationResult;
865
    }
866
867
    /**
868
     * Delete an LDAP user mapped to the Member record
869
     * @param Member $member
870
     */
871
    public function deleteLDAPMember(Member $member) {
872
        if (!$this->enabled()) {
873
            return;
874
        }
875
        if (!$member->GUID) {
876
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
877
        }
878
        $data = $this->getUserByGUID($member->GUID);
879
        if (empty($data['distinguishedname'])) {
880
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
881
        }
882
883
        try {
884
            $this->delete($data['distinguishedname']);
885
        } catch (\Exception $e) {
886
            throw new ValidationException('LDAP delete user failed: '.$e->getMessage());
887
        }
888
    }
889
890
    /**
891
     * A simple proxy to LDAP update operation.
892
     *
893
     * @param string $dn Location to add the entry at.
894
     * @param array $attributes A simple associative array of attributes.
895
     */
896
    public function update($dn, array $attributes)
897
    {
898
        $this->gateway->update($dn, $attributes);
899
    }
900
901
    /**
902
     * A simple proxy to LDAP delete operation.
903
     *
904
     * @param string $dn Location of object to delete
905
     * @param bool $recursively Recursively delete nested objects?
906
     */
907
    public function delete($dn, $recursively = false)
908
    {
909
        $this->gateway->delete($dn, $recursively);
910
    }
911
912
    /**
913
     * A simple proxy to LDAP copy/delete operation.
914
     *
915
     * @param string $fromDn
916
     * @param string $toDn
917
     * @param bool $recursively Recursively move nested objects?
918
     */
919
    public function move($fromDn, $toDn, $recursively = false)
920
    {
921
        $this->gateway->move($fromDn, $toDn, $recursively);
922
    }
923
924
    /**
925
     * A simple proxy to LDAP add operation.
926
     *
927
     * @param string $dn Location to add the entry at.
928
     * @param array $attributes A simple associative array of attributes.
929
     */
930
    public function add($dn, array $attributes)
931
    {
932
        $this->gateway->add($dn, $attributes);
933
    }
934
}
935