-
Notifications
You must be signed in to change notification settings - Fork 641
/
Users.php
1657 lines (1437 loc) · 55.2 KB
/
Users.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\services;
use Craft;
use craft\db\Query;
use craft\db\Table;
use craft\elements\Asset;
use craft\elements\User;
use craft\enums\CmsEdition;
use craft\errors\ImageException;
use craft\errors\InvalidElementException;
use craft\errors\InvalidSubpathException;
use craft\errors\UserNotFoundException;
use craft\errors\VolumeException;
use craft\events\ConfigEvent;
use craft\events\DefineUserGroupsEvent;
use craft\events\UserAssignGroupEvent;
use craft\events\UserEvent;
use craft\events\UserGroupsAssignEvent;
use craft\events\UserPhotoEvent;
use craft\helpers\Assets as AssetsHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\Image;
use craft\helpers\Json;
use craft\helpers\ProjectConfig as ProjectConfigHelper;
use craft\helpers\StringHelper;
use craft\helpers\Template;
use craft\helpers\UrlHelper;
use craft\models\FieldLayout;
use craft\models\UserGroup;
use craft\models\Volume;
use craft\records\User as UserRecord;
use craft\web\Request;
use DateTime;
use DateTimeZone;
use Throwable;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\UserException;
/**
* The Users service provides APIs for managing users.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getUsers()|`Craft::$app->users`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Users extends Component
{
/**
* @event UserEvent The event that is triggered before a user’s email is verified.
*/
public const EVENT_BEFORE_VERIFY_EMAIL = 'beforeVerifyEmail';
/**
* @event UserEvent The event that is triggered after a user’s email is verified.
*/
public const EVENT_AFTER_VERIFY_EMAIL = 'afterVerifyEmail';
/**
* @event UserEvent The event that is triggered before a user is activated.
*
* You may set [[\craft\events\CancelableEvent::$isValid]] to `false` to prevent the user from getting activated.
*/
public const EVENT_BEFORE_ACTIVATE_USER = 'beforeActivateUser';
/**
* @event UserEvent The event that is triggered after a user is activated.
*/
public const EVENT_AFTER_ACTIVATE_USER = 'afterActivateUser';
/**
* @event UserEvent The event that is triggered before a user is deactivated.
*
* You may set [[UserEvent::isValid]] to `false` to prevent the user from getting deactivated.
*
* @since 4.0.0
*/
public const EVENT_BEFORE_DEACTIVATE_USER = 'beforeDeactivateUser';
/**
* @event UserEvent The event that is triggered after a user is deactivated.
* @since 4.0.0
*/
public const EVENT_AFTER_DEACTIVATE_USER = 'afterDeactivateUser';
/**
* @event UserEvent The event that is triggered after a user is locked.
*/
public const EVENT_AFTER_LOCK_USER = 'afterLockUser';
/**
* @event UserEvent The event that is triggered before a user is unlocked.
*
* You may set [[\craft\events\CancelableEvent::$isValid]] to `false` to prevent the user from getting unlocked.
*/
public const EVENT_BEFORE_UNLOCK_USER = 'beforeUnlockUser';
/**
* @event UserEvent The event that is triggered after a user is unlocked.
*/
public const EVENT_AFTER_UNLOCK_USER = 'afterUnlockUser';
/**
* @event UserEvent The event that is triggered before a user is suspended.
*
* You may set [[\craft\events\CancelableEvent::$isValid]] to `false` to prevent the user from getting suspended.
*/
public const EVENT_BEFORE_SUSPEND_USER = 'beforeSuspendUser';
/**
* @event UserEvent The event that is triggered after a user is suspended.
*/
public const EVENT_AFTER_SUSPEND_USER = 'afterSuspendUser';
/**
* @event UserEvent The event that is triggered before a user is unsuspended.
*
* You may set [[\craft\events\CancelableEvent::isValid]] to `false` to prevent the user from getting unsuspended.
*/
public const EVENT_BEFORE_UNSUSPEND_USER = 'beforeUnsuspendUser';
/**
* @event UserEvent The event that is triggered after a user is unsuspended.
*/
public const EVENT_AFTER_UNSUSPEND_USER = 'afterUnsuspendUser';
/**
* @event UserGroupsAssignEvent The event that is triggered before a user is assigned to some user groups.
*
* You may set [[\craft\events\CancelableEvent::$isValid]] to `false` to prevent the user from getting assigned to the groups.
*/
public const EVENT_BEFORE_ASSIGN_USER_TO_GROUPS = 'beforeAssignUserToGroups';
/**
* @event UserGroupsAssignEvent The event that is triggered after a user is assigned to some user groups.
*/
public const EVENT_AFTER_ASSIGN_USER_TO_GROUPS = 'afterAssignUserToGroups';
/**
* @event DefineUserGroupsEvent The event that is triggered when defining the default user groups to assign to a publicly-registered user.
* @see getDefaultUserGroups()
* @since 4.5.4
*/
public const EVENT_DEFINE_DEFAULT_USER_GROUPS = 'defineDefaultUserGroups';
/**
* @event UserAssignGroupEvent The event that is triggered before a user is assigned to the default user group.
*
* You may set [[\craft\events\CancelableEvent::$isValid]] to `false` to prevent the user from getting assigned to the default
* user group.
*/
public const EVENT_BEFORE_ASSIGN_USER_TO_DEFAULT_GROUP = 'beforeAssignUserToDefaultGroup';
/**
* @event UserAssignGroupEvent The event that is triggered after a user is assigned to the default user group.
*/
public const EVENT_AFTER_ASSIGN_USER_TO_DEFAULT_GROUP = 'afterAssignUserToDefaultGroup';
/**
* @event UserSavePhotoEvent The event that is triggered before a user photo is saved.
* @since 4.4.0
*/
public const EVENT_BEFORE_SAVE_USER_PHOTO = 'beforeSaveUserPhoto';
/**
* @event UserSavePhotoEvent The event that is triggered after a user photo is saved.
* @since 4.4.0
*/
public const EVENT_AFTER_SAVE_USER_PHOTO = 'afterSaveUserPhoto';
/**
* @event UserPhotoEvent The event that is triggered before a user photo is deleted.
* @since 4.4.0
*/
public const EVENT_BEFORE_DELETE_USER_PHOTO = 'beforeDeleteUserPhoto';
/**
* @event UserPhotoEvent The event that is triggered after a user photo is deleted.
* @since 4.4.0
*/
public const EVENT_AFTER_DELETE_USER_PHOTO = 'beforeDeleteUserPhoto';
/**
* Returns a user by an email address, creating one if none already exists.
*
* @param string $email
* @return User
* @throws InvalidArgumentException if `$email` is invalid
* @throws Exception if the user couldn’t be saved for some unexpected reason
* @since 4.0.0
*/
public function ensureUserByEmail(string $email): User
{
/** @var User|null $user */
$user = User::find()
->email($email)
->status(null)
->one();
if (!$user) {
$user = new User();
$user->email = $email;
if (!$user->validate(['email'])) {
throw new InvalidArgumentException($user->getFirstError('email'));
}
if (!Craft::$app->getElements()->saveElement($user, false)) {
throw new Exception('Unable to save user: ' . implode(', ', $user->getFirstErrors()));
}
}
return $user;
}
/**
* @var array Cached user preferences.
* @see getUserPreferences()
*/
private array $_userPreferences = [];
/**
* Returns a user by their ID.
*
* ```php
* $user = Craft::$app->users->getUserById($userId);
* ```
*
* @param int $userId The user’s ID.
* @return User|null The user with the given ID, or `null` if a user could not be found.
*/
public function getUserById(int $userId): ?User
{
return Craft::$app->getElements()->getElementById($userId, User::class);
}
/**
* Returns a user by their username or email.
*
* ```php
* $user = Craft::$app->users->getUserByUsernameOrEmail($loginName);
* ```
*
* @param string $usernameOrEmail The user’s username or email.
* @return User|null The user with the given username/email, or `null` if a user could not be found.
*/
public function getUserByUsernameOrEmail(string $usernameOrEmail): ?User
{
$query = User::find()
->addSelect(['users.password', 'users.passwordResetRequired'])
->status(null);
if (Craft::$app->getDb()->getIsMysql()) {
$query
->where([
'username' => $usernameOrEmail,
])
->orWhere([
'email' => $usernameOrEmail,
]);
} else {
// Postgres is case-sensitive
$query
->where([
'lower([[username]])' => mb_strtolower($usernameOrEmail),
])
->orWhere([
'lower([[email]])' => mb_strtolower($usernameOrEmail),
]);
}
/** @var User|null */
return $query->one();
}
/**
* Returns a user by their UID.
*
* ```php
* $user = Craft::$app->users->getUserByUid($userUid);
* ```
*
* @param string $uid The user’s UID.
* @return User|null The user with the given UID, or `null` if a user could not be found.
*/
public function getUserByUid(string $uid): ?User
{
/** @var User|null */
return User::find()
->uid($uid)
->status(null)
->one();
}
/**
* Returns whether a verification code is valid for the given user.
*
* This method first checks if the code has expired past the
* <config5:verificationCodeDuration> config setting. If it is still valid,
* then, the checks the validity of the contents of the code.
*
* @param User $user The user to check the code for.
* @param string $code The verification code to check for.
* @return bool Whether the code is still valid.
*/
public function isVerificationCodeValidForUser(User $user, string $code): bool
{
if (!$user->verificationCode || !$user->verificationCodeIssuedDate) {
// Fetch from the DB
$userRecord = $this->_getUserRecordById($user->id);
$user->verificationCode = $userRecord->verificationCode;
$user->verificationCodeIssuedDate = $userRecord->verificationCodeIssuedDate
? new DateTime($userRecord->verificationCodeIssuedDate, new DateTimeZone('UTC'))
: null;
if (!$user->verificationCode || !$user->verificationCodeIssuedDate) {
return false;
}
}
// Make sure the verification code isn't expired
$minCodeIssueDate = DateTimeHelper::currentUTCDateTime();
$generalConfig = Craft::$app->getConfig()->getGeneral();
$interval = DateTimeHelper::secondsToInterval($generalConfig->verificationCodeDuration);
$minCodeIssueDate->sub($interval);
// Make sure it’s not expired
if ($user->verificationCodeIssuedDate < $minCodeIssueDate) {
$userRecord = $userRecord ?? $this->_getUserRecordById($user->id);
$userRecord->verificationCode = $user->verificationCode = null;
$userRecord->verificationCodeIssuedDate = $user->verificationCodeIssuedDate = null;
$userRecord->save();
Craft::warning('The verification code (' . $code . ') given for userId: ' . $user->id . ' is expired.', __METHOD__);
return false;
}
try {
$valid = Craft::$app->getSecurity()->validatePassword($code, $user->verificationCode);
} catch (InvalidArgumentException) {
$valid = false;
}
if (!$valid) {
Craft::warning('The verification code (' . $code . ') given for userId: ' . $user->id . ' does not match the hash in the database.', __METHOD__);
return false;
}
return true;
}
/**
* Returns a user’s preferences.
*
* @param int $userId The user’s ID
* @return array The user’s preferences
*/
public function getUserPreferences(int $userId): array
{
if (!isset($this->_userPreferences[$userId])) {
$preferences = (new Query())
->select(['preferences'])
->from([Table::USERPREFERENCES])
->where(['userId' => $userId])
->scalar();
if ($preferences) {
if (is_string($preferences)) {
$preferences = Json::decode($preferences);
}
} else {
$preferences = [];
}
$this->_userPreferences[$userId] = $preferences;
}
return $this->_userPreferences[$userId];
}
/**
* Saves a user’s preferences.
*
* @param User $user The user
* @param array $preferences The user’s new preferences
*/
public function saveUserPreferences(User $user, array $preferences): void
{
// Merge in any other saved preferences
$preferences += $this->getUserPreferences($user->id);
$tableSchema = Craft::$app->getDb()->getSchema()->getTableSchema(Table::USERPREFERENCES);
Db::upsert(Table::USERPREFERENCES, [
'userId' => $user->id,
'preferences' => Db::prepareValueForDb($preferences, $tableSchema->columns['preferences']->dbType),
]);
$this->_userPreferences[$user->id] = $preferences;
}
/**
* Returns one of a user’s preferences by its key.
*
* @param int $userId The user’s ID
* @param string $key The preference’s key
* @param mixed $default The default value, if the preference hasn’t been set
* @return mixed The user’s preference
*/
public function getUserPreference(int $userId, string $key, mixed $default = null): mixed
{
$preferences = $this->getUserPreferences($userId);
return $preferences[$key] ?? $default;
}
/**
* Sends a new account activation email for a user, regardless of their status.
*
* A new verification code will generated for the user overwriting any existing one.
*
* @param User $user The user to send the activation email to.
* @return bool Whether the email was sent successfully.
* @throws InvalidElementException if the user doesn't validate
*/
public function sendActivationEmail(User $user): bool
{
$url = $this->getActivationUrl($user);
return Craft::$app->getMailer()
->composeFromKey('account_activation', ['link' => Template::raw($url)])
->setTo($user)
->send();
}
/**
* Sends a new email verification email to a user, regardless of their status.
*
* A new verification code will generated for the user overwriting any existing one.
*
* @param User $user The user to send the activation email to.
* @return bool Whether the email was sent successfully.
* @throws InvalidElementException if the user doesn't validate
*/
public function sendNewEmailVerifyEmail(User $user): bool
{
$url = $this->getEmailVerifyUrl($user);
return Craft::$app->getMailer()
->composeFromKey('verify_new_email', ['link' => Template::raw($url)])
->setTo($user)
->send();
}
/**
* Sends a password reset email to a user.
*
* A new verification code be will generated for the user, overwriting any existing one.
*
* @param User $user The user to send the forgot password email to.
* @return bool Whether the email was sent successfully.
* @throws InvalidElementException if the user doesn't validate
*/
public function sendPasswordResetEmail(User $user): bool
{
$url = $this->getPasswordResetUrl($user);
return Craft::$app->getMailer()
->composeFromKey('forgot_password', ['link' => Template::raw($url)])
->setTo($user)
->send();
}
/**
* Sets a new verification code on a user, and returns their activation URL.
*
* @param User $user
* @return string
* @throws InvalidElementException if the user doesn't validate
*/
public function getActivationUrl(User $user): string
{
// If the user doesn't have a password yet, use a Password Reset URL
if (!$user->password) {
return $this->getPasswordResetUrl($user);
}
return $this->getEmailVerifyUrl($user);
}
/**
* Sets a new verification code on a user, and returns their new Email Verification URL.
*
* @param User $user The user that should get the new Email Verification URL.
* @return string The new Email Verification URL.
* @throws InvalidElementException if the user doesn't validate
*/
public function getEmailVerifyUrl(User $user): string
{
$fePath = Craft::$app->getConfig()->getGeneral()->getVerifyEmailPath();
return $this->_getUserUrl($user, $fePath, Request::CP_PATH_VERIFY_EMAIL);
}
/**
* Sets a new verification code on a user, and returns their new Password Reset URL.
*
* @param User $user The user that should get the new Password Reset URL
* @return string The new Password Reset URL.
* @throws InvalidElementException if the user doesn't validate
*/
public function getPasswordResetUrl(User $user): string
{
$fePath = Craft::$app->getConfig()->getGeneral()->getSetPasswordPath();
return $this->_getUserUrl($user, $fePath, Request::CP_PATH_SET_PASSWORD);
}
/**
* Removes credentials for a user.
*
* @param User $user The user that should have credentials removed.
* @throws InvalidElementException
* @since 4.0.0
*/
public function removeCredentials(User $user): void
{
$userRecord = $this->_getUserRecordById($user->id);
$userRecord->active = false;
$userRecord->pending = false;
$userRecord->password = null;
$userRecord->verificationCode = null;
if (!$userRecord->save()) {
$user->addErrors($userRecord->getErrors());
throw new InvalidElementException($user);
}
$user->active = false;
$user->pending = false;
$user->password = null;
$user->verificationCode = null;
}
/**
* Crops and saves a user’s photo.
*
* @param User $user the user.
* @param string $fileLocation the local image path on server
* @param string|null $filename name of the file to use, defaults to filename of `$fileLocation`
* @throws ImageException if the file provided is not a manipulatable image
* @throws VolumeException if the user photo volume is not provided or is invalid
*/
public function saveUserPhoto(string $fileLocation, User $user, ?string $filename = null): void
{
$filename = AssetsHelper::prepareAssetName($filename ?? pathinfo($fileLocation, PATHINFO_BASENAME), true, true);
if (!Image::canManipulateAsImage(pathinfo($fileLocation, PATHINFO_EXTENSION))) {
throw new ImageException(Craft::t('app', 'User photo must be an image that Craft can manipulate.'));
}
$assetsService = Craft::$app->getAssets();
$photoId = $user->photoId;
// Fire a 'beforeSaveUserPhoto' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_USER_PHOTO)) {
$event = new UserPhotoEvent([
'user' => $user,
'photoId' => $photoId,
]);
$this->trigger(self::EVENT_BEFORE_SAVE_USER_PHOTO, $event);
$photoId = $event->photoId;
}
// If the photo exists, just replace the file.
if ($photoId && ($photo = Craft::$app->getAssets()->getAssetById($photoId)) !== null) {
$assetsService->replaceAssetFile($photo, $fileLocation, $filename);
} else {
$volume = $this->_userPhotoVolume();
$folderId = $this->_userPhotoFolderId($user, $volume);
$filename = $assetsService->getNameReplacementInFolder($filename, $folderId);
$photo = new Asset();
$photo->setScenario(Asset::SCENARIO_CREATE);
$photo->tempFilePath = $fileLocation;
$photo->setFilename($filename);
$photo->newFolderId = $folderId;
$photo->setVolumeId($volume->id);
// Save photo.
$elementsService = Craft::$app->getElements();
$elementsService->saveElement($photo);
$user->setPhoto($photo);
$elementsService->saveElement($user, false);
}
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_USER_PHOTO)) {
$this->trigger(self::EVENT_AFTER_SAVE_USER_PHOTO, new UserPhotoEvent([
'photoId' => $photo->id,
'user' => $user,
]));
}
}
/**
* Updates the location of a user’s photo.
*
* @param User $user
* @since 3.5.14
*/
public function relocateUserPhoto(User $user): void
{
if (!$user->photoId || ($photo = $user->getPhoto()) === null) {
return;
}
$volume = $this->_userPhotoVolume();
$folderId = $this->_userPhotoFolderId($user, $volume);
if ($photo->folderId == $folderId) {
return;
}
$photo->setScenario(Asset::SCENARIO_MOVE);
$photo->avoidFilenameConflicts = true;
$photo->newFolderId = $folderId;
Craft::$app->getElements()->saveElement($photo);
}
/**
* Returns the user photo volume.
*
* @return Volume
* @throws VolumeException if no user photo volume is set, or it's set to an invalid volume UID
*/
private function _userPhotoVolume(): Volume
{
$uid = Craft::$app->getProjectConfig()->get('users.photoVolumeUid');
if (!$uid) {
throw new VolumeException('No user photo volume is set.');
}
$volume = Craft::$app->getVolumes()->getVolumeByUid($uid);
if ($volume === null) {
throw new VolumeException("Invalid volume UID: $uid");
}
return $volume;
}
/**
* Returns the folder that a user’s photo should be stored.
*
* @param User $user
* @param Volume $volume The user photo volume
* @return int
* @throws VolumeException if the user photo volume doesn’t exist
* @throws InvalidSubpathException if the user photo subpath can’t be resolved
*/
private function _userPhotoFolderId(User $user, Volume $volume): int
{
$subpath = (string)Craft::$app->getProjectConfig()->get('users.photoSubpath');
if ($subpath !== '') {
try {
$subpath = Craft::$app->getView()->renderObjectTemplate($subpath, $user);
} catch (Throwable) {
throw new InvalidSubpathException($subpath);
}
}
return Craft::$app->getAssets()->ensureFolderByFullPathAndVolume($subpath, $volume)->id;
}
/**
* Deletes a user’s photo.
*
* @param User $user The user
* @return bool Whether the user’s photo was deleted successfully
*/
public function deleteUserPhoto(User $user): bool
{
$photoId = $user->photoId;
if ($this->hasEventHandlers(self::EVENT_BEFORE_DELETE_USER_PHOTO)) {
$this->trigger(self::EVENT_BEFORE_DELETE_USER_PHOTO, new UserPhotoEvent([
'user' => $user,
'photoId' => $photoId,
]));
}
$result = Craft::$app->getElements()->deleteElementById($photoId, Asset::class);
if ($result) {
$user->setPhoto(null);
if ($this->hasEventHandlers(self::EVENT_AFTER_DELETE_USER_PHOTO)) {
$this->trigger(self::EVENT_AFTER_DELETE_USER_PHOTO, new UserPhotoEvent([
'user' => $user,
'photoId' => $photoId,
]));
}
}
return $result;
}
/**
* Handles a valid login for a user.
*
* @param User $user The user
*/
public function handleValidLogin(User $user): void
{
$now = DateTimeHelper::currentUTCDateTime();
// Update the User record
$userRecord = $this->_getUserRecordById($user->id);
$userRecord->lastLoginDate = Db::prepareDateForDb($now);
$userRecord->invalidLoginWindowStart = null;
$userRecord->invalidLoginCount = null;
if (Craft::$app->getConfig()->getGeneral()->storeUserIps) {
$userRecord->lastLoginAttemptIp = Craft::$app->getRequest()->getUserIP();
}
$userRecord->save();
// Update the User model too
$user->lastLoginDate = $now;
$user->invalidLoginCount = null;
// Invalidate caches
Craft::$app->getElements()->invalidateCachesForElement($user);
}
/**
* Handles an invalid login for a user.
*
* @param User $user The user
*/
public function handleInvalidLogin(User $user): void
{
$userRecord = $this->_getUserRecordById($user->id);
$now = DateTimeHelper::currentUTCDateTime();
$userRecord->lastInvalidLoginDate = Db::prepareDateForDb($now);
if (Craft::$app->getConfig()->getGeneral()->storeUserIps) {
$userRecord->lastLoginAttemptIp = Craft::$app->getRequest()->getUserIP();
}
// Was that one too many?
$maxInvalidLogins = Craft::$app->getConfig()->getGeneral()->maxInvalidLogins;
$alreadyLocked = $user->locked;
if ($maxInvalidLogins) {
if ($this->_isUserInsideInvalidLoginWindow($userRecord)) {
$userRecord->invalidLoginCount++;
// Was that one bad password too many?
if ($userRecord->invalidLoginCount >= $maxInvalidLogins) {
$userRecord->locked = true;
$userRecord->invalidLoginCount = null;
$userRecord->invalidLoginWindowStart = null;
$userRecord->lockoutDate = Db::prepareDateForDb($now);
$user->locked = true;
$user->lockoutDate = $now;
}
} else {
// Start the invalid login window and counter
$userRecord->invalidLoginWindowStart = Db::prepareDateForDb($now);
$userRecord->invalidLoginCount = 1;
}
// Update the counter on the user model
$user->invalidLoginCount = $userRecord->invalidLoginCount;
}
$userRecord->save();
// Update the User model too
$user->lastInvalidLoginDate = $now;
if (!$alreadyLocked && $user->locked && $this->hasEventHandlers(self::EVENT_AFTER_LOCK_USER)) {
// Fire an 'afterLockUser' event
$this->trigger(self::EVENT_AFTER_LOCK_USER, new UserEvent([
'user' => $user,
]));
}
// Invalidate caches
Craft::$app->getElements()->invalidateCachesForElement($user);
}
/**
* Activates a user, bypassing email verification.
*
* @param User $user The user.
* @throws InvalidElementException
*/
public function activateUser(User $user): void
{
// Fire a 'beforeActivateUser' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_ACTIVATE_USER)) {
$event = new UserEvent(['user' => $user]);
$this->trigger(self::EVENT_BEFORE_ACTIVATE_USER, $event);
if (!$event->isValid) {
throw new InvalidElementException($user);
}
}
$originalUser = clone $user;
$user->setScenario(User::SCENARIO_ACTIVATION);
$user->active = true;
$user->pending = false;
$user->locked = false;
$user->suspended = false;
$user->verificationCode = null;
$user->verificationCodeIssuedDate = null;
$user->invalidLoginCount = null;
$user->lastInvalidLoginDate = null;
$user->lockoutDate = null;
if (!$user->validate()) {
$user->active = $originalUser->active;
$user->pending = $originalUser->pending;
$user->locked = $originalUser->locked;
$user->suspended = $originalUser->suspended;
$user->verificationCode = $originalUser->verificationCode;
$user->verificationCodeIssuedDate = $originalUser->verificationCodeIssuedDate;
$user->invalidLoginCount = $originalUser->invalidLoginCount;
$user->lastInvalidLoginDate = $originalUser->lastInvalidLoginDate;
$user->lockoutDate = $originalUser->lockoutDate;
throw new InvalidElementException($user);
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$userRecord = $this->_getUserRecordById($user->id);
$userRecord->active = true;
$userRecord->pending = false;
$userRecord->locked = false;
$userRecord->suspended = false;
$userRecord->verificationCode = null;
$userRecord->verificationCodeIssuedDate = null;
$userRecord->invalidLoginWindowStart = null;
$userRecord->invalidLoginCount = null;
$userRecord->lastInvalidLoginDate = null;
$userRecord->lockoutDate = null;
$userRecord->save();
// If they have an unverified email address, now is the time to set it to their primary email address
$this->verifyEmailForUser($user);
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Fire an 'afterActivateUser' event
if ($this->hasEventHandlers(self::EVENT_AFTER_ACTIVATE_USER)) {
$this->trigger(self::EVENT_AFTER_ACTIVATE_USER, new UserEvent([
'user' => $user,
]));
}
// Invalidate caches
Craft::$app->getElements()->invalidateCachesForElement($user);
}
/**
* Deactivates a user.
*
* @param User $user The user.
* @throws Throwable if reasons
* @since 4.0.0
* @throws InvalidElementException
*/
public function deactivateUser(User $user): void
{
// Fire a 'beforeActivateUser' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DEACTIVATE_USER)) {
$event = new UserEvent(['user' => $user]);
$this->trigger(self::EVENT_BEFORE_DEACTIVATE_USER, $event);
if (!$event->isValid) {
throw new InvalidElementException($user);
}
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$userRecord = $this->_getUserRecordById($user->id);
$userRecord->active = false;
$userRecord->pending = false;
$userRecord->locked = false;
$userRecord->suspended = false;
$userRecord->verificationCode = null;
$userRecord->verificationCodeIssuedDate = null;
$userRecord->invalidLoginWindowStart = null;
$userRecord->invalidLoginCount = null;
$userRecord->lastInvalidLoginDate = null;
$userRecord->lockoutDate = null;
$userRecord->save();
$user->active = false;
$user->pending = false;
$user->locked = false;
$user->suspended = false;
$user->verificationCode = null;
$user->verificationCodeIssuedDate = null;
$user->invalidLoginCount = null;
$user->lastInvalidLoginDate = null;
$user->lockoutDate = null;
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Fire an 'afterActivateUser' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DEACTIVATE_USER)) {
$this->trigger(self::EVENT_AFTER_DEACTIVATE_USER, new UserEvent([
'user' => $user,
]));
}
// Invalidate caches
Craft::$app->getElements()->invalidateCachesForElement($user);
}
/**
* If 'unverifiedEmail' is set on the User, then this method will transfer it to the official email property
* and clear the unverified one.
*
* @param User $user
* @throws InvalidElementException
*/
public function verifyEmailForUser(User $user): void
{
// Bail if they don't have an unverified email to begin with
if (!$user->unverifiedEmail) {
return;
}
$userRecord = $this->_getUserRecordById($user->id);
$userRecord->email = $user->unverifiedEmail;
$userRecord->unverifiedEmail = null;
if (Craft::$app->getConfig()->getGeneral()->useEmailAsUsername) {
$userRecord->username = $user->unverifiedEmail;
}
if (!$userRecord->save()) {
$user->addErrors($userRecord->getErrors());
throw new InvalidElementException($user);
}
// If the user status is pending, let's activate them.
if ($userRecord->pending) {
$this->activateUser($user);
}
}
/**
* Unlocks a user, bypassing the cooldown phase.
*
* @param User $user The user.
* @throws InvalidElementException
*/
public function unlockUser(User $user): void
{
// Fire a 'beforeUnlockUser' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_UNLOCK_USER)) {
$event = new UserEvent(['user' => $user]);
$this->trigger(self::EVENT_BEFORE_UNLOCK_USER, $event);
if (!$event->isValid) {
throw new InvalidElementException($user);
}
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$userRecord = $this->_getUserRecordById($user->id);
$userRecord->locked = false;
$userRecord->invalidLoginCount = null;
$userRecord->invalidLoginWindowStart = null;
$userRecord->lockoutDate = null;
$userRecord->save();
$transaction->commit();
} catch (Throwable $e) {