Member::inGroup()   B
last analyzed

Complexity

Conditions 9
Paths 22

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 17
nc 22
nop 2
dl 0
loc 28
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Security;
4
5
use IntlDateFormatter;
6
use InvalidArgumentException;
7
use SilverStripe\Admin\LeftAndMain;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use SilverStripe\CMS\Controllers\CMSMain;
0 ignored issues
show
Bug introduced by
The type SilverStripe\CMS\Controllers\CMSMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use SilverStripe\Control\Controller;
10
use SilverStripe\Control\Director;
11
use SilverStripe\Control\Email\Email;
12
use SilverStripe\Control\Email\Mailer;
13
use SilverStripe\Control\HTTPRequest;
14
use SilverStripe\Core\Config\Config;
15
use SilverStripe\Core\Convert;
16
use SilverStripe\Core\Injector\Injector;
17
use SilverStripe\Dev\Deprecation;
18
use SilverStripe\Dev\TestMailer;
19
use SilverStripe\Forms\ConfirmedPasswordField;
20
use SilverStripe\Forms\DropdownField;
21
use SilverStripe\Forms\FieldList;
22
use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig;
23
use SilverStripe\Forms\ListboxField;
24
use SilverStripe\Forms\Tab;
25
use SilverStripe\Forms\TabSet;
26
use SilverStripe\i18n\i18n;
27
use SilverStripe\ORM\ArrayList;
28
use SilverStripe\ORM\DataList;
29
use SilverStripe\ORM\DataObject;
30
use SilverStripe\ORM\DB;
31
use SilverStripe\ORM\FieldType\DBDatetime;
32
use SilverStripe\ORM\HasManyList;
33
use SilverStripe\ORM\ManyManyList;
34
use SilverStripe\ORM\Map;
35
use SilverStripe\ORM\SS_List;
36
use SilverStripe\ORM\UnsavedRelationList;
37
use SilverStripe\ORM\ValidationException;
38
use SilverStripe\ORM\ValidationResult;
39
40
/**
41
 * The member class which represents the users of the system
42
 *
43
 * @method HasManyList LoggedPasswords()
44
 * @method HasManyList RememberLoginHashes()
45
 * @property string $FirstName
46
 * @property string $Surname
47
 * @property string $Email
48
 * @property string $Password
49
 * @property string $TempIDHash
50
 * @property string $TempIDExpired
51
 * @property string $AutoLoginHash
52
 * @property string $AutoLoginExpired
53
 * @property string $PasswordEncryption
54
 * @property string $Salt
55
 * @property string $PasswordExpiry
56
 * @property string $LockedOutUntil
57
 * @property string $Locale
58
 * @property int $FailedLoginCount
59
 * @property string $DateFormat
60
 * @property string $TimeFormat
61
 */
