/
UserRoleController.php
577 lines (509 loc) · 20.3 KB
/
UserRoleController.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
<?php
class UserRoleController extends LSBaseController
{
/**
* Run filters
*
* @return array|void
*/
public function filters()
{
return [
'postOnly + delete, applyEdit, savePermissions, batchDelete'
];
}
/**
* Renders the list of user roles.
*
* @throws CException
*/
public function actionIndex()
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
App()->session['flashmessage'] = gT('You have no access to the role management!');
$this->redirect(array('/admin'));
}
App()->getClientScript()->registerPackage('permissionroles');
$request = App()->request;
$massiveAction = $this->renderPartial(
'massiveAction/_selector',
[],
true
);
// Set page size
$pageSize = $request->getParam('pageSize');
if ($pageSize != null) {
App()->user->setState('pageSize', (int)$pageSize);
}
$model = Permissiontemplates::model();
$aPermissiontemplatesParam = $request->getParam('Permissiontemplates');
if ($aPermissiontemplatesParam) {
$model->setAttributes($aPermissiontemplatesParam, false);
}
// Green Bar (SurveyManagerBar) Page Title
$aData['pageTitle'] = gT('User roles');
//this is really important, so we have the aData also before rendering the content
$this->aData = $aData;
$this->render(
'index',
[
'model' => $model,
'massiveAction' => $massiveAction,
'pageTitle' => gT('User roles'),
]
);
}
/**
* Returns the modal view for adding/editing a user role
*
* @param int $ptid (optional)
* @throws CException
*/
public function actionEditRoleModal(?int $ptid = 0)
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
Yii::app()->session['flashmessage'] = gT('You have no access to the role management!');
$this->getController()->redirect(array('/admin'));
}
$model = $this->loadModel($ptid);
$this->renderPartial('partials/_form', ['model' => $model]);
}
/**
* Updates the role itself (name, description).
* Renders a modal view with success/error message.
*
* @return string|string[]|null
* @throws CException
* @throws CHttpException
*/
public function actionApplyEdit()
{
$aPermissiontemplate = Yii::app()->request->getPost('Permissiontemplates');
$model = $this->loadModel($aPermissiontemplate['ptid']);
// XSS filter
$aPermissiontemplate['name'] = CHtml::encode($aPermissiontemplate['name']);
$aPermissiontemplate['description'] = CHtml::encode($aPermissiontemplate['description']);
$newAttributes = array_merge($model->attributes, $aPermissiontemplate);
$model->attributes = $newAttributes;
$success = $model->save();
if ($success) {
$message = gT('Role successfully saved');
} else {
$message = gT('Failed saving the role');
$errors = $model->getErrors();
$errorDiv = $this->renderErrors($errors);
}
return $this->renderPartial('/admin/super/_renderJson', [
"data" => [
'success' => $success,
'message' => $message,
'errors' => $errorDiv ?? ''
]
]);
}
/**
* Renders the modal for adding the permissions to the role.
*
* @return array|false|mixed|string|string[]|void|null
* @throws CException
*/
public function actionRenderModalPermissions()
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")],'noButton' => true]
);
}
$oRequest = Yii::app()->request;
$ptid = $oRequest->getParam('ptid');
$oPermissionTemplate = Permissiontemplates::model()->findByPk($ptid);
// Check permissions
$aBasePermissions = Permission::model()->getGlobalBasePermissions();
/**
* REFACTORED
*
* this part could never be reached at any time, because same if-clause above is already
* returning with an error ...
*
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->renderPartial(
'partials/_permissions',
[
"oModel" => $oPermissionTemplate,
"aBasePermissions" => $aBasePermissions
]
);
}
/**
* Save Permissions
*
* @return array|false|mixed|string|string[]|void|null
* @throws CException
*/
public function actionSavePermissions()
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
return $this->renderPartial(
'partial/error',
['errors' => [gT("You do not have permission to access this page.")],'noButton' => true]
);
}
$oRequest = Yii::app()->request;
$ptid = $oRequest->getPost('ptid');
$aPermissions = $oRequest->getPost('Permission', []);
$oPermissionTemplate = Permissiontemplates::model()->findByPk((int)$ptid);
$results = $this->applyPermissionFromArray($ptid, $aPermissions);
$oPermissionTemplate->renewed_last = date('Y-m-d H:i:s');
$oPermissionTemplate->save();
$html = $this->renderPartial('/userManagement/partial/permissionsuccess', ['results' => $results], true);
return $this->renderPartial('/userManagement/partial/json', ["data" => [
'success' => true,
'html' => $html
]]);
}
/**
* Displays a particular role.
*
* @param int $ptid
* @return array|false|mixed|string|string[]|void|null
* @throws CException
*/
public function actionViewRole(int $ptid)
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
Yii::app()->session['flashmessage'] = gT('You have no access to the role management!');
$this->redirect(array('/admin'));
}
$oPermissionTemplate = Permissiontemplates::model()->findByPk($ptid);
return $this->renderPartial(
'partials/_view',
[
"oModel" => $oPermissionTemplate,
]
);
}
/**
* Creates an xml content/file to export. Opens dialog to save
* the xml file.
*
* @param int $ptid
*/
public function actionRunExport($ptid)
{
$oModel = $this->loadModel($ptid);
$oXML = $oModel->compileExportXML();
$filename = preg_replace("/[^a-zA-Z0-9-_]*/", '', $oModel->name);
header('Content-type: application/xml');
header('Content-Disposition: attachment; filename="' . $filename . '.xml"');
print($oXML->asXML());
Yii::app()->end();
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
*
*/
public function actionDelete()
{
$this->requirePostRequest();
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
Yii::app()->session['flashmessage'] = gT('You have no access to the role management!');
$this->getController()->redirect(array('/admin'));
}
$ptid = Yii::app()->request->getPost('ptid', 0);
try {
$this->loadModel((int)$ptid)->delete();
Yii::app()->setFlashMessage(gT("Role was successfully deleted."), 'success');
} catch (Exception $e) {
Yii::app()->setFlashMessage(gT("Role could not be deleted."), 'error');
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax'])) {
$this->redirect($_POST['returnUrl'] ?? ['index']);
}
}
/**
* Opens modal to import role (xml-file).
*
* @throws CException
*/
public function actionShowImportXML()
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
Yii::app()->session['flashmessage'] = gT('You have no access to the role management!');
$this->redirect(array('/admin'));
}
$this->renderPartial('partials/_import');
}
/**
* Imports a role (and the permissions) from a xml-file.
* Shows error message in case of
* - file to large
* - wrong file extension
* - error while parsing xml to db
* Shows success message if role could be imported.
* Redirects to index in any case.
*
*/
public function actionImportXML()
{
$sRandomFileName = randomChars(20);
$sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName;
$aPathinfo = pathinfo($_FILES['the_file']['name']);
$sExtension = $aPathinfo['extension'];
$bMoveFileResult = false;
if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) {
Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error');
$this->redirect(array('userRole/index'));
Yii::app()->end(); //todo: is this necessary? after redirect this line will never be reached?!?
} elseif (strtolower($sExtension) !== 'xml') {
Yii::app()->setFlashMessage(gT("This is not a .xml file.") . 'It is a ' . $sExtension, 'error');
$this->redirect(array('userRole/index'));
Yii::app()->end();
} else {
$bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath);
}
if ($bMoveFileResult === false) {
Yii::app()->setFlashMessage(gT("An error occurred uploading your file. This may be caused by incorrect permissions for the application /tmp folder."), 'error');
$this->redirect(array('userRole/index'));
Yii::app()->end();
return;
}
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(false);
}
$oRoleDefinition = simplexml_load_file(realpath($sFilePath));
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(true);
}
$oNewRole = Permissiontemplates::model()->createFromXML($oRoleDefinition);
if ($oNewRole == false) {
Yii::app()->setFlashMessage(gT("Error creating role"), 'error');
Yii::app()->getController()->redirect(array('userRole/index'));
Yii::app()->end();
return;
}
$applyPermissions = $this->applyPermissionFromXML($oNewRole->ptid, $oRoleDefinition->permissions);
Yii::app()->setFlashMessage(gT("Role was successfully imported."), 'success');
Yii::app()->getController()->redirect(array('userRole/index'));
Yii::app()->end();
}
/**
* Batch Delete
* Massive action for deleting multiple roles at once.
*
* Renders a modal with deleting results for all roles that should be deleted.
*
* @throws CDbException
* @throws CException
*/
public function actionBatchDelete()
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
Yii::app()->session['flashmessage'] = gT('You have no access to the role management!');
$this->redirect(array('/admin'));
}
$sPtids = Yii::app()->request->getPost('sItems', []);
$aPtids = json_decode($sPtids, true);
$success = [];
foreach ($aPtids as $ptid) {
$success[$ptid] = $this->loadModel($ptid)->delete();
}
$this->renderPartial(
'/userManagement/partial/success',
[
'sMessage' => gT('Roles successfully deleted'),
'sDebug' => json_encode($success, JSON_PRETTY_PRINT),
'noButton' => true
]
);
}
/**
* Batch Export
* Massive action to export multiple roles.
*
* Redirects to index.
*/
public function actionBatchExport()
{
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
Yii::app()->session['flashmessage'] = gT('You have no access to the role management!');
$this->redirect(array('/admin'));
}
$sPtids = Yii::app()->request->getParam('sItems', '');
$aPtids = explode(',', $sPtids);
$sRandomFolderName = randomChars(20);
$sRandomFileName = "RoleExport-" . randomChars(5) . '-' . time();
$tempdir = Yii::app()->getConfig('tempdir');
$zipfile = "$tempdir/$sRandomFileName.zip";
Yii::app()->loadLibrary('admin.pclzip');
$zip = new PclZip($zipfile);
$sFilePath = $tempdir . DIRECTORY_SEPARATOR . $sRandomFolderName;
mkdir($sFilePath);
$filesInArchive = [];
foreach ($aPtids as $iPtid) {
$oModel = $this->loadModel($iPtid);
$oXML = $oModel->compileExportXML();
$filename = preg_replace("/[^a-zA-Z0-9-_]*/", '', $oModel->name) . '.xml';
file_put_contents($sFilePath . DIRECTORY_SEPARATOR . $filename, $oXML->asXML());
$filesInArchive[] = $sFilePath . DIRECTORY_SEPARATOR . $filename;
}
$zip->create($filesInArchive, PCLZIP_OPT_REMOVE_ALL_PATH);
if (is_file($zipfile)) {
// Send the file for download!
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=$sRandomFileName.zip");
header("Content-Description: File Transfer");
@readfile($zipfile);
// Delete the temporary file
array_map('unlink', glob("$sFilePath/*.*"));
rmdir($sFilePath);
unlink($zipfile);
return;
}
$this->redirect('index');
}
/** THIS FUNCTIONS DO NOT BELONG TO CONTROLLERS ** */
/**
* Apply Permission from XML.
*
* @param int $iRoleId Role ID
* @param array $oPermissionObject Permission
* @return array
*/
private function applyPermissionFromXML($iRoleId, $oPermissionObject)
{
$oCriteria = new CDbCriteria();
$oCriteria->compare('entity_id', $iRoleId);
$oCriteria->compare('entity', 'role');
//Kill all Permissions of that role.
$aPermissionsCurrently = Permission::model()->deleteAll($oCriteria); //todo: why delete here???
$results = [];
//Apply the permission array
$aCleanPermissionObject = json_decode(json_encode($oPermissionObject), true);
foreach ($aCleanPermissionObject as $sPermissionKey => $aPermissionSettings) {
$oPermission = new Permission();
$oPermission->entity = 'role';
$oPermission->entity_id = $iRoleId;
$oPermission->uid = 0;
$oPermission->permission = $sPermissionKey;
foreach ($aPermissionSettings as $sSettingKey => $sSettingValue) {
$oPermissionDBSettingKey = $sSettingKey . '_p';
if (isset($oPermission->$oPermissionDBSettingKey)) {
$oPermission->$oPermissionDBSettingKey = $sSettingValue;
}
}
$aPermissionData = Permission::getGlobalPermissionData($sPermissionKey);
$results[$sPermissionKey] = [
'descriptionData' => $aPermissionData,
'success' => $oPermission->save(),
'storedValue' => $oPermission->attributes
];
}
return $results;
}
/**
* Returns the data model based on the id. If no entry exists with the given id, then a
* new model for Permissiontemplates is returned.
*
* @param integer|null $ptid the ID of the model to be loaded
* @return Permissiontemplates the loaded model
*/
private function loadModel($ptid): Permissiontemplates
{
$model = Permissiontemplates::model()->findByPk($ptid);
if ($model === null) {
$model = new Permissiontemplates();
}
return $model;
}
/**
* Returns HTML fragment of errors
*
* @param array $errors
*
* @return string $errorDiv
*/
private function renderErrors(array $errors): string
{
$errorDiv = '<ul class="list-unstyled">';
foreach ($errors as $key => $error) {
foreach ($error as $errormessages) {
$errorDiv .= '<li>' . print_r($errormessages, true) . '</li>';
}
}
$errorDiv .= '</ul>';
return $errorDiv;
}
/**
* Adds permission to a role
* Needs an array in the form of [PERMISSIONID][PERMISSION]
*
* @param int $iRoleId
* @param array $aPermissionArray
* @return array
*/
private function applyPermissionFromArray($iRoleId, $aPermissionArray)
{
$oCriteria = new CDbCriteria();
$oCriteria->compare('entity_id', $iRoleId);
$oCriteria->compare('entity', 'role');
//Kill all Permissions of that role.
$aPermissionsCurrently = Permission::model()->deleteAll($oCriteria);
$results = [];
//Apply the permission array
foreach ($aPermissionArray as $sPermissionKey => $aPermissionSettings) {
$oPermission = new Permission();
$oPermission->entity = 'role';
$oPermission->entity_id = $iRoleId;
$oPermission->uid = 0;
$oPermission->permission = $sPermissionKey;
foreach ($aPermissionSettings as $sSettingKey => $sSettingValue) {
$oPermissionDBSettingKey = $sSettingKey . '_p';
$oPermission->$oPermissionDBSettingKey = $sSettingValue == 'on' ? 1 : 0;
}
$aPermissionData = Permission::getGlobalPermissionData($sPermissionKey);
$results[$sPermissionKey] = [
'descriptionData' => $aPermissionData,
'success' => $oPermission->save(),
'storedValue' => $oPermission->attributes
];
}
return $results;
}
}