TreeBehavior.php 36 KB

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