62
class Member extends DataObject
63
{
64
    private static $db = array(
65
        'FirstName' => 'Varchar',
66
        'Surname' => 'Varchar',
67
        'Email' => 'Varchar(254)', // See RFC 5321, Section 4.5.3.1.3. (256 minus the < and > character)
68
        'TempIDHash' => 'Varchar(160)', // Temporary id used for cms re-authentication
69
        'TempIDExpired' => 'Datetime', // Expiry of temp login
70
        'Password' => 'Varchar(160)',
71
        'AutoLoginHash' => 'Varchar(160)', // Used to auto-login the user on password reset
72
        'AutoLoginExpired' => 'Datetime',
73
        // This is an arbitrary code pointing to a PasswordEncryptor instance,
74
        // not an actual encryption algorithm.
75
        // Warning: Never change this field after its the first password hashing without
76
        // providing a new cleartext password as well.
77
        'PasswordEncryption' => "Varchar(50)",
78
        'Salt' => 'Varchar(50)',
79
        'PasswordExpiry' => 'Date',
80
        'LockedOutUntil' => 'Datetime',
81
        'Locale' => 'Varchar(6)',
82
        // handled in registerFailedLogin(), only used if $lock_out_after_incorrect_logins is set
83
        'FailedLoginCount' => 'Int',
84
    );
85
86
    private static $belongs_many_many = array(
87
        'Groups' => Group::class,
88
    );
89
90
    private static $has_many = array(
91
        'LoggedPasswords' => MemberPassword::class,
92
        'RememberLoginHashes' => RememberLoginHash::class,
93
    );
94
95
    private static $table_name = "Member";
96
97
    private static $default_sort = '"Surname", "FirstName"';
98
99
    private static $indexes = array(
100
        'Email' => true,
101
        //Removed due to duplicate null values causing MSSQL problems
102
        //'AutoLoginHash' => Array('type'=>'unique', 'value'=>'AutoLoginHash', 'ignoreNulls'=>true)
103
    );
104
105
    /**
106
     * @config
107
     * @var boolean
108
     */
109
    private static $notify_password_change = false;
110
111
    /**
112
     * All searchable database columns
113
     * in this object, currently queried
114
     * with a "column LIKE '%keywords%'
115
     * statement.
116
     *
117
     * @var array
118
     * @todo Generic implementation of $searchable_fields on DataObject,
119
     * with definition for different searching algorithms
120
     * (LIKE, FULLTEXT) and default FormFields to construct a searchform.
121
     */
122
    private static $searchable_fields = array(
123
        'FirstName',
124
        'Surname',
125
        'Email',
126
    );
127
128
    /**
129
     * @config
130
     * @var array
131
     */
132
    private static $summary_fields = array(
133
        'FirstName',
134
        'Surname',
135
        'Email',
136
    );
137
138
    /**
139
     * @config
140
     * @var array
141
     */
142
    private static $casting = array(
143
        'Name' => 'Varchar',
144
    );
145
146
    /**
147
     * Internal-use only fields
148
     *
149
     * @config
150
     * @var array
151
     */
152
    private static $hidden_fields = array(
153
        'AutoLoginHash',
154
        'AutoLoginExpired',
155
        'PasswordEncryption',
156
        'PasswordExpiry',
157
        'LockedOutUntil',
158
        'TempIDHash',
159
        'TempIDExpired',
160
        'Salt',
161
    );
162
163
    /**
164
     * @config
165
     * @var array See {@link set_title_columns()}
166
     */
167
    private static $title_format = null;
168
169
    /**
170
     * The unique field used to identify this member.
171
     * By default, it's "Email", but another common
172
     * field could be Username.
173
     *
174
     * @config
175
     * @var string
176
     * @skipUpgrade
177
     */
178
    private static $unique_identifier_field = 'Email';
179
180
    /**
181
     * @config
182
     * The number of days that a password should be valid for.
183
     * By default, this is null, which means that passwords never expire
184
     */
185
    private static $password_expiry_days = null;
186
187
    /**
188
     * @config
189
     * @var bool enable or disable logging of previously used passwords. See {@link onAfterWrite}
190
     */
191
    private static $password_logging_enabled = true;
192
193
    /**
194
     * @config
195
     * @var Int Number of incorrect logins after which
196
     * the user is blocked from further attempts for the timespan
197
     * defined in {@link $lock_out_delay_mins}.
198
     */
199
    private static $lock_out_after_incorrect_logins = 10;
200
201
    /**
202
     * @config
203
     * @var integer Minutes of enforced lockout after incorrect password attempts.
204
     * Only applies if {@link $lock_out_after_incorrect_logins} greater than 0.
205
     */
206
    private static $lock_out_delay_mins = 15;
207
208
    /**
209
     * @config
210
     * @var String If this is set, then a session cookie with the given name will be set on log-in,
211
     * and cleared on logout.
212
     */
213
    private static $login_marker_cookie = null;
214
215
    /**
216
     * Indicates that when a {@link Member} logs in, Member:session_regenerate_id()
217
     * should be called as a security precaution.
218
     *
219
     * This doesn't always work, especially if you're trying to set session cookies
220
     * across an entire site using the domain parameter to session_set_cookie_params()
221
     *
222
     * @config
223
     * @var boolean
224
     */
225
    private static $session_regenerate_id = true;
226
227
228
    /**
229
     * Default lifetime of temporary ids.
230
     *
231
     * This is the period within which a user can be re-authenticated within the CMS by entering only their password
232
     * and without losing their workspace.
233
     *
234
     * Any session expiration outside of this time will require them to login from the frontend using their full
235
     * username and password.
236
     *
237
     * Defaults to 72 hours. Set to zero to disable expiration.
238
     *
239
     * @config
240
     * @var int Lifetime in seconds
241
     */
242
    private static $temp_id_lifetime = 259200;
243
244
    /**
245
     * Default lifetime of auto login token.
246
     *
247
     * This is the maximum allowed period between a user requesting a password reset link and using it to reset
248
     * their password.
249
     *
250
     * Defaults to 2 days.
251
     *
252
     * @config
253
     * @var int Lifetime in seconds
254
     */
255
    private static $auto_login_token_lifetime = 172800;
256
257
    /**
258
     * Used to track whether {@link Member::changePassword} has made changed that need to be written. Used to prevent
259
     * the write from calling changePassword again.
260
     *
261
     * @var bool
262
     */
263
    protected $passwordChangesToWrite = false;
264
265
    /**
266
     * Ensure the locale is set to something sensible by default.
267
     */
268
    public function populateDefaults()
269
    {
270
        parent::populateDefaults();
271
        $this->Locale = i18n::config()->get('default_locale');
272
    }
273
274
    public function requireDefaultRecords()
275
    {
276
        parent::requireDefaultRecords();
277
        // Default groups should've been built by Group->requireDefaultRecords() already
278
        $service = DefaultAdminService::singleton();
279
        $service->findOrCreateDefaultAdmin();
280
    }
281
282
    /**
283
     * Get the default admin record if it exists, or creates it otherwise if enabled
284
     *
285
     * @deprecated 4.0.0:5.0.0 Use DefaultAdminService::findOrCreateDefaultAdmin() instead
286
     * @return Member
287
     */
288
    public static function default_admin()
289
    {
290
        Deprecation::notice('5.0', 'Use DefaultAdminService::findOrCreateDefaultAdmin() instead');
291
        return DefaultAdminService::singleton()->findOrCreateDefaultAdmin();
292
    }
293
294
    /**
295
     * Check if the passed password matches the stored one (if the member is not locked out).
296
     *
297
     * @deprecated 4.0.0:5.0.0 Use Authenticator::checkPassword() instead
298
     *
299
     * @param  string $password
300
     * @return ValidationResult
301
     */
302
    public function checkPassword($password)
303
    {
304
        Deprecation::notice('5.0', 'Use Authenticator::checkPassword() instead');
305
306
        // With a valid user and password, check the password is correct
307
        $result = ValidationResult::create();
308
        $authenticators = Security::singleton()->getApplicableAuthenticators(Authenticator::CHECK_PASSWORD);
309
        foreach ($authenticators as $authenticator) {
310
            $authenticator->checkPassword($this, $password, $result);
311
            if (!$result->isValid()) {
312
                break;
313
            }
314
        }
315
        return $result;
316
    }
317
318
    /**
319
     * Check if this user is the currently configured default admin
320
     *
321
     * @return bool
322
     */
323
    public function isDefaultAdmin()
324
    {
325
        return DefaultAdminService::isDefaultAdmin($this->Email);
326
    }
327
328
    /**
329
     * Check if this user can login
330
     *
331
     * @return bool
332
     */
333
    public function canLogin()
334
    {
335
        return $this->validateCanLogin()->isValid();
336
    }
337
338
    /**
339
     * Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid
340
     * one with error messages to display if the member is locked out.
341
     *
342
     * You can hook into this with a "canLogIn" method on an attached extension.
343
     *
344
     * @param ValidationResult $result Optional result to add errors to
345
     * @return ValidationResult
346
     */
347
    public function validateCanLogin(ValidationResult &$result = null)
348
    {
349
        $result = $result ?: ValidationResult::create();
350
        if ($this->isLockedOut()) {
351
            $result->addError(
352
                _t(
353
                    __CLASS__ . '.ERRORLOCKEDOUT2',
354
                    'Your account has been temporarily disabled because of too many failed attempts at '
355
                    . 'logging in. Please try again in {count} minutes.',
356
                    null,
357
                    ['count' => static::config()->get('lock_out_delay_mins')]
358
                )
359
            );
360
        }
361
362
        $this->extend('canLogIn', $result);
363
364
        return $result;
365
    }
366
367
    /**
368
     * Returns true if this user is locked out
369
     *
370
     * @skipUpgrade
371
     * @return bool
372
     */
373
    public function isLockedOut()
374
    {
375
        /** @var DBDatetime $lockedOutUntilObj */
376
        $lockedOutUntilObj = $this->dbObject('LockedOutUntil');
377
        if ($lockedOutUntilObj->InFuture()) {
378
            return true;
379
        }
380
381
        $maxAttempts = $this->config()->get('lock_out_after_incorrect_logins');
382
        if ($maxAttempts <= 0) {
383
            return false;
384
        }
385
386
        $idField = static::config()->get('unique_identifier_field');
387
        $attempts = LoginAttempt::getByEmail($this->{$idField})
388
            ->sort('Created', 'DESC')
389
            ->limit($maxAttempts);
390
391
        if ($attempts->count() < $maxAttempts) {
392
            return false;
393
        }
394
395
        foreach ($attempts as $attempt) {
396
            if ($attempt->Status === 'Success') {
0 ignored issues
show
Bug Best Practice introduced by
The property Status does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
397
                return false;
398
            }
399
        }
400
401
        // Calculate effective LockedOutUntil
402
        /** @var DBDatetime $firstFailureDate */
403
        $firstFailureDate = $attempts->first()->dbObject('Created');
404
        $maxAgeSeconds = $this->config()->get('lock_out_delay_mins') * 60;
405
        $lockedOutUntil = $firstFailureDate->getTimestamp() + $maxAgeSeconds;
406
        $now = DBDatetime::now()->getTimestamp();
407
        if ($now < $lockedOutUntil) {
408
            return true;
409
        }
410
411
        return false;
412
    }
413
414
    /**
415
     * Set a {@link PasswordValidator} object to use to validate member's passwords.
416
     *
417
     * @param PasswordValidator $validator
418
     */
419
    public static function set_password_validator(PasswordValidator $validator = null)
420
    {
421
        // Override existing config
422
        Config::modify()->remove(Injector::class, PasswordValidator::class);
423
        if ($validator) {
424
            Injector::inst()->registerService($validator, PasswordValidator::class);
425
        } else {
426
            Injector::inst()->unregisterNamedObject(PasswordValidator::class);
427
        }
428
    }
429
430
    /**
431
     * Returns the default {@link PasswordValidator}
432
     *
433
     * @return PasswordValidator
434
     */
435
    public static function password_validator()
436
    {
437
        if (Injector::inst()->has(PasswordValidator::class)) {
438
            return Injector::inst()->get(PasswordValidator::class);
439
        }
440
        return null;
441
    }
442
443
    public function isPasswordExpired()
444
    {
445
        if (!$this->PasswordExpiry) {
446
            return false;
447
        }
448
449
        return strtotime(date('Y-m-d')) >= strtotime($this->PasswordExpiry);
450
    }
451
452
    /**
453
     * @deprecated 5.0.0 Use Security::setCurrentUser() or IdentityStore::logIn()
454
     *
455
     */
456
    public function logIn()
457
    {
458
        Deprecation::notice(
459
            '5.0.0',
460
            'This method is deprecated and only logs in for the current request. Please use '
461
            . 'Security::setCurrentUser($user) or an IdentityStore'
462
        );
463
        Security::setCurrentUser($this);
464
    }
465
466
    /**
467
     * Called before a member is logged in via session/cookie/etc
468
     */
469
    public function beforeMemberLoggedIn()
470
    {
471
        // @todo Move to middleware on the AuthenticationMiddleware IdentityStore
472
        $this->extend('beforeMemberLoggedIn');
473
    }
474
475
    /**
476
     * Called after a member is logged in via session/cookie/etc
477
     */
478
    public function afterMemberLoggedIn()
479
    {
480
        // Clear the incorrect log-in count
481
        $this->registerSuccessfulLogin();
482
483
        $this->LockedOutUntil = null;
484
485
        $this->regenerateTempID();
486
487
        $this->write();
488
489
        // Audit logging hook
490
        $this->extend('afterMemberLoggedIn');
491
    }
492
493
    /**
494
     * Trigger regeneration of TempID.
495
     *
496
     * This should be performed any time the user presents their normal identification (normally Email)
497
     * and is successfully authenticated.
498
     */
499
    public function regenerateTempID()
500
    {
501
        $generator = new RandomGenerator();
502
        $lifetime = self::config()->get('temp_id_lifetime');
503
        $this->TempIDHash = $generator->randomToken('sha1');
504
        $this->TempIDExpired = $lifetime
505
            ? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime)
506
            : null;
507
        $this->write();
508
    }
