Completed
Pull Request — master (#64)
by Sean
03:38 queued 52s
created

LDAPService::enabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
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
        $member->IsImportedFromLDAP = true;
427
428
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
429
            if (!isset($data[$attribute])) {
430
                SS_Log::log(sprintf(
431
                    'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
432
                    $attribute,
433
                    $data['objectguid'],
434
                    $member->ID
435
                ), SS_Log::NOTICE);
436
437
                continue;
438
            }
439
440
            if ($attribute == 'thumbnailphoto') {
441
                $imageClass = $member->getRelationClass($field);
442
                if ($imageClass !== 'Image' && !is_subclass_of($imageClass, 'Image')) {
443
                    SS_Log::log(sprintf(
444
                        'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
445
                        $field
446
                    ), SS_Log::WARN);
447
448
                    continue;
449
                }
450
451
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
452
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
453
                $absPath = BASE_PATH . '/' . $path;
454
                if (!file_exists($absPath)) {
455
                    Filesystem::makeFolder($absPath);
456
                }
457
458
                // remove existing record if it exists
459
                $existingObj = $member->getComponent($field);
460
                if ($existingObj && $existingObj->exists()) {
461
                    $existingObj->delete();
462
                }
463
464
                // The image data is provided in raw binary.
465
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
466
                $record = new $imageClass();
467
                $record->Name = $filename;
468
                $record->Filename = $path . '/' . $filename;
469
                $record->write();
470
471
                $relationField = $field . 'ID';
472
                $member->{$relationField} = $record->ID;
473
            } else {
474
                $member->$field = $data[$attribute];
475
            }
476
        }
477
478
        // if a default group was configured, ensure the user is in that group
479
        if ($this->config()->default_group) {
480
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
481
            if (!($group && $group->exists())) {
482
                SS_Log::log(
483
                    sprintf(
484
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
485
                        $this->config()->default_group
486
                    ),
487
                    SS_Log::WARN
488
                );
489
            } else {
490
                $group->Members()->add($member, array(
491
                    'IsImportedFromLDAP' => '1'
492
                ));
493
            }
494
        }
495
496
        // this is to keep track of which groups the user gets mapped to
497
        // and we'll use that later to remove them from any groups that they're no longer mapped to
498
        $mappedGroupIDs = array();
499
500
        // ensure the user is in any mapped groups
501
        if (isset($data['memberof'])) {
502
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : array($data['memberof']);
503
            foreach ($ldapGroups as $groupDN) {
504
                foreach (LDAPGroupMapping::get() as $mapping) {
505
                    if (!$mapping->DN) {
506
                        SS_Log::log(
507
                            sprintf(
508
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
509
                                $mapping->ID
510
                            ),
511
                            SS_Log::WARN
512
                        );
513
                        continue;
514
                    }
515
516
                    // the user is a direct member of group with a mapping, add them to the SS group.
517 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...
518
                        $group = $mapping->Group();
519
                        if ($group && $group->exists()) {
520
                            $group->Members()->add($member, array(
521
                                'IsImportedFromLDAP' => '1'
522
                            ));
523
                            $mappedGroupIDs[] = $mapping->GroupID;
524
                        }
525
                    }
526
527
                    // the user *might* be a member of a nested group provided the scope of the mapping
528
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
529
                    // to see if they are a member of one of those. If they are, add them to the SS group
530
                    if ($mapping->Scope == 'Subtree') {
531
                        $childGroups = $this->getNestedGroups($mapping->DN, array('dn'));
532
                        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...
533
                            continue;
534
                        }
535
536
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
537 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...
538
                                $group = $mapping->Group();
539
                                if ($group && $group->exists()) {
540
                                    $group->Members()->add($member, array(
541
                                        'IsImportedFromLDAP' => '1'
542
                                    ));
543
                                    $mappedGroupIDs[] = $mapping->GroupID;
544
                                }
545
                            }
546
                        }
547
                    }
548
                }
549
            }
550
        }
551
552
        // remove the user from any previously mapped groups, where the mapping has since been removed
553
        $groupRecords = DB::query(sprintf('SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s', $member->ID));
554
        foreach ($groupRecords as $groupRecord) {
555
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
556
                $group = Group::get()->byId($groupRecord['GroupID']);
557
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
558
                if ($group) {
559
                    $group->Members()->remove($member);
560
                }
561
            }
562
        }
563
        // This will throw an exception if there are two distinct GUIDs with the same email address.
564
        // We are happy with a raw 500 here at this stage.
565
        $member->write();
566
    }
567
568
    /**
569
     * Sync a specific Group by updating it with LDAP data.
570
     *
571
     * @param Group $group An existing Group or a new Group object
572
     * @param array $data LDAP group object data
573
     *
574
     * @return bool
575
     */
576
    public function updateGroupFromLDAP(Group $group, $data)
