/lib/Cake/Model/Behavior/TreeBehavior.php

https://bitbucket.org/floresj/notetime · PHP · 1006 lines · 660 code · 64 blank · 282 comment · 157 complexity · 6f327d4c59e715311737df8ce7132487 MD5 · raw file

  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->escapeField($data['foreignKey']) . ' = ' . $Parent->escapeField();
  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->escapeField($Model->primaryKey) => $Model->id),
  120. 'fields' => array($Model->escapeField($left), $Model->escapeField($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->escapeField($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->escapeField($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. 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. * @todo Could be written to be faster, *maybe*. Ideally using a subquery and putting all the logic burden on the DB.
  550. * @param Model $Model Model instance
  551. * @param string $mode parent or tree
  552. * @param string|integer $missingParentAction 'return' to do nothing and return, 'delete' to
  553. * delete, or the id of the parent to set as the parent_id
  554. * @return boolean true on success, false on failure
  555. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recover
  556. */
  557. public function recover(Model $Model, $mode = 'parent', $missingParentAction = null) {
  558. if (is_array($mode)) {
  559. extract(array_merge(array('mode' => 'parent'), $mode));
  560. }
  561. extract($this->settings[$Model->alias]);
  562. $Model->recursive = $recursive;
  563. if ($mode == 'parent') {
  564. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  565. 'className' => $Model->name,
  566. 'foreignKey' => $parent,
  567. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  568. ))));
  569. $missingParents = $Model->find('list', array(
  570. 'recursive' => 0,
  571. 'conditions' => array($scope, array(
  572. 'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null
  573. ))
  574. ));
  575. $Model->unbindModel(array('belongsTo' => array('VerifyParent')));
  576. if ($missingParents) {
  577. if ($missingParentAction == 'return') {
  578. foreach ($missingParents as $id => $display) {
  579. $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')';
  580. }
  581. return false;
  582. } elseif ($missingParentAction == 'delete') {
  583. $Model->deleteAll(array($Model->primaryKey => array_flip($missingParents)));
  584. } else {
  585. $Model->updateAll(array($parent => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
  586. }
  587. }
  588. $count = 1;
  589. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey), 'order' => $left)) as $array) {
  590. $lft = $count++;
  591. $rght = $count++;
  592. $Model->create(false);
  593. $Model->id = $array[$Model->alias][$Model->primaryKey];
  594. $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false, 'validate' => false));
  595. }
  596. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  597. $Model->create(false);
  598. $Model->id = $array[$Model->alias][$Model->primaryKey];
  599. $this->_setParent($Model, $array[$Model->alias][$parent]);
  600. }
  601. } else {
  602. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  603. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  604. $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]);
  605. if ($path == null || count($path) < 2) {
  606. $parentId = null;
  607. } else {
  608. $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
  609. }
  610. $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
  611. }
  612. }
  613. return true;
  614. }
  615. /**
  616. * Reorder method.
  617. *
  618. * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
  619. * This method does not change the parent of any node.
  620. *
  621. * Requires a valid tree, by default it verifies the tree before beginning.
  622. *
  623. * Options:
  624. *
  625. * - 'id' id of record to use as top node for reordering
  626. * - 'field' Which field to use in reordering defaults to displayField
  627. * - 'order' Direction to order either DESC or ASC (defaults to ASC)
  628. * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
  629. *
  630. * @param Model $Model Model instance
  631. * @param array $options array of options to use in reordering.
  632. * @return boolean true on success, false on failure
  633. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder
  634. */
  635. public function reorder(Model $Model, $options = array()) {
  636. $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options);
  637. extract($options);
  638. if ($verify && !$this->verify($Model)) {
  639. return false;
  640. }
  641. $verify = false;
  642. extract($this->settings[$Model->alias]);
  643. $fields = array($Model->primaryKey, $field, $left, $right);
  644. $sort = $field . ' ' . $order;
  645. $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
  646. $cacheQueries = $Model->cacheQueries;
  647. $Model->cacheQueries = false;
  648. if ($nodes) {
  649. foreach ($nodes as $node) {
  650. $id = $node[$Model->alias][$Model->primaryKey];
  651. $this->moveDown($Model, $id, true);
  652. if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
  653. $this->reorder($Model, compact('id', 'field', 'order', 'verify'));
  654. }
  655. }
  656. }
  657. $Model->cacheQueries = $cacheQueries;
  658. return true;
  659. }
  660. /**
  661. * Remove the current node from the tree, and reparent all children up one level.
  662. *
  663. * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
  664. * after the children are reparented.
  665. *
  666. * @param Model $Model Model instance
  667. * @param integer|string $id The ID of the record to remove
  668. * @param boolean $delete whether to delete the node after reparenting children (if any)
  669. * @return boolean true on success, false on failure
  670. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree
  671. */
  672. public function removeFromTree(Model $Model, $id = null, $delete = false) {
  673. if (is_array($id)) {
  674. extract(array_merge(array('id' => null), $id));
  675. }
  676. extract($this->settings[$Model->alias]);
  677. list($node) = array_values($Model->find('first', array(
  678. 'conditions' => array($scope, $Model->escapeField() => $id),
  679. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  680. 'recursive' => $recursive
  681. )));
  682. if ($node[$right] == $node[$left] + 1) {
  683. if ($delete) {
  684. return $Model->delete($id);
  685. } else {
  686. $Model->id = $id;
  687. return $Model->saveField($parent, null);
  688. }
  689. } elseif ($node[$parent]) {
  690. list($parentNode) = array_values($Model->find('first', array(
  691. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  692. 'fields' => array($Model->primaryKey, $left, $right),
  693. 'recursive' => $recursive
  694. )));
  695. } else {
  696. $parentNode[$right] = $node[$right] + 1;
  697. }
  698. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  699. $Model->updateAll(
  700. array($parent => $db->value($node[$parent], $parent)),
  701. array($Model->escapeField($parent) => $node[$Model->primaryKey])
  702. );
  703. $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
  704. $this->_sync($Model, 2, '-', '> ' . ($node[$right]));
  705. $Model->id = $id;
  706. if ($delete) {
  707. $Model->updateAll(
  708. array(
  709. $Model->escapeField($left) => 0,
  710. $Model->escapeField($right) => 0,
  711. $Model->escapeField($parent) => null
  712. ),
  713. array($Model->escapeField() => $id)
  714. );
  715. return $Model->delete($id);
  716. } else {
  717. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  718. if ($node[$right] == $edge) {
  719. $edge = $edge - 2;
  720. }
  721. $Model->id = $id;
  722. return $Model->save(
  723. array($left => $edge + 1, $right => $edge + 2, $parent => null),
  724. array('callbacks' => false, 'validate' => false)
  725. );
  726. }
  727. }
  728. /**
  729. * Check if the current tree is valid.
  730. *
  731. * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
  732. *
  733. * @param Model $Model Model instance
  734. * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
  735. * [incorrect left/right index,node id], message)
  736. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify
  737. */
  738. public function verify(Model $Model) {
  739. extract($this->settings[$Model->alias]);
  740. if (!$Model->find('count', array('conditions' => $scope))) {
  741. return true;
  742. }
  743. $min = $this->_getMin($Model, $scope, $left, $recursive);
  744. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  745. $errors = array();
  746. for ($i = $min; $i <= $edge; $i++) {
  747. $count = $Model->find('count', array('conditions' => array(
  748. $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
  749. )));
  750. if ($count != 1) {
  751. if ($count == 0) {
  752. $errors[] = array('index', $i, 'missing');
  753. } else {
  754. $errors[] = array('index', $i, 'duplicate');
  755. }
  756. }
  757. }
  758. $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0));
  759. if ($node) {
  760. $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
  761. }
  762. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  763. 'className' => $Model->name,
  764. 'foreignKey' => $parent,
  765. 'fields' => array($Model->primaryKey, $left, $right, $parent)
  766. ))));
  767. foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) {
  768. if (is_null($instance[$Model->alias][$left]) || is_null($instance[$Model->alias][$right])) {
  769. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  770. 'has invalid left or right values');
  771. } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
  772. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  773. 'left and right values identical');
  774. } elseif ($instance[$Model->alias][$parent]) {
  775. if (!$instance['VerifyParent'][$Model->primaryKey]) {
  776. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  777. 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
  778. } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
  779. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  780. 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  781. } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
  782. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  783. 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  784. }
  785. } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
  786. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
  787. }
  788. }
  789. if ($errors) {
  790. return $errors;
  791. }
  792. return true;
  793. }
  794. /**
  795. * Sets the parent of the given node
  796. *
  797. * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
  798. * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
  799. * method could be private, since calling save with parent_id set also calls setParent
  800. *
  801. * @param Model $Model Model instance
  802. * @param integer|string $parentId
  803. * @param boolean $created
  804. * @return boolean true on success, false on failure
  805. */
  806. protected function _setParent(Model $Model, $parentId = null, $created = false) {
  807. extract($this->settings[$Model->alias]);
  808. list($node) = array_values($Model->find('first', array(
  809. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  810. 'fields' => array($Model->primaryKey, $parent, $left, $right),
  811. 'recursive' => $recursive
  812. )));
  813. $edge = $this->_getMax($Model, $scope, $right, $recursive, $created);
  814. if (empty ($parentId)) {
  815. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  816. $this->_sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
  817. } else {
  818. $values = $Model->find('first', array(
  819. 'conditions' => array($scope, $Model->escapeField() => $parentId),
  820. 'fields' => array($Model->primaryKey, $left, $right),
  821. 'recursive' => $recursive
  822. ));
  823. if ($values === false) {
  824. return false;
  825. }
  826. $parentNode = array_values($values);
  827. if (empty($parentNode) || empty($parentNode[0])) {
  828. return false;
  829. }
  830. $parentNode = $parentNode[0];
  831. if (($Model->id == $parentId)) {
  832. return false;
  833. } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  834. return false;
  835. }
  836. if (empty($node[$left]) && empty($node[$right])) {
  837. $this->_sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
  838. $result = $Model->save(
  839. array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
  840. array('validate' => false, 'callbacks' => false)
  841. );
  842. $Model->data = $result;
  843. } else {
  844. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  845. $diff = $node[$right] - $node[$left] + 1;
  846. if ($node[$left] > $parentNode[$left]) {
  847. if ($node[$right] < $parentNode[$right]) {
  848. $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  849. $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  850. } else {
  851. $this->_sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
  852. $this->_sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
  853. }
  854. } else {
  855. $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  856. $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  857. }
  858. }
  859. }
  860. return true;
  861. }
  862. /**
  863. * get the maximum index value in the table.
  864. *
  865. * @param Model $Model
  866. * @param string $scope
  867. * @param string $right
  868. * @param integer $recursive
  869. * @param boolean $created
  870. * @return integer
  871. */
  872. protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $created = false) {
  873. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  874. if ($created) {
  875. if (is_string($scope)) {
  876. $scope .= " AND " . $Model->escapeField() . " <> ";
  877. $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
  878. } else {
  879. $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  880. }
  881. }
  882. $name = $Model->escapeField($right);
  883. list($edge) = array_values($Model->find('first', array(
  884. 'conditions' => $scope,
  885. 'fields' => $db->calculate($Model, 'max', array($name, $right)),
  886. 'recursive' => $recursive
  887. )));
  888. return (empty($edge[$right])) ? 0 : $edge[$right];
  889. }
  890. /**
  891. * get the minimum index value in the table.
  892. *
  893. * @param Model $Model
  894. * @param string $scope
  895. * @param string $left
  896. * @param integer $recursive
  897. * @return integer
  898. */
  899. protected function _getMin(Model $Model, $scope, $left, $recursive = -1) {
  900. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  901. $name = $Model->escapeField($left);
  902. list($edge) = array_values($Model->find('first', array(
  903. 'conditions' => $scope,
  904. 'fields' => $db->calculate($Model, 'min', array($name, $left)),
  905. 'recursive' => $recursive
  906. )));
  907. return (empty($edge[$left])) ? 0 : $edge[$left];
  908. }
  909. /**
  910. * Table sync method.
  911. *
  912. * Handles table sync operations, Taking account of the behavior scope.
  913. *
  914. * @param Model $Model
  915. * @param integer $shift
  916. * @param string $dir
  917. * @param array $conditions
  918. * @param boolean $created
  919. * @param string $field
  920. * @return void
  921. */
  922. protected function _sync(Model $Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
  923. $ModelRecursive = $Model->recursive;
  924. extract($this->settings[$Model->alias]);
  925. $Model->recursive = $recursive;
  926. if ($field == 'both') {
  927. $this->_sync($Model, $shift, $dir, $conditions, $created, $left);
  928. $field = $right;
  929. }
  930. if (is_string($conditions)) {
  931. $conditions = array($Model->escapeField($field) . " {$conditions}");
  932. }
  933. if (($scope != '1 = 1' && $scope !== true) && $scope) {
  934. $conditions[] = $scope;
  935. }
  936. if ($created) {
  937. $conditions['NOT'][$Model->escapeField()] = $Model->id;
  938. }
  939. $Model->updateAll(array($Model->escapeField($field) => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
  940. $Model->recursive = $ModelRecursive;
  941. }
  942. }