509
510
    /**
511
     * Check if the member ID logged in session actually
512
     * has a database record of the same ID. If there is
513
     * no logged in user, FALSE is returned anyway.
514
     *
515
     * @deprecated Not needed anymore, as it returns Security::getCurrentUser();
516
     *
517
     * @return boolean TRUE record found FALSE no record found
518
     */
519
    public static function logged_in_session_exists()
520
    {
521
        Deprecation::notice(
522
            '5.0.0',
523
            'This method is deprecated and now does not add value. Please use Security::getCurrentUser()'
524
        );
525
526
        $member = Security::getCurrentUser();
527
        if ($member && $member->exists()) {
528
            return true;
529
        }
530
531
        return false;
532
    }
533
534
    /**
535
     * @deprecated Use Security::setCurrentUser(null) or an IdentityStore
536
     * Logs this member out.
537
     */
538
    public function logOut()
539
    {
540
        Deprecation::notice(
541
            '5.0.0',
542
            'This method is deprecated and now does not persist. Please use '
543
            . 'Security::setCurrentUser(null) or an IdentityStore'
544
        );
545
546
        Injector::inst()->get(IdentityStore::class)->logOut(Controller::curr()->getRequest());
547
    }
548
549
    /**
550
     * Audit logging hook, called before a member is logged out
551
     *
552
     * @param HTTPRequest|null $request
553
     */
554
    public function beforeMemberLoggedOut(HTTPRequest $request = null)
555
    {
556
        $this->extend('beforeMemberLoggedOut', $request);
557
    }
558
559
    /**
560
     * Audit logging hook, called after a member is logged out
561
     *
562
     * @param HTTPRequest|null $request
563
     */
564
    public function afterMemberLoggedOut(HTTPRequest $request = null)
565
    {
566
        $this->extend('afterMemberLoggedOut', $request);
567
    }
568
569
    /**
570
     * Utility for generating secure password hashes for this member.
571
     *
572
     * @param string $string
573
     * @return string
574
     * @throws PasswordEncryptor_NotFoundException
575
     */
576
    public function encryptWithUserSettings($string)
577
    {
578
        if (!$string) {
579
            return null;
580
        }
581
582
        // If the algorithm or salt is not available, it means we are operating
583
        // on legacy account with unhashed password. Do not hash the string.
584
        if (!$this->PasswordEncryption) {
585
            return $string;
586
        }
587
588
        // We assume we have PasswordEncryption and Salt available here.
589
        $e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption);
590
591
        return $e->encrypt($string, $this->Salt);
592
    }
593
594
    /**
595
     * Generate an auto login token which can be used to reset the password,
596
     * at the same time hashing it and storing in the database.
597
     *
598
     * @param int|null $lifetime DEPRECATED: The lifetime of the auto login hash in days. Overrides
599
     *                           the Member.auto_login_token_lifetime config value
600
     * @return string Token that should be passed to the client (but NOT persisted).
601
     */
602
    public function generateAutologinTokenAndStoreHash($lifetime = null)
603
    {
604
        if ($lifetime !== null) {
605
            Deprecation::notice(
606
                '5.0',
607
                'Passing a $lifetime to Member::generateAutologinTokenAndStoreHash() is deprecated,
608
                    use the Member.auto_login_token_lifetime config setting instead',
609
                Deprecation::SCOPE_GLOBAL
610
            );
611
            $lifetime = (86400 * $lifetime); // Method argument is days, convert to seconds
612
        } else {
613
            $lifetime = $this->config()->auto_login_token_lifetime;
0 ignored issues
show
Bug Best Practice introduced by
The property auto_login_token_lifetime does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
614
        }
615
616
        do {
617
            $generator = new RandomGenerator();
618
            $token = $generator->randomToken();
619
            $hash = $this->encryptWithUserSettings($token);
620
        } while (DataObject::get_one(Member::class, array(
621
            '"Member"."AutoLoginHash"' => $hash
622
        )));
623
624
        $this->AutoLoginHash = $hash;
625
        $this->AutoLoginExpired = date('Y-m-d H:i:s', time() + $lifetime);
626
627
        $this->write();
628
629
        return $token;
630
    }
631
632
    /**
633
     * Check the token against the member.
634
     *
635
     * @param string $autologinToken
636
     *
637
     * @returns bool Is token valid?
638
     */
639
    public function validateAutoLoginToken($autologinToken)
640
    {
641
        $hash = $this->encryptWithUserSettings($autologinToken);
642
        $member = self::member_from_autologinhash($hash, false);
643
644
        return (bool)$member;
645
    }
646
647
    /**
648
     * Return the member for the auto login hash
649
     *
650
     * @param string $hash The hash key
651
     * @param bool $login Should the member be logged in?
652
     *
653
     * @return Member the matching member, if valid
654
     * @return Member
655
     */
656
    public static function member_from_autologinhash($hash, $login = false)
657
    {
658
        /** @var Member $member */
659
        $member = static::get()->filter([
660
            'AutoLoginHash' => $hash,
661
            'AutoLoginExpired:GreaterThan' => DBDatetime::now()->getValue(),
662
        ])->first();
663
664
        if ($login && $member) {
665
            Injector::inst()->get(IdentityStore::class)->logIn($member);
666
        }
667
668
        return $member;
669
    }
670
671
    /**
672
     * Find a member record with the given TempIDHash value
673
     *
674
     * @param string $tempid
675
     * @return Member
676
     */
677
    public static function member_from_tempid($tempid)
678
    {
679
        $members = static::get()
680
            ->filter('TempIDHash', $tempid);
681
682
        // Exclude expired
683
        if (static::config()->get('temp_id_lifetime')) {
684
            /** @var DataList|Member[] $members */
685
            $members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue());
686
        }
687
688
        return $members->first();
689
    }
690
691
    /**
692
     * Returns the fields for the member form - used in the registration/profile module.
693
     * It should return fields that are editable by the admin and the logged-in user.
694
     *
695
     * @todo possibly move this to an extension
696
     *
697
     * @return FieldList Returns a {@link FieldList} containing the fields for
698
     *                   the member form.
699
     */
700
    public function getMemberFormFields()
701
    {
702
        $fields = parent::getFrontEndFields();
703
704
        $fields->replaceField('Password', $this->getMemberPasswordField());
705
706
        $fields->replaceField('Locale', new DropdownField(
707
            'Locale',
708
            $this->fieldLabel('Locale'),
709
            i18n::getSources()->getKnownLocales()
710
        ));
711
712
        $fields->removeByName(static::config()->get('hidden_fields'));
713
        $fields->removeByName('FailedLoginCount');
714
715
716
        $this->extend('updateMemberFormFields', $fields);
717
718
        return $fields;
719
    }
720
721
    /**
722
     * Builds "Change / Create Password" field for this member
723
     *
724
     * @return ConfirmedPasswordField
725
     */
726
    public function getMemberPasswordField()
