-
Notifications
You must be signed in to change notification settings - Fork 667
/
Copy pathUser.php
2006 lines (1747 loc) · 57.5 KB
/
User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\elements;
use Craft;
use craft\base\Element;
use craft\base\NameTrait;
use craft\db\Query;
use craft\db\Table;
use craft\elements\actions\DeleteUsers;
use craft\elements\actions\Restore;
use craft\elements\actions\SuspendUsers;
use craft\elements\actions\UnsuspendUsers;
use craft\elements\conditions\ElementConditionInterface;
use craft\elements\conditions\users\UserCondition;
use craft\elements\db\AddressQuery;
use craft\elements\db\ElementQueryInterface;
use craft\elements\db\UserQuery;
use craft\enums\PropagationMethod;
use craft\events\AuthenticateUserEvent;
use craft\events\DefineValueEvent;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\Html;
use craft\helpers\Json;
use craft\helpers\Session;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\i18n\Formatter;
use craft\i18n\Locale;
use craft\models\FieldLayout;
use craft\models\UserGroup;
use craft\records\User as UserRecord;
use craft\validators\DateTimeValidator;
use craft\validators\UniqueValidator;
use craft\validators\UsernameValidator;
use craft\validators\UserPasswordValidator;
use DateInterval;
use DateTime;
use DateTimeZone;
use Throwable;
use yii\base\ErrorHandler;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\validators\InlineValidator;
use yii\validators\Validator;
use yii\web\IdentityInterface;
/**
* User represents a user element.
*
* @property Asset|null $photo the user’s photo
* @property UserGroup[] $groups the user’s groups
* @property string $name the user’s full name or username
* @property string|null $friendlyName the user’s first name or username
* @property-read Address[]|null $addresses the user’s addresses
* @property-read DateInterval|null $remainingCooldownTime the remaining cooldown time for this user, if they've entered their password incorrectly too many times
* @property-read DateTime|null $cooldownEndTime the time when the user will be over their cooldown period
* @property-read array $preferences the user’s preferences
* @property-read bool $isCredentialed whether the user account can be logged into
* @property-read bool $isCurrent whether this is the current logged-in user
* @property-read string|null $preferredLanguage the user’s preferred language
* @property-read string|null $preferredLocale the user’s preferred formatting locale
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class User extends Element implements IdentityInterface
{
use NameTrait;
/**
* @since 5.0.0
*/
public const GQL_TYPE_NAME = 'User';
/**
* @event AuthenticateUserEvent The event that is triggered before a user is authenticated.
*
* If you wish to offload authentication logic, then set [[AuthenticateUserEvent::$performAuthentication]] to `false`, and set [[$authError]] to
* something if there is an authentication error.
*/
public const EVENT_BEFORE_AUTHENTICATE = 'beforeAuthenticate';
/**
* @event DefineValueEvent The event that is triggered when defining the user’s name, as returned by [[getName()]] or [[__toString()]].
* @since 3.7.0
*/
public const EVENT_DEFINE_NAME = 'defineName';
/**
* @event DefineValueEvent The event that is triggered when defining the user’s friendly name, as returned by [[getFriendlyName()]].
* @since 3.7.0
*/
public const EVENT_DEFINE_FRIENDLY_NAME = 'defineFriendlyName';
public const IMPERSONATE_KEY = 'Craft.UserSessionService.prevImpersonateUserId';
private static array $photoColors = [
'red-100',
'orange-200',
'amber-200',
'yellow-200',
'lime-200',
'green-200',
'emerald-200',
'teal-200',
'cyan-200',
'sky-200',
'blue-200',
'indigo-200',
'violet-200',
'purple-200',
'fuchsia-200',
'pink-100',
'rose-200',
];
// User statuses
// -------------------------------------------------------------------------
/**
* @since 4.0.0
*/
public const STATUS_INACTIVE = 'inactive';
public const STATUS_ACTIVE = 'active';
public const STATUS_PENDING = 'pending';
public const STATUS_SUSPENDED = 'suspended';
public const STATUS_LOCKED = 'locked';
// Authentication error codes
// -------------------------------------------------------------------------
public const AUTH_INVALID_CREDENTIALS = 'invalid_credentials';
public const AUTH_PENDING_VERIFICATION = 'pending_verification';
public const AUTH_ACCOUNT_LOCKED = 'account_locked';
public const AUTH_ACCOUNT_COOLDOWN = 'account_cooldown';
public const AUTH_PASSWORD_RESET_REQUIRED = 'password_reset_required';
public const AUTH_ACCOUNT_SUSPENDED = 'account_suspended';
public const AUTH_NO_CP_ACCESS = 'no_cp_access';
public const AUTH_NO_CP_OFFLINE_ACCESS = 'no_cp_offline_access';
public const AUTH_NO_SITE_OFFLINE_ACCESS = 'no_site_offline_access';
// Validation scenarios
// -------------------------------------------------------------------------
/**
* @since 4.4.8
*/
public const SCENARIO_ACTIVATION = 'activation';
public const SCENARIO_REGISTRATION = 'registration';
public const SCENARIO_PASSWORD = 'password';
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('app', 'User');
}
/**
* @inheritdoc
*/
public static function lowerDisplayName(): string
{
return Craft::t('app', 'user');
}
/**
* @inheritdoc
*/
public static function pluralDisplayName(): string
{
return Craft::t('app', 'Users');
}
/**
* @inheritdoc
*/
public static function pluralLowerDisplayName(): string
{
return Craft::t('app', 'users');
}
/**
* @inheritdoc
*/
public static function refHandle(): ?string
{
return 'user';
}
/**
* @inheritdoc
*/
public static function trackChanges(): bool
{
return true;
}
/**
* @inheritdoc
*/
public static function hasThumbs(): bool
{
return true;
}
/**
* @inheritdoc
*/
public static function hasStatuses(): bool
{
return true;
}
/**
* @inheritdoc
*/
public static function statuses(): array
{
return [
self::STATUS_ACTIVE => [
'label' => Craft::t('app', 'Active'),
'color' => 'green',
],
self::STATUS_PENDING => [
'label' => Craft::t('app', 'Pending'),
'color' => 'orange',
],
self::STATUS_SUSPENDED => [
'label' => Craft::t('app', 'Suspended'),
'color' => 'red',
],
self::STATUS_LOCKED => [
'label' => Craft::t('app', 'Locked'),
'color' => 'red',
],
self::STATUS_INACTIVE => [
'label' => Craft::t('app', 'Inactive'),
],
];
}
/**
* @inheritdoc
* @return UserQuery The newly created [[UserQuery]] instance.
*/
public static function find(): UserQuery
{
return new UserQuery(static::class);
}
/**
* @inheritdoc
* @return UserCondition
*/
public static function createCondition(): ElementConditionInterface
{
return Craft::createObject(UserCondition::class, [static::class]);
}
/**
* @inheritdoc
*/
protected static function defineSources(string $context): array
{
$sources = [
[
'key' => '*',
'label' => Craft::t('app', 'All users'),
'hasThumbs' => true,
'data' => [
'slug' => 'all',
],
],
[
'key' => 'admins',
'label' => Craft::t('app', 'Admins'),
'criteria' => ['admin' => true],
'hasThumbs' => true,
'data' => [
'slug' => 'admins',
],
],
[
'heading' => Craft::t('app', 'Account Type'),
],
[
'key' => 'credentialed',
'label' => Craft::t('app', 'Credentialed'),
'criteria' => [
'status' => UserQuery::STATUS_CREDENTIALED,
],
'hasThumbs' => true,
'data' => [
'slug' => 'credentialed',
],
],
[
'key' => 'inactive',
'label' => Craft::t('app', 'Inactive'),
'criteria' => [
'status' => self::STATUS_INACTIVE,
],
'hasThumbs' => true,
'data' => [
'slug' => 'inactive',
],
],
];
$groups = Craft::$app->getUserGroups()->getAllGroups();
if (!empty($groups)) {
$sources[] = ['heading' => Craft::t('app', 'Groups')];
foreach ($groups as $group) {
$sources[] = [
'key' => 'group:' . $group->uid,
'label' => Craft::t('site', $group->name),
'criteria' => ['groupId' => $group->id],
'hasThumbs' => true,
'data' => [
'slug' => $group->handle,
],
];
}
}
return $sources;
}
/**
* @inheritdoc
*/
protected static function defineActions(string $source): array
{
$actions = [];
if (Craft::$app->getUser()->checkPermission('moderateUsers')) {
// Suspend
$actions[] = SuspendUsers::class;
// Unsuspend
$actions[] = UnsuspendUsers::class;
}
if (Craft::$app->getUser()->checkPermission('deleteUsers')) {
// Delete
$actions[] = DeleteUsers::class;
}
// Restore
$actions[] = Restore::class;
return $actions;
}
/**
* @inheritdoc
*/
protected static function defineSearchableAttributes(): array
{
return ['username', 'fullName', 'firstName', 'lastName', 'email'];
}
/**
* @inheritdoc
*/
protected static function defineSortOptions(): array
{
if (Craft::$app->getConfig()->getGeneral()->useEmailAsUsername) {
$attributes = [
'email' => Craft::t('app', 'Email'),
'fullName' => Craft::t('app', 'Full Name'),
'firstName' => Craft::t('app', 'First Name'),
'lastName' => Craft::t('app', 'Last Name'),
[
'label' => Craft::t('app', 'Last Login'),
'orderBy' => 'lastLoginDate',
'defaultDir' => 'desc',
],
[
'label' => Craft::t('app', 'Date Created'),
'orderBy' => 'dateCreated',
'defaultDir' => 'desc',
],
[
'label' => Craft::t('app', 'Date Updated'),
'orderBy' => 'dateUpdated',
'defaultDir' => 'desc',
],
'id' => Craft::t('app', 'ID'),
];
} else {
$attributes = [
'username' => Craft::t('app', 'Username'),
'fullName' => Craft::t('app', 'Full Name'),
'firstName' => Craft::t('app', 'First Name'),
'lastName' => Craft::t('app', 'Last Name'),
'email' => Craft::t('app', 'Email'),
[
'label' => Craft::t('app', 'Last Login'),
'orderBy' => 'lastLoginDate',
'defaultDir' => 'desc',
],
[
'label' => Craft::t('app', 'Date Created'),
'orderBy' => 'dateCreated',
'defaultDir' => 'desc',
],
[
'label' => Craft::t('app', 'Date Updated'),
'orderBy' => 'dateUpdated',
'defaultDir' => 'desc',
],
'id' => Craft::t('app', 'ID'),
];
}
return $attributes;
}
/**
* @inheritdoc
*/
protected static function defineTableAttributes(): array
{
return [
'email' => ['label' => Craft::t('app', 'Email')],
'username' => ['label' => Craft::t('app', 'Username')],
'fullName' => ['label' => Craft::t('app', 'Full Name')],
'firstName' => ['label' => Craft::t('app', 'First Name')],
'lastName' => ['label' => Craft::t('app', 'Last Name')],
'groups' => ['label' => Craft::t('app', 'Groups')],
'preferredLanguage' => ['label' => Craft::t('app', 'Preferred Language')],
'preferredLocale' => ['label' => Craft::t('app', 'Preferred Locale')],
'id' => ['label' => Craft::t('app', 'ID')],
'uid' => ['label' => Craft::t('app', 'UID')],
'lastLoginDate' => ['label' => Craft::t('app', 'Last Login')],
'dateCreated' => ['label' => Craft::t('app', 'Date Created')],
'dateUpdated' => ['label' => Craft::t('app', 'Date Updated')],
];
}
/**
* @inheritdoc
*/
protected static function defineDefaultTableAttributes(string $source): array
{
return [
'fullName',
'email',
'dateCreated',
'lastLoginDate',
];
}
/**
* @inheritdoc
*/
protected static function prepElementQueryForTableAttribute(ElementQueryInterface $elementQuery, string $attribute): void
{
/** @var UserQuery $elementQuery */
if ($attribute === 'groups') {
$elementQuery->withGroups();
} else {
parent::prepElementQueryForTableAttribute($elementQuery, $attribute);
}
}
/**
* @inheritdoc
*/
public static function eagerLoadingMap(array $sourceElements, string $handle): array|null|false
{
// Get the source element IDs
$sourceElementIds = ArrayHelper::getColumn($sourceElements, 'id');
if ($handle == 'addresses') {
$map = (new Query())
->select([
'source' => 'ownerId',
'target' => 'id',
])
->from([Table::ADDRESSES])
->where(['ownerId' => $sourceElementIds])
->all();
return [
'elementType' => Address::class,
'map' => $map,
'createElement' => function(AddressQuery $query, array $result, self $source) {
// set the addresses' owners to the source user elements
// (must get set before behaviors - see https://github.com/craftcms/cms/issues/13400)
return $query->createElement(['owner' => $source] + $result);
},
];
}
if ($handle === 'photo') {
$map = (new Query())
->select(['id as source', 'photoId as target'])
->from([Table::USERS])
->where(['id' => $sourceElementIds])
->andWhere(['not', ['photoId' => null]])
->all();
return [
'elementType' => Asset::class,
'map' => $map,
];
}
return parent::eagerLoadingMap($sourceElements, $handle);
}
// IdentityInterface Methods
// -------------------------------------------------------------------------
/**
* @inheritdoc
*/
public static function findIdentity($id): ?self
{
/** @var User|null $user */
$user = self::find()
->addSelect(['users.password'])
->id($id)
->status(null)
->one();
if ($user === null) {
return null;
}
/** @var static $user */
if ($user->getStatus() === self::STATUS_ACTIVE) {
return $user;
}
// If the current user is being impersonated by an admin, ignore their status
if ($previousUserId = Session::get(self::IMPERSONATE_KEY)) {
/** @var self|null $previousUser */
$previousUser = self::find()
->id($previousUserId)
->status(null)
->one();
if ($previousUser && $previousUser->can('impersonateUsers')) {
return $user;
}
}
return null;
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null): ?self
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* @var int|null Photo asset ID
*/
public ?int $photoId = null;
/**
* @var bool Active
* @since 4.0.0
*/
public bool $active = false;
/**
* @var bool Pending
*/
public bool $pending = false;
/**
* @var bool Locked
*/
public bool $locked = false;
/**
* @var bool Suspended
*/
public bool $suspended = false;
/**
* @var bool Admin
*/
public bool $admin = false;
/**
* @var string|null Username
*/
public ?string $username = null;
/**
* @var string|null Email
*/
public ?string $email = null;
/**
* @var string|null Password
*/
public ?string $password = null;
/**
* @var DateTime|null Last login date
*/
public ?DateTime $lastLoginDate = null;
/**
* @var int|null Invalid login count
*/
public ?int $invalidLoginCount = null;
/**
* @var DateTime|null Last invalid login date
*/
public ?DateTime $lastInvalidLoginDate = null;
/**
* @var DateTime|null Lockout date
*/
public ?DateTime $lockoutDate = null;
/**
* @var bool Whether the user has a dashboard
* @since 3.0.4
*/
public bool $hasDashboard = false;
/**
* @var bool Password reset required
*/
public bool $passwordResetRequired = false;
/**
* @var DateTime|null Last password change date
*/
public ?DateTime $lastPasswordChangeDate = null;
/**
* @var string|null Unverified email
*/
public ?string $unverifiedEmail = null;
/**
* @var string|null New password
*/
public ?string $newPassword = null;
/**
* @var string|null Current password
*/
public ?string $currentPassword = null;
/**
* @var DateTime|null Verification code issued date
*/
public ?DateTime $verificationCodeIssuedDate = null;
/**
* @var string|null Verification code
*/
public ?string $verificationCode = null;
/**
* @var string|null Last login attempt IP address.
*/
public ?string $lastLoginAttemptIp = null;
/**
* @var string|null Auth error
*/
public ?string $authError = null;
/**
* @var self|null The user who should take over the user’s content if the user is deleted.
*/
public ?User $inheritorOnDelete = null;
/**
* @var Address[] Addresses
* @see getAddresses()
*/
private array $_addresses;
/**
* @see getAddressManager()
*/
private NestedElementManager $_addressManager;
/**
* @var string|null
* @see getName()
* @see setName()
*/
private ?string $_name = null;
/**
* @var string|bool|null
* @see getFriendlyName()
* @see setFriendlyName()
*/
private string|bool|null $_friendlyName = null;
/**
* @var Asset|false|null user photo
*/
private Asset|null|false $_photo = null;
/**
* @var UserGroup[]|null The cached list of groups the user belongs to. Set by [[getGroups()]].
*/
private ?array $_groups = null;
/**
* @inheritdoc
*/
public function init(): void
{
parent::init();
// Is this user in cooldown mode, and are they past their window?
if (
$this->locked &&
Craft::$app->getConfig()->getGeneral()->cooldownDuration &&
!$this->getRemainingCooldownTime()
) {
Craft::$app->getUsers()->unlockUser($this);
}
// Convert IDNA ASCII to Unicode
if ($this->username) {
$this->username = StringHelper::idnToUtf8Email($this->username);
}
if ($this->email) {
$this->email = StringHelper::idnToUtf8Email($this->email);
}
$this->normalizeNames();
}
/**
* Use the full name or username as the string representation.
*
* @return string
*/
public function __toString(): string
{
try {
if (($name = $this->getName()) !== '') {
return $name;
}
} catch (Throwable $e) {
ErrorHandler::convertExceptionToError($e);
}
return parent::__toString();
}
/**
* @inheritdoc
*/
protected function uiLabel(): ?string
{
return $this->getName() ?: ($this->email ?? $this->id ?? static::class);
}
/**
* @inheritdoc
*/
public function attributes(): array
{
$names = parent::attributes();
$names[] = 'cooldownEndTime';
$names[] = 'friendlyName';
$names[] = 'fullName';
$names[] = 'isCredentialed';
$names[] = 'isCurrent';
$names[] = 'name';
$names[] = 'preferredLanguage';
$names[] = 'remainingCooldownTime';
return $names;
}
/**
* @inheritdoc
*/
public function extraFields(): array
{
$names = parent::extraFields();
$names[] = 'groups';
$names[] = 'addresses';
$names[] = 'photo';
return $names;
}
/**
* @inheritdoc
*/
public function attributeLabels(): array
{
$labels = parent::attributeLabels();
$labels['currentPassword'] = Craft::t('app', 'Current Password');
$labels['email'] = Craft::t('app', 'Email');
$labels['fullName'] = Craft::t('app', 'Full Name');
$labels['firstName'] = Craft::t('app', 'First Name');
$labels['lastName'] = Craft::t('app', 'Last Name');
$labels['newPassword'] = Craft::t('app', 'New Password');
$labels['password'] = Craft::t('app', 'Password');
$labels['unverifiedEmail'] = Craft::t('app', 'Email');
$labels['username'] = Craft::t('app', 'Username');
return $labels;
}
/**
* @inheritdoc
*/
protected function defineRules(): array
{
$rules = parent::defineRules();
$treatAsActive = fn() => $this->getIsCredentialed() || in_array($this->getScenario(), [
self::SCENARIO_REGISTRATION,
self::SCENARIO_ACTIVATION,
]);
$rules[] = [['lastLoginDate', 'lastInvalidLoginDate', 'lockoutDate', 'lastPasswordChangeDate', 'verificationCodeIssuedDate'], DateTimeValidator::class];
$rules[] = [['invalidLoginCount', 'photoId'], 'number', 'integerOnly' => true];
$rules[] = [['username', 'email', 'unverifiedEmail', 'fullName', 'firstName', 'lastName'], 'trim', 'skipOnEmpty' => true];
$rules[] = [['email', 'unverifiedEmail'], 'email', 'enableIDN' => App::supportsIdn(), 'enableLocalIDN' => false];
$rules[] = [['email', 'username', 'fullName', 'firstName', 'lastName', 'password', 'unverifiedEmail'], 'string', 'max' => 255];
$rules[] = [['verificationCode'], 'string', 'max' => 100];
$rules[] = [['email'], 'required', 'when' => $treatAsActive];
$rules[] = [['lastLoginAttemptIp'], 'string', 'max' => 45];
if (!Craft::$app->getConfig()->getGeneral()->useEmailAsUsername) {
$rules[] = [['username'], 'required', 'when' => $treatAsActive];
$rules[] = [['username'], UsernameValidator::class];
}
if (Craft::$app->getIsInstalled()) {
$rules[] = [
['username', 'email'],
UniqueValidator::class,
'targetClass' => UserRecord::class,
'caseInsensitive' => true,
];
$rules[] = [['unverifiedEmail'], 'validateUnverifiedEmail'];
}
if (isset($this->id) && $this->passwordResetRequired) {
// Get the current password hash
$currentPassword = (new Query())
->select(['password'])
->from([Table::USERS])
->where(['id' => $this->id])
->scalar();
} else {
$currentPassword = null;
}
$rules[] = [
['newPassword'],
UserPasswordValidator::class,
'forceDifferent' => $this->passwordResetRequired,
'currentPassword' => $currentPassword,
];
$rules[] = [
['fullName', 'firstName', 'lastName'], function($attribute, $params, Validator $validator) {
if (str_contains($this->$attribute, '://')) {
$validator->addError($this, $attribute, Craft::t('app', 'Invalid value “{value}”.'));
}
},
];
return $rules;
}
/**
* Returns whether the user account can be logged into.
*
* @return bool
* @since 4.0.0
*/
public function getIsCredentialed(): bool
{
return $this->active || $this->pending;
}
/**
* Validates the unverifiedEmail value is unique.
*
* @param string $attribute
* @param array|null $params
* @param InlineValidator $validator
*/
public function validateUnverifiedEmail(string $attribute, ?array $params, InlineValidator $validator): void
{
$query = self::find()
->status(null);
if (Craft::$app->getDb()->getIsMysql()) {
$query->where([
'email' => $this->unverifiedEmail,
]);
} else {
// Postgres is case-sensitive
$query->where([
'lower([[email]])' => mb_strtolower($this->unverifiedEmail),
]);
}
if ($this->id) {
$query->andWhere(['not', ['elements.id' => $this->id]]);
}
if ($query->exists()) {
$validator->addError($this, $attribute, Craft::t('yii', '{attribute} "{value}" has already been taken.'), $params);
}
}
/**
* @inheritdoc
*/
public function scenarios(): array
{
$scenarios = parent::scenarios();
$scenarios[self::SCENARIO_PASSWORD] = ['newPassword'];
$scenarios[self::SCENARIO_REGISTRATION] = ['username', 'email', 'newPassword'];
$scenarios[self::SCENARIO_ACTIVATION] = ['username', 'email'];
return $scenarios;
}
/**
* @inheritdoc
*/
public function getFieldLayout(): ?FieldLayout
{
return Craft::$app->getFields()->getLayoutByType(self::class);
}
/**
* Gets the user’s addresses.
*
* @return Address[]
* @since 4.0.0
*/
public function getAddresses(): array
{
if (!isset($this->_addresses)) {
if (!$this->id) {
return [];
}
/** @var Address[] $addresses */
$addresses = $this->createAddressQuery()->all();
$this->_addresses = $addresses;
}
return $this->_addresses;
}
/**
* Returns a nested element manager for the user’s addresses.
*
* @return NestedElementManager
* @since 5.0.0
*/
public function getAddressManager(): NestedElementManager
{
if (!isset($this->_addressManager)) {
$this->_addressManager = new NestedElementManager(
Address::class,
fn() => $this->createAddressQuery(),
[
'attribute' => 'addresses',
'propagationMethod' => PropagationMethod::None,
],