Completed
Push — master ( 5670a0...79a44e )
by Stig
11s
created

LDAPService::createLDAPUser()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 39
rs 8.439
cc 5
eloc 23
nc 5
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
     * @var array
42
     */
43
    private static $_cache_nested_groups = array();
44
45
    /**
46
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
47
     * be added to this group's membership when imported, regardless of any sort of group mappings.
48
     *
49
     * @var string
50
     * @config
51
     */
52
    private static $default_group;
0 ignored issues
show
Unused Code introduced by
The property $default_group is not used and could be removed.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
348
                return $records[0];
349
            }
350
        }
351
    }
352
353
    /**
354
     * Get a username for an email.
355
     *
356
     * @param string $email
357
     * @return string|null
358
     */
359
    public function getUsernameByEmail($email)
360
    {
361
        $data = $this->getUserByEmail($email);
362
        if (empty($data)) {
363
            return null;
364
        }
365
366
        return $this->gateway->getCanonicalUsername($data);
367
    }
368
369
    /**
370
     * Given a group DN, get the group membership data in LDAP.
371
     *
372
     * @param string $dn
373
     * @return array
374
     */
375
    public function getLDAPGroupMembers($dn)
376
    {
377
        if (!$this->enabled()) {
378
            return;
379
        }
380
381
        $groupObj = Group::get()->filter('DN', $dn)->first();
382
        $groupData = $this->getGroupByGUID($groupObj->GUID);
383
        $members = !empty($groupData['member']) ? $groupData['member'] : array();
384
        // If a user belongs to a single group, this comes through as a string.
385
        // Normalise to a array so it's consistent.
386
        if ($members && is_string($members)) {
387
            $members = array($members);
388
        }
389
390
        return $members;
391
    }
392
393
    /**
394
     * Update the current Member record with data from LDAP.
395
     *
396
     * Constraints:
397
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
398
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
399
     *
400
     * @param Member
401
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
402
     *            If not given, the data will be looked up by the user's GUID.
403
     * @return bool
404
     */
405
    public function updateMemberFromLDAP(Member $member, $data = null)
406
    {
407
        if (!$this->enabled()) {
408
            return false;
409
        }
410
411
        if (!$member->GUID) {
412
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
413
            return false;
414
        }
415
416
        if (!$data) {
417
            $data = $this->getUserByGUID($member->GUID);
418
            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...
419
                SS_Log::log(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID), SS_Log::WARN);
420
                return false;
421
            }
422
        }
423
424
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
425
        $member->LastSynced = (string)SS_Datetime::now();
426
427
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
428
            if (!isset($data[$attribute])) {
429
                SS_Log::log(sprintf(
430
                    'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
431
                    $attribute,
432
                    $data['objectguid'],
433
                    $member->ID
434
                ), SS_Log::NOTICE);
435
436
                continue;
437
            }
438
439
            if ($attribute == 'thumbnailphoto') {
440
                $imageClass = $member->getRelationClass($field);
441
                if ($imageClass !== 'Image' && !is_subclass_of($imageClass, 'Image')) {
442
                    SS_Log::log(sprintf(
443
                        'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
444
                        $field
445
                    ), SS_Log::WARN);
446
447
                    continue;
448
                }
449
450
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
451
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
452
                $absPath = BASE_PATH . '/' . $path;
453
                if (!file_exists($absPath)) {
454
                    Filesystem::makeFolder($absPath);
455
                }
456
457
                // remove existing record if it exists
458
                $existingObj = $member->getComponent($field);
459
                if ($existingObj && $existingObj->exists()) {
460
                    $existingObj->delete();
461
                }
462
463
                // The image data is provided in raw binary.
464
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
465
                $record = new $imageClass();
466
                $record->Name = $filename;
467
                $record->Filename = $path . '/' . $filename;
468
                $record->write();
469
470
                $relationField = $field . 'ID';
471
                $member->{$relationField} = $record->ID;
472
            } else {
473
                $member->$field = $data[$attribute];
474
            }
475
        }
476
477
        // if a default group was configured, ensure the user is in that group
478
        if ($this->config()->default_group) {
479
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
480
            if (!($group && $group->exists())) {
481
                SS_Log::log(
482
                    sprintf(
483
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
484
                        $this->config()->default_group
485
                    ),
486
                    SS_Log::WARN
487
                );
488
            } else {
489
                $group->Members()->add($member, array(
490
                    'IsImportedFromLDAP' => '1'
491
                ));
492
            }
493
        }
494
495
        // this is to keep track of which groups the user gets mapped to