727
    {
728
        $editingPassword = $this->isInDB();
729
        $label = $editingPassword
730
            ? _t(__CLASS__ . '.EDIT_PASSWORD', 'New Password')
731
            : $this->fieldLabel('Password');
732
        /** @var ConfirmedPasswordField $password */
733
        $password = ConfirmedPasswordField::create(
734
            'Password',
735
            $label,
736
            null,
737
            null,
738
            $editingPassword
739
        );
740
741
        // If editing own password, require confirmation of existing
742
        if ($editingPassword && $this->ID == Security::getCurrentUser()->ID) {
743
            $password->setRequireExistingPassword(true);
744
        }
745
746
        $password->setCanBeEmpty(true);
747
        $this->extend('updateMemberPasswordField', $password);
748
749
        return $password;
750
    }
751
752
753
    /**
754
     * Returns the {@link RequiredFields} instance for the Member object. This
755
     * Validator is used when saving a {@link CMSProfileController} or added to
756
     * any form responsible for saving a users data.
757
     *
758
     * To customize the required fields, add a {@link DataExtension} to member
759
     * calling the `updateValidator()` method.
760
     *
761
     * @return Member_Validator
762
     */
763
    public function getValidator()
764
    {
765
        $validator = Member_Validator::create();
766
        $validator->setForMember($this);
767
        $this->extend('updateValidator', $validator);
768
769
        return $validator;
770
    }
771
772
773
    /**
774
     * Returns the current logged in user
775
     *
776
     * @deprecated 5.0.0 use Security::getCurrentUser()
777
     *
778
     * @return Member
779
     */
780
    public static function currentUser()
781
    {
782
        Deprecation::notice(
783
            '5.0.0',
784
            'This method is deprecated. Please use Security::getCurrentUser() or an IdentityStore'
785
        );
786
787
        return Security::getCurrentUser();
788
    }
789
790
    /**
791
     * Temporarily act as the specified user, limited to a $callback, but
792
     * without logging in as that user.
793
     *
794
     * E.g.
795
     * <code>
796
     * Member::actAs(Security::findAnAdministrator(), function() {
797
     *     $record->write();
798
     * });
799
     * </code>
800
     *
801
     * @param Member|null|int $member Member or member ID to log in as.
802
     * Set to null or 0 to act as a logged out user.
803
     * @param callable $callback
804
     * @return mixed Result of $callback
805
     */
806
    public static function actAs($member, $callback)
807
    {
808
        $previousUser = Security::getCurrentUser();
809
810
        // Transform ID to member
811
        if (is_numeric($member)) {
812
            $member = DataObject::get_by_id(Member::class, $member);
813
        }
814
        Security::setCurrentUser($member);
815
816
        try {
817
            return $callback();
818
        } finally {
819
            Security::setCurrentUser($previousUser);
820
        }
821
    }
822
823
    /**
824
     * Get the ID of the current logged in user
825
     *
826
     * @deprecated 5.0.0 use Security::getCurrentUser()
827
     *
828
     * @return int Returns the ID of the current logged in user or 0.
829
     */
830
    public static function currentUserID()
831
    {
832
        Deprecation::notice(
833
            '5.0.0',
834
            'This method is deprecated. Please use Security::getCurrentUser() or an IdentityStore'
835
        );
836
837
        $member = Security::getCurrentUser();
838
        if ($member) {
0 ignored issues
show
introduced by
$member is of type SilverStripe\Security\Member, thus it always evaluated to true.
Loading history...
839
            return $member->ID;
840
        }
841
        return 0;
842
    }
843
844
    /**
845
     * Generate a random password, with randomiser to kick in if there's no words file on the
846
     * filesystem.
847
     *
848
     * @return string Returns a random password.
849
     */
850
    public static function create_new_password()