577
    {
578
        if (!$this->enabled()) {
579
            return false;
580
        }
581
582
        // Synchronise specific guaranteed fields.
583
        $group->Code = $data['samaccountname'];
584
        if (!empty($data['name'])) {
585
            $group->Title = $data['name'];
586
        } else {
587
            $group->Title = $data['samaccountname'];
588
        }
589
        if (!empty($data['description'])) {
590
            $group->Description = $data['description'];
591
        }
592
        $group->DN = $data['dn'];
593
        $group->LastSynced = (string)SS_Datetime::now();
594
        $group->IsImportedFromLDAP = true;
595
        $group->write();
596
597
        // Mappings on this group are automatically maintained to contain just the group's DN.
598
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
599
        $hasCorrectMapping = false;
600
        foreach ($group->LDAPGroupMappings() as $mapping) {
601
            if ($mapping->DN === $data['dn']) {
602
                // This is the correct mapping we want to retain.
603
                $hasCorrectMapping = true;
604
            } else {
605
                $mapping->delete();
606
            }
607
        }
608
609
        // Second, if the main mapping was not found, add it in.
610
        if (!$hasCorrectMapping) {
611
            $mapping = new LDAPGroupMapping();
612
            $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...
613
            $mapping->write();
614
            $group->LDAPGroupMappings()->add($mapping);
615
        }
616
    }
617
618
    /**
619
     * Creates a new LDAP user from the passed Member record.
620
     *
621
     * @param Member $member
622
     */
623
    public function createLDAPUser(Member $member)
624
    {
625
        if (!$this->enabled()) {
626
            return;
627
        }
628
629
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
630
        $member->Username = strtolower($member->Username);
631
632
        // Create user in LDAP using available information.
633
        $dn = sprintf('CN=%s,%s', $member->Username, LDAP_NEW_USERS_DN);
634
635
        try {
636
            $this->add($dn, array(
637
                'objectclass' => 'user',
638
                'cn' => $member->Username,
639
                'instancetype' => '4',
640
                'codepage' => '0',
641
                'countrycode' => '0',
642
                'accountexpires' => '9223372036854775807',
643
                'userprincipalname' => sprintf('%s@%s', $member->Username, LDAP_DOMAIN),
644
                'objectcategory' => LDAP_NEW_USERS_OBJECT_CATEGORY,
645
                'useraccountcontrol' => '66048',
646
                'distinguishedname' => $dn,
647
            ));
648
        } catch (\Exception $e) {
649
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
650
        }
651
652
        $user = $this->getUserByUsername($member->Username);
653
        if (empty($user['objectguid'])) {
654
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
655
        }
656
657
        // Creation was successful, mark the user as synced with LDAP.
658
        $member->GUID = $user['objectguid'];
659
        $member->IsImportedFromLDAP = 1;
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->IsImportedFromLDAP) {
674
            return;
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
696
            $attributes = array(
697
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
698
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
699
                'userprincipalname' => sprintf('%s@%s', $member->Username, LDAP_DOMAIN),
700
            );
701
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
702
                $relationClass = $member->getRelationClass($field);
703
                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...
704
                    // todo no support for writing back relations yet.
705
                } else {
706
                    $attributes[$attribute] = $member->$field;
707
                }
708
            }
709
710
            $this->update($dn, $attributes);
711
        } catch (\Exception $e) {
712
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
713
        }
714
    }
715
716
    /**
717
     * Ensure the user belongs to the correct groups in LDAP from local LDAP mapped SilverStripe groups.
718
     * This is considered a reverse sync back to LDAP.
719
     *
720
     * This also removes them from LDAP groups if they've been taken out of one.
721
     * It will not affect group membership of non-mapped groups, so it will
722
     * not touch such internal AD groups like "Domain Users".
723
     *
724
     * @param Member $member
725
     */
726
    public function updateLDAPGroupsForMember(Member $member)
