-
Notifications
You must be signed in to change notification settings - Fork 1
/
RolesManagerController.php
515 lines (429 loc) · 18.9 KB
/
RolesManagerController.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
<?php
/**
* Roles Manager plugin for Wolf CMS
*
* Manage Roles and assign/remove permissions.
*
* @author andrewmman <andrewmman@gmail.com>
* @package Plugins
* @subpackage roles_manager
* @version 0.1.4
* @copyright andrewmman, 2011
* @license http://www.gnu.org/licenses/gpl.html GPLv3 license
*/
if (!defined('IN_CMS')) { exit(); }
class RolesManagerController extends PluginController {
const PLUGIN_ID = 'roles_manager';
public function __construct() {
if (defined('CMS_BACKEND')) {
AuthUser::load();
if (!AuthUser::isLoggedIn()) {
redirect(get_url('login'));
}
else if (!AuthUser::hasPermission('admin_edit')) {
Flash::set('error', __('You do not have permission to access the requested page!'));
redirect(get_url());
}
$this->setLayout('backend');
$this->assignToLayout('sidebar', new View( PLUGINS_ROOT.DS.self::PLUGIN_ID.DS.'views/sidebar'));
}
}
public function index() {
$roles = Role::findAllFrom('Role');
foreach($roles as $role) {
$role->users = $this->_getUserCount($role->id);
}
// Add tablesorter script
Plugin::addJavascript('roles_manager', 'assets/js/jquery.tablesorter.min.js');
$this->display('index', array( 'roles' => $roles ));
}
public function documentation() {
// Check for localized documentation or fallback to the default english and display notice
$lang = ( $user = AuthUser::getRecord() ) ? strtolower($user->language) : 'en';
if( !file_exists( PLUGINS_ROOT.DS.self::PLUGIN_ID.DS.'views/documentation/'.$lang.'.php') ) {
$message = __("There's no translation for the documentation in your language, displaying the default english.");
$this->display('documentation/en', array( 'message' => $message ));
}
else
$this->display('documentation/'.$lang);
}
/*---------------------------------------------------------------------------
- ROLES actions -
---------------------------------------------------------------------------*/
public function add() {
// Trying to save?
if( get_request_method() == 'POST' ) {
return $this->_save('add');
}
// Instantiate and display the form
$role = new Role;
$token = $this->_getTokenFor('add');
$permissions = Permission::getPermissions();
$role_permissions = array();
$permissions_disabled = array();
// New Role doesn't have any permissions
foreach ($permissions as $perm) {
array_push($permissions_disabled, $perm->id);
}
$this->display('edit', array(
'action' => 'add',
'csrf_token' => $token,
'role' => $role,
'permissions' => $permissions,
'role_permissions' => $role_permissions,
'permissions_disabled' => $permissions_disabled
)
);
}
public function edit($id) {
if (!is_numeric($id)) {
Flash::set('error', __('The Role <strong>ID</strong> is not valid!'));
$this->_redirectTo();
}
// Trying to save?
if( get_request_method() == 'POST' ) {
return $this->_save('edit');
}
$role = Role::findById( (int) $id );
if(!$role) {
Flash::set('error', 'Role not found!');
$this->_redirectTo();
}
// Set data
$permissions = Permission::getPermissions();
$role_permissions = array();
$permissions_disabled = array();
foreach ($permissions as $perm) {
if( $role->id == 1 || $role->hasPermission($perm) )
array_push($role_permissions, $perm->id);
else
array_push($permissions_disabled, $perm->id);
}
$token = $this->_getTokenFor('edit');
// Display the form and pass the data to the form
$this->display('edit', array(
'action' => 'edit',
'csrf_token' => $token,
'role' => $role,
'permissions' => $permissions,
'role_permissions' => $role_permissions,
'permissions_disabled' => $permissions_disabled
)
);
}
private function _save($action) {
$data = $_POST['role'];
// Simple Validation
$errors = false;
use_helper('Validate');
// CSRF checks
if (isset($_POST['csrf_token'])) {
$csrf_token = $_POST['csrf_token'];
if( ! $this->_isTokenValid($csrf_token,$action) )
$errors[] = __('Invalid CSRF token found!');
}
else {
$errors[] = __('No CSRF token found!');
}
if( $action == 'edit' && empty($data['id']) ) {
$errors[] = __('The Role <strong>ID</strong> is not valid!');
}
$data['id'] = ($action == 'add') ? '' : (int) $data['id'] ;
$data['name'] = trim($data['name']);
if( empty($data['name']) ) {
$errors[] = __("You must specify the Role's <strong>name</strong>!");
}
// End Validation
// Protect the administrator role permissions
$admin_changed = false;
$role_perms = $data['role_permissions'];
$new_permissions = array();
foreach($role_perms as $i => $rp) {
if( ($data['id'] === 1) || (isset($rp['assigned']) && $rp['assigned'] == 'on' )) {
$perm_data = array(
'id' => (int)$rp['permission_id'],
'name' => trim($rp['permission_name'])
);
$p = new Permission($perm_data);
$new_permissions[$rp['permission_name']] = $p;
if( (!isset($rp['assigned']) ) || $rp['assigned'] != 'on') {
$admin_changed = true;
}
}
}
$role_data = array(
'id' => $data['id'],
'name' => $data['name'],
'permissions' => $new_permissions
);
$role = new Role($role_data);
// Inform the user if he tried to remove permissions from the 'administrator' role
if (false !== $admin_changed) {
$errors[] = __("Permissions <strong>can't</strong> be removed from the <strong>':name'</strong> role!", array( ':name' => $role->name ));
}
if (false !== $errors) {
// Set the errors to be displayed.
Flash::setNow('error', implode('<br/>', $errors));
// Get the data
$token = $this->_getTokenFor($action);
$permissions = Permission::getPermissions();
$role_permissions = array();
$permissions_disabled = array();
foreach ($permissions as $perm) {
if($role->hasPermission($perm))
array_push($role_permissions, $perm->id);
else
array_push($permissions_disabled, $perm->id);
}
$this->display('edit', array(
'action' => $action,
'csrf_token' => $token,
'role' => $role,
'permissions' => $permissions,
'role_permissions' => $role_permissions,
'permissions_disabled' => $permissions_disabled
)
);
}
else {
if( !$role->save() ) {
Flash::set('post_role', (object) $role_data);
Flash::set('error', __('The <strong>:name</strong> role could not be saved!', array( ':name' => $role->name )));
$action_url = ($action == 'add') ? 'add' : 'edit/'.$role->id ;
// Notify
$message = __(':username tried to :action the <strong>:name</strong> role, but it couldn\'t be saved!', array(
':name' => ($action == 'add') ? $role->name : sprintf('<a href="%s">%s</a>', get_url('plugin/roles_manager/edit/'.$role->id), $role->name),
':action' => ($action == 'add') ? 'add' : 'edit'
));
Observer::notify('log_event', $message, 'roles_manager', 3);
$this->_redirectTo($action_url);
}
else {
if( RolePermission::savePermissionsFor( (int)$role->id, $role->permissions ) ) {
Flash::set( 'success', __('The <strong>:name</strong> role was saved succesfully!', array( ':name' => $role->name )) );
// Notify
$message = __('Role <strong>:name</strong> was :action by :username.', array(
':name' => sprintf('<a href="%s">%s</a>', get_url('plugin/roles_manager/edit/'.$role->id), $role->name),
':action' => ($action == 'add') ? 'added' : 'revised'
));
Observer::notify('log_event', $message, 'roles_manager', 5);
$this->_redirectTo();
}
else {
Flash::set('post_role', (object) $role_data);
Flash::set( 'error', __('The <strong>:name</strong> role <strong>permissions</strong> could not be saved!', array( ':name' => $role->name )) );
$action_url = ($submit == 'add') ? 'add' : 'edit/' . $role->id;
// Notify
$message = __(':username tried to :action the <strong>:name</strong> role, but it couldn\'t be saved!', array(
':name' => ($action == 'add') ? $role->name : sprintf('<a href="%s">%s</a>', get_url('plugin/roles_manager/edit/'.$role->id), $role->name),
':action' => ($action == 'add') ? 'add' : 'edit'
));
Observer::notify('log_event', $message, 'roles_manager', 3);
$this->_redirectTo($action_url);
}
}
}
}
public function delete($id) {
// Protect the administrator role
if( (int)$id == 1 ) {
$admin_role = Role::findById(1);
$admin_role_name = ($admin_role) ? $admin_role->name : 'administrator';
Flash::set( 'error', __("You can't delete the '<strong>:name</strong>' role!", array( ':name' => $admin_role_name )) );
$this->_redirectTo();
}
if($role = Role::findById($id)) {
$permissions = RolePermission::findPermissionsFor((int)$role->id);
// Set data in case something goes wrong
Flash::set( 'role', (object) $role );
Flash::set( 'role_permissions', (object) $permissions );
// First delete the role_permissions relationship
if( RolePermission::savePermissionsFor( (int)$role->id, $role->permissions ) ) {
// Now let's try deleting the role
if( $role->delete() ) {
// Notify
$message = __('Role <strong>:name</strong> was deleted by :username.', array( ':name' => $role->name ));
Observer::notify('log_event', $message, 'roles_manager', 5);
Flash::set('success', __('Role <strong>:name</strong> has been deleted!', array( ':name' => $role->name )));
}
else {
// Rebuild role_permissions relationships
$permissions = Flash::get('role_permissions');
RolePermission::savePermissionsFor( (int)$role->id, $role->permissions );
// Notify
$message = __(':username tried to delete the <strong>:name</strong> role, but something went wrong!', array(
':name' => sprintf('<a href="%s">%s</a>', get_url('plugin/roles_manager/edit/'.$role->id), $role->name),
));
Observer::notify('log_event', $message, 'roles_manager', 3);
Flash::set('error', __('Role <strong>:name</strong> could not be deleted!', array( ':name' => $role->name )));
}
}
else {
// Notify
$message = __(':username tried to delete the <strong>:name</strong> role, but something went wrong!', array(
':name' => sprintf('<a href="%s">%s</a>', get_url('plugin/roles_manager/edit/'.$role->id), $role->name),
));
Observer::notify('log_event', $message, 'roles_manager', 3);
Flash::set( 'error', __('The :name role <strong>permissions</strong> could not be deleted!', array( ':name' => $role->name )));
}
}
else {
Flash::set('error', __('Role not found!'));
}
$this->_redirectTo();
}
/*---------------------------------------------------------------------------
- ROLES Users actions -
---------------------------------------------------------------------------*/
public function users($role_id) {
if ( ! is_numeric($role_id) ) {
Flash::set('error', __('The Role <strong>ID</strong> is not valid!'));
$this->_redirectTo();
}
// Trying to save?
if( get_request_method() == 'POST' ) {
return $this->_users_save();
}
$role = Role::findById( (int) $role_id );
if(!$role) {
Flash::set('error', 'Role not found!');
$this->_redirectTo('users');
}
$users = $this->_getUsersByRole($role);
$token = $this->_getTokenFor('users');
// Add tablesorter script
Plugin::addJavascript('roles_manager', 'assets/js/jquery.tablesorter.min.js');
$this->display('users', array(
'csrf_token' => $token,
'role' => $role,
'users' => $users
));
}
private function _users_save() {
$data = $_POST['role'];
// CSRF checks
if (isset($_POST['csrf_token'])) {
$csrf_token = $_POST['csrf_token'];
if( ! $this->_isTokenValid($csrf_token,'users')) {
Flash::set('error', __('Invalid CSRF token found!'));
$this->_redirectTo('users/'.$data['id']);
}
}
else {
Flash::set('error', __('No CSRF token found!'));
$this->_redirectTo('users/'.$data['id']);
}
$errors = false;
$users_deleted = false;
$role_id = (int) $data['id'];
$role_name = $data['name'];
foreach($data['users'] as $i => $user) {
if( (!isset($user['keep_role']) ) || $user['keep_role'] != 1) {
$uid = (int) $user['user_id'];
// Protect the administrator role-user
if( $role_id == 1 && $user['user_id'] == 1 ) {
Flash::set( 'error', __("You can't remove the '<strong>:name</strong>' role from user <strong>:user</strong>!", array( ':name' => $role_name, ':user' => $user['user_username'] )) );
$this->_redirectTo('users/'.$role_id);
}
if($this->_removeRoleFromUser($role_id,$uid)) {
$users_deleted[] = __("User <strong>:user</strong> no longer has the <strong>:role</strong> role.", array(':role' => $role_name, ':user' => $user['user_username']));
}
else {
$errors[] = __("Couldn't delete the <strong>:role</strong> role from user <strong>:user</strong>.", array(':role' => $role_name, ':user' => $user['user_username']));
}
}
}
// Let's show a list of the users affected
if ($users_deleted !== false) {
Flash::setNow('success', implode('<br/>', $users_deleted));
}
// Do we had any problems?
if ($errors !== false) {
Flash::setNow('error', implode('<br/>', $errors));
$this->_redirectTo('users/'.$role_id);
}
$this->_redirectTo();
}
/* overwrite */
public function render($view, $vars=array()) {
if (defined('CMS_BACKEND')) {
if ($this->layout) {
$this->layout_vars['content_for_layout'] = new View( PLUGINS_ROOT.DS.self::PLUGIN_ID.DS.'views'.DS.$view, $vars);
return new View('../layouts/'.$this->layout, $this->layout_vars);
}
else
return new View(PLUGINS_ROOT.DS.self::PLUGIN_ID.DS.'views'.DS.$view, $vars);
}
else
redirect(get_url('login'));
}
/*---------------------------------------------------------------------------
- HELPERS -
---------------------------------------------------------------------------*/
private function _redirectTo($action='index') {
$url = 'plugin/'.self::PLUGIN_ID.'/'.$action;
redirect( get_url($url) );
}
private function _getTokenFor($action) {
$url = BASE_URL.'plugin/'.self::PLUGIN_ID.'/'.$action;
return SecureToken::generateToken($url);
}
private function _isTokenValid($token, $action) {
$url = BASE_URL.'plugin/'.self::PLUGIN_ID.'/'.$action;
return (boolean) SecureToken::validateToken($token, $url);
}
private function _getUserCount($rid) {
$sql = "SELECT COUNT(user_id) FROM ".TABLE_PREFIX."user_role WHERE role_id=".(int)$rid;
$stmt = Record::getConnection()->prepare($sql);
$stmt->execute();
return (int) $stmt->fetchColumn();
}
private function _getUsersByRole(Role $role) {
if(!($role instanceof Role))
return false;
$sql = "SELECT user_id FROM ".TABLE_PREFIX."user_role WHERE role_id=".(int)$role->id;
$stmt = Record::getConnection()->prepare($sql);
$stmt->execute();
$users = array();
while( $uid = $stmt->fetchColumn()) {
$user = User::findById($uid);
if($user !== false) {
unset($user->password);
unset($user->salt);
$users[] = $user;
}
}
return $users;
}
private function _removeRoleFromUser($rid,$uid) {
$tablename = Record::tableNameFromClassName('UserRole');
$sql = 'DELETE FROM '.$tablename.' WHERE role_id='.(int)$rid.' AND user_id='.(int)$uid;
$pdo = Record::getConnection();
return $pdo->exec($sql) !== false;
}
// Not used but keep it
/*
private static function _getCorePermissions() {
return array(
'admin_view',
'admin_edit',
'user_view',
'user_add',
'user_edit',
'user_delete',
'layout_view',
'layout_add',
'layout_edit',
'layout_delete',
'snippet_view',
'snippet_add',
'snippet_edit',
'snippet_delete',
'page_view',
'page_add',
'page_edit',
'page_delete'
);
}
*/
}