496
        // and we'll use that later to remove them from any groups that they're no longer mapped to
497
        $mappedGroupIDs = array();
498
499
        // ensure the user is in any mapped groups
500
        if (isset($data['memberof'])) {
501
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : array($data['memberof']);
502
            foreach ($ldapGroups as $groupDN) {
503
                foreach (LDAPGroupMapping::get() as $mapping) {
504
                    if (!$mapping->DN) {
505
                        SS_Log::log(
506
                            sprintf(
507
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
508
                                $mapping->ID
509
                            ),
510
                            SS_Log::WARN
511
                        );
512
                        continue;
513
                    }
514
515
                    // the user is a direct member of group with a mapping, add them to the SS group.
516 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...
517
                        $group = $mapping->Group();
518
                        if ($group && $group->exists()) {
519
                            $group->Members()->add($member, array(
520
                                'IsImportedFromLDAP' => '1'
521
                            ));
522
                            $mappedGroupIDs[] = $mapping->GroupID;
523
                        }
524
                    }
525
526
                    // the user *might* be a member of a nested group provided the scope of the mapping
527
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
528
                    // to see if they are a member of one of those. If they are, add them to the SS group
529
                    if ($mapping->Scope == 'Subtree') {
530
                        $childGroups = $this->getNestedGroups($mapping->DN, array('dn'));
531
                        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...
532
                            continue;
533
                        }
534
535
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
536 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...
537
                                $group = $mapping->Group();
538
                                if ($group && $group->exists()) {
539
                                    $group->Members()->add($member, array(
540
                                        'IsImportedFromLDAP' => '1'
541
                                    ));
542
                                    $mappedGroupIDs[] = $mapping->GroupID;
543
                                }
544
                            }
545
                        }
546
                    }
547
                }
548
            }
549
        }
550
551
        // remove the user from any previously mapped groups, where the mapping has since been removed
552
        $groupRecords = DB::query(sprintf('SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s', $member->ID));
553
        foreach ($groupRecords as $groupRecord) {
554
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
555
                $group = Group::get()->byId($groupRecord['GroupID']);
556
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
557
                if ($group) {
558
                    $group->Members()->remove($member);
559
                }
560
            }
561
        }
562
        // This will throw an exception if there are two distinct GUIDs with the same email address.
563
        // We are happy with a raw 500 here at this stage.
564
        $member->write();
565
    }
566
567
    /**
568
     * Sync a specific Group by updating it with LDAP data.
569
     *
570
     * @param Group $group An existing Group or a new Group object
571
     * @param array $data LDAP group object data
572
     *
573
     * @return bool
574
     */
575
    public function updateGroupFromLDAP(Group $group, $data)
576
    {
577
        if (!$this->enabled()) {
578
            return false;
579
        }
580
581
        // Synchronise specific guaranteed fields.
582
        $group->Code = $data['samaccountname'];
583
        if (!empty($data['name'])) {
584
            $group->Title = $data['name'];
585
        } else {
586
            $group->Title = $data['samaccountname'];
587
        }
588
        if (!empty($data['description'])) {
589
            $group->Description = $data['description'];
590
        }
591
        $group->DN = $data['dn'];
592
        $group->LastSynced = (string)SS_Datetime::now();
593
        $group->write();
594
595
        // Mappings on this group are automatically maintained to contain just the group's DN.
596
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
597
        $hasCorrectMapping = false;
598
        foreach ($group->LDAPGroupMappings() as $mapping) {
599
            if ($mapping->DN === $data['dn']) {
600
                // This is the correct mapping we want to retain.
601
                $hasCorrectMapping = true;
602
            } else {
603
                $mapping->delete();
604
            }
605
        }
606
607
        // Second, if the main mapping was not found, add it in.
608
        if (!$hasCorrectMapping) {
609
            $mapping = new LDAPGroupMapping();
610
            $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...
611
            $mapping->write();
612
            $group->LDAPGroupMappings()->add($mapping);
613
        }
614
    }
615
616
    /**
617
     * Creates a new LDAP user from the passed Member record.
618
     * Note that the Member record must have a non-empty Username field for this to work.
619
     *
620
     * @param Member $member
621
     */
622
    public function createLDAPUser(Member $member)