851
    {
852
        $words = Security::config()->uninherited('word_list');
853
854
        if ($words && file_exists($words)) {
855
            $words = file($words);
856
857
            list($usec, $sec) = explode(' ', microtime());
858
            mt_srand($sec + ((float)$usec * 100000));
0 ignored issues
show
Bug introduced by
$sec + (double)$usec * 100000 of type double is incompatible with the type integer expected by parameter $seed of mt_srand(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

858
            mt_srand(/** @scrutinizer ignore-type */ $sec + ((float)$usec * 100000));
Loading history...
859
860
            $word = trim($words[random_int(0, count($words) - 1)]);
0 ignored issues
show
Bug introduced by
It seems like $words can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

860
            $word = trim($words[random_int(0, count(/** @scrutinizer ignore-type */ $words) - 1)]);
Loading history...
861
            $number = random_int(10, 999);
862
863
            return $word . $number;
864
        } else {
865
            $random = mt_rand();
866
            $string = md5($random);
867
            $output = substr($string, 0, 8);
868
869
            return $output;
870
        }
871
    }
872
873
    /**
874
     * Event handler called before writing to the database.
875
     */
876
    public function onBeforeWrite()
877
    {
878
        // If a member with the same "unique identifier" already exists with a different ID, don't allow merging.
879
        // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form),
880
        // but rather a last line of defense against data inconsistencies.
881
        $identifierField = Member::config()->get('unique_identifier_field');
882
        if ($this->$identifierField) {
883
            // Note: Same logic as Member_Validator class
884
            $filter = [
885
                "\"Member\".\"$identifierField\"" => $this->$identifierField
886
            ];
887
            if ($this->ID) {
888
                $filter[] = array('"Member"."ID" <> ?' => $this->ID);
889
            }
890
            $existingRecord = DataObject::get_one(Member::class, $filter);
891
892
            if ($existingRecord) {
893
                throw new ValidationException(_t(
894
                    __CLASS__ . '.ValidationIdentifierFailed',
895
                    'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))',
896
                    'Values in brackets show "fieldname = value", usually denoting an existing email address',
897
                    array(
898
                        'id' => $existingRecord->ID,
899
                        'name' => $identifierField,
900
                        'value' => $this->$identifierField
901
                    )
902
                ));
903
            }
904
        }
905
906
        // We don't send emails out on dev/tests sites to prevent accidentally spamming users.
907
        // However, if TestMailer is in use this isn't a risk.
908
        // @todo some developers use external tools, so emailing might be a good idea anyway
909
        if ((Director::isLive() || Injector::inst()->get(Mailer::class) instanceof TestMailer)
910
            && $this->isChanged('Password')
911
            && $this->record['Password']
912
            && static::config()->get('notify_password_change')
913
            && $this->isInDB()
914
        ) {
915
            Email::create()
916
                ->setHTMLTemplate('SilverStripe\\Control\\Email\\ChangePasswordEmail')
917
                ->setData($this)
918
                ->setTo($this->Email)
919
                ->setSubject(_t(
920
                    __CLASS__ . '.SUBJECTPASSWORDCHANGED',
921
                    "Your password has been changed",
922
                    'Email subject'
923
                ))
924
                ->send();
925
        }
926
927
        // The test on $this->ID is used for when records are initially created. Note that this only works with
928
        // cleartext passwords, as we can't rehash existing passwords.
929
        if (!$this->ID || $this->isChanged('Password')) {
930
            $this->encryptPassword();
931
        }
932
933
        // save locale
934
        if (!$this->Locale) {
935
            $this->Locale = i18n::config()->get('default_locale');
936
        }
937
938
        parent::onBeforeWrite();
939
    }
940
941
    public function onAfterWrite()
942
    {
943
        parent::onAfterWrite();
944
945
        Permission::reset();
946
947
        if ($this->isChanged('Password') && static::config()->get('password_logging_enabled')) {
948
            MemberPassword::log($this);
949
        }
950
    }
951
952
    public function onAfterDelete()
953
    {
954
        parent::onAfterDelete();
955
956
        // prevent orphaned records remaining in the DB
957
        $this->deletePasswordLogs();
958
        $this->Groups()->removeAll();
959
    }
960
961
    /**
962
     * Delete the MemberPassword objects that are associated to this user
963
     *
964
     * @return $this
965
     */
966
    protected function deletePasswordLogs()
967
    {
968
        foreach ($this->LoggedPasswords() as $password) {
969
            $password->delete();
970
            $password->destroy();
971
        }
972
973
        return $this;
974
    }
975
976
    /**
977
     * Filter out admin groups to avoid privilege escalation,
978
     * If any admin groups are requested, deny the whole save operation.
979
     *
980
     * @param array $ids Database IDs of Group records
981
     * @return bool True if the change can be accepted
982
     */
983
    public function onChangeGroups($ids)
984
    {
985
        // Ensure none of these match disallowed list
986
        $disallowedGroupIDs = $this->disallowedGroups();
987
        return count(array_intersect($ids, $disallowedGroupIDs)) == 0;
988
    }
989
990
    /**
991
     * List of group IDs this user is disallowed from
992
     *
993
     * @return int[] List of group IDs
994
     */
995
    protected function disallowedGroups()
996
    {
997
        // unless the current user is an admin already OR the logged in user is an admin
998
        if (Permission::check('ADMIN') || Permission::checkMember($this, 'ADMIN')) {
999
            return [];
1000
        }
1001
1002
        // Non-admins may not belong to admin groups
1003
        return Permission::get_groups_by_permission('ADMIN')->column('ID');
1004
    }
1005
1006
1007
    /**
1008
     * Check if the member is in one of the given groups.
1009
     *
1010
     * @param array|SS_List $groups Collection of {@link Group} DataObjects to check
1011
     * @param boolean $strict Only determine direct group membership if set to true (Default: false)
1012
     * @return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE.
1013
     */
1014
    public function inGroups($groups, $strict = false)
1015
    {
1016
        if ($groups) {
1017
            foreach ($groups as $group) {
1018
                if ($this->inGroup($group, $strict)) {
1019
                    return true;
1020
                }
1021
            }
1022
        }
1023
1024
        return false;
1025
    }
1026
1027
1028
    /**
1029
     * Check if the member is in the given group or any parent groups.
1030
     *
1031
     * @param int|Group|string $group Group instance, Group Code or ID
1032
     * @param boolean $strict Only determine direct group membership if set to TRUE (Default: FALSE)
1033
     * @return bool Returns TRUE if the member is in the given group, otherwise FALSE.
1034
     */
1035
    public function inGroup($group, $strict = false)
1036
    {
1037
        if (is_numeric($group)) {
1038
            $groupCheckObj = DataObject::get_by_id(Group::class, $group);
0 ignored issues
show
Bug introduced by
It seems like $group can also be of type string; however, parameter $idOrCache of SilverStripe\ORM\DataObject::get_by_id() does only seem to accept boolean|integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1038
            $groupCheckObj = DataObject::get_by_id(Group::class, /** @scrutinizer ignore-type */ $group);
Loading history...
1039
        } elseif (is_string($group)) {
1040
            $groupCheckObj = DataObject::get_one(Group::class, array(
1041
                '"Group"."Code"' => $group
1042
            ));
1043
        } elseif ($group instanceof Group) {
0 ignored issues
show
introduced by
$group is always a sub-type of SilverStripe\Security\Group.
Loading history...
1044
            $groupCheckObj = $group;
1045
        } else {
1046
            throw new InvalidArgumentException('Member::inGroup(): Wrong format for $group parameter');
1047
        }
1048
1049
        if (!$groupCheckObj) {
1050
            return false;
1051
        }
1052
1053
        $groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups();
1054
        if ($groupCandidateObjs) {
1055
            foreach ($groupCandidateObjs as $groupCandidateObj) {
1056
                if ($groupCandidateObj->ID == $groupCheckObj->ID) {
1057
                    return true;
1058
                }
1059
            }
1060
        }
1061
1062
        return false;
1063
    }
1064
1065
    /**
1066
     * Adds the member to a group. This will create the group if the given
1067
     * group code does not return a valid group object.
1068
     *
1069
     * @param string $groupcode
1070
     * @param string $title Title of the group
1071
     */
1072
    public function addToGroupByCode($groupcode, $title = "")
1073
    {
1074
        $group = DataObject::get_one(Group::class, array(
1075
            '"Group"."Code"' => $groupcode
1076
        ));
1077
1078
        if ($group) {
1079
            $this->Groups()->add($group);
1080
        } else {
1081
            if (!$title) {
1082
                $title = $groupcode;
1083
            }
1084
1085
            $group = new Group();
1086
            $group->Code = $groupcode;
1087
            $group->Title = $title;
1088
            $group->write();
1089
1090
            $this->Groups()->add($group);
1091
        }
1092
    }
1093
1094
    /**
1095
     * Removes a member from a group.
1096
     *
1097
     * @param string $groupcode
1098
     */
1099
    public function removeFromGroupByCode($groupcode)
1100
    {
1101
        $group = Group::get()->filter(array('Code' => $groupcode))->first();
1102
1103
        if ($group) {
0 ignored issues
show
introduced by
$group is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
1104
            $this->Groups()->remove($group);
1105
        }
1106
    }
1107
1108
    /**
1109
     * @param array $columns Column names on the Member record to show in {@link getTitle()}.
1110
     * @param String $sep Separator
1111
     */
1112
    public static function set_title_columns($columns, $sep = ' ')
1113
    {
1114
        Deprecation::notice('5.0', 'Use Member.title_format config instead');
1115
        if (!is_array($columns)) {
0 ignored issues
show
introduced by
The condition is_array($columns) is always true.
Loading history...
1116
            $columns = array($columns);
1117
        }
1118
        self::config()->set(
1119
            'title_format',
1120
            [
1121
                'columns' => $columns,
1122
                'sep' => $sep
1123
            ]
1124
        );
1125
    }
1126
1127
    //------------------- HELPER METHODS -----------------------------------//
1128
1129
    /**
1130
     * Simple proxy method to get the Surname property of the member
1131
     *
1132
     * @return string
1133
     */
1134
    public function getLastName()
1135
    {
1136
        return $this->Surname;
1137
    }
1138
1139
    /**
1140
     * Get the complete name of the member, by default in the format "<Surname>, <FirstName>".
1141
     * Falls back to showing either field on its own.
1142
     *
1143
     * You can overload this getter with {@link set_title_format()}
1144
     * and {@link set_title_sql()}.
1145
     *
1146
     * @return string Returns the first- and surname of the member. If the ID
1147
     *  of the member is equal 0, only the surname is returned.
1148
     */
1149
    public function getTitle()
1150
    {
1151
        $format = static::config()->get('title_format');
1152
        if ($format) {
1153
            $values = array();
1154
            foreach ($format['columns'] as $col) {
1155
                $values[] = $this->getField($col);
1156
            }
1157
1158
            return implode($format['sep'], $values);
1159
        }
1160
        if ($this->getField('ID') === 0) {
1161
            return $this->getField('Surname');
1162
        } else {
1163
            if ($this->getField('Surname') && $this->getField('FirstName')) {
1164
                return $this->getField('Surname') . ', ' . $this->getField('FirstName');
1165
            } elseif ($this->getField('Surname')) {
1166
                return $this->getField('Surname');
1167
            } elseif ($this->getField('FirstName')) {
1168
                return $this->getField('FirstName');
1169
            } else {
1170
                return null;
1171
            }
1172
        }
1173
    }
1174
1175
    /**
1176
     * Return a SQL CONCAT() fragment suitable for a SELECT statement.
1177
     * Useful for custom queries which assume a certain member title format.
1178
     *
1179
     * @return String SQL
1180
     */
1181
    public static function get_title_sql()
1182
    {
1183
1184
        // Get title_format with fallback to default
1185
        $format = static::config()->get('title_format');
1186
        if (!$format) {
1187
            $format = [
1188
                'columns' => ['Surname', 'FirstName'],
1189
                'sep' => ' ',
1190
            ];
1191
        }
1192
1193
        $columnsWithTablename = array();
1194
        foreach ($format['columns'] as $column) {
1195
            $columnsWithTablename[] = static::getSchema()->sqlColumnForField(__CLASS__, $column);
1196
        }
1197
1198
        $sepSQL = Convert::raw2sql($format['sep'], true);
1199
        $op = DB::get_conn()->concatOperator();
1200
        return "(" . join(" $op $sepSQL $op ", $columnsWithTablename) . ")";
1201
    }
1202
1203
1204
    /**
1205
     * Get the complete name of the member
1206
     *
1207
     * @return string Returns the first- and surname of the member.
1208
     */
1209
    public function getName()
1210
    {
1211
        return ($this->Surname) ? trim($this->FirstName . ' ' . $this->Surname) : $this->FirstName;
1212
    }
1213
1214
1215
    /**
1216
     * Set first- and surname
1217
     *
1218
     * This method assumes that the last part of the name is the surname, e.g.
1219
     * <i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i>
1220
     *
1221
     * @param string $name The name
1222
     */
1223
    public function setName($name)
1224
    {
1225
        $nameParts = explode(' ', $name);
1226
        $this->Surname = array_pop($nameParts);
1227
        $this->FirstName = join(' ', $nameParts);
1228
    }
1229
1230
1231
    /**
1232
     * Alias for {@link setName}
1233
     *
1234
     * @param string $name The name
1235
     * @see setName()
1236
     */
1237
    public function splitName($name)
1238
    {
1239
        return $this->setName($name);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->setName($name) targeting SilverStripe\Security\Member::setName() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1240
    }
1241
1242
    /**
1243
     * Return the date format based on the user's chosen locale,
1244
     * falling back to the default format defined by the i18n::config()->get('default_locale') config setting.
1245
     *
1246
     * @return string ISO date format
1247
     */
1248
    public function getDateFormat()
1249
    {
1250
        $formatter = new IntlDateFormatter(
1251
            $this->getLocale(),
1252
            IntlDateFormatter::MEDIUM,
1253
            IntlDateFormatter::NONE
1254
        );
1255
        $format = $formatter->getPattern();
1256
1257
        $this->extend('updateDateFormat', $format);
1258
1259
        return $format;
1260
    }
1261
1262
    /**
1263
     * Get user locale, falling back to the configured default locale
1264
     */
1265
    public function getLocale()
1266
    {
1267
        $locale = $this->getField('Locale');
1268
        if ($locale) {
1269
            return $locale;
1270
        }
1271
1272
        return i18n::config()->get('default_locale');
1273
    }
1274
1275
    /**
1276
     * Return the time format based on the user's chosen locale,
1277
     * falling back to the default format defined by the i18n::config()->get('default_locale') config setting.
1278
     *
1279
     * @return string ISO date format
1280
     */
1281
    public function getTimeFormat()
1282
    {
1283
        $formatter = new IntlDateFormatter(
1284
            $this->getLocale(),
1285
            IntlDateFormatter::NONE,
1286
            IntlDateFormatter::MEDIUM
1287
        );
1288
        $format = $formatter->getPattern();
1289
1290
        $this->extend('updateTimeFormat', $format);
1291
1292
        return $format;
1293
    }
1294
1295
    //---------------------------------------------------------------------//
1296
1297
1298
    /**
1299
     * Get a "many-to-many" map that holds for all members their group memberships,
1300
     * including any parent groups where membership is implied.
1301
     * Use {@link DirectGroups()} to only retrieve the group relations without inheritance.
1302
     *
1303
     * @todo Push all this logic into Member_GroupSet's getIterator()?
1304
     * @return Member_Groupset
1305
     */
1306
    public function Groups()
1307
    {
1308
        $groups = Member_GroupSet::create(Group::class, 'Group_Members', 'GroupID', 'MemberID');
1309
        $groups = $groups->forForeignID($this->ID);
1310
1311
        $this->extend('updateGroups', $groups);
1312
1313
        return $groups;
1314
    }
1315
1316
    /**
1317
     * @return ManyManyList|UnsavedRelationList
1318
     */
1319
    public function DirectGroups()
1320
    {
1321
        return $this->getManyManyComponents('Groups');
1322
    }
1323
1324
    /**
1325
     * Get a member SQLMap of members in specific groups
1326
     *
1327
     * If no $groups is passed, all members will be returned
1328
     *
1329
     * @param mixed $groups - takes a SS_List, an array or a single Group.ID
1330
     * @return Map Returns an Map that returns all Member data.
1331
     */
1332
    public static function map_in_groups($groups = null)
1333
    {
1334
        $groupIDList = array();
1335
1336
        if ($groups instanceof SS_List) {
1337
            foreach ($groups as $group) {
1338
                $groupIDList[] = $group->ID;
1339
            }
1340
        } elseif (is_array($groups)) {
1341
            $groupIDList = $groups;
1342
        } elseif ($groups) {
1343
            $groupIDList[] = $groups;
1344
        }
1345
1346
        // No groups, return all Members
1347
        if (!$groupIDList) {
1348
            return static::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map();
1349
        }
1350
1351
        $membersList = new ArrayList();
1352
        // This is a bit ineffective, but follow the ORM style
1353
        /** @var Group $group */
1354
        foreach (Group::get()->byIDs($groupIDList) as $group) {
1355
            $membersList->merge($group->Members());
0 ignored issues
show
Bug introduced by
The method Members() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1355
            $membersList->merge($group->/** @scrutinizer ignore-call */ Members());
Loading history...
1356
        }
1357
1358
        $membersList->removeDuplicates('ID');
1359
1360
        return $membersList->map();
1361
    }
1362
1363
1364
    /**
1365
     * Get a map of all members in the groups given that have CMS permissions
1366
     *
1367
     * If no groups are passed, all groups with CMS permissions will be used.
1368
     *
1369
     * @param array $groups Groups to consider or NULL to use all groups with
1370
     *                      CMS permissions.
1371
     * @return Map Returns a map of all members in the groups given that
1372
     *                have CMS permissions.
1373
     */
1374
    public static function mapInCMSGroups($groups = null)
1375
    {
1376
        // non-countable $groups will issue a warning when using count() in PHP 7.2+
1377
        if (!$groups) {
1378
            $groups = [];
1379
        }
1380
1381
        // Check CMS module exists
1382
        if (!class_exists(LeftAndMain::class)) {
1383
            return ArrayList::create()->map();
1384
        }
1385
1386
        if (count($groups) == 0) {
1387
            $perms = array('ADMIN', 'CMS_ACCESS_AssetAdmin');
1388
1389
            if (class_exists(CMSMain::class)) {
1390
                $cmsPerms = CMSMain::singleton()->providePermissions();
1391
            } else {
1392
                $cmsPerms = LeftAndMain::singleton()->providePermissions();
1393
            }
1394
1395
            if (!empty($cmsPerms)) {
1396
                $perms = array_unique(array_merge($perms, array_keys($cmsPerms)));
1397
            }
1398
1399
            $permsClause = DB::placeholders($perms);
1400
            /** @skipUpgrade */
1401
            $groups = Group::get()
1402
                ->innerJoin("Permission", '"Permission"."GroupID" = "Group"."ID"')
1403
                ->where(array(
1404
                    "\"Permission\".\"Code\" IN ($permsClause)" => $perms
1405
                ));
1406
        }
1407
1408
        $groupIDList = array();
1409
1410
        if ($groups instanceof SS_List) {
1411
            foreach ($groups as $group) {
1412
                $groupIDList[] = $group->ID;
1413
            }
1414
        } elseif (is_array($groups)) {
0 ignored issues
show
introduced by
The condition is_array($groups) is always true.
Loading history...
1415
            $groupIDList = $groups;
1416
        }
1417
1418
        /** @skipUpgrade */
1419
        $members = static::get()
1420
            ->innerJoin("Group_Members", '"Group_Members"."MemberID" = "Member"."ID"')
1421
            ->innerJoin("Group", '"Group"."ID" = "Group_Members"."GroupID"');
1422
        if ($groupIDList) {
1423
            $groupClause = DB::placeholders($groupIDList);
1424
            $members = $members->where(array(
1425
                "\"Group\".\"ID\" IN ($groupClause)" => $groupIDList
1426
            ));
1427
        }
1428
1429
        return $members->sort('"Member"."Surname", "Member"."FirstName"')->map();
1430
    }
1431
1432
1433
    /**
1434
     * Get the groups in which the member is NOT in
1435
     *
1436
     * When passed an array of groups, and a component set of groups, this
1437
     * function will return the array of groups the member is NOT in.
1438
     *
1439
     * @param array $groupList An array of group code names.
1440
     * @param array $memberGroups A component set of groups (if set to NULL,
1441
     *                            $this->groups() will be used)
1442
     * @return array Groups in which the member is NOT in.
1443
     */
1444
    public function memberNotInGroups($groupList, $memberGroups = null)
1445
    {
1446
        if (!$memberGroups) {
1447
            $memberGroups = $this->Groups();
1448
        }
1449
1450
        foreach ($memberGroups as $group) {
1451
            if (in_array($group->Code, $groupList)) {
1452
                $index = array_search($group->Code, $groupList);
1453
                unset($groupList[$index]);
1454
            }
1455
        }
1456
1457
        return $groupList;
1458
    }
1459
1460
1461
    /**
1462
     * Return a {@link FieldList} of fields that would appropriate for editing
1463
     * this member.
1464
     *
1465
     * @skipUpgrade
1466
     * @return FieldList Return a FieldList of fields that would appropriate for
1467
     *                   editing this member.
1468
     */
1469
    public function getCMSFields()
1470
    {
1471
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
1472
            /** @var TabSet $rootTabSet */
1473
            $rootTabSet = $fields->fieldByName("Root");
1474
            /** @var Tab $mainTab */
1475
            $mainTab = $rootTabSet->fieldByName("Main");
1476
            /** @var FieldList $mainFields */
1477
            $mainFields = $mainTab->getChildren();
1478
1479
            // Build change password field
1480
            $mainFields->replaceField('Password', $this->getMemberPasswordField());
1481
1482
            $mainFields->replaceField('Locale', new DropdownField(
1483
                "Locale",
1484
                _t(__CLASS__ . '.INTERFACELANG', "Interface Language", 'Language of the CMS'),
1485
                i18n::getSources()->getKnownLocales()
1486
            ));
1487
            $mainFields->removeByName(static::config()->get('hidden_fields'));
1488
1489
            if (!static::config()->get('lock_out_after_incorrect_logins')) {
1490
                $mainFields->removeByName('FailedLoginCount');
1491
            }
1492
1493
            // Groups relation will get us into logical conflicts because
1494
            // Members are displayed within  group edit form in SecurityAdmin
1495
            $fields->removeByName('Groups');
1496
1497
            // Members shouldn't be able to directly view/edit logged passwords
1498
            $fields->removeByName('LoggedPasswords');
1499
1500
            $fields->removeByName('RememberLoginHashes');
1501
1502
            if (Permission::check('EDIT_PERMISSIONS')) {
1503
                // Filter allowed groups
1504
                $groups = Group::get();
1505
                $disallowedGroupIDs = $this->disallowedGroups();
1506
                if ($disallowedGroupIDs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $disallowedGroupIDs of type integer[] 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...
1507
                    $groups = $groups->exclude('ID', $disallowedGroupIDs);
1508
                }
1509
                $groupsMap = array();
1510
                foreach ($groups as $group) {
1511
                    // Listboxfield values are escaped, use ASCII char instead of &raquo;
1512
                    $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
0 ignored issues
show
Bug introduced by
The method getBreadcrumbs() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1512
                    /** @scrutinizer ignore-call */ 
1513
                    $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
Loading history...
1513
                }
1514
                asort($groupsMap);
1515
                $fields->addFieldToTab(
1516
                    'Root.Main',
1517
                    ListboxField::create('DirectGroups', Group::singleton()->i18n_plural_name())
1518
                        ->setSource($groupsMap)
1519
                        ->setAttribute(
1520
                            'data-placeholder',
1521
                            _t(__CLASS__ . '.ADDGROUP', 'Add group', 'Placeholder text for a dropdown')
1522
                        )
1523
                );
1524
1525
1526
                // Add permission field (readonly to avoid complicated group assignment logic).
1527
                // This should only be available for existing records, as new records start
1528
                // with no permissions until they have a group assignment anyway.
1529
                if ($this->ID) {
1530
                    $permissionsField = new PermissionCheckboxSetField_Readonly(
1531
                        'Permissions',
1532
                        false,
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $title of SilverStripe\Security\Pe...Readonly::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1532
                        /** @scrutinizer ignore-type */ false,
Loading history...
1533
                        Permission::class,
1534
                        'GroupID',
1535
                        // we don't want parent relationships, they're automatically resolved in the field
1536
                        $this->getManyManyComponents('Groups')
1537
                    );
1538
                    $fields->findOrMakeTab('Root.Permissions', Permission::singleton()->i18n_plural_name());
1539
                    $fields->addFieldToTab('Root.Permissions', $permissionsField);
1540
                }
1541
            }
1542
1543
            $permissionsTab = $rootTabSet->fieldByName('Permissions');
1544
            if ($permissionsTab) {
0 ignored issues
show
introduced by
$permissionsTab is of type SilverStripe\Forms\FormField, thus it always evaluated to true.
Loading history...
1545
                $permissionsTab->addExtraClass('readonly');
1546
            }
1547
        });
