Completed
Push — master ( 9fbdf0...35629c )
by Mateusz
02:20
created

LDAPService::authenticate()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 36
Code Lines 20

Duplication

Lines 13
Ratio 36.11 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 13
loc 36
rs 6.7272
cc 7
eloc 20
nc 12
nop 2
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
     * Location to create new users in (distinguished name).
42
     * @var string
43
     *
44
     * @config
45
     */
46
    private static $new_users_dn;
0 ignored issues
show
Unused Code introduced by
The property $new_users_dn 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...
47
48
    /**
49
     * @var array
50
     */
51
    private static $_cache_nested_groups = array();
52
53
    /**
54
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
55
     * be added to this group's membership when imported, regardless of any sort of group mappings.
56
     *
57
     * @var string
58
     * @config
59
     */
60
    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...
61
62
    /**
63
     * Get the cache objecgt used for LDAP results. Note that the default lifetime set here
64
     * is 8 hours, but you can change that by calling SS_Cache::set_lifetime('ldap', <lifetime in seconds>)
65
     *
66
     * @return Zend_Cache_Frontend
67
     */
68
    public static function get_cache()
69
    {
70
        return SS_Cache::factory('ldap', 'Output', array(
71
            'automatic_serialization' => true,
72
            'lifetime' => 28800
73
        ));
74
    }
75
76
    /**
77
     * Flushes out the LDAP results cache when flush=1 is called.
78
     */
79
    public static function flush()
80
    {
81
        $cache = self::get_cache();
82
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
83
    }
84
85
    /**
86
     * @var LDAPGateway
87
     */
88
    public $gateway;
89
90
    /**
91
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
92
     * @var LDAPGateway
93
     */
94
    public function setGateway($gateway)
95
    {
96
        $this->gateway = $gateway;
97
    }
98
99
    /**
100
     * Checkes whether or not the service is enabled.
101
     *
102
     * @return bool
103
     */
104
    public function enabled()
105
    {
106
        $options = Config::inst()->get('LDAPGateway', 'options');
107
        return !empty($options);
108
    }
109
110
    /**
111
     * Authenticate the given username and password with LDAP.
112
     *
113
     * @param string $username
114
     * @param string $password
115
     *
116
     * @return array
117
     */
118
    public function authenticate($username, $password)
119
    {
120
        $result = $this->gateway->authenticate($username, $password);
121
        $messages = $result->getMessages();
122
123
        // all messages beyond the first one are for debugging and
124
        // not suitable to display to the user.
125
        foreach ($messages as $i => $message) {
126
            if ($i > 0) {
127
                SS_Log::log(str_replace("\n", "\n  ", $message), SS_Log::DEBUG);
128
            }
129
        }
130
131
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
132
133
        // show better errors than the defaults for various status codes returned by LDAP
134 View Code Duplication
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_ACCOUNT_LOCKED_OUT') !== false) {
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...
135
            $message = _t(
136
                'LDAPService.ACCOUNTLOCKEDOUT',
137
                'Your account has been temporarily locked because of too many failed login attempts. ' .
138
                'Please try again later.'
139
            );
140
        }
141 View Code Duplication
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_LOGON_FAILURE') !== false) {
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...
142
            $message = _t(
143
                'LDAPService.INVALIDCREDENTIALS',
144
                'The provided details don\'t seem to be correct. Please try again.'
145
            );
146
        }
147
148
        return array(
149
            'success' => $result->getCode() === 1,
150
            'identity' => $result->getIdentity(),
151
            'message' => $message
152
        );
153
    }
154
155
    /**
156
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
157
     *
158
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
159
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
160
     * @return array
161
     */
162
    public function getNodes($cached = true, $attributes = array())
163
    {
164
        $cache = self::get_cache();
165
        $results = $cache->load('nodes' . md5(implode('', $attributes)));
166
167
        if (!$results || !$cached) {
168
            $results = array();
169
            $records = $this->gateway->getNodes(null, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
170
            foreach ($records as $record) {
171
                $results[$record['dn']] = $record;
172
            }
173
174
            $cache->save($results);
175
        }
176
177
        return $results;
178
    }
179
180
    /**
181
     * Return all AD groups in configured search locations, including all nested groups.
182
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
183
     * to use the default baseDn defined in the connection.
184
     *
185
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
186
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
187
     * @param string $indexBy Attribute to use as an index.
188
     * @return array
189
     */
190
    public function getGroups($cached = true, $attributes = array(), $indexBy = 'dn')
191
    {
192
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
193
        $cache = self::get_cache();
194
        $results = $cache->load('groups' . md5(implode('', array_merge($searchLocations, $attributes))));
195
196
        if (!$results || !$cached) {
197
            $results = array();
198 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...
199
                $records = $this->gateway->getGroups($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
200
                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...
201
                    continue;
202
                }
203
204
                foreach ($records as $record) {
205
                    $results[$record[$indexBy]] = $record;
206
                }
207
            }
208
209
            $cache->save($results);
210
        }
211
212
        return $results;
213
    }
