forked from cakephp/acl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAclExtras.php
543 lines (506 loc) · 17.2 KB
/
AclExtras.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
<?php
/**
* Acl Extras.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2008-2013, Mark Story.
* @link http://mark-story.com
* @author Mark Story <mark@mark-story.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace Acl;
use Acl\Controller\Component\AclComponent;
use Cake\Controller\ComponentRegistry;
use Cake\Controller\Controller;
use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Filesystem\Folder;
use Cake\Network\Request;
use Cake\Routing\Router;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
/**
* Provides features for additional ACL operations.
* Can be used in either a CLI or Web context.
*/
class AclExtras
{
/**
* Contains instance of AclComponent
*
* @var \Acl\Controller\Component\AclComponent
*/
public $Acl;
/**
* Contains arguments parsed from the command line.
*
* @var array
*/
public $args;
/**
* Contains database source to use
*
* @var string
*/
public $dataSource = 'default';
/**
* Root node name.
*
* @var string
*/
public $rootNode = 'controllers';
/**
* Internal Clean Actions switch
*
* @var bool
*/
protected $_clean = false;
/**
* Contains app route prefixes
*
* @var array
*/
protected $prefixes = [];
/**
* Contains plugins route prefixes
*
* @var array
*/
protected $pluginPrefixes = [];
/**
* List of ACOs found during synchronization
*
* @var array
*/
protected $foundACOs = [];
/**
* Start up And load Acl Component / Aco model
*
* @return void
*/
public function startup($controller = null)
{
if (!$controller) {
$controller = new Controller(new Request());
include CONFIG . 'routes.php';
}
$registry = new ComponentRegistry();
$this->Acl = new AclComponent($registry, Configure::read('Acl'));
$this->Aco = $this->Acl->Aco;
$this->controller = $controller;
$this->_buildPrefixes();
}
/**
* Output a message.
*
* Will either use shell->out, or controller->Flash->success()
*
* @param string $msg The message to output.
* @return void
*/
public function out($msg)
{
if (!empty($this->controller->Flash)) {
$this->controller->Flash->success($msg);
} else {
return $this->Shell->out($msg);
}
}
/**
* Output an error message.
*
* Will either use shell->err, or controller->Flash->error()
*
* @param string $msg The message to output.
* @return void
*/
public function err($msg)
{
if (!empty($this->controller->Flash)) {
$this->controller->Flash->error($msg);
} else {
return $this->Shell->err($msg);
}
}
/**
* Sync the ACO table
*
* @param array $params An array of parameters
* @return void
*/
public function acoSync($params = [])
{
$this->_clean = true;
$this->acoUpdate($params);
}
/**
* Updates the Aco Tree with new controller actions.
*
* @param array $params An array of parameters
* @return void
*/
public function acoUpdate($params = [])
{
$root = $this->_checkNode($this->rootNode, $this->rootNode, null);
if (empty($params['plugin'])) {
$plugins = Plugin::loaded();
$this->_processControllers($root);
$this->_processPrefixes($root);
$this->_processPlugins($root, $plugins);
} else {
$plugin = $params['plugin'];
if (!Plugin::loaded($plugin)) {
$this->err(__d('cake_acl', "<error>Plugin {0} not found or not activated.</error>", [$plugin]));
return false;
}
$plugins = [$params['plugin']];
$this->_processPlugins($root, $plugins);
$this->foundACOs = array_slice($this->foundACOs, 1, null, true);
}
if ($this->_clean) {
foreach ($this->foundACOs as $parentId => $acosList) {
$this->_cleaner($parentId, $acosList);
}
}
$this->out(__d('cake_acl', '<success>Aco Update Complete</success>'));
return true;
}
/**
* Updates the Aco Tree with all App controllers.
*
* @param \Acl\Model\Entity\Aco $root The root note of Aco Tree
* @return void
*/
protected function _processControllers($root)
{
$controllers = $this->getControllerList();
$this->foundACOs[$root->id] = $this->_updateControllers($root, $controllers);
}
/**
* Updates the Aco Tree with all App route prefixes.
*
* @param \Acl\Model\Entity\Aco $root The root note of Aco Tree
* @return void
*/
protected function _processPrefixes($root)
{
foreach (array_keys($this->prefixes) as $prefix) {
$controllers = $this->getControllerList(null, $prefix);
$path = $this->rootNode . '/' . $prefix;
$pathNode = $this->_checkNode($path, $prefix, $root->id);
$this->foundACOs[$root->id][] = $prefix;
if (isset($this->foundACOs[$pathNode->id])) {
$this->foundACOs[$pathNode->id] += $this->_updateControllers($pathNode, $controllers, null, $prefix);
} else {
$this->foundACOs[$pathNode->id] = $this->_updateControllers($pathNode, $controllers, null, $prefix);
}
}
}
/**
* Returns the aliased name for the plugin (Needed in order to correctly handle nested plugins)
*
* @param string $plugin The name of the plugin to alias
* @return string
*/
protected function _pluginAlias($plugin)
{
return preg_replace('/\//', '\\', Inflector::camelize($plugin));
}
/**
* Updates the Aco Tree with all Plugins.
*
* @param \Acl\Model\Entity\Aco $root The root note of Aco Tree
* @param array $plugins list of App plugins
* @return void
*/
protected function _processPlugins($root, array $plugins = [])
{
foreach ($plugins as $plugin) {
$controllers = $this->getControllerList($plugin);
$pluginAlias = $this->_pluginAlias($plugin);
$path = [
$this->rootNode,
$pluginAlias
];
$path = implode('/', Hash::filter($path));
$pathNode = $this->_checkNode($path, $pluginAlias, $root->id);
$this->foundACOs[$root->id][] = $pluginAlias;
if (isset($this->foundACOs[$pathNode->id])) {
$this->foundACOs[$pathNode->id] += $this->_updateControllers($pathNode, $controllers, $plugin);
} else {
$this->foundACOs[$pathNode->id] = $this->_updateControllers($pathNode, $controllers, $plugin);
}
if (isset($this->pluginPrefixes[$plugin])) {
foreach (array_keys($this->pluginPrefixes[$plugin]) as $prefix) {
$path = [
$this->rootNode,
$pluginAlias
];
$path = implode('/', Hash::filter($path));
$pluginNode = $this->_checkNode($path, $pluginAlias, $root->id);
$this->foundACOs[$root->id][] = $pluginAlias;
$path = [
$this->rootNode,
$pluginAlias,
$prefix,
];
$path = implode('/', Hash::filter($path));
$pathNode = $this->_checkNode($path, $prefix, $pluginNode->id);
$this->foundACOs[$pluginNode->id][] = $prefix;
$controllers = $this->getControllerList($plugin, $prefix);
if (isset($this->foundACOs[$pathNode->id])) {
$this->foundACOs[$pathNode->id] += $this->_updateControllers($pathNode, $controllers, $pluginAlias, $prefix);
} else {
$this->foundACOs[$pathNode->id] = $this->_updateControllers($pathNode, $controllers, $pluginAlias, $prefix);
}
}
}
}
}
/**
* Updates a collection of controllers.
*
* @param array $root Array or ACO information for root node.
* @param array $controllers Array of Controllers
* @param string $plugin Name of the plugin you are making controllers for.
* @param string $prefix Name of the prefix you are making controllers for.
* @return array
*/
protected function _updateControllers($root, $controllers, $plugin = null, $prefix = null)
{
$pluginPath = $this->_pluginAlias($plugin);
// look at each controller
$controllersNames = [];
foreach ($controllers as $controller) {
$tmp = explode('/', $controller);
$controllerName = str_replace('Controller.php', '', array_pop($tmp));
if ($controllerName == 'App') {
continue;
}
$controllersNames[] = $controllerName;
$path = [
$this->rootNode,
$pluginPath,
$prefix,
$controllerName
];
$path = implode('/', Hash::filter($path));
$controllerNode = $this->_checkNode($path, $controllerName, $root->id);
$this->_checkMethods($controller, $controllerName, $controllerNode, $pluginPath, $prefix);
}
return $controllersNames;
}
/**
* Get a list of controllers in the app and plugins.
*
* Returns an array of path => import notation.
*
* @param string $plugin Name of plugin to get controllers for
* @param string $prefix Name of prefix to get controllers for
* @return array
*/
public function getControllerList($plugin = null, $prefix = null)
{
if (!$plugin) {
$path = App::path('Controller' . (empty($prefix) ? '' : DS . Inflector::camelize($prefix)));
$dir = new Folder($path[0]);
$controllers = $dir->find('.*Controller\.php');
} else {
$path = App::path('Controller' . (empty($prefix) ? '' : DS . Inflector::camelize($prefix)), $plugin);
$dir = new Folder($path[0]);
$controllers = $dir->find('.*Controller\.php');
}
return $controllers;
}
/**
* Check a node for existance, create it if it doesn't exist.
*
* @param string $path The path to check
* @param string $alias The alias to create
* @param int $parentId The parent id to use when creating.
* @return array Aco Node array
*/
protected function _checkNode($path, $alias, $parentId = null)
{
$node = $this->Aco->node($path);
if (!$node) {
$data = [
'parent_id' => $parentId,
'model' => null,
'alias' => $alias,
];
$entity = $this->Aco->newEntity($data);
$node = $this->Aco->save($entity);
$this->out(__d('cake_acl', 'Created Aco node: <success>{0}</success>', $path));
} else {
$node = $node->first();
}
return $node;
}
/**
* Get a list of registered callback methods
*
* @param string $className The class to reflect on.
* @param string $pluginPath The plugin path.
* @param string $prefixPath The prefix path.
* @return array
*/
protected function _getCallbacks($className, $pluginPath = null, $prefixPath = null)
{
$callbacks = [];
$namespace = $this->_getNamespace($className, $pluginPath, $prefixPath);
$reflection = new \ReflectionClass($namespace);
if ($reflection->isAbstract()) {
return $callbacks;
}
try {
$method = $reflection->getMethod('implementedEvents');
} catch (ReflectionException $e) {
return $callbacks;
}
if (version_compare(phpversion(), '5.4', '>=')) {
$object = $reflection->newInstanceWithoutConstructor();
} else {
$object = unserialize(
sprintf('O:%d:"%s":0:{}', strlen($className), $className)
);
}
$implementedEvents = $method->invoke($object);
foreach ($implementedEvents as $event => $callable) {
if (is_string($callable)) {
$callbacks[] = $callable;
}
if (is_array($callable) && isset($callable['callable'])) {
$callbacks[] = $callable['callable'];
}
}
return $callbacks;
}
/**
* Check and Add/delete controller Methods
*
* @param string $className The classname to check
* @param string $controllerName The controller name
* @param array $node The node to check.
* @param string $pluginPath The plugin path to use.
* @param string $prefixPath The prefix path to use.
* @return bool
*/
protected function _checkMethods($className, $controllerName, $node, $pluginPath = null, $prefixPath = null)
{
$excludes = $this->_getCallbacks($className, $pluginPath, $prefixPath);
$baseMethods = get_class_methods(new Controller);
$namespace = $this->_getNamespace($className, $pluginPath, $prefixPath);
$methods = get_class_methods(new $namespace);
if ($methods == null) {
$this->err(__d('cake_acl', 'Unable to get methods for {0}', $className));
return false;
}
$actions = array_diff($methods, $baseMethods);
$actions = array_diff($actions, $excludes);
foreach ($actions as $key => $action) {
if (strpos($action, '_', 0) === 0) {
continue;
}
$path = [
$this->rootNode,
$pluginPath,
$prefixPath,
$controllerName,
$action
];
$path = implode('/', Hash::filter($path));
$this->_checkNode($path, $action, $node->id);
$actions[$key] = $action;
}
if ($this->_clean) {
$this->_cleaner($node->id, $actions);
}
return true;
}
/**
* Recover an Acl Tree
*
* @return void
*/
public function recover()
{
$type = Inflector::camelize($this->args[0]);
$this->Acl->{$type}->recover();
$this->out(__('Tree has been recovered, or tree did not need recovery.'));
}
/**
* Get the namespace for a given class.
*
* @param string $className The class you want a namespace for.
* @param string $pluginPath The plugin path.
* @param string $prefixPath The prefix path.
* @return string
*/
protected function _getNamespace($className, $pluginPath = null, $prefixPath = null)
{
$namespace = preg_replace('/(.*)Controller\//', '', $className);
$namespace = preg_replace('/\//', '\\', $namespace);
$namespace = preg_replace('/\.php/', '', $namespace);
$prefixPath = preg_replace('/\//', '\\', Inflector::camelize($prefixPath));
if (!$pluginPath) {
$rootNamespace = Configure::read('App.namespace');
} else {
$rootNamespace = preg_replace('/\//', '\\', $pluginPath);
}
$namespace = [
$rootNamespace,
'Controller',
$prefixPath,
$namespace
];
return implode('\\', Hash::filter($namespace));
}
/**
* Build prefixes for App and Plugins based on configured routes
*
* @return void
*/
protected function _buildPrefixes()
{
$routes = Router::routes();
foreach ($routes as $key => $route) {
if (isset($route->defaults['prefix'])) {
$prefix = Inflector::camelize($route->defaults['prefix']);
if (!isset($route->defaults['plugin'])) {
$this->prefixes[$prefix] = true;
} else {
$this->pluginPrefixes[$route->defaults['plugin']][$prefix] = true;
}
}
}
}
/**
* Delete unused ACOs.
*
* @param int $parentId Id of the parent node.
* @param array $preservedItems list of items that will not be erased.
* @return void
*/
protected function _cleaner($parentId, $preservedItems = [])
{
$nodes = $this->Aco->find()->where(['parent_id' => $parentId]);
$methodFlip = array_flip($preservedItems);
foreach ($nodes as $node) {
if (!isset($methodFlip[$node->alias])) {
$crumbs = $this->Aco->find('path', ['for' => $node->id, 'order' => 'lft']);
$path = null;
foreach ($crumbs as $crumb) {
$path .= '/' . $crumb->alias;
}
$entity = $this->Aco->get($node->id);
if ($this->Aco->delete($entity)) {
$this->out(__d('cake_acl', 'Deleted Aco node: <warning>{0}</warning> and all children', $path));
}
}
}
}
}