1548
1549
        return parent::getCMSFields();
1550
    }
1551
1552
    /**
1553
     * @param bool $includerelations Indicate if the labels returned include relation fields
1554
     * @return array
1555
     */
1556
    public function fieldLabels($includerelations = true)
1557
    {
1558
        $labels = parent::fieldLabels($includerelations);
1559
1560
        $labels['FirstName'] = _t(__CLASS__ . '.FIRSTNAME', 'First Name');
1561
        $labels['Surname'] = _t(__CLASS__ . '.SURNAME', 'Surname');
1562
        /** @skipUpgrade */
1563
        $labels['Email'] = _t(__CLASS__ . '.EMAIL', 'Email');
1564
        $labels['Password'] = _t(__CLASS__ . '.db_Password', 'Password');
1565
        $labels['PasswordExpiry'] = _t(
1566
            __CLASS__ . '.db_PasswordExpiry',
1567
            'Password Expiry Date',
1568
            'Password expiry date'
1569
        );
1570
        $labels['LockedOutUntil'] = _t(
1571
            __CLASS__ . '.db_LockedOutUntil',
1572
            'Locked out until',
1573
            'Security related date'
1574
        );
1575
        $labels['Locale'] = _t(__CLASS__ . '.db_Locale', 'Interface Locale');
1576
        if ($includerelations) {
1577
            $labels['Groups'] = _t(
1578
                __CLASS__ . '.belongs_many_many_Groups',
1579
                'Groups',
1580
                'Security Groups this member belongs to'
1581
            );
1582
        }
1583
1584
        return $labels;
1585
    }
