Completed
Pull Request — master (#73)
by Sean
02:15
created

LDAPService::getUsernameByEmail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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