TreeBehavior.php 37 KB

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