1586
1587
    /**
1588
     * Users can view their own record.
1589
     * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions.
1590
     * This is likely to be customized for social sites etc. with a looser permission model.
1591
     *
1592
     * @param Member $member
1593
     * @return bool
1594
     */
1595
    public function canView($member = null)
1596
    {
1597
        //get member
1598
        if (!$member) {
1599
            $member = Security::getCurrentUser();
1600
        }
1601
        //check for extensions, we do this first as they can overrule everything
1602
        $extended = $this->extendedCan(__FUNCTION__, $member);
1603
        if ($extended !== null) {
1604
            return $extended;
1605
        }
1606
1607
        //need to be logged in and/or most checks below rely on $member being a Member
1608
        if (!$member) {
0 ignored issues
show
introduced by
$member is of type SilverStripe\Security\Member, thus it always evaluated to true.
Loading history...
1609
            return false;
1610
        }
1611
        // members can usually view their own record
1612
        if ($this->ID == $member->ID) {
1613
            return true;
1614
        }
1615
1616
        //standard check
1617
        return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin');
1618
    }
1619
1620
    /**
1621
     * Users can edit their own record.
1622
     * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
1623
     *
1624
     * @param Member $member
1625
     * @return bool
1626
     */
1627
    public function canEdit($member = null)