214
215
    /**
216
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
217
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
218
     *
219
     * @param string $dn
220
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
221
     * @return array
222
     */
223
    public function getNestedGroups($dn, $attributes = array())
224
    {
225
        if (isset(self::$_cache_nested_groups[$dn])) {
226
            return self::$_cache_nested_groups[$dn];
227
        }
228
229
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
230
        $results = array();
231 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...
232
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
233
            foreach ($records as $record) {
234
                $results[$record['dn']] = $record;
235
            }
236
        }
237
238
        self::$_cache_nested_groups[$dn] = $results;
239
        return $results;
240
    }
241
242
    /**
243
     * Get a particular AD group's data given a GUID.
244
     *
245
     * @param string $guid
246
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
247
     * @return array
248
     */
249 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...
250
    {
251
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
252
        foreach ($searchLocations as $searchLocation) {
253
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
254
            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...
255
                return $records[0];
256
            }
257
        }
258
    }
259
260
    /**
261
     * Get a particular AD group's data given a DN.
262
     *
263
     * @param string $dn
264
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
265
     * @return array
266
     */
267 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...
268
    {
269
        $searchLocations = $this->config()->groups_search_locations ?: array(null);
270
        foreach ($searchLocations as $searchLocation) {
271
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
272
            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...
273
                return $records[0];
274
            }
275
        }
276
    }
277
278
    /**
279
     * Return all AD users in configured search locations, including all users in nested groups.
280
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
281
     * to use the default baseDn defined in the connection.
282
     *
283
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
284
     * @return array
285
     */
286
    public function getUsers($attributes = array())
287
    {
288
        $searchLocations = $this->config()->users_search_locations ?: array(null);
289
        $results = array();
290
291 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...
292
            $records = $this->gateway->getUsers($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
293
            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...
294
                continue;
295
            }
296
297
            foreach ($records as $record) {
298
                $results[$record['objectguid']] = $record;
299
            }
300
        }
301
302
        return $results;
303
    }
304
305
    /**
306
     * Get a specific AD user's data given a GUID.
307
     *
308
     * @param string $guid
309
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
310
     * @return array
311
     */
312 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...
313
    {
314
        $searchLocations = $this->config()->users_search_locations ?: array(null);
315
        foreach ($searchLocations as $searchLocation) {
316
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
317
            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...
318
                return $records[0];
319
            }
320
        }
321
    }
322
323
    /**
324
     * Get a specific AD user's data given a DN.
325
     *
326
     * @param string $dn
327
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
328
     *
329
     * @return array
330
     */
331 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...
332
    {
333
        $searchLocations = $this->config()->users_search_locations ?: array(null);
334
        foreach ($searchLocations as $searchLocation) {
335
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
336
            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...
337
                return $records[0];
338
            }
339
        }
340
    }
341
342
    /**
343
     * Get a specific user's data given an email.
344
     *
345
     * @param string $email
346
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
347
     * @return array
348
     */
349 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...
350
    {
351
        $searchLocations = $this->config()->users_search_locations ?: array(null);
352
        foreach ($searchLocations as $searchLocation) {
353
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
354
            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...
355
                return $records[0];
356
            }
357
        }
358
    }
359
360
    /**
361
     * Get a specific user's data given a username.
362
     *
363
     * @param string $username
364
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
365
     * @return array
366
     */
367 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...
368
    {
369
        $searchLocations = $this->config()->users_search_locations ?: array(null);
370
        foreach ($searchLocations as $searchLocation) {
371
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
372
            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...
373
                return $records[0];
374
            }
375
        }
376
    }
377
378
    /**
379
     * Get a username for an email.
380
     *
381
     * @param string $email
382
     * @return string|null
383
     */
