-
Notifications
You must be signed in to change notification settings - Fork 612
/
UsersController.php
1975 lines (1687 loc) · 51.1 KB
/
UsersController.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
namespace Craft;
/**
* The UsersController class is a controller that handles various user account related tasks such as logging-in,
* impersonating a user, logging out, forgetting passwords, setting passwords, validating accounts, activating
* accounts, creating users, saving users, processing user avatars, deleting, suspending and un-suspending users.
*
* Note that all actions in the controller, except {@link actionLogin}, {@link actionLogout}, {@link actionGetAuthTimeout},
* {@link actionSendPasswordResetEmail}, {@link actionSetPassword}, {@link actionVerifyEmail} and {@link actionSaveUser} require an
* authenticated Craft session via {@link BaseController::allowAnonymous}.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @copyright Copyright (c) 2014, Pixel & Tonic, Inc.
* @license http://craftcms.com/license Craft License Agreement
* @see http://craftcms.com
* @package craft.app.controllers
* @since 1.0
*/
class UsersController extends BaseController
{
// Properties
// =========================================================================
/**
* If set to false, you are required to be logged in to execute any of the given controller's actions.
*
* If set to true, anonymous access is allowed for all of the given controller's actions.
*
* If the value is an array of action names, then you must be logged in for any action method except for the ones in
* the array list.
*
* If you have a controller that where the majority of action methods will be anonymous, but you only want require
* login on a few, it's best to use {@link UserSessionService::requireLogin() craft()->userSession->requireLogin()}
* in the individual methods.
*
* @var bool
*/
protected $allowAnonymous = array('actionLogin', 'actionLogout', 'actionGetAuthTimeout', 'actionForgotPassword', 'actionSendPasswordResetEmail', 'actionSendActivationEmail', 'actionSaveUser', 'actionSetPassword', 'actionVerifyEmail');
// Public Methods
// =========================================================================
/**
* Displays the login template, and handles login post requests.
*
* @return null
*/
public function actionLogin()
{
if (craft()->userSession->isLoggedIn())
{
// Too easy.
$this->_handleSuccessfulLogin(false);
}
if (craft()->request->isPostRequest())
{
// First, a little house-cleaning for expired, pending users.
craft()->users->purgeExpiredPendingUsers();
$loginName = craft()->request->getPost('loginName');
$password = craft()->request->getPost('password');
$rememberMe = (bool) craft()->request->getPost('rememberMe');
if (craft()->userSession->login($loginName, $password, $rememberMe))
{
$this->_handleSuccessfulLogin(true);
}
else
{
$errorCode = craft()->userSession->getLoginErrorCode();
$errorMessage = craft()->userSession->getLoginErrorMessage($errorCode, $loginName);
if (craft()->request->isAjaxRequest())
{
$this->returnJson(array(
'errorCode' => $errorCode,
'error' => $errorMessage
));
}
else
{
craft()->userSession->setError($errorMessage);
craft()->urlManager->setRouteVariables(array(
'loginName' => $loginName,
'rememberMe' => $rememberMe,
'errorCode' => $errorCode,
'errorMessage' => $errorMessage,
));
}
}
}
}
/**
* Logs a user in for impersonation. Requires you to be an administrator.
*
* @return null
*/
public function actionImpersonate()
{
$this->requireLogin();
$this->requireAdmin();
$this->requirePostRequest();
$userId = craft()->request->getPost('userId');
$originalUserId = craft()->userSession->getId();
craft()->httpSession->add(UserSessionService::USER_IMPERSONATE_KEY, $originalUserId);
if (craft()->userSession->loginByUserId($userId))
{
craft()->userSession->setNotice(Craft::t('Logged in.'));
$this->_handleSuccessfulLogin(true);
}
else
{
craft()->httpSession->remove(UserSessionService::USER_IMPERSONATE_KEY);
craft()->userSession->setError(Craft::t('There was a problem impersonating this user.'));
Craft::log(craft()->userSession->getUser()->username.' tried to impersonate userId: '.$userId.' but something went wrong.', LogLevel::Error);
}
}
/**
* Returns how many seconds are left in the current user session.
*
* @return null
*/
public function actionGetAuthTimeout()
{
$return = array('timeout' => craft()->userSession->getAuthTimeout());
if (craft()->config->get('enableCsrfProtection'))
{
$return['csrfTokenValue'] = craft()->request->getCsrfToken();
}
$this->returnJson($return);
}
/**
* Returns how many seconds are left in the current elevated user session.
*
* @return null
*/
public function actionGetElevatedSessionTimeout()
{
$return = array(
'timeout' => craft()->userSession->getElevatedSessionTimeout()
);
$this->returnJson($return);
}
/**
* Starts an elevated user session.
*
* @return null
*/
public function actionStartElevatedSession()
{
$password = craft()->request->getPost('password');
$success = craft()->userSession->startElevatedSession($password);
$this->returnJson(array(
'success' => $success
));
}
/**
* @return null
*/
public function actionLogout()
{
craft()->userSession->logout(false);
if (craft()->config->get('enableCsrfProtection'))
{
// Manually nuke the CSRF cookie (if there is one).
craft()->request->deleteCookie(craft()->request->csrfTokenName);
// Generate a new one.
craft()->request->getCsrfToken();
}
if (craft()->request->isAjaxRequest())
{
$this->returnJson(array(
'success' => true
));
}
else
{
$this->redirect('');
}
}
/**
* Sends a password reset email.
*
* @throws HttpException
* @return null
*/
public function actionSendPasswordResetEmail()
{
$this->requirePostRequest();
$errors = array();
$existingUser = false;
// If someone's logged in and they're allowed to edit other users, then see if a userId was submitted
if (craft()->userSession->checkPermission('editUsers'))
{
$userId = craft()->request->getPost('userId');
if ($userId)
{
$user = craft()->users->getUserById($userId);
if (!$user)
{
throw new HttpException(404);
}
$existingUser = true;
}
}
if (!isset($user))
{
$loginName = craft()->request->getPost('loginName');
if (!$loginName)
{
// If they didn't even enter a username/email, just bail now.
$errors[] = Craft::t('Username or email is required.');
$this->_handleSendPasswordResetError($errors);
return;
}
$user = craft()->users->getUserByUsernameOrEmail($loginName);
if (!$user)
{
$errors[] = Craft::t('Invalid username or email.');
}
}
if (!empty($user))
{
if (!craft()->users->sendPasswordResetEmail($user))
{
$errors[] = Craft::t('There was a problem sending the password reset email.');
}
}
// If there haven't been any errors, or there were, and it's not one logged in user editing another
// and we want to pretend like there wasn't any errors...
if (empty($errors) || (count($errors) > 0 && !$existingUser && craft()->config->get('preventUserEnumeration')))
{
if (craft()->request->isAjaxRequest())
{
$this->returnJson(array('success' => true));
}
else
{
craft()->userSession->setNotice(Craft::t('Password reset email sent.'));
$this->redirectToPostedUrl();
}
}
// Handle the errors.
$this->_handleSendPasswordResetError($errors, $loginName);
}
/**
* Generates a new verification code for a given user, and returns its URL.
*
* @throws HttpException|Exception
* @return null
*/
public function actionGetPasswordResetUrl()
{
$this->requireAdmin();
if (!$this->_verifyElevatedSession())
{
throw new HttpException(403);
}
$userId = craft()->request->getRequiredParam('userId');
$user = craft()->users->getUserById($userId);
if (!$user)
{
$this->_noUserExists($userId);
}
echo craft()->users->getPasswordResetUrl($user);
craft()->end();
}
/**
* Sets a user's password once they've verified they have access to their email.
*
* @throws HttpException|Exception
* @return null
*/
public function actionSetPassword()
{
// Have they just submitted a password, or are we just displaying the page?
if (!craft()->request->isPostRequest())
{
if ($info = $this->_processTokenRequest())
{
$userToProcess = $info['userToProcess'];
$id = $info['id'];
$code = $info['code'];
craft()->userSession->processUsernameCookie($userToProcess->username);
// Send them to the set password template.
$this->_renderSetPasswordTemplate($userToProcess, array(
'code' => $code,
'id' => $id,
'newUser' => ($userToProcess->password ? false : true),
));
}
}
else
{
// POST request. They've just set the password.
$code = craft()->request->getRequiredPost('code');
$id = craft()->request->getRequiredParam('id');
$userToProcess = craft()->users->getUserByUid($id);
// See if we still have a valid token.
$isCodeValid = craft()->users->isVerificationCodeValidForUser($userToProcess, $code);
if (!$userToProcess || !$isCodeValid)
{
$this->_processInvalidToken($userToProcess);
}
$newPassword = craft()->request->getRequiredPost('newPassword');
$userToProcess->newPassword = $newPassword;
if ($userToProcess->passwordResetRequired)
{
$forceDifferentPassword = true;
}
else
{
$forceDifferentPassword = false;
}
if (craft()->users->changePassword($userToProcess, $forceDifferentPassword))
{
if ($userToProcess->status == UserStatus::Pending)
{
// Activate them
craft()->users->activateUser($userToProcess);
// Treat this as an activation request
$this->_onAfterActivateUser($userToProcess);
}
// Can they access the CP?
if ($userToProcess->can('accessCp'))
{
// Send them to the CP login page
$url = UrlHelper::getCpUrl(craft()->config->getCpLoginPath());
}
else
{
// Send them to the 'setPasswordSuccessPath'.
$setPasswordSuccessPath = craft()->config->getLocalized('setPasswordSuccessPath');
$url = UrlHelper::getSiteUrl($setPasswordSuccessPath);
}
$this->redirect($url);
}
craft()->userSession->setNotice(Craft::t('Couldn’t update password.'));
$errors = $userToProcess->getErrors('newPassword');
$this->_renderSetPasswordTemplate($userToProcess, array(
'errors' => $errors,
'code' => $code,
'id' => $id,
'newUser' => ($userToProcess->password ? false : true),
));
}
}
/**
* Verifies that a user has access to an email address.
*
* @deprecated Deprecated in 2.3. Use {@link UsersController::actionVerifyEmail()} instead.
* @return null
*/
public function actionValidate()
{
craft()->deprecator->log('UsersController::validate()', 'The users/validate action has been deprecated. Use users/verifyEmail instead.');
$this->actionVerifyEmail();
}
/**
* Verifies that a user has access to an email address.
*
* @return null
*/
public function actionVerifyEmail()
{
if ($info = $this->_processTokenRequest())
{
$userToProcess = $info['userToProcess'];
$userIsPending = $userToProcess->status == UserStatus::Pending;
if (craft()->users->verifyEmailForUser($userToProcess))
{
if ($userIsPending)
{
// They were just activated, so treat this as an activation request
$this->_onAfterActivateUser($userToProcess);
}
// Redirect to the site/CP root
$url = UrlHelper::getUrl('');
$this->redirect($url);
}
$this->renderTemplate('_special/emailtaken', array('email' => $userToProcess->unverifiedEmail));
}
}
/**
* Manually activates a user account. Only admins have access.
*
* @return null
*/
public function actionActivateUser()
{
$this->requireAdmin();
$this->requirePostRequest();
$userId = craft()->request->getRequiredPost('userId');
$user = craft()->users->getUserById($userId);
if (!$user)
{
$this->_noUserExists($userId);
}
if (craft()->users->activateUser($user))
{
craft()->userSession->setNotice(Craft::t('Successfully activated the user.'));
}
else
{
craft()->userSession->setError(Craft::t('There was a problem activating the user.'));
}
$this->redirectToPostedUrl();
}
/**
* Edit a user account.
*
* @param array $variables
* @param string|null $account
*
* @throws HttpException
* @return null
*/
public function actionEditUser(array $variables = array(), $account = null)
{
// Determine which user account we're editing
// ---------------------------------------------------------------------
$craftEdition = craft()->getEdition();
$isClientAccount = false;
// This will be set if there was a validation error.
if (empty($variables['account']))
{
// Are we editing a specific user account?
if ($account !== null)
{
switch ($account)
{
case 'current':
{
$variables['account'] = craft()->userSession->getUser();
break;
}
case 'client':
{
$isClientAccount = true;
$variables['account'] = craft()->users->getClient();
if (!$variables['account'])
{
// Registering the Client
$variables['account'] = new UserModel();
$variables['account']->client = true;
}
break;
}
default:
{
throw new HttpException(404);
}
}
}
else if (!empty($variables['userId']))
{
$variables['account'] = craft()->users->getUserById($variables['userId']);
if (!$variables['account'])
{
throw new HttpException(404);
}
}
else if ($craftEdition == Craft::Pro)
{
// Registering a new user
$variables['account'] = new UserModel();
}
else
{
// Nada.
throw new HttpException(404);
}
}
else
{
if ($account == 'client')
{
$isClientAccount = true;
}
}
$variables['isNewAccount'] = !$variables['account']->id;
// Make sure they have permission to edit this user
// ---------------------------------------------------------------------
if (!$variables['account']->isCurrent())
{
if ($variables['isNewAccount'])
{
craft()->userSession->requirePermission('registerUsers');
}
else
{
craft()->userSession->requirePermission('editUsers');
}
}
// Determine which actions should be available
// ---------------------------------------------------------------------
$statusActions = array();
$loginActions = array();
$sketchyActions = array();
if ($craftEdition >= Craft::Client && !$variables['isNewAccount'])
{
switch ($variables['account']->getStatus())
{
case UserStatus::Pending:
{
$variables['statusLabel'] = Craft::t('Unverified');
$statusActions[] = array('action' => 'users/sendActivationEmail', 'label' => Craft::t('Send activation email'));
if (craft()->userSession->isAdmin())
{
$statusActions[] = array('id' => 'copy-passwordreset-url', 'label' => Craft::t('Copy activation URL'));
$statusActions[] = array('action' => 'users/activateUser', 'label' => Craft::t('Activate account'));
}
break;
}
case UserStatus::Locked:
{
$variables['statusLabel'] = Craft::t('Locked');
if (craft()->userSession->checkPermission('administrateUsers'))
{
$statusActions[] = array('action' => 'users/unlockUser', 'label' => Craft::t('Unlock'));
}
break;
}
case UserStatus::Suspended:
{
$variables['statusLabel'] = Craft::t('Suspended');
if (craft()->userSession->checkPermission('administrateUsers'))
{
$statusActions[] = array('action' => 'users/unsuspendUser', 'label' => Craft::t('Unsuspend'));
}
break;
}
case UserStatus::Active:
{
$variables['statusLabel'] = Craft::t('Active');
if (!$variables['account']->isCurrent())
{
$statusActions[] = array('action' => 'users/sendPasswordResetEmail', 'label' => Craft::t('Send password reset email'));
if (craft()->userSession->isAdmin())
{
$statusActions[] = array('id' => 'copy-passwordreset-url', 'label' => Craft::t('Copy password reset URL'));
}
}
break;
}
}
if (!$variables['account']->isCurrent())
{
if (craft()->userSession->isAdmin())
{
$loginActions[] = array('action' => 'users/impersonate', 'label' => Craft::t('Login as {user}', array('user' => $variables['account']->getName())));
}
if (craft()->userSession->checkPermission('administrateUsers') && $variables['account']->getStatus() != UserStatus::Suspended)
{
$sketchyActions[] = array('action' => 'users/suspendUser', 'label' => Craft::t('Suspend'));
}
if (craft()->userSession->checkPermission('deleteUsers'))
{
// Even if they have delete user permissions, we don't want a non-admin
// to be able to delete an admin.
$currentUser = craft()->userSession->getUser();
if (($currentUser && $currentUser->admin) || !$variables['account']->admin) {
$sketchyActions[] = array('id' => 'delete-btn', 'label' => Craft::t('Delete…'));
}
}
}
}
$variables['actions'] = array();
if ($statusActions)
{
array_push($variables['actions'], $statusActions);
}
// Give plugins a chance to add more actions
$pluginActions = craft()->plugins->call('addUserAdministrationOptions', array($variables['account']), true);
if ($pluginActions)
{
$variables['actions'] = array_merge($variables['actions'], array_values($pluginActions));
}
if ($loginActions)
{
array_push($variables['actions'], $loginActions);
}
if ($sketchyActions)
{
array_push($variables['actions'], $sketchyActions);
}
// Set the appropriate page title
// ---------------------------------------------------------------------
if (!$variables['isNewAccount'])
{
if ($variables['account']->isCurrent())
{
$variables['title'] = Craft::t('My Account');
}
else
{
$variables['title'] = Craft::t("{user}’s Account", array('user' => $variables['account']->name));
}
}
else if ($isClientAccount)
{
$variables['title'] = Craft::t('Register the client’s account');
}
else
{
$variables['title'] = Craft::t("Register a new user");
}
// ---------------------------------------------------------------------
$variables['selectedTab'] = 'account';
$variables['tabs'] = array(
'account' => array(
'label' => Craft::t('Account'),
'url' => '#account',
)
);
// No need to show the Profile tab if it's a new user (can't have an avatar yet) and there's no user fields.
if (!$variables['isNewAccount'] || ($craftEdition == Craft::Pro && $variables['account']->getFieldLayout()->getFields()))
{
$variables['tabs']['profile'] = array(
'label' => Craft::t('Profile'),
'url' => '#profile',
);
}
// Show the permission tab for the users that can change them on Craft Client+ editions (unless
// you're on Client and you're the admin account. No need to show since we always need an admin on Client)
if (
($craftEdition == Craft::Pro && craft()->userSession->getUser()->can('assignUserPermissions')) ||
($craftEdition == Craft::Client && $isClientAccount && craft()->userSession->isAdmin())
)
{
$variables['tabs']['perms'] = array(
'label' => Craft::t('Permissions'),
'url' => '#perms',
);
}
// Just one tab looks awkward, so just don't show them at all then.
if (count($variables['tabs']) == 1)
{
$variables['tabs'] = array();
}
else
{
if ($variables['account']->hasErrors())
{
// Add the 'error' class to any tabs that have errors
$errors = $variables['account']->getErrors();
$accountFields = array('username', 'firstName', 'lastName', 'email', 'password', 'newPassword', 'currentPassword', 'passwordResetRequired', 'preferredLocale');
foreach ($errors as $attribute => $error)
{
if (isset($variables['tabs']['account']) && in_array($attribute, $accountFields))
{
$variables['tabs']['account']['class'] = 'error';
}
else if (isset($variables['tabs']['profile']))
{
$variables['tabs']['profile']['class'] = 'error';
}
}
}
}
// Load the resources and render the page
// ---------------------------------------------------------------------
craft()->templates->includeCssResource('css/account.css');
craft()->templates->includeJsResource('js/AccountSettingsForm.js');
craft()->templates->includeJs('new Craft.AccountSettingsForm('.JsonHelper::encode($variables['account']->id).', '.($variables['account']->isCurrent() ? 'true' : 'false').');');
craft()->templates->includeTranslations(
'Please enter your current password.',
'Please enter your password.'
);
$this->renderTemplate('users/_edit', $variables);
}
/**
* Provides an endpoint for saving a user account.
*
* This action accounts for the following scenarios:
*
* - An admin registering a new user account.
* - An admin editing an existing user account.
* - A normal user with user-administration permissions registering a new user account.
* - A normal user with user-administration permissions editing an existing user account.
* - A guest registering a new user account ("public registration").
*
* This action behaves the same regardless of whether it was requested from the Control Panel or the front-end site.
*
* @throws HttpException|Exception
* @return null
*/
public function actionSaveUser()
{
$this->requirePostRequest();
$craftEdition = craft()->getEdition();
$currentUser = craft()->userSession->getUser();
$requireEmailVerification = craft()->systemSettings->getSetting('users', 'requireEmailVerification');
// Get the user being edited
// ---------------------------------------------------------------------
$userId = craft()->request->getPost('userId');
$isNewUser = !$userId;
$thisIsPublicRegistration = false;
// Are we editing an existing user?
if ($userId)
{
$user = craft()->users->getUserById($userId);
if (!$user)
{
throw new Exception(Craft::t('No user exists with the ID “{id}”.', array('id' => $userId)));
}
if (!$user->isCurrent())
{
// Make sure they have permission to edit other users
craft()->userSession->requirePermission('editUsers');
}
}
else if ($craftEdition == Craft::Client)
{
// Make sure they're logged in
craft()->userSession->requireAdmin();
// Make sure there's no Client user yet
if (craft()->users->getClient())
{
throw new Exception(Craft::t('A client account already exists.'));
}
$user = new UserModel();
$user->client = true;
}
else
{
// Make sure this is Craft Pro, since that's required for having multiple user accounts
craft()->requireEdition(Craft::Pro);
// Is someone logged in?
if ($currentUser)
{
// Make sure they have permission to register users
craft()->userSession->requirePermission('registerUsers');
}
else
{
// Make sure public registration is allowed
if (!craft()->systemSettings->getSetting('users', 'allowPublicRegistration'))
{
throw new HttpException(403);
}
$thisIsPublicRegistration = true;
}
$user = new UserModel();
}
$isCurrentUser = $user->isCurrent();
if ($isCurrentUser)
{
// Remember the old username in case it changes
$oldUsername = $user->username;
}
// Handle secure properties (email and password)
// ---------------------------------------------------------------------
$verifyNewEmail = false;
// Are they allowed to set the email address?
if ($isNewUser || $isCurrentUser || $currentUser->can('changeUserEmails'))
{
$newEmail = craft()->request->getPost('email');
// Did it just change?
if ($newEmail && $newEmail == $user->email)
{
$newEmail = null;
}
if ($newEmail)
{
// Does that email need to be verified?
if ($requireEmailVerification && (!$currentUser || !$currentUser->admin || craft()->request->getPost('sendVerificationEmail')))
{
// Save it as an unverified email for now
$user->unverifiedEmail = $newEmail;
$verifyNewEmail = true;
// If this is a new user, set it as their main email address too
if ($isNewUser)
{
$user->email = $newEmail;
}
}
else
{
// We trust them
$user->email = $newEmail;
}
}
}
// Are they allowed to set a new password?
if ($thisIsPublicRegistration)
{
if (!craft()->config->get('deferPublicRegistrationPassword'))
{
$user->newPassword = craft()->request->getPost('password', '');
}
}
else if ($isCurrentUser)
{
// If there was a newPassword input but it was empty, pretend it didn't exist
$user->newPassword = (craft()->request->getPost('newPassword') ?: null);
}
// If editing an existing user and either of these properties are being changed,
// require the user's current password for additional security
if (!$isNewUser && (!empty($newEmail) || $user->newPassword))
{
if (!$this->_verifyElevatedSession())
{
Craft::log('Tried to change the email or password for userId: '.$user->id.', but the current password does not match what the user supplied.', LogLevel::Warning);
$user->addError('currentPassword', Craft::t('Incorrect current password.'));
}
}
// Handle the rest of the user properties
// ---------------------------------------------------------------------
// Is the site set to use email addresses as usernames?
if (craft()->config->get('useEmailAsUsername'))
{
$user->username = $user->email;
}
else
{
$user->username = craft()->request->getPost('username', ($user->username ? $user->username : $user->email));
}
$user->firstName = craft()->request->getPost('firstName', $user->firstName);
$user->lastName = craft()->request->getPost('lastName', $user->lastName);
$user->preferredLocale = craft()->request->getPost('preferredLocale', $user->preferredLocale);
$user->weekStartDay = craft()->request->getPost('weekStartDay', $user->weekStartDay);
// If email verification is required, then new users will be saved in a pending state,
// even if an admin is doing this and opted to not send the verification email
if ($isNewUser && $requireEmailVerification)
{
$user->pending = true;
}
// There are some things only admins can change
if ($currentUser && $currentUser->admin)
{
$user->passwordResetRequired = (bool) craft()->request->getPost('passwordResetRequired', $user->passwordResetRequired);
// Is their admin status changing?
if (($adminParam = craft()->request->getPost('admin', $user->admin)) != $user->admin)
{
// Making someone an admin requires an elevated session
if ($adminParam)
{
$this->requireElevatedSession();
}
$user->admin = $adminParam;
}
}
// If this is Craft Pro, grab any profile content from post
if ($craftEdition == Craft::Pro)
{
$user->setContentFromPost('fields');
}
// Validate and save!
// ---------------------------------------------------------------------
$imageValidates = true;
$userPhoto = UploadedFile::getInstanceByName('userPhoto');
if ($userPhoto && !ImageHelper::isImageManipulatable($userPhoto->getExtensionName()))
{
$imageValidates = false;
$user->addError('userPhoto', Craft::t("The user photo provided is not an image."));
}
if ($imageValidates && craft()->users->saveUser($user))
{