623
    {
624
        if (!$this->enabled()) {
625
            return;
626
        }
627
        if (empty($member->Username)) {
628
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
629
        }
630
631
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
632
        $member->Username = strtolower($member->Username);
633
634
        // Create user in LDAP using available information.
635
        $dn = sprintf('CN=%s,%s', $member->Username, LDAP_NEW_USERS_DN);
636
637
        try {
638
            $this->add($dn, array(
639
                'objectclass' => 'user',
640
                'cn' => $member->Username,
641
                'accountexpires' => '9223372036854775807',
642
                'useraccountcontrol' => '66048',
643
                'userprincipalname' => sprintf(
644
                    '%s@%s',
645
                    $member->Username,
646
                    $this->gateway->config()->options['accountDomainName']
647
                ),
648
            ));
649
        } catch (\Exception $e) {
650
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
651
        }
652
653
        $user = $this->getUserByUsername($member->Username);
654
        if (empty($user['objectguid'])) {
655
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
656
        }
657
658
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
659
        $member->GUID = $user['objectguid'];
660
    }
661
662
    /**
663
     * Update the Member data back to the corresponding LDAP user object.
664
     *
665
     * @param Member $member
666
     * @throws ValidationException
667
     */
668
    public function updateLDAPFromMember(Member $member)
669
    {
670
        if (!$this->enabled()) {
671
            return;
672
        }
673
        if (!$member->GUID) {
674
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
675
        }
676
677
        $data = $this->getUserByGUID($member->GUID);
678
        if (empty($data['objectguid'])) {
679
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
680
        }
681
682
        $dn = $data['distinguishedname'];
683
684
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
685
        $member->Username = strtolower($member->Username);
686
687
        try {
688
            // If the common name (cn) has changed, we need to ensure they've been moved
689
            // to the new DN, to avoid any clashes between user objects.
690
            if ($data['cn'] != $member->Username) {
691
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
692
                $this->move($dn, $newDn);
693
                $dn = $newDn;
694
            }
695
        } catch (\Exception $e) {
696
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
697
        }
698
699
        try {
700
            $attributes = array(
701
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
702
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
703
                'userprincipalname' => sprintf(
704
                    '%s@%s',
705
                    $member->Username,
706
                    $this->gateway->config()->options['accountDomainName']
707
                ),
708
            );
709
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
710
                $relationClass = $member->getRelationClass($field);
711
                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...
712
                    // todo no support for writing back relations yet.
713
                } else {
714
                    $attributes[$attribute] = $member->$field;
715
                }
716
            }
717
718
            $this->update($dn, $attributes);
719
        } catch (\Exception $e) {
720
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
721
        }
722
    }
723
724
    /**
725
     * Ensure the user belongs to the correct groups in LDAP from their membership
726
     * to local LDAP mapped SilverStripe groups.
727
     *
728
     * This also removes them from LDAP groups if they've been taken out of one.
729
     * It will not affect group membership of non-mapped groups, so it will
730
     * not touch such internal AD groups like "Domain Users".
731
     *
732
     * @param Member $member
733
     */
734
    public function updateLDAPGroupsForMember(Member $member)
735
    {
736
        if (!$this->enabled()) {
737
            return;
738
        }
739
        if (!$member->GUID) {
740
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
741
        }
742
743
        $addGroups = array();
744
        $removeGroups = array();
745
746
        $user = $this->getUserByGUID($member->GUID);
747
        if (empty($user['objectguid'])) {
748
            throw new ValidationException('LDAP update failure: user missing GUID');
749
        }
750
751
        // If a user belongs to a single group, this comes through as a string.
752
        // Normalise to a array so it's consistent.
753
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : array();
754
        if ($existingGroups && is_string($existingGroups)) {
755
            $existingGroups = array($existingGroups);
756
        }
757
758
        foreach ($member->Groups() as $group) {
759
            if (!$group->GUID) {
760
                continue;
761
            }
762
763
            // mark this group as something we need to ensure the user belongs to in LDAP.
764
            $addGroups[] = $group->DN;
765
        }
766
767
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
768
        // see if the user should be removed from any of them.
769
        $remainingGroups = array_diff($existingGroups, $addGroups);
770
771
        foreach ($remainingGroups as $groupDn) {
772
            // We only want to be removing groups we have a local Group mapped to. Removing
773
            // membership for anything else would be bad!
774
            $group = Group::get()->filter('DN', $groupDn)->first();
775
            if (!$group || !$group->exists()) {
776
                continue;
777
            }
778
779
            // this group should be removed from the user's memberof attribute, as it's been removed.
780
            $removeGroups[] = $groupDn;
781
        }
782
783
        // go through the groups we want the user to be in and ensure they're in them.
784
        foreach ($addGroups as $groupDn) {
785
            $members = $this->getLDAPGroupMembers($groupDn);
786
787
            // this user is already in the group, no need to do anything.
788
            if (in_array($user['distinguishedname'], $members)) {
789
                continue;
790
            }
791
792
            $members[] = $user['distinguishedname'];
793
794
            try {
795
                $this->update($groupDn, array('member' => $members));
796
            } catch (\Exception $e) {
797
                throw new ValidationException('LDAP group membership add failure: '.$e->getMessage());
798
            }
799
        }
800
801
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
802
        foreach ($removeGroups as $groupDn) {
803
            $members = $this->getLDAPGroupMembers($groupDn);
804
805
            // remove the user from the members data.
806
            if (in_array($user['distinguishedname'], $members)) {
807
                foreach ($members as $i => $dn) {
808
                    if ($dn == $user['distinguishedname']) {
809
                        unset($members[$i]);
810
                    }
811
                }
812
            }
813
814
            try {
815
                $this->update($groupDn, array('member' => $members));
816
            } catch (\Exception $e) {
817
                throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage());
818
            }
819
        }
