TreeBehavior.php 36 KB

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