727
    {
728
        if (!$this->enabled()) {
729
            return;
730
        }
731
        if (!$member->IsImportedFromLDAP) {
732
            return;
733
        }
734
735
        $addGroups = array();
736
        $removeGroups = array();
737
738
        $user = $this->getUserByGUID($this->owner->GUID);
0 ignored issues
show
Bug introduced by
The property owner does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
739
        if (empty($user['objectguid'])) {
740
            throw new ValidationException('LDAP update failure: user missing GUID');
741
        }
742
743
        // If a user belongs to a single group, this comes through as a string.
744
        // Normalise to a array so it's consistent.
745
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : array();
746
        if ($existingGroups && is_string($existingGroups)) {
747
            $existingGroups = array($existingGroups);
748
        }
749
750
        foreach ($this->owner->Groups() as $group) {
751
            if (!$group->IsImportedFromLDAP) {
752
                continue;
753
            }
754
755
            // mark this group as something we need to ensure the user belongs to in LDAP.
756
            $addGroups[] = $group->DN;
757
        }
758
759
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
760
        // see if the user should be removed from any of them.
761
        $remainingGroups = array_diff($existingGroups, $addGroups);
762
763
        foreach ($remainingGroups as $groupDn) {
764
            // We only want to be removing groups we have a local Group mapped to. Removing
765
            // membership for anything else would be bad!
766
            $group = Group::get()->filter('DN', $groupDn)->first();
767
            if (!$group || !$group->exists()) {
768
                continue;
769
            }
770
771
            // this group should be removed from the user's memberof attribute, as it's been removed.
772
            $removeGroups[] = $groupDn;
773
        }
774
775
        // go through the groups we want the user to be in and ensure they're in them.
776
        foreach ($addGroups as $groupDn) {
777
            $members = $this->getLDAPGroupMembers($groupDn);
778
779
            // this user is already in the group, no need to do anything.
780
            if (in_array($user['distinguishedname'], $members)) {
781
                continue;
782
            }
783
784
            $members[] = $user['distinguishedname'];
785
786
            try {
787
                $this->update($groupDn, array('member' => $members));
788
            } catch (\Exception $e) {
789
                throw new ValidationException('LDAP group membership add failure: '.$e->getMessage());
790
            }
791
        }
792
793
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
794
        foreach ($removeGroups as $groupDn) {
795
            $members = $this->getLDAPGroupMembers($groupDn);
796
797
            // remove the user from the members data.
798
            if (in_array($user['distinguishedname'], $members)) {
799
                foreach ($members as $i => $dn) {
800
                    if ($dn == $user['distinguishedname']) {
801
                        unset($members[$i]);
802
                    }
803
                }
804
            }
805
806
            try {
807
                $this->update($groupDn, array('member' => $members));
808
            } catch (\Exception $e) {
809
                throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage());
810
            }
811
        }
812
    }
813
814
    /**
815
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
816
     * password in the `unicodePwd` attribute.
817
     *
818
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
819
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
820
     *
821
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
822
     *
823
     * @param Member $member
824
     * @param string $password
825
     * @return ValidationResult
826
     * @throws Exception
827
     */
828
    public function setPassword(Member $member, $password)
829
    {
830
        $validationResult = ValidationResult::create(true);
831
        if (!$member->GUID) {
832
            SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
833
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
834
            return $validationResult;
835
        }
836
837
        $userData = $this->getUserByGUID($member->GUID);
838
        if (empty($userData['distinguishedname'])) {
839
            $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
840
            return $validationResult;
841
        }
842
843
        try {
844
            $this->update(
845
                $userData['distinguishedname'],
846
                array('unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password)))
847
            );
848
        } catch (Exception $e) {
849
            // Try to parse the exception to get the error message to display to user, eg:
850
            // 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
851
            $pattern = '/^([^\s])*\s([^\;]*);\s([^\:]*):\s([^\:]*):\s([^\)]*)/i';
852
            if (preg_match($pattern, $e->getMessage(), $matches) && !empty($matches[5])) {
853
                $validationResult->error($matches[5]);
854
            } else {
855
                // Unparsable exception, an administrator should check the logs
856
                $validationResult->error(_t('LDAPAuthenticator.CANTCHANGEPASSWORD', 'We couldn\'t change your password, please contact an administrator.'));
857
            }
858
        }
859
860
        return $validationResult;
861
    }
862
863
    /**
864
     * A simple proxy to LDAP update operation.
865
     *
866
     * @param string $dn Location to add the entry at.
867
     * @param array $attributes A simple associative array of attributes.
868
     */
869
    public function update($dn, array $attributes)
870
    {
871
        $this->gateway->update($dn, $attributes);
872
    }
873
874
    /**
875
     * A simple proxy to LDAP delete operation.
876
     *
877
     * @param string $dn Location of object to delete
878
     * @param bool $recursively Recursively delete nested objects?
879
     */
880
    public function delete($dn, $recursively = false)
881
    {
882
        $this->gateway->delete($dn, $recursively);
883
    }
884
885
    /**
886
     * A simple proxy to LDAP copy/delete operation.
887
     *
888
     * @param string $fromDn
889
     * @param string $toDn
890
     * @param bool $recursively Recursively move nested objects?
891
     */
892
    public function move($fromDn, $toDn, $recursively = false)
893
    {
894
        $this->gateway->move($fromDn, $toDn, $recursively);
895
    }
896
897
    /**
898
     * A simple proxy to LDAP add operation.
899
     *
900
     * @param string $dn Location to add the entry at.
901
     * @param array $attributes A simple associative array of attributes.
902
     */
903
    public function add($dn, array $attributes)
904
    {
905
        $this->gateway->add($dn, $attributes);
906
    }
907
}
908