TreeBehavior.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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');
  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 = array();
  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->escapeField($data['foreignKey']) . ' = ' . $Parent->escapeField();
  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->escapeField($Model->primaryKey) => $Model->id),
  121. 'fields' => array($Model->escapeField($left), $Model->escapeField($right)),
  122. 'recursive' => -1));
  123. if ($data) {
  124. $this->_deletedRow[$Model->alias] = 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[$Model->alias];
  139. $this->_deletedRow[$Model->alias] = 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->escapeField($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 || !$Model->exists()) {
  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->escapeField($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. $fields = null;
  331. if (!$keyPath && !$valuePath && $Model->hasField($Model->displayField)) {
  332. $fields = array($Model->primaryKey, $Model->displayField, $left, $right);
  333. }
  334. if (!$keyPath) {
  335. $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
  336. }
  337. if (!$valuePath) {
  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. array_unshift($valuePath, '%s' . $valuePath[0], '{n}.tree_prefix');
  343. }
  344. $order = $Model->escapeField($left) . " asc";
  345. $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
  346. $stack = array();
  347. foreach ($results as $i => $result) {
  348. $count = count($stack);
  349. while ($stack && ($stack[$count - 1] < $result[$Model->alias][$right])) {
  350. array_pop($stack);
  351. $count--;
  352. }
  353. $results[$i]['tree_prefix'] = str_repeat($spacer, $count);
  354. $stack[] = $result[$Model->alias][$right];
  355. }
  356. if (empty($results)) {
  357. return array();
  358. }
  359. return Hash::combine($results, $keyPath, $valuePath);
  360. }
  361. /**
  362. * Get the parent node
  363. *
  364. * reads the parent id and returns this node
  365. *
  366. * @param Model $Model Model instance
  367. * @param integer|string $id The ID of the record to read
  368. * @param string|array $fields
  369. * @param integer $recursive The number of levels deep to fetch associated records
  370. * @return array|boolean Array of data for the parent node
  371. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode
  372. */
  373. public function getParentNode(Model $Model, $id = null, $fields = null, $recursive = null) {
  374. if (is_array($id)) {
  375. extract(array_merge(array('id' => null), $id));
  376. }
  377. $overrideRecursive = $recursive;
  378. if (empty ($id)) {
  379. $id = $Model->id;
  380. }
  381. extract($this->settings[$Model->alias]);
  382. if (!is_null($overrideRecursive)) {
  383. $recursive = $overrideRecursive;
  384. }
  385. $parentId = $Model->find('first', array('conditions' => array($Model->primaryKey => $id), 'fields' => array($parent), 'recursive' => -1));
  386. if ($parentId) {
  387. $parentId = $parentId[$Model->alias][$parent];
  388. $parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive));
  389. return $parent;
  390. }
  391. return false;
  392. }
  393. /**
  394. * Get the path to the given node
  395. *
  396. * @param Model $Model Model instance
  397. * @param integer|string $id The ID of the record to read
  398. * @param string|array $fields Either a single string of a field name, or an array of field names
  399. * @param integer $recursive The number of levels deep to fetch associated records
  400. * @return array Array of nodes from top most parent to current node
  401. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPath
  402. */
  403. public function getPath(Model $Model, $id = null, $fields = null, $recursive = null) {
  404. if (is_array($id)) {
  405. extract(array_merge(array('id' => null), $id));
  406. }
  407. $overrideRecursive = $recursive;
  408. if (empty ($id)) {
  409. $id = $Model->id;
  410. }
  411. extract($this->settings[$Model->alias]);
  412. if (!is_null($overrideRecursive)) {
  413. $recursive = $overrideRecursive;
  414. }
  415. $result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive));
  416. if ($result) {
  417. $result = array_values($result);
  418. } else {
  419. return null;
  420. }
  421. $item = $result[0];
  422. $results = $Model->find('all', array(
  423. 'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]),
  424. 'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive
  425. ));
  426. return $results;
  427. }
  428. /**
  429. * Reorder the node without changing the parent.
  430. *
  431. * If the node is the last child, or is a top level node with no subsequent node this method will return false
  432. *
  433. * @param Model $Model Model instance
  434. * @param integer|string $id The ID of the record to move
  435. * @param integer|boolean $number how many places to move the node or true to move to last position
  436. * @return boolean true on success, false on failure
  437. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDown
  438. */
  439. public function moveDown(Model $Model, $id = null, $number = 1) {
  440. if (is_array($id)) {
  441. extract(array_merge(array('id' => null), $id));
  442. }
  443. if (!$number) {
  444. return false;
  445. }
  446. if (empty ($id)) {
  447. $id = $Model->id;
  448. }
  449. extract($this->settings[$Model->alias]);
  450. list($node) = array_values($Model->find('first', array(
  451. 'conditions' => array($scope, $Model->escapeField() => $id),
  452. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  453. )));
  454. if ($node[$parent]) {
  455. list($parentNode) = array_values($Model->find('first', array(
  456. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  457. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  458. )));
  459. if (($node[$right] + 1) == $parentNode[$right]) {
  460. return false;
  461. }
  462. }
  463. $nextNode = $Model->find('first', array(
  464. 'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)),
  465. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive)
  466. );
  467. if ($nextNode) {
  468. list($nextNode) = array_values($nextNode);
  469. } else {
  470. return false;
  471. }
  472. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  473. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  474. $this->_sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]);
  475. $this->_sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge);
  476. if (is_int($number)) {
  477. $number--;
  478. }
  479. if ($number) {
  480. $this->moveDown($Model, $id, $number);
  481. }
  482. return true;
  483. }
  484. /**
  485. * Reorder the node without changing the parent.
  486. *
  487. * If the node is the first child, or is a top level node with no previous node this method will return false
  488. *
  489. * @param Model $Model Model instance
  490. * @param integer|string $id The ID of the record to move
  491. * @param integer|boolean $number how many places to move the node, or true to move to first position
  492. * @return boolean true on success, false on failure
  493. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUp
  494. */
  495. public function moveUp(Model $Model, $id = null, $number = 1) {
  496. if (is_array($id)) {
  497. extract(array_merge(array('id' => null), $id));
  498. }
  499. if (!$number) {
  500. return false;
  501. }
  502. if (empty ($id)) {
  503. $id = $Model->id;
  504. }
  505. extract($this->settings[$Model->alias]);
  506. list($node) = array_values($Model->find('first', array(
  507. 'conditions' => array($scope, $Model->escapeField() => $id),
  508. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  509. )));
  510. if ($node[$parent]) {
  511. list($parentNode) = array_values($Model->find('first', array(
  512. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  513. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  514. )));
  515. if (($node[$left] - 1) == $parentNode[$left]) {
  516. return false;
  517. }
  518. }
  519. $previousNode = $Model->find('first', array(
  520. 'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)),
  521. 'fields' => array($Model->primaryKey, $left, $right),
  522. 'recursive' => $recursive
  523. ));
  524. if ($previousNode) {
  525. list($previousNode) = array_values($previousNode);
  526. } else {
  527. return false;
  528. }
  529. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  530. $this->_sync($Model, $edge - $previousNode[$left] + 1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]);
  531. $this->_sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  532. $this->_sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge);
  533. if (is_int($number)) {
  534. $number--;
  535. }
  536. if ($number) {
  537. $this->moveUp($Model, $id, $number);
  538. }
  539. return true;
  540. }
  541. /**
  542. * Recover a corrupted tree
  543. *
  544. * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data
  545. * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode
  546. * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
  547. * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
  548. *
  549. * @param Model $Model Model instance
  550. * @param string $mode parent or tree
  551. * @param string|integer $missingParentAction 'return' to do nothing and return, 'delete' to
  552. * delete, or the id of the parent to set as the parent_id
  553. * @return boolean true on success, false on failure
  554. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recover
  555. */
  556. public function recover(Model $Model, $mode = 'parent', $missingParentAction = null) {
  557. if (is_array($mode)) {
  558. extract(array_merge(array('mode' => 'parent'), $mode));
  559. }
  560. extract($this->settings[$Model->alias]);
  561. $Model->recursive = $recursive;
  562. if ($mode === 'parent') {
  563. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  564. 'className' => $Model->name,
  565. 'foreignKey' => $parent,
  566. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  567. ))));
  568. $missingParents = $Model->find('list', array(
  569. 'recursive' => 0,
  570. 'conditions' => array($scope, array(
  571. 'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null
  572. ))
  573. ));
  574. $Model->unbindModel(array('belongsTo' => array('VerifyParent')));
  575. if ($missingParents) {
  576. if ($missingParentAction === 'return') {
  577. foreach ($missingParents as $id => $display) {
  578. $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')';
  579. }
  580. return false;
  581. } elseif ($missingParentAction === 'delete') {
  582. $Model->deleteAll(array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)), false);
  583. } else {
  584. $Model->updateAll(array($Model->escapeField($parent) => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
  585. }
  586. }
  587. $count = 1;
  588. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey), 'order' => $left)) as $array) {
  589. $lft = $count++;
  590. $rght = $count++;
  591. $Model->create(false);
  592. $Model->id = $array[$Model->alias][$Model->primaryKey];
  593. $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false, 'validate' => false));
  594. }
  595. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  596. $Model->create(false);
  597. $Model->id = $array[$Model->alias][$Model->primaryKey];
  598. $this->_setParent($Model, $array[$Model->alias][$parent]);
  599. }
  600. } else {
  601. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  602. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  603. $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]);
  604. $parentId = null;
  605. if (count($path) > 1) {
  606. $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
  607. }
  608. $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
  609. }
  610. }
  611. return true;
  612. }
  613. /**
  614. * Reorder method.
  615. *
  616. * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
  617. * This method does not change the parent of any node.
  618. *
  619. * Requires a valid tree, by default it verifies the tree before beginning.
  620. *
  621. * Options:
  622. *
  623. * - 'id' id of record to use as top node for reordering
  624. * - 'field' Which field to use in reordering defaults to displayField
  625. * - 'order' Direction to order either DESC or ASC (defaults to ASC)
  626. * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
  627. *
  628. * @param Model $Model Model instance
  629. * @param array $options array of options to use in reordering.
  630. * @return boolean true on success, false on failure
  631. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder
  632. */
  633. public function reorder(Model $Model, $options = array()) {
  634. $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options);
  635. extract($options);
  636. if ($verify && !$this->verify($Model)) {
  637. return false;
  638. }
  639. $verify = false;
  640. extract($this->settings[$Model->alias]);
  641. $fields = array($Model->primaryKey, $field, $left, $right);
  642. $sort = $field . ' ' . $order;
  643. $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
  644. $cacheQueries = $Model->cacheQueries;
  645. $Model->cacheQueries = false;
  646. if ($nodes) {
  647. foreach ($nodes as $node) {
  648. $id = $node[$Model->alias][$Model->primaryKey];
  649. $this->moveDown($Model, $id, true);
  650. if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
  651. $this->reorder($Model, compact('id', 'field', 'order', 'verify'));
  652. }
  653. }
  654. }
  655. $Model->cacheQueries = $cacheQueries;
  656. return true;
  657. }
  658. /**
  659. * Remove the current node from the tree, and reparent all children up one level.
  660. *
  661. * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
  662. * after the children are reparented.
  663. *
  664. * @param Model $Model Model instance
  665. * @param integer|string $id The ID of the record to remove
  666. * @param boolean $delete whether to delete the node after reparenting children (if any)
  667. * @return boolean true on success, false on failure
  668. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree
  669. */
  670. public function removeFromTree(Model $Model, $id = null, $delete = false) {
  671. if (is_array($id)) {
  672. extract(array_merge(array('id' => null), $id));
  673. }
  674. extract($this->settings[$Model->alias]);
  675. list($node) = array_values($Model->find('first', array(
  676. 'conditions' => array($scope, $Model->escapeField() => $id),
  677. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  678. 'recursive' => $recursive
  679. )));
  680. if ($node[$right] == $node[$left] + 1) {
  681. if ($delete) {
  682. return $Model->delete($id);
  683. } else {
  684. $Model->id = $id;
  685. return $Model->saveField($parent, null);
  686. }
  687. } elseif ($node[$parent]) {
  688. list($parentNode) = array_values($Model->find('first', array(
  689. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  690. 'fields' => array($Model->primaryKey, $left, $right),
  691. 'recursive' => $recursive
  692. )));
  693. } else {
  694. $parentNode[$right] = $node[$right] + 1;
  695. }
  696. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  697. $Model->updateAll(
  698. array($parent => $db->value($node[$parent], $parent)),
  699. array($Model->escapeField($parent) => $node[$Model->primaryKey])
  700. );
  701. $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
  702. $this->_sync($Model, 2, '-', '> ' . ($node[$right]));
  703. $Model->id = $id;
  704. if ($delete) {
  705. $Model->updateAll(
  706. array(
  707. $Model->escapeField($left) => 0,
  708. $Model->escapeField($right) => 0,
  709. $Model->escapeField($parent) => null
  710. ),
  711. array($Model->escapeField() => $id)
  712. );
  713. return $Model->delete($id);
  714. } else {
  715. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  716. if ($node[$right] == $edge) {
  717. $edge = $edge - 2;
  718. }
  719. $Model->id = $id;
  720. return $Model->save(
  721. array($left => $edge + 1, $right => $edge + 2, $parent => null),
  722. array('callbacks' => false, 'validate' => false)
  723. );
  724. }
  725. }
  726. /**
  727. * Check if the current tree is valid.
  728. *
  729. * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
  730. *
  731. * @param Model $Model Model instance
  732. * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
  733. * [incorrect left/right index,node id], message)
  734. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify
  735. */
  736. public function verify(Model $Model) {
  737. extract($this->settings[$Model->alias]);
  738. if (!$Model->find('count', array('conditions' => $scope))) {
  739. return true;
  740. }
  741. $min = $this->_getMin($Model, $scope, $left, $recursive);
  742. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  743. $errors = array();
  744. for ($i = $min; $i <= $edge; $i++) {
  745. $count = $Model->find('count', array('conditions' => array(
  746. $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
  747. )));
  748. if ($count != 1) {
  749. if (!$count) {
  750. $errors[] = array('index', $i, 'missing');
  751. } else {
  752. $errors[] = array('index', $i, 'duplicate');
  753. }
  754. }
  755. }
  756. $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0));
  757. if ($node) {
  758. $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
  759. }
  760. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  761. 'className' => $Model->name,
  762. 'foreignKey' => $parent,
  763. 'fields' => array($Model->primaryKey, $left, $right, $parent)
  764. ))));
  765. foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) {
  766. if (is_null($instance[$Model->alias][$left]) || is_null($instance[$Model->alias][$right])) {
  767. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  768. 'has invalid left or right values');
  769. } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
  770. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  771. 'left and right values identical');
  772. } elseif ($instance[$Model->alias][$parent]) {
  773. if (!$instance['VerifyParent'][$Model->primaryKey]) {
  774. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  775. 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
  776. } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
  777. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  778. 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  779. } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
  780. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  781. 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  782. }
  783. } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
  784. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
  785. }
  786. }
  787. if ($errors) {
  788. return $errors;
  789. }
  790. return true;
  791. }
  792. /**
  793. * Sets the parent of the given node
  794. *
  795. * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
  796. * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
  797. * method could be private, since calling save with parent_id set also calls setParent
  798. *
  799. * @param Model $Model Model instance
  800. * @param integer|string $parentId
  801. * @param boolean $created
  802. * @return boolean true on success, false on failure
  803. */
  804. protected function _setParent(Model $Model, $parentId = null, $created = false) {
  805. extract($this->settings[$Model->alias]);
  806. list($node) = array_values($Model->find('first', array(
  807. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  808. 'fields' => array($Model->primaryKey, $parent, $left, $right),
  809. 'recursive' => $recursive
  810. )));
  811. $edge = $this->_getMax($Model, $scope, $right, $recursive, $created);
  812. if (empty ($parentId)) {
  813. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  814. $this->_sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
  815. } else {
  816. $values = $Model->find('first', array(
  817. 'conditions' => array($scope, $Model->escapeField() => $parentId),
  818. 'fields' => array($Model->primaryKey, $left, $right),
  819. 'recursive' => $recursive
  820. ));
  821. if ($values === false) {
  822. return false;
  823. }
  824. $parentNode = array_values($values);
  825. if (empty($parentNode) || empty($parentNode[0])) {
  826. return false;
  827. }
  828. $parentNode = $parentNode[0];
  829. if (($Model->id == $parentId)) {
  830. return false;
  831. } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  832. return false;
  833. }
  834. if (empty($node[$left]) && empty($node[$right])) {
  835. $this->_sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
  836. $result = $Model->save(
  837. array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
  838. array('validate' => false, 'callbacks' => false)
  839. );
  840. $Model->data = $result;
  841. } else {
  842. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  843. $diff = $node[$right] - $node[$left] + 1;
  844. if ($node[$left] > $parentNode[$left]) {
  845. if ($node[$right] < $parentNode[$right]) {
  846. $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  847. $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  848. } else {
  849. $this->_sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
  850. $this->_sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
  851. }
  852. } else {
  853. $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  854. $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  855. }
  856. }
  857. }
  858. return true;
  859. }
  860. /**
  861. * get the maximum index value in the table.
  862. *
  863. * @param Model $Model
  864. * @param string $scope
  865. * @param string $right
  866. * @param integer $recursive
  867. * @param boolean $created
  868. * @return integer
  869. */
  870. protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $created = false) {
  871. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  872. if ($created) {
  873. if (is_string($scope)) {
  874. $scope .= " AND " . $Model->escapeField() . " <> ";
  875. $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
  876. } else {
  877. $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  878. }
  879. }
  880. $name = $Model->escapeField($right);
  881. list($edge) = array_values($Model->find('first', array(
  882. 'conditions' => $scope,
  883. 'fields' => $db->calculate($Model, 'max', array($name, $right)),
  884. 'recursive' => $recursive
  885. )));
  886. return (empty($edge[$right])) ? 0 : $edge[$right];
  887. }
  888. /**
  889. * get the minimum index value in the table.
  890. *
  891. * @param Model $Model
  892. * @param string $scope
  893. * @param string $left
  894. * @param integer $recursive
  895. * @return integer
  896. */
  897. protected function _getMin(Model $Model, $scope, $left, $recursive = -1) {
  898. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  899. $name = $Model->escapeField($left);
  900. list($edge) = array_values($Model->find('first', array(
  901. 'conditions' => $scope,
  902. 'fields' => $db->calculate($Model, 'min', array($name, $left)),
  903. 'recursive' => $recursive
  904. )));
  905. return (empty($edge[$left])) ? 0 : $edge[$left];
  906. }
  907. /**
  908. * Table sync method.
  909. *
  910. * Handles table sync operations, Taking account of the behavior scope.
  911. *
  912. * @param Model $Model
  913. * @param integer $shift
  914. * @param string $dir
  915. * @param array $conditions
  916. * @param boolean $created
  917. * @param string $field
  918. * @return void
  919. */
  920. protected function _sync(Model $Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
  921. $ModelRecursive = $Model->recursive;
  922. extract($this->settings[$Model->alias]);
  923. $Model->recursive = $recursive;
  924. if ($field === 'both') {
  925. $this->_sync($Model, $shift, $dir, $conditions, $created, $left);
  926. $field = $right;
  927. }
  928. if (is_string($conditions)) {
  929. $conditions = array($Model->escapeField($field) . " {$conditions}");
  930. }
  931. if (($scope !== '1 = 1' && $scope !== true) && $scope) {
  932. $conditions[] = $scope;
  933. }
  934. if ($created) {
  935. $conditions['NOT'][$Model->escapeField()] = $Model->id;
  936. }
  937. $Model->updateAll(array($Model->escapeField($field) => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
  938. $Model->recursive = $ModelRecursive;
  939. }
  940. }