384
    public function getUsernameByEmail($email)
385
    {
386
        $data = $this->getUserByEmail($email);
387
        if (empty($data)) {
388
            return null;
389
        }
390
391
        return $this->gateway->getCanonicalUsername($data);
392
    }
393
394
    /**
395
     * Given a group DN, get the group membership data in LDAP.
396
     *
397
     * @param string $dn
398
     * @return array
399
     */
400
    public function getLDAPGroupMembers($dn)
401
    {
402
        $groupObj = Group::get()->filter('DN', $dn)->first();
403
        $groupData = $this->getGroupByGUID($groupObj->GUID);
404
        $members = !empty($groupData['member']) ? $groupData['member'] : array();
405
        // If a user belongs to a single group, this comes through as a string.
406
        // Normalise to a array so it's consistent.
407
        if ($members && is_string($members)) {
408
            $members = array($members);
409
        }
410
411
        return $members;
412
    }
413
414
    /**
415
     * Update the current Member record with data from LDAP.
416
     *
417
     * Constraints:
418
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
419
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
420
     *
421
     * @param Member
422
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
423
     *            If not given, the data will be looked up by the user's GUID.
424
     * @return bool
425
     */
426
    public function updateMemberFromLDAP(Member $member, $data = null)
427
    {
428
        if (!$this->enabled()) {
429
            return false;
430
        }
431
432
        if (!$member->GUID) {
433
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
434
            return false;
435
        }
436
437
        if (!$data) {
438
            $data = $this->getUserByGUID($member->GUID);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $data. This often makes code more readable.
Loading history...
439
            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...
440
                SS_Log::log(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID), SS_Log::WARN);
441
                return false;
442
            }
443
        }
444
445
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
446
        $member->LastSynced = (string)SS_Datetime::now();
447
448
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
449
            if (!isset($data[$attribute])) {
450
                SS_Log::log(sprintf(
451
                    'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
452
                    $attribute,
453
                    $data['objectguid'],
454
                    $member->ID
455
                ), SS_Log::NOTICE);
456
457
                continue;
458
            }
459
460
            if ($attribute == 'thumbnailphoto') {
461
                $imageClass = $member->getRelationClass($field);
462
                if ($imageClass !== 'Image' && !is_subclass_of($imageClass, 'Image')) {
463
                    SS_Log::log(sprintf(
464
                        'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
465
                        $field
466
                    ), SS_Log::WARN);
467
468
                    continue;
469
                }
470
471
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
472
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
473
                $absPath = BASE_PATH . '/' . $path;
474
                if (!file_exists($absPath)) {
475
                    Filesystem::makeFolder($absPath);
476
                }
477
478
                // remove existing record if it exists
479
                $existingObj = $member->getComponent($field);
480
                if ($existingObj && $existingObj->exists()) {
481
                    $existingObj->delete();
482
                }
483
484
                // The image data is provided in raw binary.
485
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
486
                $record = new $imageClass();
487
                $record->Name = $filename;
488
                $record->Filename = $path . '/' . $filename;
489
                $record->write();
490
491
                $relationField = $field . 'ID';
492
                $member->{$relationField} = $record->ID;
493
            } else {
494
                $member->$field = $data[$attribute];
495
            }
496
        }
497
498
        // if a default group was configured, ensure the user is in that group
499
        if ($this->config()->default_group) {
500
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
501
            if (!($group && $group->exists())) {
502
                SS_Log::log(
503
                    sprintf(
504
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
505
                        $this->config()->default_group
506
                    ),
507
                    SS_Log::WARN
508
                );
509
            } else {
510
                $group->Members()->add($member, array(
511
                    'IsImportedFromLDAP' => '1'
512
                ));
513
            }
514
        }
515
516
        // this is to keep track of which groups the user gets mapped to
517
        // and we'll use that later to remove them from any groups that they're no longer mapped to
518
        $mappedGroupIDs = array();
519
520
        // ensure the user is in any mapped groups
