TreeBehavior.php 35 KB

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