Repository navigation
Expand file tree
/
Copy pathUserManagementController.php
More file actions
2219 lines (2052 loc) · 87.9 KB
/
Copy pathUserManagementController.php
File metadata and controls
2219 lines (2052 loc) · 87.9 KB
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
use LimeSurvey\Models\Services\UserManager;
//LSYii_Controller
/**
* Class UserManagementController
*/
class UserManagementController extends LSBaseController
{
/**
* @return array
**/
public function accessRules()
{
return array(
array(
'allow',
'actions' => array(),
'users' => array('*'), //everybody
),
array(
'allow',
'actions' => array(
'index', 'addEditUser', 'applyEdit',
'addRole', 'batchAddGroup', 'batchApplyRoles', 'batchPermissions', 'batchPermissionStates', 'batchExpires',
'batchSendAndResetLoginData', 'deleteConfirm', 'deleteMultiple', 'exportUser', 'importUser',
'renderSelectedItems', 'renderUserImport', 'saveRole', 'saveThemePermissions',
'takeOwnership', 'userPermissions', 'userTemplatePermissions', 'viewUser'
),
'users' => array('@'), //only login users
),
array('deny'),
);
}
/**
* @inheritdoc
*/
public function filters()
{
return [
'postOnly + applyEdit, deleteUser, userActivateDeactivate,'
. ' batchStatus, saveUserPermissions, saveThemePermissions, saveRole, importUsers, deleteMultiple,'
. ' batchSendAndResetLoginData, batchPermissions, batchPermissionStates, batchAddGroup, batchApplyRoles,'
. ' batchExpires, '
. ' TakeOwnership'
];
}
/**
* @return string|string[]|null
* @throws CException
*/
public function actionIndex()
{
if (!Permission::model()->hasGlobalPermission('users', 'read')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
if (isset($_GET['pageSize'])) {
Yii::app()->user->setState('pageSize', Yii::app()->request->getParam('pageSize'));
}
App()->getClientScript()->registerPackage('usermanagement');
App()->getClientScript()->registerPackage('select2-bootstrap');
$aData = [];
$model = new User('search');
$model->setAttributes(Yii::app()->getRequest()->getParam('User'), false);
$aData['model'] = $model;
// $aData['columnDefinition'] = $model->getManagementColums();
$aData['pageSize'] = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']);
$aData['formUrl'] = $this->createUrl('userManagement/index');
$aData['topbar']['title'] = gT('User management');
$aData['topbar']['backLink'] = App()->createUrl('dashboard/view');
$aData['topbar']['middleButtons'] = $this->renderPartial('partial/topbarBtns/leftSideButtons', [], true);
//this is really important, so we have the aData also before rendering the content
$this->aData = $aData;
return $this->render('index', [
'model' => $aData['model'],
//'columnDefinition' => $aData['columnDefinition'],
'pageSize' => $aData['pageSize'],
'formUrl' => $aData['formUrl'],
]);
}
/**
* Open modal to edit, or create a new user
*
* @param int|null $userid
* @throws CException
*/
public function actionAddEditUser($userid = null)
{
if (
($userid === null && !Permission::model()->hasGlobalPermission('users', 'create'))
|| ($userid !== null && !Permission::model()->hasGlobalPermission('users', 'update'))
) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")]]
);
}
if ($userid === null) {
$oUser = new User();
} else {
$oUser = User::model()->findByPk((int)$userid);
if ($oUser === null) {
App()->user->setFlash('error', gT("User does not exist"));
$this->redirect(App()->request->urlReferrer);
}
}
$randomPassword = \LimeSurvey\Models\Services\PasswordManagement::getRandomPassword();
$dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
// The login methods can only be chosen when adding a user and when there is more than one
$loginMethods = $oUser->isNewRecord ? $this->getAvailableLoginMethods() : [];
if (count($loginMethods) < 2) {
$loginMethods = [];
}
return $this->renderPartial('partial/addedituser', [
'oUser' => $oUser,
'randomPassword' => $randomPassword,
'dateformatdetails' => $dateformatdetails,
'loginMethods' => $loginMethods,
]);
}
/**
* Stores changes to user, or triggers userCreateEvent
*
* @return string | JSON
* @throws CException
* @throws \PHPMailer\PHPMailer\Exception
*/
public function actionApplyEdit()
{
$aUser = Yii::app()->request->getParam('User');
$isNewUser = empty($aUser['uid']);
if (!Permission::model()->hasGlobalPermission('users', $isNewUser ? 'create' : 'update')) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => false,
'errors' => gT("You do not have permission to access this page."),
]]);
}
// Sanitize full name to prevent XSS attack
if (isset($aUser['full_name'])) {
$aUser['full_name'] = flattenText($aUser['full_name'], false, true);
}
$passwordTest = Yii::app()->request->getParam('password_repeat', '');
if (!empty($passwordTest)) {
if ($passwordTest !== $aUser['password']) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => false,
'errors' => gT('Passwords do not match!'),
]]);
}
$user = new User();
if ($passwordError = $user->checkPasswordStrength($passwordTest)) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => false,
'errors' => gT('Passwords does not fulfill minimum requirement:') . '<br/>' . $passwordError,
]]);
}
}
$expires = Yii::app()->request->getPost('expires', null);
if (!empty($expires)) {
$dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
$displayTz = Yii::app()->getConfig('displayTimezone') ?: 'UTC';
$datetimeobj = DateTime::createFromFormat('!' . $dateformatdetails['phpdate'] . ' H:i', $expires, new DateTimeZone($displayTz));
$errors = DateTime::getLastErrors();
if (!$datetimeobj || ($errors && ($errors['error_count'] > 0 || $errors['warning_count'] > 0))) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => sprintf(gT('Invalid expiry date, please use "%s" format.'), $dateformatdetails['phpdate'] . ' H:i'),
]
]);
}
$datetimeobj->setTimezone(new DateTimeZone('UTC'));
$aUser['expires'] = $datetimeobj->format('Y-m-d H:i:s');
} else {
$aUser['expires'] = null;
}
// A user may not edit himself using this action
if (isset($aUser['uid']) && $aUser['uid'] && $aUser['uid'] == Yii::app()->user->id) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => gT('No permission')
]
]);
}
if (isset($aUser['uid']) && $aUser['uid']) {
$oUser = $this->updateAdminUser($aUser);
if ($oUser->hasErrors()) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => CHtml::errorSummary($oUser)
]
]);
}
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => true,
'message' => gT('User successfully updated')
]
]);
} else {
//generate random password when password is empty
if (empty($aUser['password'])) {
$newPassword = \LimeSurvey\Models\Services\PasswordManagement::getRandomPassword();
$aUser['password'] = $newPassword;
}
//retrieve the raw password
$aUser['rawPassword'] = $aUser['password'];
$loginMethods = $this->getPostedLoginMethods();
if (empty($loginMethods)) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => gT('Please select at least one login method.'),
]
]);
}
// LDAP users are looked up in the LDAP directory by the AuthLDAP plugin, all others are created by Authdb
$aUser['user_type'] = in_array('auth_ldap', $loginMethods) ? 'LDAP' : 'DB';
// Without a database login, a password link is of no use
$passwordSetByUser = Yii::app()->request->getParam('preset_password');
$sendEmail = $passwordSetByUser == 0 && in_array('auth_db', $loginMethods);
$data = $this->createAdminUser($aUser, $sendEmail, $loginMethods);
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => $data
]);
}
}
/**
* Handle user deletion request: validates permissions, optionally transfers surveys, deletes the user, and returns a JSON response.
*
* Performs permission and safety checks, may render a survey-transfer selection when the target owns surveys, transfers surveys when a destination is provided, invokes UserManager->deleteUser for the resolved user model, and returns a JSON partial describing the outcome.
*
* @return string JSON partial containing either:
* - `success` (false) and `errors` (array|string|object) when permission or validation checks fail, or
* - `success` (bool) and `message` (string) after an attempted deletion, or
* - `success` (true) and `html` (string) with a survey-transfer selection when the target owns surveys and no transfer destination was provided.
*/
public function actionDeleteUser()
{
$permission_users_delete = Permission::model()->hasGlobalPermission('users', 'delete');
$permission_superadmin_read = Permission::model()->hasGlobalPermission('superadmin', 'read');
if (!$permission_users_delete) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("We are sorry but you don't have permissions to do this.")
]
]);
}
$userId = (int) App()->request->getPost('userid');
$oUser = User::model()->findByPk($userId);
$currentUser = (int) App()->user->getId();
if (!$oUser) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("User does not exist")
]
]);
}
if ($permission_superadmin_read) {
// Can't delete forced superadmins
if (Permission::isForcedSuperAdmin($userId)) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("We are sorry but you don't have permissions to do this.")
]
]);
}
// Can't delete yourself
if ($userId === $currentUser) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("You cannot delete yourself.")
]
]);
}
}
if (!$permission_superadmin_read) {
// Can't delete yourself
if ($userId === $currentUser) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("You cannot delete yourself.")
]
]);
}
// Dont have permission to delete users
if (!$permission_users_delete) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("We are sorry but you don't have permissions to do this.")
]
]);
}
// Can't delete users that are not owned by the current user
if ((int) $oUser->parent_id !== $currentUser) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("We are sorry but you don't have permissions to do this.")
]
]);
}
// Can't delete forced superadmins
if (Permission::isForcedSuperAdmin($userId)) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false,
'errors' => gT("We are sorry but you don't have permissions to do this.")
]
]);
}
}
$messages = [];
$transferTo = Yii::app()->request->getPost('transfer_surveys_to');
if (empty($transferTo)) {
// If $transferTo is empty, check if user owns a survey.
// If so, render the "transfer to" selection screen
$aOwnedSurveys = Survey::model()->findAllByAttributes(array('owner_id' => $userId));
if (count($aOwnedSurveys)) {
$postuser = flattenText(Yii::app()->request->getPost("user"));
$aUsers = User::model()->findAll();
return Yii::app()->getController()->renderPartial(
'/admin/super/_renderJson',
[
"data" => [
'success' => true,
'html' => $this->renderPartial(
'partial/transfersurveys',
[
'postuserid' => $userId,
'postuser' => $postuser,
'current_user' => Yii::app()->user->id,
'users' => $aUsers,
],
true
),
]
]
);
}
} else {
// If $transferTo is not null, transfer the surveys
$iSurveysTransferred = Survey::model()->updateAll(array('owner_id' => $transferTo), 'owner_id=' . $userId);
if ($iSurveysTransferred) {
$sTransferredTo = User::model()->findByPk($transferTo)->users_name;
$messages[] = sprintf(gT("All of the user's surveys were transferred to %s."), $sTransferredTo);
}
}
$userManager = new UserManager();
$result = $userManager->deleteUser($oUser);
$messages = array_merge($messages, $result->getRawMessages());
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => $result->isSuccess(),
'message' => implode(" ", $messages),
]
]);
}
/**
* Show user activation confirmation
*
* @return void|string
* @throws CException
*/
public function actionActivationConfirm()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
$userId = Yii::app()->request->getParam('userid');
$action = Yii::app()->request->getParam('action');
$userId = sanitize_int($userId);
// Only allow the two known actions
$action = in_array($action, ['activate', 'deactivate'], true) ? $action : 'deactivate';
$aData['userId'] = $userId;
$aData['action'] = $action;
return $this->renderPartial('partial/confirmuseractivation', $aData);
}
/**
* Stores the status settings
*
* @return void|string
* @throws CException
*/
public function actionUserActivateDeactivate()
{
// See User_>getManagementButtons for permission
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
$userId = sanitize_int(Yii::app()->request->getParam('userid'));
$action = Yii::app()->request->getParam('action', 'deactivate');
if (!in_array($action, ['activate', 'deactivate'], true)) {
throw new CHttpException(400, gT("Invalid action"));
}
$oUser = User::model()->findByPk($userId);
if ($oUser == null) {
throw new CHttpException(404, gT("Invalid user ID"));
}
if (Permission::model()->getUserId() == $userId) { // canEdit allow user to update himself
throw new CHttpException(403, gT("You can not update this user."));
}
if (!$oUser->canEdit()) {
throw new CHttpException(403, gT("You can not update this user."));
}
if ($oUser->setActivationStatus($action)) {
return $this->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => true,
'message' => gT('Status successfully updated')
]
]);
};
/* activationstatus is not OK */
return $this->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => false
]
]);
}
/**
* Stores the status settings run via MassEdit
*
* @throws CException
*/
public function actionBatchStatus()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
$userIds = json_decode(Yii::app()->request->getPost('sItems', "[]"));
$operation = Yii::app()->request->getPost('status_selector', '');
$results = $this->userActivation($userIds, $operation);
$error = null;
foreach ($results as $result) {
if (isset($result['error']) && $result['error'] == 'Reached the limit') {
$error = true;
}
}
$tableLabels = array(gT('User ID'), gT('Username'), gT('Status'));
$data = array(
'aResults' => $results,
'successLabel' => gT('Saved successfully'),
'tableLabels' => $tableLabels,
);
if ($error) {
$data['additionalMessage'] = $this->renderPartial('/userManagement/partial/planupgradebutton');
}
Yii::app()->getController()->renderPartial('ext.admin.survey.ListSurveysWidget.views.massive_actions._action_results', $data);
}
/**
* Activate / deactivate user
* @todo : move this to a private function !!!
* @param array $userIds
* @param string $operation activate or deactivate
* @return array
*/
public function userActivation($userIds, $operation)
{
if (!App()->getRequest()->getIsPostRequest()) {
throw new CHttpException(400, gT('Your request is invalid.'));
}
$results = [];
foreach ($userIds as $iUserId) {
$oUser = User::model()->findByPk($iUserId);
if ($oUser == null) {
throw new CHttpException(404, gT("Invalid user ID"));
} else {
$results[$iUserId]['title'] = $oUser->users_name;
if (!$this->isAllowedToEdit($oUser)) {
$results[$iUserId]['error'] = gT('Unauthorized');
$results[$iUserId]['result'] = false;
continue;
}
$results[$iUserId]['result'] = $oUser->setActivationStatus($operation);
if (!$results[$iUserId]['result']) {
$results[$iUserId]['error'] = gT('Error');
}
}
}
return $results;
}
/**
* Check if the current user allowed to update $user
*
* @return boolean
*/
private function isAllowedToEdit($user)
{
$permission_superadmin_read = Permission::model()->hasGlobalPermission('superadmin', 'read');
$permission_users_update = Permission::model()->hasGlobalPermission('users', 'update');
$ownedOrCreated = $user->parent_id == App()->session['loginID']; // User is owned or created by you
return ( $permission_superadmin_read && !(Permission::isForcedSuperAdmin($user->uid) || $user->uid == App()->user->getId()))
|| (!$permission_superadmin_read && ($user->uid != App()->session['loginID'] //Can't change your own permissions
&& ( $permission_users_update && $ownedOrCreated)
&& !Permission::isForcedSuperAdmin($user->uid)
)
);
}
/**
* Show user delete confirmation
*
* @return void|string
* @throws CException
*/
public function actionDeleteConfirm()
{
if (!Permission::model()->hasGlobalPermission('users', 'delete')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userId = Yii::app()->request->getParam('userid');
$userId = sanitize_int($userId);
$aData['userId'] = $userId;
return $this->renderPartial('partial/confirmuserdelete', $aData);
}
/**
* Show some user detail and statistics
*
* @param int $userid
* @return string|null
* @throws CException
*/
public function actionViewUser(int $userid): ?string
{
if (!Permission::model()->hasGlobalPermission('users', 'read')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$oUser = User::model()->findByPk($userid);
$userGroups = array_map(function ($oUGMap) {
return $oUGMap->group->name;
}, UserInGroup::model()->findAllByAttributes(['uid' => $oUser->uid]));
if (App()->getRequest()->getIsAjaxRequest()) {
return $this->renderPartial('partial/showuser', [
'usergroups' => $userGroups,
'oUser' => $oUser,
'ajax' => true
]);
}
return $this->render('partial/showuser', [
'usergroups' => $userGroups,
'oUser' => $oUser,
'ajax' => false
]);
}
/**
* Opens a modal to edit user permissions
*
* @return string
* @throws CException
*/
public function actionUserPermissions()
{
$userId = Yii::app()->request->getParam('userid');
$userId = sanitize_int($userId);
$oUser = User::model()->findByPk($userId);
$userManager = new UserManager(Yii::app()->user, $oUser);
if (!$userManager->canAssignPermissions()) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
// Check permissions
$aBasePermissions = Permission::model()->getGlobalBasePermissions();
// superadmin permission always need create
if (!Permission::model()->hasGlobalPermission('superadmin', 'create')) {
unset($aBasePermissions['superadmin']);
}
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
// if not superadmin filter the available permissions as no admin may give more permissions than he owns
Yii::app()->session['flashmessage'] = gT("Note: You can only give limited permissions to other users because your own permissions are limited, too.");
$aFilteredPermissions = array();
foreach ($aBasePermissions as $PermissionName => $aPermission) {
foreach ($aPermission as $sPermissionKey => &$sPermissionValue) {
if (
$sPermissionKey != 'title' && $sPermissionKey != 'img' &&
!Permission::model()->hasGlobalPermission($PermissionName, $sPermissionKey)
) {
$sPermissionValue = false;
}
}
// Only show a row for that permission if there is at least one permission he may give to other users
if (
$aPermission['create'] || $aPermission['read'] || $aPermission['update']
|| $aPermission['delete'] || $aPermission['import'] || $aPermission['export']
) {
$aFilteredPermissions[$PermissionName] = $aPermission;
}
}
$aBasePermissions = $aFilteredPermissions;
}
// Only the permissions set on the user itself are shown as checked, not the ones coming from a role
$aUserPermissions = [];
$oUserPermissions = Permission::model()->findAllByAttributes([
'uid' => $oUser->uid,
'entity' => 'global',
'entity_id' => 0,
]);
foreach ($oUserPermissions as $oUserPermission) {
$aUserPermissions[$oUserPermission->permission] = $oUserPermission;
}
// Saving removes the roles of the user, so their names are shown in the warning and the confirmation
$aRoleNames = [];
$aRoleIds = CHtml::listData(Permission::getUserRole($oUser->uid), 'ptid', 'ptid');
if (!empty($aRoleIds)) {
$aRoleNames = CHtml::listData(
Permissiontemplates::model()->findAllByPk(array_values($aRoleIds)),
'ptid',
'name'
);
}
return $this->renderPartial(
'partial/editpermissions',
[
"oUser" => $oUser,
"aBasePermissions" => $aBasePermissions,
"aUserPermissions" => $aUserPermissions,
"aRoleNames" => $aRoleNames,
]
);
}
/**
* Stores the changed permissions
*
* @return string | JSON
* @throws CException
*/
public function actionSaveUserPermissions(): string
{
$userId = Yii::app()->request->getPost('userid');
$oUser = User::model()->findByPk($userId);
$userManager = new UserManager(Yii::app()->user, $oUser);
if (!$userManager->canAssignPermissions()) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => [gT("You do not have permission to access this page.")],
]
]);
}
$aPermissions = Yii::app()->request->getPost('Permission', []);
Permissiontemplates::model()->clearUser($userId);
$results = $this->applyPermissionFromArray($userId, $aPermissions);
$oUser->modified = date('Y-m-d H:i:s');
$oUser->save();
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => true,
'message' => gT("Saved permissions successfully.")
]
]);
}
/**
* Opens a modal to edit user theme permissions
*
* @return string|null
* @throws CException
*/
public function actionUserTemplatePermissions(): ?string
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$aTemplateModels = Template::model()->findAll();
$userId = Yii::app()->request->getParam('userid');
$oUser = User::model()->findByPk((int)$userId);
$aTemplates = array_map(function ($oTemplate) use ($userId) {
$oPermission = Permission::model()->findByAttributes(array('permission' => $oTemplate->folder, 'uid' => $userId, 'entity' => 'template'));
$aTemplate = $oTemplate->attributes;
$aTemplate['value'] = $oPermission == null ? 0 : $oPermission->read_p;
return $aTemplate;
}, $aTemplateModels);
return $this->renderPartial(
'partial/edittemplatepermissions',
[
"oUser" => $oUser,
"aTemplates" => $aTemplates,
]
);
}
/**
* Stores the changed permissions
*
* @return string | JSON
* @throws CException
*/
public function actionSaveThemePermissions(): string
{
if (
!(Permission::model()->hasGlobalPermission('users', 'update') &&
Permission::model()->hasGlobalPermission('templates', 'update'))
) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => [gT("You do not have permission to access this page.")],
]
]);
}
$userId = Yii::app()->request->getPost('userid');
$aTemplatePermissions = Yii::app()->request->getPost('TemplatePermissions', []);
Permission::editThemePermissionsUser($userId, $aTemplatePermissions);
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => true,
'message' => gT("Saved theme permissions successfully.")
]
]);
}
/**
* Opens the modal to edit the roles of a user
* Only the roles the current user is allowed to assign are offered
*
* @return string|null
* @throws CException
*/
public function actionAddRole(): ?string
{
$userId = Yii::app()->request->getParam('userid');
$oUser = User::model()->findByPk($userId);
$userManager = new UserManager(Yii::app()->user, $oUser);
if (!$userManager->canAssignRole() || $oUser->uid == App()->user->getId()) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$aAssignableRoles = $userManager->getAssignableRoles();
$aPossibleRoles = [];
foreach ($aAssignableRoles as $oPermissionRole) {
$aPossibleRoles[$oPermissionRole->ptid] = $oPermissionRole->name;
}
$aCurrentRoles = [];
$aLockedRoles = [];
foreach ($oUser->roles as $oRole) {
if (isset($aAssignableRoles[$oRole->ptid])) {
$aCurrentRoles[] = $oRole->ptid;
} else {
$aLockedRoles[] = $oRole->name;
}
}
return $this->renderPartial(
'partial/addrole',
[
'oUser' => $oUser,
'aPossibleRoles' => $aPossibleRoles,
'aCurrentRoles' => $aCurrentRoles,
'aLockedRoles' => $aLockedRoles,
'hasIndividualPermissions' => $userManager->hasIndividualGlobalPermissions(),
'hasRoles' => !empty($oUser->roles),
]
);
}
/**
* Save role of user
*
* @return string|null
* @throws CException
*/
public function actionSaveRole(): ?string
{
$iUserId = Yii::app()->request->getPost('userid');
$oUser = User::model()->findByPk($iUserId);
$userManager = new UserManager(Yii::app()->user, $oUser);
if (!$userManager->canAssignRole() || $oUser->uid == App()->user->getId()) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => gT("You do not have permission to access this page."),
]
]);
}
$aUserRoleIds = array_map('intval', (array) Yii::app()->request->getPost('roleselector', []));
$aAssignableRoleIds = array_keys($userManager->getAssignableRoles());
/* Keep the current roles the managing user is not allowed to remove */
$aLockedRoleIds = array_diff(
array_map(function ($oRole) {
return $oRole->ptid;
}, $oUser->roles),
$aAssignableRoleIds
);
$userManager->setRoles(array_merge($aLockedRoleIds, array_intersect($aUserRoleIds, $aAssignableRoleIds)));
return $this->renderPartial('partial/json', [
"data" => [
'success' => true,
'message' => 'Saved user roles successfuly',
]
]);
}
/**
* Render the import-users modal part for a given import format.
*
* @param string $importFormat The import format to render; allowed values are 'csv' or 'json'.
* @return string The rendered HTML partial for the import modal.
* @throws LSUserException If an unsupported import format is provided.
*/
public function actionRenderUserImport(string $importFormat = 'csv')
{
if (!Permission::model()->hasGlobalPermission('users', 'create')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
if (!in_array($importFormat, ['csv', 'json'])) {
throw new LSUserException(400, gT("Invalid format"));
}
switch ($importFormat) {
case "json":
$importNote = sprintf(gT("Please make sure that your JSON arrays contain the fields '%s', '%s'; '%s' and '%s' are not imported."), '<b>users_name</b>', '<b>email</b>', '<b>uid</b>', '<b>parent_id</b>');
$allowFileType = ".json,application/json";
break;
case "csv":
default:
$importNote = sprintf(gT("Please make sure that your CSV contains the fields '%s', '%s'; '%s' and '%s' are not imported."), '<b>users_name</b>', '<b>email</b>', '<b>uid</b>', '<b>parent_id</b>');
$allowFileType = ".csv";
}
return $this->renderPartial('partial/importuser', [
"note" => $importNote,
"importFormat" => $importFormat,
"allowFile" => $allowFileType
]);
}
/**
* Imports users from an uploaded CSV or JSON file, creating new users or updating existing ones, then redirects to the user index after adding alert message.
*
* @param string $importFormat Format of the uploaded file; must be "csv" or "json".
* @return string Never returns normally; always ends with a redirect.
* @throws CHttpException If the current user lacks permission to create users.
* @throws LSUserException If an unsupported $importFormat is provided.
*/
public function actionImportUsers(string $importFormat = 'csv'): string
{
if (!Permission::model()->hasGlobalPermission('users', 'create')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
if (!in_array($importFormat, ['csv', 'json'])) {
throw new LSUserException(400, gT("Invalid format"));
}
$overwriteUsers = boolval(App()->getRequest()->getPost('overwrite'));
switch ($importFormat) {
case "json":
$aNewUsers = UserParser::getDataFromJSON($_FILES);
break;
case "csv":
default:
$aNewUsers = UserParser::getDataFromCSV($_FILES);
}
if (empty($aNewUsers)) {
Yii::app()->setFlashMessage(gT("No user definition found in file."), 'error');
$this->redirect(['userManagement/index']);
App()->end();
}
$created = [];
$updated = [];
$hasDuplicateIdentity = false;
$hasInvalidUsername = false;
$canOverwriteDuplicateEmail = false;
$existingAttributes = User::model()->attributeNames();
$dateAttributes = ['last_login', 'validation_key_expiration','last_forgot_email_password','expires'];
foreach ($aNewUsers as $aNewUser) {
// Unset not imported or invalid attribute
$aNewUser = array_intersect_key($aNewUser, array_flip($existingAttributes));
$aNewUser = array_diff_key($aNewUser, array_flip(['uid','parent_id', 'created', 'modified']));
$aNewUser['users_name'] = flattenText($aNewUser['users_name'] ?? '');
if (empty($aNewUser['users_name'])) {
$hasInvalidUsername = true;
continue;
}
$oUser = User::model()->find(
'users_name = :name OR email = :email',
[
':name' => $aNewUser['users_name'],
':email' => $aNewUser['email'],
]
);
if ($oUser !== null) {
if ($overwriteUsers) {
/* Check permission to edit this user */
if (!$oUser->canEdit()) {
Yii::app()->setFlashMessage(sprintf(gT("You don't have permission to edit user %s."), $aNewUser['users_name']), 'warning');
continue;
}
/* Check permission to edit self */
if ($oUser->uid == App()->user->id) {
Yii::app()->setFlashMessage(gT("You can't use the import function to update your own account."), 'warning');
continue;
}
foreach ($aNewUser as $attribute => $value) {
if ($attribute === 'password') {
continue; // Handle password separately via setPassword()
}
if (!empty($value) || !in_array($attribute, $dateAttributes)) {
$oUser->setAttribute($attribute, $value);
}
}
$saveAttributes = array_keys($aNewUser);
if (!empty($aNewUser['password']) && $aNewUser['password'] != ' ') {
$oUser->setPassword($aNewUser['password'], false);