/
UserManagement.php
1439 lines (1286 loc) · 54.3 KB
/
UserManagement.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
use LimeSurvey\PluginManager\AuthPluginBase;
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
/*
* LimeSurvey
* Copyright (C) 2013 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
/**
* Usermanagement Controller
*
* This controller is for the user management panel
*
* @package LimeSurvey
* @subpackage Backend
*/
class UserManagement extends Survey_Common_Action
{
/**
* @inheritdoc
*/
public function index()
{
$subAction = Yii::app()->request->getParam('sa', null);
if ($subAction == null) {
$this->getController()->redirect(App()->createUrl('admin/usermanagement/sa/view'));
return;
}
throw new CHttpException(404, gT('The specified page cannot be found.'));
}
/**
* Basic view method
*/
public function view()
{
if (!Permission::model()->hasGlobalPermission('users', 'read')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/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('bootstrap-select2');
$aData = [];
$model = new User('search');
$model->setAttributes(Yii::app()->getRequest()->getParam('User'), false);
$aData['model'] = $model;
$aData['columnDefinition'] = $model->managementColums;
$aData['pageSize'] = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']);
$aData['formUrl'] = App()->createUrl('admin/usermanagement/sa/view');
$aData['massiveAction'] = App()->getController()->renderPartial(
'/admin/usermanagement/massiveAction/_selector',
[],
true,
false
);
$this->_renderWrappedTemplate('usermanagement', 'view', $aData);
}
/**
* Open modal to edit, or create a new user
*
* @param integer $userid
* @return string
*/
public function editusermodal($userid = null)
{
if (
($userid === null && !Permission::model()->hasGlobalPermission('users', 'create'))
|| ($userid !== null && !Permission::model()->hasGlobalPermission('users', 'update'))
) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")]]
);
}
$oUser = $userid === null ? new User() : User::model()->findByPk($userid);
$randomPassword = $this->getRandomPassword();
return Yii::app()->getController()->renderPartial('/admin/usermanagement/partial/addedituser', ['oUser' => $oUser, 'randomPassword' => $randomPassword]);
}
/**
* Stores changes to user, or triggers userCreateEvent
*
* @return string | JSON
*/
public function applyedit()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => false,
'errors' => gT("You do not have permission to access this page."),
]]);
}
$aUser = Yii::app()->request->getParam('User');
$passwordTest = Yii::app()->request->getParam('password_repeat', false);
if (!empty($passwordTest)) {
if ($passwordTest !== $aUser['password']) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => false,
'errors' => gT('Passwords do not match'),
]]);
}
$oPasswordTestEvent = new PluginEvent('checkPasswordRequirement');
$oPasswordTestEvent->set('password', $passwordTest);
$oPasswordTestEvent->set('passwordOk', true);
$oPasswordTestEvent->set('passwordError', '');
Yii::app()->getPluginManager()->dispatchEvent($oPasswordTestEvent);
if (!$oPasswordTestEvent->get('passwordOk')) {
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => false,
'errors' => gT('Passwords does not fulfill minimum requirement:') . '<br/>' . $oPasswordTestEvent->get('passwordError'),
]]);
}
}
if (isset($aUser['uid']) && $aUser['uid']) {
$oUser = $this->updateAdminUser($aUser);
if ($oUser->hasErrors()) {
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => false,
'errors' => $this->renderErrors($oUser->getErrors()) ?? ''
]
]);
}
return App()->getController()->renderPartial('/admin/super/_renderJson', [
'data' => [
'success' => true,
'message' => gT('User successfully updated')
]
]);
} else {
$this->createAdminUser($aUser);
}
}
/**
* this method create a new admin user
* @param array a$user
* @return string
*/
private function createAdminUser($aUser)
{
if (!isset($aUser['uid']) || $aUser['uid'] == null) {
$sendMail = (bool) Yii::app()->request->getPost('preset_password', false);
$newUser = $this->_createNewUser($aUser);
$sReturnMessage = gT('User successfully created');
$success = true;
if ($sendMail) {
$mailer = $this->_sendAdminMail('registration', $aUser);
if ($mailer->getError()) {
$sReturnMessage = CHtml::tag("h4", array(), gT("Error"));
$sReturnMessage .= CHtml::tag("p", array(), sprintf(gT("Email to %s (%s) failed."), "<strong>" . $newUser['users_name'] . "</strong>", $newUser['email']));
$sReturnMessage .= CHtml::tag("p", array(), $mailer->getError());
$success = false;
} else {
// has to be sent again or no other way
$sReturnMessage = CHtml::tag("h4", array(), gT("Success"));;
$sReturnMessage .= CHtml::tag("p", array(), sprintf(gT("Username: %s - Email: %s"), $newUser['users_name'], $newUser['email']));
$sReturnMessage .= CHtml::tag("p", array(), gT("An email with a generated password was sent to the user."));
}
}
$display_user_password_in_html = Yii::app()->getConfig("display_user_password_in_html");
$sReturnMessage .= $display_user_password_in_html ? CHtml::tag("p", array('class' => 'alert alert-danger'), 'New password set: <b>' . $aUser['password'] . '</b>') : '';
$data = array();
if ($success) {
$data = [
'success' => $success,
'message' => $sReturnMessage
];
} else {
$data = [
'success' => $success,
'errors' => $sReturnMessage
];
}
return App()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => $data
]);
}
}
/**
* @param array $errors
*
* @return string $errorDiv
*/
private function renderErrors($errors)
{
$errorDiv = '<ul class="list-unstyled">';
foreach ($errors as $key => $error) {
foreach ($error as $errormessages) {
$errorDiv .= '<li>' . print_r($errormessages, true) . '</li>';
}
}
$errorDiv .= '</ul>';
return (string) $errorDiv;
}
/**
* Show some user detail and statistics
*
* @return string
*/
public function viewuser($userid)
{
if (!Permission::model()->hasGlobalPermission('users', 'read')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/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]));
return $this->getController()->renderPartial('/admin/usermanagement/partial/showuser', ['usergroups' => $usergroups, 'oUser' => $oUser]);
}
/**
* Takes ownership on user after confirmation
*
* @return void
*/
public function takeownership()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userId = Yii::app()->request->getPost('userid');
$oUser = User::model()->findByPk($userId);
$oUser->parent_id = Yii::app()->user->id;
$oUser->save();
App()->getController()->redirect(App()->createUrl('/admin/usermanagement'));
}
/**
* Deletes a user
*
* @param int $uid
* @param bool $recursive
* @return boolean
*/
public function deleteUser(int $uid, bool $recursive = true)
{
if (!Permission::model()->hasGlobalPermission('users', 'delete')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
if ($uid == Yii::app()->user->id) {
return false;
} else {
$oUser = User::model()->findByPk($uid);
return $oUser->delete($recursive);
}
}
/**
* Delete multiple users selected by massive action
* @return void
*/
public function deleteMultiple()
{
if (!Permission::model()->hasGlobalPermission('users', 'delete')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$aUsers = json_decode(App()->request->getPost('sItems'));
$aResults = [];
foreach ($aUsers as $user) {
$aResults[$user]['title'] = '';
$model = $this->loadModel($user);
$aResults[$user]['title'] = $model->users_name;
$aResults[$user]['result'] = $this->deleteUser($user);
if (!$aResults[$user]['result'] && $user == Yii::app()->user->id) {
$aResults[$user]['error'] = gT("You cannot delete yourself.");
}
}
$tableLabels = array(gT('User ID'), gT('Username'), gT('Status'));
Yii::app()->getController()->renderPartial(
'ext.admin.survey.ListSurveysWidget.views.massive_actions._action_results',
array(
'aResults' => $aResults,
'successLabel' => gT('Deleted'),
'tableLabels' => $tableLabels
)
);
}
/**
* Deletes a user after confirmation
*
* @return void
*/
public function deleteconfirm()
{
if (!Permission::model()->hasGlobalPermission('users', 'delete')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userId = Yii::app()->request->getPost('userid');
if ($userId == Yii::app()->user->id) {
Yii::app()->setFlashMessage(gT("You cannot delete yourself."), 'error');
Yii::app()->getController()->redirect(
Yii::app()->createUrl('admin/usermanagement/sa/view')
);
return;
}
$oUser = User::model()->findByPk($userId);
$oUser->delete();
Yii::app()->setFlashMessage(gT("User successfully deleted."), 'success');
Yii::app()->getController()->redirect(App()->createUrl('/admin/usermanagement'));
return;
}
/**
* Opens a modal to edit user template permissions
*
* @return string
*/
public function usertemplatepermissions()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$aTemplateModels = Template::model()->findAll();
$oRequest = Yii::app()->request;
$userId = $oRequest->getParam('userid');
$oUser = User::model()->findByPk($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->getController()->renderPartial(
'/admin/usermanagement/partial/edittemplatepermissions',
[
"oUser" => $oUser,
"aTemplates" => $aTemplates,
]
);
}
/**
* Opens a modal to edit user permissions
*
* @return string
*/
public function userpermissions()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$oRequest = Yii::app()->request;
$userId = $oRequest->getParam('userid');
$oUser = User::model()->findByPk($userId);
// Check permissions
$aBasePermissions = Permission::model()->getGlobalBasePermissions();
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;
}
$aAllSurveys = Survey::model()->findAll();
$aMySurveys = array_filter($aAllSurveys, function ($oSurvey) {
if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
return true;
}
if ($oSurvey->owner_id == App()->user->id) {
return true;
}
return array_reduce($oSurvey->permissions, function ($coll, $oPermission) {
if ($oPermission->permission == 'surveysecurity' && $oPermission->update_p == 1 && $oPermission->uid == App()->user->id) {
return true;
}
return $coll;
}, false);
});
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/editpermissions',
[
"oUser" => $oUser,
"aBasePermissions" => $aBasePermissions,
]
);
}
/**
* Stores the changed permissions
*
* @return string | JSON
*/
public function applythemepermissions()
{
if (!(Permission::model()->hasGlobalPermission('users', 'update') && Permission::model()->hasGlobalPermission('templates', 'update'))) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userId = Yii::app()->request->getPost('userid');
$aPermissions = Yii::app()->request->getPost('Permission', []);
$aTemplatePermissions = Yii::app()->request->getPost('TemplatePermissions', []);
$aTemplates = Template::model()->findAll();
// foreach ($aTemplates as $oTemplate) {
// $transferredOption = Yii::app()->request->getPost($oTemplate->folder, false);
// $aTemplatePermissions[$oTemplate->folder] = $transferredOption !== false ? $transferredOption : 0;
// }
$results = [];
foreach ($aTemplatePermissions as $key => $value) {
$oPermission = Permission::model()->findByAttributes(array('permission' => $key, 'uid' => $userId, 'entity' => 'template'));
if (empty($oPermission)) {
$oPermission = new Permission;
$oPermission->uid = $userId;
$oPermission->permission = $key;
$oPermission->entity = 'template';
$oPermission->entity_id = 0;
}
$oPermission->read_p = $value;
$results[$key] = $oPermission->save();
}
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => true,
'html' => $this->getController()->renderPartial('/admin/usermanagement/partial/permissionsuccess', ['results' => $results], true),
]
]);
}
/**
* Stores the changed permissions
*
* @return string | JSON
*/
public function saveuserpermissions()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userId = Yii::app()->request->getPost('userid');
$aPermissions = Yii::app()->request->getPost('Permission', []);
$results = $this->applyPermissionFromArray($userId, $aPermissions);
$oUser = User::model()->findByPk($userId);
$oUser->modified = date('Y-m-d H:i:s');
$save = $oUser->save();
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => true,
'html' => $this->getController()->renderPartial('/admin/usermanagement/partial/permissionsuccess', ['results' => $results], true),
]
]);
}
/**
* Opens the modal to add dummy users
*
* @return string
*/
public function addrole()
{
$userId = Yii::app()->request->getParam('userid');
$oUser = User::model()->findByPk($userId);
$aPermissiontemplates = Permissiontemplates::model()->findAll();
$aPossibleRoles = [];
array_walk(
$aPermissiontemplates,
function ($oPermissionRole) use (&$aPossibleRoles) {
$aPossibleRoles[$oPermissionRole->ptid] = $oPermissionRole->name;
}
);
$aCurrentRoles = array_map(function ($oRole) {
return $oRole->ptid;
}, $oUser->roles);
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/addrole',
[
'oUser' => $oUser,
'aPossibleRoles' => $aPossibleRoles,
'aCurrentRoles' => $aCurrentRoles,
]
);
}
/**
* Apply role to user
*
*
* @return string
*/
public function applyaddrole()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$iUserId = Yii::app()->request->getPost('userid');
$aUserRoleIds = Yii::app()->request->getPost('roleselector', []);
$results = [];
$clearUser = Permissiontemplates::model()->clearUser($iUserId);
foreach ($aUserRoleIds as $iUserRoleId) {
if ($iUserRoleId == '') {
continue;
}
$results[$iUserRoleId] = Permissiontemplates::model()->applyToUser($iUserId, $iUserRoleId);
}
if (empty($aUserRoleIds)) {
$results['clear'] = $clearUser;
}
return Yii::app()->getController()->renderPartial('/admin/usermanagement/partial/json', [
"data" => [
'success' => true,
'html' => $this->getController()->renderPartial('/admin/usermanagement/partial/permissionsuccess', ['results' => $results], true),
]
]);
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
*
* @param integer $id the ID of the model to be loaded
*
* @return User|null object
* @throws CHttpException
*/
public function loadModel($id)
{
$model = User::model()->findByPk($id);
if ($model === null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
return $model;
}
/**
* render selected items for massive action modal
*
* @return void
* @throws CHttpException
* @throws CException
*/
public function renderSelectedItems()
{
$aUsers = json_decode(App()->request->getPost('$oCheckedItems'));
$aResults = [];
$gridid = App()->request->getParam('$grididvalue');
foreach ($aUsers as $user) {
$aResults[$user]['title'] = '';
$model = $this->loadModel($user);
if ($gridid == 'usermanagement--identity-gridPanel') {
$aResults[$user]['title'] = $model->users_name;
}
$aResults[$user]['result'] = gT('Selected');
}
//set Modal table labels
$tableLabels = array(gT('User ID'), gT('Username'), gT('Status'));
App()->getController()->renderPartial(
'ext.admin.grid.MassiveActionsWidget.views._selected_items',
array(
'aResults' => $aResults,
'successLabel' => gT('Selected'),
'tableLabels' => $tableLabels,
)
);
}
/**
* Stores the permission settings run via MassEdit
*
* @return string
*/
public function batchPermissions()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userIds = Yii::app()->request->getPost('userids', []);
$aPermissions = Yii::app()->request->getPost('Permission', []);
$results = [];
foreach ($userIds as $iUserId) {
$results[$iUserId] = $this->applyPermissionFromArray($iUserId, $aPermissions);
$oUser = User::model()->findByPk($iUserId);
$oUser->modified = date('Y-m-d H:i:s');
$results[$iUserId]['save'] = $oUser->save();
}
return $this->getController()->renderPartial('/admin/usermanagement/partial/permissionsuccess', ['results' => $results, "noButton" => true]);
}
/**
* Method to resend a password to selected surveyadministrators (MassAction)
*
* @return String
*/
public function batchSendAndResetLoginData()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$userIds = json_decode(Yii::app()->request->getPost('sItems', "[]"));
$entity_ids = Yii::app()->request->getPost('entity_ids', []);
$permissionclass = Yii::app()->request->getPost('permissionclass');
$results = [];
foreach ($userIds as $userId) {
$oUser = User::model()->findByPk($userId);
$result[] = $this->resetLoginData($oUser, true);
$oUser->modified = date('Y-m-d H:i:s');
$result['saved'] = $oUser->save();
$results[] = $result;
}
$success = array_reduce($results, function ($coll, $arr) {
return $coll = $coll && $arr['saved'];
}, true);
if (!$success) { }
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/success',
[
'sMessage' => gT('Emails successfully sent'),
'sDebug' => json_encode($results, JSON_PRETTY_PRINT),
'noButton' => true,
]
);
}
/**
* Mass edition apply roles
*
*
* @return string
*/
public function batchAddGroup()
{
if (!Permission::model()->hasGlobalPermission('users', 'delete')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$aItems = json_decode(Yii::app()->request->getPost('sItems', []));
$iUserGroupId = Yii::app()->request->getPost('addtousergroup');
$oUserGroup = UserGroup::model()->findByPk($iUserGroupId);
$aResults = [];
foreach ($aItems as $sItem) {
$aResults[$sItem]['title'] = '';
$model = $this->loadModel($sItem);
$aResults[$sItem]['title'] = $model->users_name;
if (!$oUserGroup->hasUser($sItem)) {
$aResults[$sItem]['result'] = $oUserGroup->addUser($sItem);
} else {
$aResults[$sItem]['result'] = false;
$aResults[$sItem]['error'] = gT('User is already a part of the group');
}
}
$tableLabels = array(gT('User ID'), gT('Username'), gT('Status'));
Yii::app()->getController()->renderPartial(
'ext.admin.survey.ListSurveysWidget.views.massive_actions._action_results',
array(
'aResults' => $aResults,
'successLabel' => gT('Usergroup updated'),
'tableLabels' => $tableLabels
)
);
}
/**
* Mass edition apply roles
*
* @return string
* @throws CException
*/
public function batchApplyRoles()
{
if (!Permission::model()->hasGlobalPermission('users', 'update')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$aItems = json_decode(Yii::app()->request->getPost('sItems', []));
$aUserRoleIds = Yii::app()->request->getPost('roleselector');
$results = [];
$aResults = [];
foreach ($aItems as $sItem) {
$aResults[$sItem]['title'] = '';
$model = $this->loadModel($sItem);
$aResults[$sItem]['title'] = $model->users_name;
//check if user is admin otherwhise change the role
if (intval($sItem) == 1) {
$aResults[$sItem]['result'] = false;
$aResults[$sItem]['error'] = gT('The superadmin role cannot be changed.');
} else {
foreach ($aUserRoleIds as $iUserRoleId) {
$aResults[$sItem]['result'] = Permissiontemplates::model()->applyToUser($sItem, $iUserRoleId);
}
}
}
$tableLabels = array(gT('User ID'), gT('Username'), gT('Status'));
Yii::app()->getController()->renderPartial(
'ext.admin.survey.ListSurveysWidget.views.massive_actions._action_results',
array(
'aResults' => $aResults,
'successLabel' => gT('Role updated'),
'tableLabels' => $tableLabels
)
);
}
/**
* Opens the modal to add dummy users
*
* @return string
*/
public function adddummyuser()
{
return $this->getController()->renderPartial('/admin/usermanagement/partial/adddummyuser', []);
}
/**
* Creates a batch of dummy users
*
*
* @return string | JSON
*/
public function runadddummyuser()
{
if (!Permission::model()->hasGlobalPermission('users', 'create')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$times = App()->request->getParam('times', 5);
$passwordsize = (int) App()->request->getParam('passwordsize', 5);
$passwordsize = $passwordsize < 8 || is_nan($passwordsize) ? 8 : $passwordsize;
$prefix = App()->request->getParam('prefix', 'randuser_');
$email = App()->request->getParam('email', User::model()->findByPk(App()->user->id)->email);
$randomUsers = [];
for (; $times > 0; $times--) {
$name = $this->getRandomUsername($prefix);
$password = $this->getRandomPassword($passwordsize);
$oUser = new User;
$oUser->users_name = $name;
$oUser->full_name = $name;
$oUser->email = $email;
$oUser->parent_id = App()->user->id;
$oUser->created = date('Y-m-d H:i:s');
$oUser->modified = date('Y-m-d H:i:s');
$oUser->password = password_hash($password, PASSWORD_DEFAULT);
$save = $oUser->save();
$randomUsers[] = ['username' => $name, 'password' => $password, 'save' => $save];
//Permission::model()->setGlobalPermission($oUser->uid, 'auth_db');
}
return Yii::app()->getController()->renderPartial('/admin/super/_renderJson', ["data" => [
'success' => true,
'html' => $this->getController()->renderPartial('/admin/usermanagement/partial/createdrandoms', ['randomUsers' => $randomUsers, 'filename' => $prefix], true),
]]);
}
/**
* Calls up a modal to import users via csv/json file
*
*@param string $importFormat - Importformat (csv/json) to render
*@return string
*/
public function renderUserImport(string $importFormat = 'csv')
{
if (!Permission::model()->hasGlobalPermission('users', 'create')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$importNote = sprintf(gT("Please make sure that your CSV contains the fields '%s', '%s', '%s', '%s', and '%s'"), '<b>users_name</b>', '<b>full_name</b>', '<b>email</b>', '<b>lang</b>', '<b>password</b>');
$allowFileType = ".csv";
if ($importFormat == 'json') {
$importNote = sprintf(gT("Wrong definition! Please make sure that your JSON arrays contains the fields '%s', '%s', '%s', '%s', and '%s'"), '<b>users_name</b>','<b>full_name</b>','<b>email</b>','<b>lang</b>','<b>password</b>');
$allowFileType = ".json,application/json";
}
return $this->getController()->renderPartial('/admin/usermanagement/partial/importuser', [
"note" => $importNote,
"importFormat" => $importFormat,
"allowFile" => $allowFileType
]);
}
/**
* Creates users from an uploaded CSV / JSON file
*
* @param string importFormat - format of the imported file - Choice between csv / json
* @return string
*/
public function importUsers(string $importFormat = 'csv')
{
if (!Permission::model()->hasGlobalPermission('users', 'create')) {
return $this->getController()->renderPartial(
'/admin/usermanagement/partial/error',
['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true]
);
}
$overwriteUsers = false;
if (isset($_POST['overwrite'])) {
$overwriteUsers = true;
}
switch ($importFormat) {
case "csv":
$aNewUsers = UserParser::getDataFromCSV($_FILES);
break;
case "json":
$aNewUsers = UserParser::getDataFromJSON($_FILES);
break;
}
$created = [];
$updated = [];
foreach ($aNewUsers as $aNewUser) {
$oUser = User::model()->findByAttributes(['users_name' => $aNewUser['users_name']]);
if ($oUser !== null) {
if ($overwriteUsers) {
$oUser->full_name = $aNewUser['full_name'];
$oUser->email = $aNewUser['email'];
$oUser->parent_id = App()->user->id;
$oUser->modified = date('Y-m-d H:i:s');
if ($aNewUser['password'] != ' ') {
$oUser->password = password_hash($aNewUser['password'], PASSWORD_DEFAULT);
}
$save = $oUser->save();
if ($save) {
$updated[] = [
'username' => $aNewUser['users_name'],
'full_name' => $aNewUser['full_name'],
'email' => $aNewUser['email'],
];
}
}
} else {
$password = $this->getRandomPassword(8);
$passwordText = $password;
if ($aNewUser['password'] != ' ') {
$password = password_hash($aNewUser['password'], PASSWORD_DEFAULT);
}
$save = $this->_createNewUser([
'users_name' => $aNewUser['users_name'],
'full_name' => $aNewUser['full_name'],
'password' => $password,
'email' => $aNewUser['email'],
'lang' => $aNewUser['lang'],
], false);
if ($save) {
$created[] = [
'username' => $aNewUser['users_name'],
'full_name' => $aNewUser['full_name'],
'email' => $aNewUser['email'],
'password' => $passwordText,
];
}
}
}
Yii::app()->setFlashMessage(gT("Users imported successfully."), 'success');
Yii::app()->getController()->redirect(
Yii::app()->createUrl('admin/usermanagement/sa/view')
);
return;
}