820
    }
821
822
    /**
823
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
824
     * password in the `unicodePwd` attribute.
825
     *
826
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
827
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
828
     *
829
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
830
     *
831
     * @param Member $member
832
     * @param string $password
833
     * @return ValidationResult
834
     * @throws Exception
835
     */
836
    public function setPassword(Member $member, $password)
837
    {
838
        $validationResult = ValidationResult::create(true);
839
        if (!$member->GUID) {
840
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
841
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
842
            return $validationResult;
843
        }
844
845
        $userData = $this->getUserByGUID($member->GUID);
846
        if (empty($userData['distinguishedname'])) {
847
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
848
            return $validationResult;
849
        }
850
851
        try {
852
            $this->update(
853
                $userData['distinguishedname'],
854
                array('unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password)))
855
            );
856
        } catch (Exception $e) {
857
            // Try to parse the exception to get the error message to display to user, eg:
858
            // 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
859
            $pattern = '/^([^\s])*\s([^\;]*);\s([^\:]*):\s([^\:]*):\s([^\)]*)/i';
860
            if (preg_match($pattern, $e->getMessage(), $matches) && !empty($matches[5])) {
861
                $validationResult->error($matches[5]);
862
            } else {
863
                // Unparsable exception, an administrator should check the logs
864
                $validationResult->error(_t('LDAPAuthenticator.CANTCHANGEPASSWORD', 'We couldn\'t change your password, please contact an administrator.'));
865
            }
866
        }
867
868
        return $validationResult;
869
    }
870
871
    /**
872
     * Delete an LDAP user mapped to the Member record
873
     * @param Member $member
874
     */
875
    public function deleteLDAPMember(Member $member) {
876
        if (!$this->enabled()) {
877
            return;
878
        }
879
        if (!$member->GUID) {
880
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
881
        }
882
        $data = $this->getUserByGUID($member->GUID);
883
        if (empty($data['distinguishedname'])) {
884
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
885
        }
886
887
        try {
888
            $this->delete($data['distinguishedname']);
889
        } catch (\Exception $e) {
890
            throw new ValidationException('LDAP delete user failed: '.$e->getMessage());
891
        }
892
    }
893
894
    /**
895
     * A simple proxy to LDAP update operation.
896
     *
897
     * @param string $dn Location to add the entry at.
898
     * @param array $attributes A simple associative array of attributes.
899
     */
900
    public function update($dn, array $attributes)
901
    {
902
        $this->gateway->update($dn, $attributes);
903
    }
904
905
    /**
906
     * A simple proxy to LDAP delete operation.
907
     *
908
     * @param string $dn Location of object to delete
909
     * @param bool $recursively Recursively delete nested objects?
910
     */
911
    public function delete($dn, $recursively = false)
912
    {
913
        $this->gateway->delete($dn, $recursively);
914
    }
915
916
    /**
917
     * A simple proxy to LDAP copy/delete operation.
918
     *
919
     * @param string $fromDn
920
     * @param string $toDn
921
     * @param bool $recursively Recursively move nested objects?
922
     */
923
    public function move($fromDn, $toDn, $recursively = false)
924
    {
925
        $this->gateway->move($fromDn, $toDn, $recursively);
926
    }
927
928
    /**
929
     * A simple proxy to LDAP add operation.
930
     *
931
     * @param string $dn Location to add the entry at.
932
     * @param array $attributes A simple associative array of attributes.
933
     */
934
    public function add($dn, array $attributes)
935
    {
936
        $this->gateway->add($dn, $attributes);
937
    }
938
}
939