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. App::uses('ModelBehavior', 'Model/Behavior');
  22. /**
  23. * Tree Behavior.
  24. *
  25. * Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
  26. *
  27. * @see http://en.wikipedia.org/wiki/Tree_traversal
  28. * @package Cake.Model.Behavior
  29. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
  30. */
  31. class TreeBehavior extends ModelBehavior {
  32. /**
  33. * Errors
  34. *
  35. * @var array
  36. */
  37. public $errors = array();
  38. /**
  39. * Defaults
  40. *
  41. * @var array
  42. */
  43. protected $_defaults = array(
  44. 'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght',
  45. 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1
  46. );
  47. /**
  48. * Used to preserve state between delete callbacks.
  49. *
  50. * @var array
  51. */
  52. protected $_deletedRow = null;
  53. /**
  54. * Initiate Tree behavior
  55. *
  56. * @param Model $Model instance of model
  57. * @param array $config array of configuration settings.
  58. * @return void
  59. */
  60. public function setup(Model $Model, $config = array()) {
  61. if (isset($config[0])) {
  62. $config['type'] = $config[0];
  63. unset($config[0]);
  64. }
  65. $settings = array_merge($this->_defaults, $config);
  66. if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
  67. $data = $Model->getAssociated($settings['scope']);
  68. $parent = $Model->{$settings['scope']};
  69. $settings['scope'] = $Model->alias . '.' . $data['foreignKey'] . ' = ' . $parent->alias . '.' . $parent->primaryKey;
  70. $settings['recursive'] = 0;
  71. }
  72. $this->settings[$Model->alias] = $settings;
  73. }
  74. /**
  75. * After save method. Called after all saves
  76. *
  77. * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  78. * parameters to be saved.
  79. *
  80. * @param Model $Model Model instance.
  81. * @param boolean $created indicates whether the node just saved was created or updated
  82. * @return boolean true on success, false on failure
  83. */
  84. public function afterSave(Model $Model, $created) {
  85. extract($this->settings[$Model->alias]);
  86. if ($created) {
  87. if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) {
  88. return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created);
  89. }
  90. } elseif ($this->settings[$Model->alias]['__parentChange']) {
  91. $this->settings[$Model->alias]['__parentChange'] = false;
  92. return $this->_setParent($Model, $Model->data[$Model->alias][$parent]);
  93. }
  94. }
  95. /**
  96. * Runs before a find() operation
  97. *
  98. * @param Model $Model Model using the behavior
  99. * @param array $query Query parameters as set by cake
  100. * @return array
  101. */
  102. public function beforeFind(Model $Model, $query) {
  103. if ($Model->findQueryType == 'threaded' && !isset($query['parent'])) {
  104. $query['parent'] = $this->settings[$Model->alias]['parent'];
  105. }
  106. return $query;
  107. }
  108. /**
  109. * Stores the record about to be deleted.
  110. *
  111. * This is used to delete child nodes in the afterDelete.
  112. *
  113. * @param Model $Model Model instance
  114. * @param boolean $cascade
  115. * @return boolean
  116. */
  117. public function beforeDelete(Model $Model, $cascade = true) {
  118. extract($this->settings[$Model->alias]);
  119. $data = $Model->find('first', array(
  120. 'conditions' => array($Model->alias . '.' . $Model->primaryKey => $Model->id),
  121. 'fields' => array($Model->alias . '.' . $left, $Model->alias . '.' . $right),
  122. 'recursive' => -1));
  123. if ($data) {
  124. $this->_deletedRow = current($data);
  125. }
  126. return true;
  127. }
  128. /**
  129. * After delete method.
  130. *
  131. * Will delete the current node and all children using the deleteAll method and sync the table
  132. *
  133. * @param Model $Model Model instance
  134. * @return boolean true to continue, false to abort the delete
  135. */
  136. public function afterDelete(Model $Model) {
  137. extract($this->settings[$Model->alias]);
  138. $data = $this->_deletedRow;
  139. $this->_deletedRow = null;
  140. if (!$data[$right] || !$data[$left]) {
  141. return true;
  142. }
  143. $diff = $data[$right] - $data[$left] + 1;
  144. if ($diff > 2) {
  145. if (is_string($scope)) {
  146. $scope = array($scope);
  147. }
  148. $scope[]["{$Model->alias}.{$left} BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1);
  149. $Model->deleteAll($scope);
  150. }
  151. $this->_sync($Model, $diff, '-', '> ' . $data[$right]);
  152. return true;
  153. }
  154. /**
  155. * Before save method. Called before all saves
  156. *
  157. * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  158. * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
  159. * this method bypassing the setParent logic.
  160. *
  161. * @since 1.2
  162. * @param Model $Model Model instance
  163. * @return boolean true to continue, false to abort the save
  164. */
  165. public function beforeSave(Model $Model) {
  166. extract($this->settings[$Model->alias]);
  167. $this->_addToWhitelist($Model, array($left, $right));
  168. if (!$Model->id) {
  169. if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) {
  170. $parentNode = $Model->find('first', array(
  171. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  172. 'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive
  173. ));
  174. if (!$parentNode) {
  175. return false;
  176. }
  177. list($parentNode) = array_values($parentNode);
  178. $Model->data[$Model->alias][$left] = 0;
  179. $Model->data[$Model->alias][$right] = 0;
  180. } else {
  181. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  182. $Model->data[$Model->alias][$left] = $edge + 1;
  183. $Model->data[$Model->alias][$right] = $edge + 2;
  184. }
  185. } elseif (array_key_exists($parent, $Model->data[$Model->alias])) {
  186. if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) {
  187. $this->settings[$Model->alias]['__parentChange'] = true;
  188. }
  189. if (!$Model->data[$Model->alias][$parent]) {
  190. $Model->data[$Model->alias][$parent] = null;
  191. $this->_addToWhitelist($Model, $parent);
  192. } else {
  193. $values = $Model->find('first', array(
  194. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  195. 'fields' => array($Model->primaryKey, $parent, $left, $right), 'recursive' => $recursive)
  196. );
  197. if ($values === false) {
  198. return false;
  199. }
  200. list($node) = array_values($values);
  201. $parentNode = $Model->find('first', array(
  202. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  203. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  204. ));
  205. if (!$parentNode) {
  206. return false;
  207. }
  208. list($parentNode) = array_values($parentNode);
  209. if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  210. return false;
  211. } elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) {
  212. return false;
  213. }
  214. }
  215. }
  216. return true;
  217. }
  218. /**
  219. * Get the number of child nodes
  220. *
  221. * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
  222. * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
  223. *
  224. * @param Model $Model Model instance
  225. * @param integer|string|boolean $id The ID of the record to read or false to read all top level nodes
  226. * @param boolean $direct whether to count direct, or all, children
  227. * @return integer number of child nodes
  228. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCount
  229. */
  230. public function childCount(Model $Model, $id = null, $direct = false) {
  231. if (is_array($id)) {
  232. extract(array_merge(array('id' => null), $id));
  233. }
  234. if ($id === null && $Model->id) {
  235. $id = $Model->id;
  236. } elseif (!$id) {
  237. $id = null;
  238. }
  239. extract($this->settings[$Model->alias]);
  240. if ($direct) {
  241. return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id)));
  242. }
  243. if ($id === null) {
  244. return $Model->find('count', array('conditions' => $scope));
  245. } elseif ($Model->id === $id && isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) {
  246. $data = $Model->data[$Model->alias];
  247. } else {
  248. $data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive));
  249. if (!$data) {
  250. return 0;
  251. }
  252. $data = $data[$Model->alias];
  253. }
  254. return ($data[$right] - $data[$left] - 1) / 2;
  255. }
  256. /**
  257. * Get the child nodes of the current model
  258. *
  259. * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
  260. * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
  261. *
  262. * @param Model $Model Model instance
  263. * @param integer|string $id The ID of the record to read
  264. * @param boolean $direct whether to return only the direct, or all, children
  265. * @param string|array $fields Either a single string of a field name, or an array of field names
  266. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
  267. * @param integer $limit SQL LIMIT clause, for calculating items per page.
  268. * @param integer $page Page number, for accessing paged data
  269. * @param integer $recursive The number of levels deep to fetch associated records
  270. * @return array Array of child nodes
  271. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::children
  272. */
  273. public function children(Model $Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
  274. if (is_array($id)) {
  275. extract(array_merge(array('id' => null), $id));
  276. }
  277. $overrideRecursive = $recursive;
  278. if ($id === null && $Model->id) {
  279. $id = $Model->id;
  280. } elseif (!$id) {
  281. $id = null;
  282. }
  283. extract($this->settings[$Model->alias]);
  284. if (!is_null($overrideRecursive)) {
  285. $recursive = $overrideRecursive;
  286. }
  287. if (!$order) {
  288. $order = $Model->alias . '.' . $left . ' asc';
  289. }
  290. if ($direct) {
  291. $conditions = array($scope, $Model->escapeField($parent) => $id);
  292. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  293. }
  294. if (!$id) {
  295. $conditions = $scope;
  296. } else {
  297. $result = array_values((array)$Model->find('first', array(
  298. 'conditions' => array($scope, $Model->escapeField() => $id),
  299. 'fields' => array($left, $right),
  300. 'recursive' => $recursive
  301. )));
  302. if (empty($result) || !isset($result[0])) {
  303. return array();
  304. }
  305. $conditions = array($scope,
  306. $Model->escapeField($right) . ' <' => $result[0][$right],
  307. $Model->escapeField($left) . ' >' => $result[0][$left]
  308. );
  309. }
  310. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  311. }
  312. /**
  313. * A convenience method for returning a hierarchical array used for HTML select boxes
  314. *
  315. * @param Model $Model Model instance
  316. * @param string|array $conditions SQL conditions as a string or as an array('field' =>'value',...)
  317. * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
  318. * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
  319. * @param string $spacer The character or characters which will be repeated
  320. * @param integer $recursive The number of levels deep to fetch associated records
  321. * @return array An associative array of records, where the id is the key, and the display field is the value
  322. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList
  323. */
  324. public function generateTreeList(Model $Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) {
  325. $overrideRecursive = $recursive;
  326. extract($this->settings[$Model->alias]);
  327. if (!is_null($overrideRecursive)) {
  328. $recursive = $overrideRecursive;
  329. }
  330. if ($keyPath == null && $valuePath == null && $Model->hasField($Model->displayField)) {
  331. $fields = array($Model->primaryKey, $Model->displayField, $left, $right);
  332. } else {
  333. $fields = null;
  334. }
  335. if ($keyPath == null) {
  336. $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
  337. }
  338. if ($valuePath == null) {
  339. $valuePath = array('%s%s', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
  340. } elseif (is_string($valuePath)) {
  341. $valuePath = array('%s%s', '{n}.tree_prefix', $valuePath);
  342. } else {
  343. array_unshift($valuePath, '%s' . $valuePath[0], '{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. }