521
        if (isset($data['memberof'])) {
522
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : array($data['memberof']);
523
            foreach ($ldapGroups as $groupDN) {
524
                foreach (LDAPGroupMapping::get() as $mapping) {
525
                    if (!$mapping->DN) {
526
                        SS_Log::log(
527
                            sprintf(
528
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
529
                                $mapping->ID
530
                            ),
531
                            SS_Log::WARN
532
                        );
533
                        continue;
534
                    }
535
536
                    // the user is a direct member of group with a mapping, add them to the SS group.
537 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...
538
                        $group = $mapping->Group();
539
                        if ($group && $group->exists()) {
540
                            $group->Members()->add($member, array(
541
                                'IsImportedFromLDAP' => '1'
542
                            ));
543
                            $mappedGroupIDs[] = $mapping->GroupID;
544
                        }
545
                    }
546
547
                    // the user *might* be a member of a nested group provided the scope of the mapping
548
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
549
                    // to see if they are a member of one of those. If they are, add them to the SS group
550
                    if ($mapping->Scope == 'Subtree') {
551
                        $childGroups = $this->getNestedGroups($mapping->DN, array('dn'));
552
                        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...
553
                            continue;
554
                        }
555
556
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
557 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...
558
                                $group = $mapping->Group();
559
                                if ($group && $group->exists()) {
560
                                    $group->Members()->add($member, array(
561
                                        'IsImportedFromLDAP' => '1'
562
                                    ));
563
                                    $mappedGroupIDs[] = $mapping->GroupID;
564
                                }
565
                            }
566
                        }
567
                    }
568
                }
569
            }
570
        }
571
572
        // remove the user from any previously mapped groups, where the mapping has since been removed
573
        $groupRecords = DB::query(sprintf('SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s', $member->ID));
574
        foreach ($groupRecords as $groupRecord) {
575
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
576
                $group = Group::get()->byId($groupRecord['GroupID']);
577
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
578
                if ($group) {
579
                    $group->Members()->remove($member);
580
                }
581
            }
582
        }
583
        // This will throw an exception if there are two distinct GUIDs with the same email address.
584
        // We are happy with a raw 500 here at this stage.
585
        $member->write();
586
    }
587
588
    /**
589
     * Sync a specific Group by updating it with LDAP data.
590
     *
591
     * @param Group $group An existing Group or a new Group object
592
     * @param array $data LDAP group object data
593
     *
594
     * @return bool
595
     */
596
    public function updateGroupFromLDAP(Group $group, $data)
597
    {
598
        if (!$this->enabled()) {
599
            return false;
600
        }
601
602
        // Synchronise specific guaranteed fields.
603
        $group->Code = $data['samaccountname'];
604
        if (!empty($data['name'])) {
605
            $group->Title = $data['name'];
606
        } else {
607
            $group->Title = $data['samaccountname'];
608
        }
609
        if (!empty($data['description'])) {
610
            $group->Description = $data['description'];
611
        }
612
        $group->DN = $data['dn'];
613
        $group->LastSynced = (string)SS_Datetime::now();
614
        $group->write();
615
616
        // Mappings on this group are automatically maintained to contain just the group's DN.
617
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
618
        $hasCorrectMapping = false;
619
        foreach ($group->LDAPGroupMappings() as $mapping) {
620
            if ($mapping->DN === $data['dn']) {
621
                // This is the correct mapping we want to retain.
622
                $hasCorrectMapping = true;
623
            } else {
624
                $mapping->delete();
625
            }
626
        }
627
628
        // Second, if the main mapping was not found, add it in.
629
        if (!$hasCorrectMapping) {
630
            $mapping = new LDAPGroupMapping();
631
            $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...
632
            $mapping->write();
633
            $group->LDAPGroupMappings()->add($mapping);
634
        }
635
    }
636
637
    /**
638
     * Creates a new LDAP user from the passed Member record.
639
     * Note that the Member record must have a non-empty Username field for this to work.
640
     *
641
     * @param Member $member
642
     */
643
    public function createLDAPUser(Member $member)
644
    {
645
        if (!$this->enabled()) {
646
            return;
647
        }
648
        if (empty($member->Username)) {
649
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
650
        }
651
        if (!$this->config()->new_users_dn) {
652
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
653
        }
654
655
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
656
        $member->Username = strtolower($member->Username);
657
658
        // Create user in LDAP using available information.
659
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
660
661
        try {
662
            $this->add($dn, array(
663
                'objectclass' => 'user',
664
                'cn' => $member->Username,
665
                'accountexpires' => '9223372036854775807',
666
                'useraccountcontrol' => '66048',
667
                'userprincipalname' => sprintf(
668
                    '%s@%s',
669
                    $member->Username,
670
                    $this->gateway->config()->options['accountDomainName']
671
                ),
672
            ));
673
        } catch (\Exception $e) {
674
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
675
        }
676
677
        $user = $this->getUserByUsername($member->Username);
678
        if (empty($user['objectguid'])) {
679
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
680
        }
681
682
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
683
        $member->GUID = $user['objectguid'];
684
    }
