TreeBehavior.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. <?php
  2. /**
  3. * Tree behavior class.
  4. *
  5. * Enables a model object to act as a node-based tree.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2006-2010, Cake Software Foundation, Inc.
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
  16. * @link http://cakephp.org CakePHP Project
  17. * @package cake.libs.model.behaviors
  18. * @since CakePHP v 1.2.0.4487
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. /**
  22. * Tree Behavior.
  23. *
  24. * Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
  25. *
  26. * @see http://en.wikipedia.org/wiki/Tree_traversal
  27. * @package cake.libs.model.behaviors
  28. * @link http://book.cakephp.org/view/1339/Tree
  29. */
  30. class TreeBehavior extends ModelBehavior {
  31. /**
  32. * Errors
  33. *
  34. * @var array
  35. */
  36. public $errors = array();
  37. /**
  38. * Defaults
  39. *
  40. * @var array
  41. * @access protected
  42. */
  43. protected $_defaults = array(
  44. 'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght',
  45. 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1
  46. );
  47. /**
  48. * Initiate Tree behavior
  49. *
  50. * @param object $Model instance of model
  51. * @param array $config array of configuration settings.
  52. * @return void
  53. */
  54. public function setup($Model, $config = array()) {
  55. if (!is_array($config)) {
  56. $config = array('type' => $config);
  57. }
  58. $settings = array_merge($this->_defaults, $config);
  59. if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
  60. $data = $Model->getAssociated($settings['scope']);
  61. $parent = $Model->{$settings['scope']};
  62. $settings['scope'] = $Model->alias . '.' . $data['foreignKey'] . ' = ' . $parent->alias . '.' . $parent->primaryKey;
  63. $settings['recursive'] = 0;
  64. }
  65. $this->settings[$Model->alias] = $settings;
  66. }
  67. /**
  68. * After save method. Called after all saves
  69. *
  70. * Overriden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  71. * parameters to be saved.
  72. *
  73. * @param AppModel $Model Model instance.
  74. * @param boolean $created indicates whether the node just saved was created or updated
  75. * @return boolean true on success, false on failure
  76. */
  77. public function afterSave($Model, $created) {
  78. extract($this->settings[$Model->alias]);
  79. if ($created) {
  80. if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) {
  81. return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created);
  82. }
  83. } elseif ($__parentChange) {
  84. $this->settings[$Model->alias]['__parentChange'] = false;
  85. return $this->_setParent($Model, $Model->data[$Model->alias][$parent]);
  86. }
  87. }
  88. /**
  89. * Before delete method. Called before all deletes
  90. *
  91. * Will delete the current node and all children using the deleteAll method and sync the table
  92. *
  93. * @param AppModel $Model Model instance
  94. * @return boolean true to continue, false to abort the delete
  95. */
  96. public function beforeDelete($Model, $cascade = true) {
  97. extract($this->settings[$Model->alias]);
  98. list($name, $data) = array($Model->alias, $Model->read());
  99. $data = $data[$name];
  100. if (!$data[$right] || !$data[$left]) {
  101. return true;
  102. }
  103. $diff = $data[$right] - $data[$left] + 1;
  104. if ($diff > 2) {
  105. if (is_string($scope)) {
  106. $scope = array($scope);
  107. }
  108. $scope[]["{$Model->alias}.{$left} BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1);
  109. $Model->deleteAll($scope);
  110. }
  111. $this->__sync($Model, $diff, '-', '> ' . $data[$right]);
  112. return true;
  113. }
  114. /**
  115. * Before save method. Called before all saves
  116. *
  117. * Overriden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  118. * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
  119. * this method bypassing the setParent logic.
  120. *
  121. * @since 1.2
  122. * @param AppModel $Model Model instance
  123. * @return boolean true to continue, false to abort the save
  124. */
  125. public function beforeSave($Model) {
  126. extract($this->settings[$Model->alias]);
  127. $this->_addToWhitelist($Model, array($left, $right));
  128. if (!$Model->id) {
  129. if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) {
  130. $parentNode = $Model->find('first', array(
  131. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  132. 'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive
  133. ));
  134. if (!$parentNode) {
  135. return false;
  136. }
  137. list($parentNode) = array_values($parentNode);
  138. $Model->data[$Model->alias][$left] = 0; //$parentNode[$right];
  139. $Model->data[$Model->alias][$right] = 0; //$parentNode[$right] + 1;
  140. } else {
  141. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  142. $Model->data[$Model->alias][$left] = $edge + 1;
  143. $Model->data[$Model->alias][$right] = $edge + 2;
  144. }
  145. } elseif (array_key_exists($parent, $Model->data[$Model->alias])) {
  146. if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) {
  147. $this->settings[$Model->alias]['__parentChange'] = true;
  148. }
  149. if (!$Model->data[$Model->alias][$parent]) {
  150. $Model->data[$Model->alias][$parent] = null;
  151. $this->_addToWhitelist($Model, $parent);
  152. } else {
  153. $values = $Model->find('first', array(
  154. 'conditions' => array($scope,$Model->escapeField() => $Model->id),
  155. 'fields' => array($Model->primaryKey, $parent, $left, $right ), 'recursive' => $recursive)
  156. );
  157. if ($values === false) {
  158. return false;
  159. }
  160. list($node) = array_values($values);
  161. $parentNode = $Model->find('first', array(
  162. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  163. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  164. ));
  165. if (!$parentNode) {
  166. return false;
  167. }
  168. list($parentNode) = array_values($parentNode);
  169. if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  170. return false;
  171. } elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) {
  172. return false;
  173. }
  174. }
  175. }
  176. return true;
  177. }
  178. /**
  179. * Get the number of child nodes
  180. *
  181. * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
  182. * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
  183. *
  184. * @param AppModel $Model Model instance
  185. * @param mixed $id The ID of the record to read or false to read all top level nodes
  186. * @param boolean $direct whether to count direct, or all, children
  187. * @return integer number of child nodes
  188. * @link http://book.cakephp.org/view/1347/Counting-children
  189. */
  190. public function childCount($Model, $id = null, $direct = false) {
  191. if (is_array($id)) {
  192. extract (array_merge(array('id' => null), $id));
  193. }
  194. if ($id === null && $Model->id) {
  195. $id = $Model->id;
  196. } elseif (!$id) {
  197. $id = null;
  198. }
  199. extract($this->settings[$Model->alias]);
  200. if ($direct) {
  201. return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id)));
  202. }
  203. if ($id === null) {
  204. return $Model->find('count', array('conditions' => $scope));
  205. } elseif (isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) {
  206. $data = $Model->data[$Model->alias];
  207. } else {
  208. $data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive));
  209. if (!$data) {
  210. return 0;
  211. }
  212. $data = $data[$Model->alias];
  213. }
  214. return ($data[$right] - $data[$left] - 1) / 2;
  215. }
  216. /**
  217. * Get the child nodes of the current model
  218. *
  219. * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
  220. * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
  221. *
  222. * @param AppModel $Model Model instance
  223. * @param mixed $id The ID of the record to read
  224. * @param boolean $direct whether to return only the direct, or all, children
  225. * @param mixed $fields Either a single string of a field name, or an array of field names
  226. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
  227. * @param integer $limit SQL LIMIT clause, for calculating items per page.
  228. * @param integer $page Page number, for accessing paged data
  229. * @param integer $recursive The number of levels deep to fetch associated records
  230. * @return array Array of child nodes
  231. * @link http://book.cakephp.org/view/1346/Children
  232. */
  233. public function children($Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
  234. if (is_array($id)) {
  235. extract (array_merge(array('id' => null), $id));
  236. }
  237. $overrideRecursive = $recursive;
  238. if ($id === null && $Model->id) {
  239. $id = $Model->id;
  240. } elseif (!$id) {
  241. $id = null;
  242. }
  243. $name = $Model->alias;
  244. extract($this->settings[$Model->alias]);
  245. if (!is_null($overrideRecursive)) {
  246. $recursive = $overrideRecursive;
  247. }
  248. if (!$order) {
  249. $order = $Model->alias . '.' . $left . ' asc';
  250. }
  251. if ($direct) {
  252. $conditions = array($scope, $Model->escapeField($parent) => $id);
  253. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  254. }
  255. if (!$id) {
  256. $conditions = $scope;
  257. } else {
  258. $result = array_values((array)$Model->find('first', array(
  259. 'conditions' => array($scope, $Model->escapeField() => $id),
  260. 'fields' => array($left, $right),
  261. 'recursive' => $recursive
  262. )));
  263. if (empty($result) || !isset($result[0])) {
  264. return array();
  265. }
  266. $conditions = array($scope,
  267. $Model->escapeField($right) . ' <' => $result[0][$right],
  268. $Model->escapeField($left) . ' >' => $result[0][$left]
  269. );
  270. }
  271. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  272. }
  273. /**
  274. * A convenience method for returning a hierarchical array used for HTML select boxes
  275. *
  276. * @param AppModel $Model Model instance
  277. * @param mixed $conditions SQL conditions as a string or as an array('field' =>'value',...)
  278. * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
  279. * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
  280. * @param string $spacer The character or characters which will be repeated
  281. * @param integer $recursive The number of levels deep to fetch associated records
  282. * @return array An associative array of records, where the id is the key, and the display field is the value
  283. * @link http://book.cakephp.org/view/1348/generatetreelist
  284. */
  285. public function generateTreeList($Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) {
  286. $overrideRecursive = $recursive;
  287. extract($this->settings[$Model->alias]);
  288. if (!is_null($overrideRecursive)) {
  289. $recursive = $overrideRecursive;
  290. }
  291. if ($keyPath == null && $valuePath == null && $Model->hasField($Model->displayField)) {
  292. $fields = array($Model->primaryKey, $Model->displayField, $left, $right);
  293. } else {
  294. $fields = null;
  295. }
  296. if ($keyPath == null) {
  297. $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
  298. }
  299. if ($valuePath == null) {
  300. $valuePath = array('{0}{1}', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
  301. } elseif (is_string($valuePath)) {
  302. $valuePath = array('{0}{1}', '{n}.tree_prefix', $valuePath);
  303. } else {
  304. $valuePath[0] = '{' . (count($valuePath) - 1) . '}' . $valuePath[0];
  305. $valuePath[] = '{n}.tree_prefix';
  306. }
  307. $order = $Model->alias . '.' . $left . ' asc';
  308. $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
  309. $stack = array();
  310. foreach ($results as $i => $result) {
  311. while ($stack && ($stack[count($stack) - 1] < $result[$Model->alias][$right])) {
  312. array_pop($stack);
  313. }
  314. $results[$i]['tree_prefix'] = str_repeat($spacer,count($stack));
  315. $stack[] = $result[$Model->alias][$right];
  316. }
  317. if (empty($results)) {
  318. return array();
  319. }
  320. return Set::combine($results, $keyPath, $valuePath);
  321. }
  322. /**
  323. * Get the parent node
  324. *
  325. * reads the parent id and returns this node
  326. *
  327. * @param AppModel $Model Model instance
  328. * @param mixed $id The ID of the record to read
  329. * @param integer $recursive The number of levels deep to fetch associated records
  330. * @return array Array of data for the parent node
  331. * @link http://book.cakephp.org/view/1349/getparentnode
  332. */
  333. public function getParentNode($Model, $id = null, $fields = null, $recursive = null) {
  334. if (is_array($id)) {
  335. extract (array_merge(array('id' => null), $id));
  336. }
  337. $overrideRecursive = $recursive;
  338. if (empty ($id)) {
  339. $id = $Model->id;
  340. }
  341. extract($this->settings[$Model->alias]);
  342. if (!is_null($overrideRecursive)) {
  343. $recursive = $overrideRecursive;
  344. }
  345. $parentId = $Model->find('first', array('conditions' => array($Model->primaryKey => $id), 'fields' => array($parent), 'recursive' => -1));
  346. if ($parentId) {
  347. $parentId = $parentId[$Model->alias][$parent];
  348. $parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive));
  349. return $parent;
  350. }
  351. return false;
  352. }
  353. /**
  354. * Get the path to the given node
  355. *
  356. * @param AppModel $Model Model instance
  357. * @param mixed $id The ID of the record to read
  358. * @param mixed $fields Either a single string of a field name, or an array of field names
  359. * @param integer $recursive The number of levels deep to fetch associated records
  360. * @return array Array of nodes from top most parent to current node
  361. * @link http://book.cakephp.org/view/1350/getpath
  362. */
  363. public function getPath($Model, $id = null, $fields = null, $recursive = null) {
  364. if (is_array($id)) {
  365. extract (array_merge(array('id' => null), $id));
  366. }
  367. $overrideRecursive = $recursive;
  368. if (empty ($id)) {
  369. $id = $Model->id;
  370. }
  371. extract($this->settings[$Model->alias]);
  372. if (!is_null($overrideRecursive)) {
  373. $recursive = $overrideRecursive;
  374. }
  375. $result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive));
  376. if ($result) {
  377. $result = array_values($result);
  378. } else {
  379. return null;
  380. }
  381. $item = $result[0];
  382. $results = $Model->find('all', array(
  383. 'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]),
  384. 'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive
  385. ));
  386. return $results;
  387. }
  388. /**
  389. * Reorder the node without changing the parent.
  390. *
  391. * If the node is the last child, or is a top level node with no subsequent node this method will return false
  392. *
  393. * @param AppModel $Model Model instance
  394. * @param mixed $id The ID of the record to move
  395. * @param int|bool $number how many places to move the node or true to move to last position
  396. * @return boolean true on success, false on failure
  397. * @link http://book.cakephp.org/view/1352/moveDown
  398. */
  399. public function moveDown($Model, $id = null, $number = 1) {
  400. if (is_array($id)) {
  401. extract (array_merge(array('id' => null), $id));
  402. }
  403. if (!$number) {
  404. return false;
  405. }
  406. if (empty ($id)) {
  407. $id = $Model->id;
  408. }
  409. extract($this->settings[$Model->alias]);
  410. list($node) = array_values($Model->find('first', array(
  411. 'conditions' => array($scope, $Model->escapeField() => $id),
  412. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  413. )));
  414. if ($node[$parent]) {
  415. list($parentNode) = array_values($Model->find('first', array(
  416. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  417. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  418. )));
  419. if (($node[$right] + 1) == $parentNode[$right]) {
  420. return false;
  421. }
  422. }
  423. $nextNode = $Model->find('first', array(
  424. 'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)),
  425. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive)
  426. );
  427. if ($nextNode) {
  428. list($nextNode) = array_values($nextNode);
  429. } else {
  430. return false;
  431. }
  432. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  433. $this->__sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  434. $this->__sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]);
  435. $this->__sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge);
  436. if (is_int($number)) {
  437. $number--;
  438. }
  439. if ($number) {
  440. $this->moveDown($Model, $id, $number);
  441. }
  442. return true;
  443. }
  444. /**
  445. * Reorder the node without changing the parent.
  446. *
  447. * If the node is the first child, or is a top level node with no previous node this method will return false
  448. *
  449. * @param AppModel $Model Model instance
  450. * @param mixed $id The ID of the record to move
  451. * @param int|bool $number how many places to move the node, or true to move to first position
  452. * @return boolean true on success, false on failure
  453. * @link http://book.cakephp.org/view/1353/moveUp
  454. */
  455. public function moveUp($Model, $id = null, $number = 1) {
  456. if (is_array($id)) {
  457. extract (array_merge(array('id' => null), $id));
  458. }
  459. if (!$number) {
  460. return false;
  461. }
  462. if (empty ($id)) {
  463. $id = $Model->id;
  464. }
  465. extract($this->settings[$Model->alias]);
  466. list($node) = array_values($Model->find('first', array(
  467. 'conditions' => array($scope, $Model->escapeField() => $id),
  468. 'fields' => array($Model->primaryKey, $left, $right, $parent ), 'recursive' => $recursive
  469. )));
  470. if ($node[$parent]) {
  471. list($parentNode) = array_values($Model->find('first', array(
  472. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  473. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  474. )));
  475. if (($node[$left] - 1) == $parentNode[$left]) {
  476. return false;
  477. }
  478. }
  479. $previousNode = $Model->find('first', array(
  480. 'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)),
  481. 'fields' => array($Model->primaryKey, $left, $right),
  482. 'recursive' => $recursive
  483. ));
  484. if ($previousNode) {
  485. list($previousNode) = array_values($previousNode);
  486. } else {
  487. return false;
  488. }
  489. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  490. $this->__sync($Model, $edge - $previousNode[$left] +1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]);
  491. $this->__sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' .$node[$left] . ' AND ' . $node[$right]);
  492. $this->__sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge);
  493. if (is_int($number)) {
  494. $number--;
  495. }
  496. if ($number) {
  497. $this->moveUp($Model, $id, $number);
  498. }
  499. return true;
  500. }
  501. /**
  502. * Recover a corrupted tree
  503. *
  504. * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data
  505. * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode
  506. * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
  507. * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
  508. *
  509. * @todo Could be written to be faster, *maybe*. Ideally using a subquery and putting all the logic burden on the DB.
  510. * @param AppModel $Model Model instance
  511. * @param string $mode parent or tree
  512. * @param mixed $missingParentAction 'return' to do nothing and return, 'delete' to
  513. * delete, or the id of the parent to set as the parent_id
  514. * @return boolean true on success, false on failure
  515. * @link http://book.cakephp.org/view/1628/Recover
  516. */
  517. public function recover($Model, $mode = 'parent', $missingParentAction = null) {
  518. if (is_array($mode)) {
  519. extract (array_merge(array('mode' => 'parent'), $mode));
  520. }
  521. extract($this->settings[$Model->alias]);
  522. $Model->recursive = $recursive;
  523. if ($mode == 'parent') {
  524. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  525. 'className' => $Model->alias,
  526. 'foreignKey' => $parent,
  527. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  528. ))));
  529. $missingParents = $Model->find('list', array(
  530. 'recursive' => 0,
  531. 'conditions' => array($scope, array(
  532. 'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null
  533. ))
  534. ));
  535. $Model->unbindModel(array('belongsTo' => array('VerifyParent')));
  536. if ($missingParents) {
  537. if ($missingParentAction == 'return') {
  538. foreach ($missingParents as $id => $display) {
  539. $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')';
  540. }
  541. return false;
  542. } elseif ($missingParentAction == 'delete') {
  543. $Model->deleteAll(array($Model->primaryKey => array_flip($missingParents)));
  544. } else {
  545. $Model->updateAll(array($parent => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
  546. }
  547. }
  548. $count = 1;
  549. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey), 'order' => $left)) as $array) {
  550. $Model->id = $array[$Model->alias][$Model->primaryKey];
  551. $lft = $count++;
  552. $rght = $count++;
  553. $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false));
  554. }
  555. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  556. $Model->create();
  557. $Model->id = $array[$Model->alias][$Model->primaryKey];
  558. $this->_setParent($Model, $array[$Model->alias][$parent]);
  559. }
  560. } else {
  561. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  562. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  563. $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]);
  564. if ($path == null || count($path) < 2) {
  565. $parentId = null;
  566. } else {
  567. $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
  568. }
  569. $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
  570. }
  571. }
  572. return true;
  573. }
  574. /**
  575. * Reorder method.
  576. *
  577. * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
  578. * This method does not change the parent of any node.
  579. *
  580. * Requires a valid tree, by default it verifies the tree before beginning.
  581. *
  582. * Options:
  583. *
  584. * - 'id' id of record to use as top node for reordering
  585. * - 'field' Which field to use in reordeing defaults to displayField
  586. * - 'order' Direction to order either DESC or ASC (defaults to ASC)
  587. * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
  588. *
  589. * @param AppModel $Model Model instance
  590. * @param array $options array of options to use in reordering.
  591. * @return boolean true on success, false on failure
  592. * @link http://book.cakephp.org/view/1355/reorder
  593. * @link http://book.cakephp.org/view/1629/Reorder
  594. */
  595. function reorder($Model, $options = array()) {
  596. $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options);
  597. extract($options);
  598. if ($verify && !$this->verify($Model)) {
  599. return false;
  600. }
  601. $verify = false;
  602. extract($this->settings[$Model->alias]);
  603. $fields = array($Model->primaryKey, $field, $left, $right);
  604. $sort = $field . ' ' . $order;
  605. $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
  606. $cacheQueries = $Model->cacheQueries;
  607. $Model->cacheQueries = false;
  608. if ($nodes) {
  609. foreach ($nodes as $node) {
  610. $id = $node[$Model->alias][$Model->primaryKey];
  611. $this->moveDown($Model, $id, true);
  612. if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
  613. $this->reorder($Model, compact('id', 'field', 'order', 'verify'));
  614. }
  615. }
  616. }
  617. $Model->cacheQueries = $cacheQueries;
  618. return true;
  619. }
  620. /**
  621. * Remove the current node from the tree, and reparent all children up one level.
  622. *
  623. * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
  624. * after the children are reparented.
  625. *
  626. * @param AppModel $Model Model instance
  627. * @param mixed $id The ID of the record to remove
  628. * @param boolean $delete whether to delete the node after reparenting children (if any)
  629. * @return boolean true on success, false on failure
  630. * @link http://book.cakephp.org/view/1354/removeFromTree
  631. */
  632. public function removeFromTree($Model, $id = null, $delete = false) {
  633. if (is_array($id)) {
  634. extract (array_merge(array('id' => null), $id));
  635. }
  636. extract($this->settings[$Model->alias]);
  637. list($node) = array_values($Model->find('first', array(
  638. 'conditions' => array($scope, $Model->escapeField() => $id),
  639. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  640. 'recursive' => $recursive
  641. )));
  642. if ($node[$right] == $node[$left] + 1) {
  643. if ($delete) {
  644. return $Model->delete($id);
  645. } else {
  646. $Model->id = $id;
  647. return $Model->saveField($parent, null);
  648. }
  649. } elseif ($node[$parent]) {
  650. list($parentNode) = array_values($Model->find('first', array(
  651. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  652. 'fields' => array($Model->primaryKey, $left, $right),
  653. 'recursive' => $recursive
  654. )));
  655. } else {
  656. $parentNode[$right] = $node[$right] + 1;
  657. }
  658. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  659. $Model->updateAll(
  660. array($parent => $db->value($node[$parent], $parent)),
  661. array($Model->escapeField($parent) => $node[$Model->primaryKey])
  662. );
  663. $this->__sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
  664. $this->__sync($Model, 2, '-', '> ' . ($node[$right]));
  665. $Model->id = $id;
  666. if ($delete) {
  667. $Model->updateAll(
  668. array(
  669. $Model->escapeField($left) => 0,
  670. $Model->escapeField($right) => 0,
  671. $Model->escapeField($parent) => null
  672. ),
  673. array($Model->escapeField() => $id)
  674. );
  675. return $Model->delete($id);
  676. } else {
  677. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  678. if ($node[$right] == $edge) {
  679. $edge = $edge - 2;
  680. }
  681. $Model->id = $id;
  682. return $Model->save(
  683. array($left => $edge + 1, $right => $edge + 2, $parent => null),
  684. array('callbacks' => false)
  685. );
  686. }
  687. }
  688. /**
  689. * Check if the current tree is valid.
  690. *
  691. * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
  692. *
  693. * @param AppModel $Model Model instance
  694. * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
  695. * [incorrect left/right index,node id], message)
  696. * @link http://book.cakephp.org/view/1630/Verify
  697. */
  698. public function verify($Model) {
  699. extract($this->settings[$Model->alias]);
  700. if (!$Model->find('count', array('conditions' => $scope))) {
  701. return true;
  702. }
  703. $min = $this->__getMin($Model, $scope, $left, $recursive);
  704. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  705. $errors = array();
  706. for ($i = $min; $i <= $edge; $i++) {
  707. $count = $Model->find('count', array('conditions' => array(
  708. $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
  709. )));
  710. if ($count != 1) {
  711. if ($count == 0) {
  712. $errors[] = array('index', $i, 'missing');
  713. } else {
  714. $errors[] = array('index', $i, 'duplicate');
  715. }
  716. }
  717. }
  718. $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0));
  719. if ($node) {
  720. $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
  721. }
  722. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  723. 'className' => $Model->alias,
  724. 'foreignKey' => $parent,
  725. 'fields' => array($Model->primaryKey, $left, $right, $parent)
  726. ))));
  727. foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) {
  728. if (is_null($instance[$Model->alias][$left]) || is_null($instance[$Model->alias][$right])) {
  729. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  730. 'has invalid left or right values');
  731. } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
  732. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  733. 'left and right values identical');
  734. } elseif ($instance[$Model->alias][$parent]) {
  735. if (!$instance['VerifyParent'][$Model->primaryKey]) {
  736. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  737. 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
  738. } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
  739. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  740. 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  741. } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
  742. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  743. 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  744. }
  745. } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
  746. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
  747. }
  748. }
  749. if ($errors) {
  750. return $errors;
  751. }
  752. return true;
  753. }
  754. /**
  755. * Sets the parent of the given node
  756. *
  757. * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
  758. * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
  759. * method could be private, since calling save with parent_id set also calls setParent
  760. *
  761. * @param AppModel $Model Model instance
  762. * @param mixed $parentId
  763. * @return boolean true on success, false on failure
  764. */
  765. protected function _setParent($Model, $parentId = null, $created = false) {
  766. extract($this->settings[$Model->alias]);
  767. list($node) = array_values($Model->find('first', array(
  768. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  769. 'fields' => array($Model->primaryKey, $parent, $left, $right),
  770. 'recursive' => $recursive
  771. )));
  772. $edge = $this->__getMax($Model, $scope, $right, $recursive, $created);
  773. if (empty ($parentId)) {
  774. $this->__sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  775. $this->__sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
  776. } else {
  777. $values = $Model->find('first', array(
  778. 'conditions' => array($scope, $Model->escapeField() => $parentId),
  779. 'fields' => array($Model->primaryKey, $left, $right),
  780. 'recursive' => $recursive
  781. ));
  782. if ($values === false) {
  783. return false;
  784. }
  785. $parentNode = array_values($values);
  786. if (empty($parentNode) || empty($parentNode[0])) {
  787. return false;
  788. }
  789. $parentNode = $parentNode[0];
  790. if (($Model->id == $parentId)) {
  791. return false;
  792. } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  793. return false;
  794. }
  795. if (empty ($node[$left]) && empty ($node[$right])) {
  796. $this->__sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
  797. $result = $Model->save(
  798. array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
  799. array('validate' => false, 'callbacks' => false)
  800. );
  801. $Model->data = $result;
  802. } else {
  803. $this->__sync($Model, $edge - $node[$left] +1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  804. $diff = $node[$right] - $node[$left] + 1;
  805. if ($node[$left] > $parentNode[$left]) {
  806. if ($node[$right] < $parentNode[$right]) {
  807. $this->__sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  808. $this->__sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  809. } else {
  810. $this->__sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
  811. $this->__sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
  812. }
  813. } else {
  814. $this->__sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  815. $this->__sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  816. }
  817. }
  818. }
  819. return true;
  820. }
  821. /**
  822. * get the maximum index value in the table.
  823. *
  824. * @param AppModel $Model
  825. * @param string $scope
  826. * @param string $right
  827. * @return int
  828. * @access private
  829. */
  830. function __getMax($Model, $scope, $right, $recursive = -1, $created = false) {
  831. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  832. if ($created) {
  833. if (is_string($scope)) {
  834. $scope .= " AND {$Model->alias}.{$Model->primaryKey} <> ";
  835. $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
  836. } else {
  837. $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  838. }
  839. }
  840. $name = $Model->alias . '.' . $right;
  841. list($edge) = array_values($Model->find('first', array(
  842. 'conditions' => $scope,
  843. 'fields' => $db->calculate($Model, 'max', array($name, $right)),
  844. 'recursive' => $recursive
  845. )));
  846. return (empty($edge[$right])) ? 0 : $edge[$right];
  847. }
  848. /**
  849. * get the minimum index value in the table.
  850. *
  851. * @param AppModel $Model
  852. * @param string $scope
  853. * @param string $right
  854. * @return int
  855. * @access private
  856. */
  857. function __getMin($Model, $scope, $left, $recursive = -1) {
  858. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  859. $name = $Model->alias . '.' . $left;
  860. list($edge) = array_values($Model->find('first', array(
  861. 'conditions' => $scope,
  862. 'fields' => $db->calculate($Model, 'min', array($name, $left)),
  863. 'recursive' => $recursive
  864. )));
  865. return (empty($edge[$left])) ? 0 : $edge[$left];
  866. }
  867. /**
  868. * Table sync method.
  869. *
  870. * Handles table sync operations, Taking account of the behavior scope.
  871. *
  872. * @param AppModel $Model
  873. * @param integer $shift
  874. * @param string $direction
  875. * @param array $conditions
  876. * @param string $field
  877. * @access private
  878. */
  879. function __sync($Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
  880. $ModelRecursive = $Model->recursive;
  881. extract($this->settings[$Model->alias]);
  882. $Model->recursive = $recursive;
  883. if ($field == 'both') {
  884. $this->__sync($Model, $shift, $dir, $conditions, $created, $left);
  885. $field = $right;
  886. }
  887. if (is_string($conditions)) {
  888. $conditions = array("{$Model->alias}.{$field} {$conditions}");
  889. }
  890. if (($scope != '1 = 1' && $scope !== true) && $scope) {
  891. $conditions[] = $scope;
  892. }
  893. if ($created) {
  894. $conditions['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  895. }
  896. $Model->updateAll(array($Model->alias . '.' . $field => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
  897. $Model->recursive = $ModelRecursive;
  898. }
  899. }