PageRenderTime 30ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Console/Command/AclShell.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 607 lines | 410 code | 51 blank | 146 comment | 55 complexity | f8f190bbc76b9b990b46fc639541a421 MD5 | raw file
  1. <?php
  2. /**
  3. * Acl Shell provides Acl access in the CLI environment
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.2.0.5012
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. App::uses('AppShell', 'Console/Command');
  19. App::uses('ComponentCollection', 'Controller');
  20. App::uses('AclComponent', 'Controller/Component');
  21. App::uses('DbAcl', 'Model');
  22. /**
  23. * Shell for ACL management. This console is known to have issues with zend.ze1_compatibility_mode
  24. * being enabled. Be sure to turn it off when using this shell.
  25. *
  26. * @package Cake.Console.Command
  27. */
  28. class AclShell extends AppShell {
  29. /**
  30. * Contains instance of AclComponent
  31. *
  32. * @var AclComponent
  33. */
  34. public $Acl;
  35. /**
  36. * Contains arguments parsed from the command line.
  37. *
  38. * @var array
  39. */
  40. public $args;
  41. /**
  42. * Contains database source to use
  43. *
  44. * @var string
  45. */
  46. public $connection = 'default';
  47. /**
  48. * Contains tasks to load and instantiate
  49. *
  50. * @var array
  51. */
  52. public $tasks = array('DbConfig');
  53. /**
  54. * Override startup of the Shell
  55. *
  56. * @return void
  57. */
  58. public function startup() {
  59. parent::startup();
  60. if (isset($this->params['connection'])) {
  61. $this->connection = $this->params['connection'];
  62. }
  63. if (!in_array(Configure::read('Acl.classname'), array('DbAcl', 'DB_ACL'))) {
  64. $out = "--------------------------------------------------\n";
  65. $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
  66. $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
  67. $out .= "--------------------------------------------------\n";
  68. $out .= __d('cake_console', 'Current ACL Classname: %s', Configure::read('Acl.classname')) . "\n";
  69. $out .= "--------------------------------------------------\n";
  70. $this->err($out);
  71. $this->_stop();
  72. }
  73. if ($this->command) {
  74. if (!config('database')) {
  75. $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
  76. $this->args = null;
  77. return $this->DbConfig->execute();
  78. }
  79. require_once (APP . 'Config' . DS . 'database.php');
  80. if (!in_array($this->command, array('initdb'))) {
  81. $collection = new ComponentCollection();
  82. $this->Acl = new AclComponent($collection);
  83. $controller = null;
  84. $this->Acl->startup($controller);
  85. }
  86. }
  87. }
  88. /**
  89. * Override main() for help message hook
  90. *
  91. * @return void
  92. */
  93. public function main() {
  94. $this->out($this->OptionParser->help());
  95. }
  96. /**
  97. * Creates an ARO/ACO node
  98. *
  99. * @return void
  100. */
  101. public function create() {
  102. extract($this->_dataVars());
  103. $class = ucfirst($this->args[0]);
  104. $parent = $this->parseIdentifier($this->args[1]);
  105. if (!empty($parent) && $parent != '/' && $parent != 'root') {
  106. $parent = $this->_getNodeId($class, $parent);
  107. } else {
  108. $parent = null;
  109. }
  110. $data = $this->parseIdentifier($this->args[2]);
  111. if (is_string($data) && $data != '/') {
  112. $data = array('alias' => $data);
  113. } elseif (is_string($data)) {
  114. $this->error(__d('cake_console', '/ can not be used as an alias!') . __d('cake_console', " / is the root, please supply a sub alias"));
  115. }
  116. $data['parent_id'] = $parent;
  117. $this->Acl->{$class}->create();
  118. if ($this->Acl->{$class}->save($data)) {
  119. $this->out(__d('cake_console', "<success>New %s</success> '%s' created.", $class, $this->args[2]), 2);
  120. } else {
  121. $this->err(__d('cake_console', "There was a problem creating a new %s '%s'.", $class, $this->args[2]));
  122. }
  123. }
  124. /**
  125. * Delete an ARO/ACO node.
  126. *
  127. * @return void
  128. */
  129. public function delete() {
  130. extract($this->_dataVars());
  131. $identifier = $this->parseIdentifier($this->args[1]);
  132. $nodeId = $this->_getNodeId($class, $identifier);
  133. if (!$this->Acl->{$class}->delete($nodeId)) {
  134. $this->error(__d('cake_console', 'Node Not Deleted') . __d('cake_console', 'There was an error deleting the %s. Check that the node exists.', $class) . "\n");
  135. }
  136. $this->out(__d('cake_console', '<success>%s deleted.</success>', $class), 2);
  137. }
  138. /**
  139. * Set parent for an ARO/ACO node.
  140. *
  141. * @return void
  142. */
  143. public function setParent() {
  144. extract($this->_dataVars());
  145. $target = $this->parseIdentifier($this->args[1]);
  146. $parent = $this->parseIdentifier($this->args[2]);
  147. $data = array(
  148. $class => array(
  149. 'id' => $this->_getNodeId($class, $target),
  150. 'parent_id' => $this->_getNodeId($class, $parent)
  151. )
  152. );
  153. $this->Acl->{$class}->create();
  154. if (!$this->Acl->{$class}->save($data)) {
  155. $this->out(__d('cake_console', 'Error in setting new parent. Please make sure the parent node exists, and is not a descendant of the node specified.'), true);
  156. } else {
  157. $this->out(__d('cake_console', 'Node parent set to %s', $this->args[2]) . "\n", true);
  158. }
  159. }
  160. /**
  161. * Get path to specified ARO/ACO node.
  162. *
  163. * @return void
  164. */
  165. public function getPath() {
  166. extract($this->_dataVars());
  167. $identifier = $this->parseIdentifier($this->args[1]);
  168. $id = $this->_getNodeId($class, $identifier);
  169. $nodes = $this->Acl->{$class}->getPath($id);
  170. if (empty($nodes)) {
  171. $this->error(
  172. __d('cake_console', "Supplied Node '%s' not found", $this->args[1]),
  173. __d('cake_console', 'No tree returned.')
  174. );
  175. }
  176. $this->out(__d('cake_console', 'Path:'));
  177. $this->hr();
  178. for ($i = 0; $i < count($nodes); $i++) {
  179. $this->_outputNode($class, $nodes[$i], $i);
  180. }
  181. }
  182. /**
  183. * Outputs a single node, Either using the alias or Model.key
  184. *
  185. * @param string $class Class name that is being used.
  186. * @param array $node Array of node information.
  187. * @param integer $indent indent level.
  188. * @return void
  189. */
  190. protected function _outputNode($class, $node, $indent) {
  191. $indent = str_repeat(' ', $indent);
  192. $data = $node[$class];
  193. if ($data['alias']) {
  194. $this->out($indent . "[" . $data['id'] . "] " . $data['alias']);
  195. } else {
  196. $this->out($indent . "[" . $data['id'] . "] " . $data['model'] . '.' . $data['foreign_key']);
  197. }
  198. }
  199. /**
  200. * Check permission for a given ARO to a given ACO.
  201. *
  202. * @return void
  203. */
  204. public function check() {
  205. extract($this->_getParams());
  206. if ($this->Acl->check($aro, $aco, $action)) {
  207. $this->out(__d('cake_console', '%s is <success>allowed</success>.', $aroName), true);
  208. } else {
  209. $this->out(__d('cake_console', '%s is <error>not allowed</error>.', $aroName), true);
  210. }
  211. }
  212. /**
  213. * Grant permission for a given ARO to a given ACO.
  214. *
  215. * @return void
  216. */
  217. public function grant() {
  218. extract($this->_getParams());
  219. if ($this->Acl->allow($aro, $aco, $action)) {
  220. $this->out(__d('cake_console', 'Permission <success>granted</success>.'), true);
  221. } else {
  222. $this->out(__d('cake_console', 'Permission was <error>not granted</error>.'), true);
  223. }
  224. }
  225. /**
  226. * Deny access for an ARO to an ACO.
  227. *
  228. * @return void
  229. */
  230. public function deny() {
  231. extract($this->_getParams());
  232. if ($this->Acl->deny($aro, $aco, $action)) {
  233. $this->out(__d('cake_console', 'Permission denied.'), true);
  234. } else {
  235. $this->out(__d('cake_console', 'Permission was not denied.'), true);
  236. }
  237. }
  238. /**
  239. * Set an ARO to inherit permission to an ACO.
  240. *
  241. * @return void
  242. */
  243. public function inherit() {
  244. extract($this->_getParams());
  245. if ($this->Acl->inherit($aro, $aco, $action)) {
  246. $this->out(__d('cake_console', 'Permission inherited.'), true);
  247. } else {
  248. $this->out(__d('cake_console', 'Permission was not inherited.'), true);
  249. }
  250. }
  251. /**
  252. * Show a specific ARO/ACO node.
  253. *
  254. * @return void
  255. */
  256. public function view() {
  257. extract($this->_dataVars());
  258. if (isset($this->args[1])) {
  259. $identity = $this->parseIdentifier($this->args[1]);
  260. $topNode = $this->Acl->{$class}->find('first', array(
  261. 'conditions' => array($class . '.id' => $this->_getNodeId($class, $identity))
  262. ));
  263. $nodes = $this->Acl->{$class}->find('all', array(
  264. 'conditions' => array(
  265. $class . '.lft >=' => $topNode[$class]['lft'],
  266. $class . '.lft <=' => $topNode[$class]['rght']
  267. ),
  268. 'order' => $class . '.lft ASC'
  269. ));
  270. } else {
  271. $nodes = $this->Acl->{$class}->find('all', array('order' => $class . '.lft ASC'));
  272. }
  273. if (empty($nodes)) {
  274. if (isset($this->args[1])) {
  275. $this->error(__d('cake_console', '%s not found', $this->args[1]), __d('cake_console', 'No tree returned.'));
  276. } elseif (isset($this->args[0])) {
  277. $this->error(__d('cake_console', '%s not found', $this->args[0]), __d('cake_console', 'No tree returned.'));
  278. }
  279. }
  280. $this->out($class . ' tree:');
  281. $this->hr();
  282. $stack = array();
  283. $last = null;
  284. foreach ($nodes as $n) {
  285. $stack[] = $n;
  286. if (!empty($last)) {
  287. $end = end($stack);
  288. if ($end[$class]['rght'] > $last) {
  289. foreach ($stack as $k => $v) {
  290. $end = end($stack);
  291. if ($v[$class]['rght'] < $end[$class]['rght']) {
  292. unset($stack[$k]);
  293. }
  294. }
  295. }
  296. }
  297. $last = $n[$class]['rght'];
  298. $count = count($stack);
  299. $this->_outputNode($class, $n, $count);
  300. }
  301. $this->hr();
  302. }
  303. /**
  304. * Initialize ACL database.
  305. *
  306. * @return mixed
  307. */
  308. public function initdb() {
  309. return $this->dispatchShell('schema create DbAcl');
  310. }
  311. /**
  312. * Get the option parser.
  313. *
  314. * @return void
  315. */
  316. public function getOptionParser() {
  317. $parser = parent::getOptionParser();
  318. $type = array(
  319. 'choices' => array('aro', 'aco'),
  320. 'required' => true,
  321. 'help' => __d('cake_console', 'Type of node to create.')
  322. );
  323. $parser->description(__d('cake_console', 'A console tool for managing the DbAcl'))
  324. ->addSubcommand('create', array(
  325. 'help' => __d('cake_console', 'Create a new ACL node'),
  326. 'parser' => array(
  327. 'description' => __d('cake_console', 'Creates a new ACL object <node> under the parent'),
  328. 'arguments' => array(
  329. 'type' => $type,
  330. 'parent' => array(
  331. 'help' => __d('cake_console', 'The node selector for the parent.'),
  332. 'required' => true
  333. ),
  334. 'alias' => array(
  335. 'help' => __d('cake_console', 'The alias to use for the newly created node.'),
  336. 'required' => true
  337. )
  338. )
  339. )
  340. ))->addSubcommand('delete', array(
  341. 'help' => __d('cake_console', 'Deletes the ACL object with the given <node> reference'),
  342. 'parser' => array(
  343. 'description' => __d('cake_console', 'Delete an ACL node.'),
  344. 'arguments' => array(
  345. 'type' => $type,
  346. 'node' => array(
  347. 'help' => __d('cake_console', 'The node identifier to delete.'),
  348. 'required' => true,
  349. )
  350. )
  351. )
  352. ))->addSubcommand('setparent', array(
  353. 'help' => __d('cake_console', 'Moves the ACL node under a new parent.'),
  354. 'parser' => array(
  355. 'description' => __d('cake_console', 'Moves the ACL object specified by <node> beneath <parent>'),
  356. 'arguments' => array(
  357. 'type' => $type,
  358. 'node' => array(
  359. 'help' => __d('cake_console', 'The node to move'),
  360. 'required' => true,
  361. ),
  362. 'parent' => array(
  363. 'help' => __d('cake_console', 'The new parent for <node>.'),
  364. 'required' => true
  365. )
  366. )
  367. )
  368. ))->addSubcommand('getpath', array(
  369. 'help' => __d('cake_console', 'Print out the path to an ACL node.'),
  370. 'parser' => array(
  371. 'description' => array(
  372. __d('cake_console', "Returns the path to the ACL object specified by <node>."),
  373. __d('cake_console', "This command is useful in determining the inheritance of permissions for a certain object in the tree.")
  374. ),
  375. 'arguments' => array(
  376. 'type' => $type,
  377. 'node' => array(
  378. 'help' => __d('cake_console', 'The node to get the path of'),
  379. 'required' => true,
  380. )
  381. )
  382. )
  383. ))->addSubcommand('check', array(
  384. 'help' => __d('cake_console', 'Check the permissions between an ACO and ARO.'),
  385. 'parser' => array(
  386. 'description' => array(
  387. __d('cake_console', 'Use this command to check ACL permissions.')
  388. ),
  389. 'arguments' => array(
  390. 'aro' => array('help' => __d('cake_console', 'ARO to check.'), 'required' => true),
  391. 'aco' => array('help' => __d('cake_console', 'ACO to check.'), 'required' => true),
  392. 'action' => array('help' => __d('cake_console', 'Action to check'), 'default' => 'all')
  393. )
  394. )
  395. ))->addSubcommand('grant', array(
  396. 'help' => __d('cake_console', 'Grant an ARO permissions to an ACO.'),
  397. 'parser' => array(
  398. 'description' => array(
  399. __d('cake_console', 'Use this command to grant ACL permissions. Once executed, the ARO specified (and its children, if any) will have ALLOW access to the specified ACO action (and the ACO\'s children, if any).')
  400. ),
  401. 'arguments' => array(
  402. 'aro' => array('help' => __d('cake_console', 'ARO to grant permission to.'), 'required' => true),
  403. 'aco' => array('help' => __d('cake_console', 'ACO to grant access to.'), 'required' => true),
  404. 'action' => array('help' => __d('cake_console', 'Action to grant'), 'default' => 'all')
  405. )
  406. )
  407. ))->addSubcommand('deny', array(
  408. 'help' => __d('cake_console', 'Deny an ARO permissions to an ACO.'),
  409. 'parser' => array(
  410. 'description' => array(
  411. __d('cake_console', 'Use this command to deny ACL permissions. Once executed, the ARO specified (and its children, if any) will have DENY access to the specified ACO action (and the ACO\'s children, if any).')
  412. ),
  413. 'arguments' => array(
  414. 'aro' => array('help' => __d('cake_console', 'ARO to deny.'), 'required' => true),
  415. 'aco' => array('help' => __d('cake_console', 'ACO to deny.'), 'required' => true),
  416. 'action' => array('help' => __d('cake_console', 'Action to deny'), 'default' => 'all')
  417. )
  418. )
  419. ))->addSubcommand('inherit', array(
  420. 'help' => __d('cake_console', 'Inherit an ARO\'s parent permissions.'),
  421. 'parser' => array(
  422. 'description' => array(
  423. __d('cake_console', "Use this command to force a child ARO object to inherit its permissions settings from its parent.")
  424. ),
  425. 'arguments' => array(
  426. 'aro' => array('help' => __d('cake_console', 'ARO to have permissions inherit.'), 'required' => true),
  427. 'aco' => array('help' => __d('cake_console', 'ACO to inherit permissions on.'), 'required' => true),
  428. 'action' => array('help' => __d('cake_console', 'Action to inherit'), 'default' => 'all')
  429. )
  430. )
  431. ))->addSubcommand('view', array(
  432. 'help' => __d('cake_console', 'View a tree or a single node\'s subtree.'),
  433. 'parser' => array(
  434. 'description' => array(
  435. __d('cake_console', "The view command will return the ARO or ACO tree."),
  436. __d('cake_console', "The optional node parameter allows you to return"),
  437. __d('cake_console', "only a portion of the requested tree.")
  438. ),
  439. 'arguments' => array(
  440. 'type' => $type,
  441. 'node' => array('help' => __d('cake_console', 'The optional node to view the subtree of.'))
  442. )
  443. )
  444. ))->addSubcommand('initdb', array(
  445. 'help' => __d('cake_console', 'Initialize the DbAcl tables. Uses this command : cake schema create DbAcl')
  446. ))->epilog(
  447. array(
  448. 'Node and parent arguments can be in one of the following formats:',
  449. '',
  450. ' - <model>.<id> - The node will be bound to a specific record of the given model.',
  451. '',
  452. ' - <alias> - The node will be given a string alias (or path, in the case of <parent>)',
  453. " i.e. 'John'. When used with <parent>, this takes the form of an alias path,",
  454. " i.e. <group>/<subgroup>/<parent>.",
  455. '',
  456. "To add a node at the root level, enter 'root' or '/' as the <parent> parameter."
  457. )
  458. );
  459. return $parser;
  460. }
  461. /**
  462. * Checks that given node exists
  463. *
  464. * @return boolean Success
  465. */
  466. public function nodeExists() {
  467. if (!isset($this->args[0]) || !isset($this->args[1])) {
  468. return false;
  469. }
  470. extract($this->_dataVars($this->args[0]));
  471. $key = is_numeric($this->args[1]) ? $secondary_id : 'alias';
  472. $conditions = array($class . '.' . $key => $this->args[1]);
  473. $possibility = $this->Acl->{$class}->find('all', compact('conditions'));
  474. if (empty($possibility)) {
  475. $this->error(__d('cake_console', '%s not found', $this->args[1]), __d('cake_console', 'No tree returned.'));
  476. }
  477. return $possibility;
  478. }
  479. /**
  480. * Parse an identifier into Model.foreignKey or an alias.
  481. * Takes an identifier determines its type and returns the result as used by other methods.
  482. *
  483. * @param string $identifier Identifier to parse
  484. * @return mixed a string for aliases, and an array for model.foreignKey
  485. */
  486. public function parseIdentifier($identifier) {
  487. if (preg_match('/^([\w]+)\.(.*)$/', $identifier, $matches)) {
  488. return array(
  489. 'model' => $matches[1],
  490. 'foreign_key' => $matches[2],
  491. );
  492. }
  493. return $identifier;
  494. }
  495. /**
  496. * Get the node for a given identifier. $identifier can either be a string alias
  497. * or an array of properties to use in AcoNode::node()
  498. *
  499. * @param string $class Class type you want (Aro/Aco)
  500. * @param mixed $identifier A mixed identifier for finding the node.
  501. * @return integer Integer of NodeId. Will trigger an error if nothing is found.
  502. */
  503. protected function _getNodeId($class, $identifier) {
  504. $node = $this->Acl->{$class}->node($identifier);
  505. if (empty($node)) {
  506. if (is_array($identifier)) {
  507. $identifier = var_export($identifier, true);
  508. }
  509. $this->error(__d('cake_console', 'Could not find node using reference "%s"', $identifier));
  510. }
  511. return Set::extract($node, "0.{$class}.id");
  512. }
  513. /**
  514. * get params for standard Acl methods
  515. *
  516. * @return array aro, aco, action
  517. */
  518. protected function _getParams() {
  519. $aro = is_numeric($this->args[0]) ? intval($this->args[0]) : $this->args[0];
  520. $aco = is_numeric($this->args[1]) ? intval($this->args[1]) : $this->args[1];
  521. $aroName = $aro;
  522. $acoName = $aco;
  523. if (is_string($aro)) {
  524. $aro = $this->parseIdentifier($aro);
  525. }
  526. if (is_string($aco)) {
  527. $aco = $this->parseIdentifier($aco);
  528. }
  529. $action = null;
  530. if (isset($this->args[2])) {
  531. $action = $this->args[2];
  532. if ($action == '' || $action == 'all') {
  533. $action = '*';
  534. }
  535. }
  536. return compact('aro', 'aco', 'action', 'aroName', 'acoName');
  537. }
  538. /**
  539. * Build data parameters based on node type
  540. *
  541. * @param string $type Node type (ARO/ACO)
  542. * @return array Variables
  543. */
  544. protected function _dataVars($type = null) {
  545. if ($type == null) {
  546. $type = $this->args[0];
  547. }
  548. $vars = array();
  549. $class = ucwords($type);
  550. $vars['secondary_id'] = (strtolower($class) == 'aro') ? 'foreign_key' : 'object_id';
  551. $vars['data_name'] = $type;
  552. $vars['table_name'] = $type . 's';
  553. $vars['class'] = $class;
  554. return $vars;
  555. }
  556. }