685
686
    /**
687
     * Update the Member data back to the corresponding LDAP user object.
688
     *
689
     * @param Member $member
690
     * @throws ValidationException
691
     */
692
    public function updateLDAPFromMember(Member $member)
693
    {
694
        if (!$this->enabled()) {
695
            return;
696
        }
697
        if (!$member->GUID) {
698
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
699
        }
700
701
        $data = $this->getUserByGUID($member->GUID);
702
        if (empty($data['objectguid'])) {
703
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
704
        }
705
706
        if (empty($member->Username)) {
707
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
708
        }
709
710
        $dn = $data['distinguishedname'];
711
712
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
713
        $member->Username = strtolower($member->Username);
714
715
        try {
716
            // If the common name (cn) has changed, we need to ensure they've been moved
717
            // to the new DN, to avoid any clashes between user objects.
718
            if ($data['cn'] != $member->Username) {
719
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
720
                $this->move($dn, $newDn);
721
                $dn = $newDn;
722
            }
723
        } catch (\Exception $e) {
724
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
725
        }
726
727
        try {
728
            $attributes = array(
729
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
730
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
731
                'userprincipalname' => sprintf(
732
                    '%s@%s',
733
                    $member->Username,
734
                    $this->gateway->config()->options['accountDomainName']
735
                ),
736
            );
737
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
738
                $relationClass = $member->getRelationClass($field);
739
                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...
740
                    // todo no support for writing back relations yet.
741
                } else {
742
                    $attributes[$attribute] = $member->$field;
743
                }
744
            }
745
746
            $this->update($dn, $attributes);
747
        } catch (\Exception $e) {
748
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
749
        }
750
    }
751
752
    /**
753
     * Ensure the user belongs to the correct groups in LDAP from their membership
754
     * to local LDAP mapped SilverStripe groups.
755
     *
756
     * This also removes them from LDAP groups if they've been taken out of one.
757
     * It will not affect group membership of non-mapped groups, so it will
758
     * not touch such internal AD groups like "Domain Users".
759
     *
760
     * @param Member $member
761
     */
762
    public function updateLDAPGroupsForMember(Member $member)
763
    {
764
        if (!$this->enabled()) {
765
            return;
766
        }
767
        if (!$member->GUID) {
768
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
769
        }
770
771
        $addGroups = array();
772
        $removeGroups = array();
773
774
        $user = $this->getUserByGUID($member->GUID);
775
        if (empty($user['objectguid'])) {
776
            throw new ValidationException('LDAP update failure: user missing GUID');
777
        }
778
779
        // If a user belongs to a single group, this comes through as a string.
780
        // Normalise to a array so it's consistent.
781
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : array();
782
        if ($existingGroups && is_string($existingGroups)) {
783
            $existingGroups = array($existingGroups);
784
        }
785
786
        foreach ($member->Groups() as $group) {
787
            if (!$group->GUID) {
788
                continue;
789
            }
790
791
            // mark this group as something we need to ensure the user belongs to in LDAP.
792
            $addGroups[] = $group->DN;
793
        }
794
795
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
796
        // see if the user should be removed from any of them.
797
        $remainingGroups = array_diff($existingGroups, $addGroups);
798
799
        foreach ($remainingGroups as $groupDn) {
800
            // We only want to be removing groups we have a local Group mapped to. Removing
801
            // membership for anything else would be bad!
802
            $group = Group::get()->filter('DN', $groupDn)->first();
803
            if (!$group || !$group->exists()) {
804
                continue;
805
            }
806
807
            // this group should be removed from the user's memberof attribute, as it's been removed.
808
            $removeGroups[] = $groupDn;
809
        }
810
811
        // go through the groups we want the user to be in and ensure they're in them.
812
        foreach ($addGroups as $groupDn) {
813
            $members = $this->getLDAPGroupMembers($groupDn);
814
815
            // this user is already in the group, no need to do anything.
816
            if (in_array($user['distinguishedname'], $members)) {
817
                continue;
818
            }
819
820
            $members[] = $user['distinguishedname'];
821
822
            try {
823
                $this->update($groupDn, array('member' => $members));
824
            } catch (\Exception $e) {
825
                throw new ValidationException('LDAP group membership add failure: '.$e->getMessage());
826
            }
827
        }
828
829
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
830
        foreach ($removeGroups as $groupDn) {
831
            $members = $this->getLDAPGroupMembers($groupDn);
832
833
            // remove the user from the members data.
834
            if (in_array($user['distinguishedname'], $members)) {
835
                foreach ($members as $i => $dn) {
836
                    if ($dn == $user['distinguishedname']) {
837
                        unset($members[$i]);
838
                    }
839
                }
840
            }
841
842
            try {
843
                $this->update($groupDn, array('member' => $members));
844
            } catch (\Exception $e) {
845
                throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage());
846
            }
847
        }