1628
    {
1629
        //get member
1630
        if (!$member) {
1631
            $member = Security::getCurrentUser();
1632
        }
1633
        //check for extensions, we do this first as they can overrule everything
1634
        $extended = $this->extendedCan(__FUNCTION__, $member);
1635
        if ($extended !== null) {
1636
            return $extended;
1637
        }
1638
1639
        //need to be logged in and/or most checks below rely on $member being a Member
1640
        if (!$member) {
0 ignored issues
show
introduced by
$member is of type SilverStripe\Security\Member, thus it always evaluated to true.
Loading history...
1641
            return false;
1642
        }
1643
1644
        // HACK: we should not allow for an non-Admin to edit an Admin
1645
        if (!Permission::checkMember($member, 'ADMIN') && Permission::checkMember($this, 'ADMIN')) {
1646
            return false;
1647
        }
1648
        // members can usually edit their own record
1649
        if ($this->ID == $member->ID) {
1650
            return true;
1651
        }
1652
1653
        //standard check
1654
        return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin');
1655
    }
1656
1657
    /**
1658
     * Users can edit their own record.
1659
     * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
1660
     *
1661
     * @param Member $member
1662
     * @return bool
1663
     */
1664
    public function canDelete($member = null)
1665
    {
1666
        if (!$member) {
1667
            $member = Security::getCurrentUser();
1668
        }
1669
        //check for extensions, we do this first as they can overrule everything
1670
        $extended = $this->extendedCan(__FUNCTION__, $member);
1671
        if ($extended !== null) {
1672
            return $extended;
1673
        }
1674
1675
        //need to be logged in and/or most checks below rely on $member being a Member
1676
        if (!$member) {
0 ignored issues
show
introduced by
$member is of type SilverStripe\Security\Member, thus it always evaluated to true.
Loading history...
1677
            return false;
1678
        }
1679
        // Members are not allowed to remove themselves,
1680
        // since it would create inconsistencies in the admin UIs.
1681
        if ($this->ID && $member->ID == $this->ID) {
1682
            return false;
1683
        }
1684
1685
        // HACK: if you want to delete a member, you have to be a member yourself.
1686
        // this is a hack because what this should do is to stop a user
1687
        // deleting a member who has more privileges (e.g. a non-Admin deleting an Admin)
1688
        if (Permission::checkMember($this, 'ADMIN')) {
1689
            if (!Permission::checkMember($member, 'ADMIN')) {
1690
                return false;
1691
            }
1692
        }
1693
1694
        //standard check
1695
        return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin');
1696
    }
1697
1698
    /**
1699
     * Validate this member object.
1700
     */
1701
    public function validate()
1702
    {
1703
        // If validation is disabled, skip this step
1704
        if (!DataObject::config()->uninherited('validation_enabled')) {
1705
            return ValidationResult::create();
1706
        }
1707
1708
        $valid = parent::validate();
1709
        $validator = static::password_validator();
1710
1711
        if (!$this->ID || $this->isChanged('Password')) {
1712
            if ($this->Password && $validator) {
1713
                $userValid = $validator->validate($this->Password, $this);
1714
                $valid->combineAnd($userValid);
1715
            }
1716
        }
1717
1718
        return $valid;
1719
    }
1720
1721
    /**
1722
     * Change password. This will cause rehashing according to the `PasswordEncryption` property via the
1723
     * `onBeforeWrite()` method. This method will allow extensions to perform actions and augment the validation
1724
     * result if required before the password is written and can check it after the write also.
1725
     *
1726
     * `onBeforeWrite()` will encrypt the password prior to writing.
1727
     *
1728
     * @param string $password Cleartext password
1729
     * @param bool $write Whether to write the member afterwards
1730
     * @return ValidationResult
1731
     */
1732
    public function changePassword($password, $write = true)
1733
    {
1734
        $this->Password = $password;
1735
        $result = $this->validate();
1736
1737
        $this->extend('onBeforeChangePassword', $password, $result);
1738
1739
        if ($result->isValid()) {
1740
            $this->AutoLoginHash = null;
1741
1742
            if ($write) {
1743
                $this->write();
1744
            }
1745
        }
1746
1747
        $this->extend('onAfterChangePassword', $password, $result);
1748
1749
        return $result;
1750
    }
1751
1752
    /**
1753
     * Takes a plaintext password (on the Member object) and encrypts it
1754
     *
1755
     * @return $this
1756
     */
1757
    protected function encryptPassword()
1758
    {
1759
        // reset salt so that it gets regenerated - this will invalidate any persistent login cookies
1760
        // or other information encrypted with this Member's settings (see self::encryptWithUserSettings)
1761
        $this->Salt = '';
1762
1763
        // Password was changed: encrypt the password according the settings
1764
        $encryption_details = Security::encrypt_password(
1765
            $this->Password,
1766
            $this->Salt,
1767
            $this->isChanged('PasswordEncryption') ? $this->PasswordEncryption : null,
1768
            $this
1769
        );
1770
1771
        // Overwrite the Password property with the hashed value
1772
        $this->Password = $encryption_details['password'];
1773
        $this->Salt = $encryption_details['salt'];
1774
        $this->PasswordEncryption = $encryption_details['algorithm'];
1775
1776
        // If we haven't manually set a password expiry
1777
        if (!$this->isChanged('PasswordExpiry')) {
1778
            // then set it for us
1779
            if (static::config()->get('password_expiry_days')) {
1780
                $this->PasswordExpiry = date('Y-m-d', time() + 86400 * static::config()->get('password_expiry_days'));
1781
            } else {
1782
                $this->PasswordExpiry = null;
1783
            }
1784
        }
1785
1786
        return $this;
1787
    }
1788
1789
    /**
1790
     * Tell this member that someone made a failed attempt at logging in as them.
1791
     * This can be used to lock the user out temporarily if too many failed attempts are made.
1792
     */
1793
    public function registerFailedLogin()
1794
    {
1795
        $lockOutAfterCount = self::config()->get('lock_out_after_incorrect_logins');
1796
        if ($lockOutAfterCount) {
1797
            // Keep a tally of the number of failed log-ins so that we can lock people out
1798
            ++$this->FailedLoginCount;
1799
1800
            if ($this->FailedLoginCount >= $lockOutAfterCount) {
1801
                $lockoutMins = self::config()->get('lock_out_delay_mins');
1802
                $this->LockedOutUntil = date('Y-m-d H:i:s', DBDatetime::now()->getTimestamp() + $lockoutMins * 60);
1803
                $this->FailedLoginCount = 0;
1804
            }
1805
        }
1806
        $this->extend('registerFailedLogin');
1807
        $this->write();
1808
    }
1809
1810
    /**
1811
     * Tell this member that a successful login has been made
1812
     */
1813
    public function registerSuccessfulLogin()
1814
    {
1815
        if (self::config()->get('lock_out_after_incorrect_logins')) {
1816
            // Forgive all past login failures
1817
            $this->FailedLoginCount = 0;
1818
            $this->LockedOutUntil = null;
1819
            $this->write();
1820
        }
1821
    }
1822
1823
    /**
1824
     * Get the HtmlEditorConfig for this user to be used in the CMS.
1825
     * This is set by the group. If multiple configurations are set,
1826
     * the one with the highest priority wins.
1827
     *
1828
     * @return string
1829
     */
1830
    public function getHtmlEditorConfigForCMS()
1831
    {
1832
        $currentName = '';
1833
        $currentPriority = 0;
1834
1835
        foreach ($this->Groups() as $group) {
1836
            $configName = $group->HtmlEditorConfig;
0 ignored issues
show
Bug Best Practice introduced by
The property HtmlEditorConfig does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1837
            if ($configName) {
1838
                $config = HTMLEditorConfig::get($group->HtmlEditorConfig);
1839
                if ($config && $config->getOption('priority') > $currentPriority) {
1840
                    $currentName = $configName;
1841
                    $currentPriority = $config->getOption('priority');
1842
                }
1843
            }
1844
        }
1845
1846
        // If can't find a suitable editor, just default to cms
1847
        return $currentName ? $currentName : 'cms';
1848
    }
1849
}
1850