PageRenderTime 202ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 1ms

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

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