848
    }
849
850
    /**
851
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
852
     * password in the `unicodePwd` attribute.
853
     *
854
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
855
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
856
     *
857
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
858
     *
859
     * @param Member $member
860
     * @param string $password
861
     * @return ValidationResult
862
     * @throws Exception
863
     */
864
    public function setPassword(Member $member, $password)
865
    {
866
        $validationResult = ValidationResult::create(true);
867
868
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
869
870
        if (!$member->GUID) {
871
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
872
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
873
            return $validationResult;
874
        }
875
876
        $userData = $this->getUserByGUID($member->GUID);
877
        if (empty($userData['distinguishedname'])) {
878
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
879
            return $validationResult;
880
        }
881
882
        try {
883
            $this->update(
884
                $userData['distinguishedname'],
885
                array('unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password)))
886
            );
887
888
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
889
        } catch (Exception $e) {
890
            // Try to parse the exception to get the error message to display to user, eg:
891
            // 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
892
            $pattern = '/^([^\s])*\s([^\;]*);\s([^\:]*):\s([^\:]*):\s([^\)]*)/i';
893
            if (preg_match($pattern, $e->getMessage(), $matches) && !empty($matches[5])) {
894
                $validationResult->error($matches[5]);
895
            } else {
896
                // Unparsable exception, an administrator should check the logs
897
                $validationResult->error(_t('LDAPAuthenticator.CANTCHANGEPASSWORD', 'We couldn\'t change your password, please contact an administrator.'));
898
            }
899
        }
900
901
        return $validationResult;
902
    }
903
904
    /**
905
     * Delete an LDAP user mapped to the Member record
906
     * @param Member $member
907
     */
908
    public function deleteLDAPMember(Member $member) {
909
        if (!$this->enabled()) {
910
            return;
911
        }
912
        if (!$member->GUID) {
913
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
914
        }
915
        $data = $this->getUserByGUID($member->GUID);
916
        if (empty($data['distinguishedname'])) {
917
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
918
        }
919
920
        try {
921
            $this->delete($data['distinguishedname']);
922
        } catch (\Exception $e) {
923
            throw new ValidationException('LDAP delete user failed: '.$e->getMessage());
924
        }
925
    }
926
927
    /**
928
     * A simple proxy to LDAP update operation.
929
     *
930
     * @param string $dn Location to add the entry at.
931
     * @param array $attributes A simple associative array of attributes.
932
     */
933
    public function update($dn, array $attributes)
934
    {
935
        $this->gateway->update($dn, $attributes);
936
    }
937
938
    /**
939
     * A simple proxy to LDAP delete operation.
940
     *
941
     * @param string $dn Location of object to delete
942
     * @param bool $recursively Recursively delete nested objects?
943
     */
944
    public function delete($dn, $recursively = false)
945
    {
946
        $this->gateway->delete($dn, $recursively);
947
    }
948
949
    /**
950
     * A simple proxy to LDAP copy/delete operation.
951
     *
952
     * @param string $fromDn
953
     * @param string $toDn
954
     * @param bool $recursively Recursively move nested objects?
955
     */
956
    public function move($fromDn, $toDn, $recursively = false)
957
    {
958
        $this->gateway->move($fromDn, $toDn, $recursively);
959
    }
960
961
    /**
962
     * A simple proxy to LDAP add operation.
963
     *
964
     * @param string $dn Location to add the entry at.
965
     * @param array $attributes A simple associative array of attributes.
966
     */
967
    public function add($dn, array $attributes)
968
    {
969
        $this->gateway->add($dn, $attributes);
970
    }
971
}
972