TreeBehavior.php 37 KB

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