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. /**
  22. * Tree Behavior.
  23. *
  24. * Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
  25. *
  26. * @see http://en.wikipedia.org/wiki/Tree_traversal
  27. * @package Cake.Model.Behavior
  28. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
  29. */
  30. class TreeBehavior extends ModelBehavior {
  31. /**
  32. * Errors
  33. *
  34. * @var array
  35. */
  36. public $errors = array();
  37. /**
  38. * Defaults
  39. *
  40. * @var array
  41. */
  42. protected $_defaults = array(
  43. 'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght',
  44. 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1
  45. );
  46. /**
  47. * Used to preserve state between delete callbacks.
  48. *
  49. * @var array
  50. */
  51. protected $_deletedRow = null;
  52. /**
  53. * Initiate Tree behavior
  54. *
  55. * @param Model $Model instance of model
  56. * @param array $config array of configuration settings.
  57. * @return void
  58. */
  59. public function setup(Model $Model, $config = array()) {
  60. if (isset($config[0])) {
  61. $config['type'] = $config[0];
  62. unset($config[0]);
  63. }
  64. $settings = array_merge($this->_defaults, $config);
  65. if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
  66. $data = $Model->getAssociated($settings['scope']);
  67. $parent = $Model->{$settings['scope']};
  68. $settings['scope'] = $Model->alias . '.' . $data['foreignKey'] . ' = ' . $parent->alias . '.' . $parent->primaryKey;
  69. $settings['recursive'] = 0;
  70. }
  71. $this->settings[$Model->alias] = $settings;
  72. }
  73. /**
  74. * After save method. Called after all saves
  75. *
  76. * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  77. * parameters to be saved.
  78. *
  79. * @param Model $Model Model instance.
  80. * @param boolean $created indicates whether the node just saved was created or updated
  81. * @return boolean true on success, false on failure
  82. */
  83. public function afterSave(Model $Model, $created) {
  84. extract($this->settings[$Model->alias]);
  85. if ($created) {
  86. if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) {
  87. return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created);
  88. }
  89. } elseif ($this->settings[$Model->alias]['__parentChange']) {
  90. $this->settings[$Model->alias]['__parentChange'] = false;
  91. return $this->_setParent($Model, $Model->data[$Model->alias][$parent]);
  92. }
  93. }
  94. /**
  95. * Runs before a find() operation
  96. *
  97. * @param Model $Model Model using the behavior
  98. * @param array $query Query parameters as set by cake
  99. * @return array
  100. */
  101. public function beforeFind(Model $Model, $query) {
  102. if ($Model->findQueryType == 'threaded' && !isset($query['parent'])) {
  103. $query['parent'] = $this->settings[$Model->alias]['parent'];
  104. }
  105. return $query;
  106. }
  107. /**
  108. * Stores the record about to be deleted.
  109. *
  110. * This is used to delete child nodes in the afterDelete.
  111. *
  112. * @param Model $Model Model instance
  113. * @param boolean $cascade
  114. * @return boolean
  115. */
  116. public function beforeDelete(Model $Model, $cascade = true) {
  117. extract($this->settings[$Model->alias]);
  118. $data = current($Model->find('first', array(
  119. 'conditions' => array($Model->alias . '.' . $Model->primaryKey => $Model->id),
  120. 'fields' => array($Model->alias . '.' . $left, $Model->alias . '.' . $right),
  121. 'recursive' => -1)));
  122. $this->_deletedRow = $data;
  123. return true;
  124. }
  125. /**
  126. * After delete method.
  127. *
  128. * Will delete the current node and all children using the deleteAll method and sync the table
  129. *
  130. * @param Model $Model Model instance
  131. * @return boolean true to continue, false to abort the delete
  132. */
  133. public function afterDelete(Model $Model) {
  134. extract($this->settings[$Model->alias]);
  135. $data = $this->_deletedRow;
  136. $this->_deletedRow = null;
  137. if (!$data[$right] || !$data[$left]) {
  138. return true;
  139. }
  140. $diff = $data[$right] - $data[$left] + 1;
  141. if ($diff > 2) {
  142. if (is_string($scope)) {
  143. $scope = array($scope);
  144. }
  145. $scope[]["{$Model->alias}.{$left} BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1);
  146. $Model->deleteAll($scope);
  147. }
  148. $this->_sync($Model, $diff, '-', '> ' . $data[$right]);
  149. return true;
  150. }
  151. /**
  152. * Before save method. Called before all saves
  153. *
  154. * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  155. * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
  156. * this method bypassing the setParent logic.
  157. *
  158. * @since 1.2
  159. * @param Model $Model Model instance
  160. * @return boolean true to continue, false to abort the save
  161. */
  162. public function beforeSave(Model $Model) {
  163. extract($this->settings[$Model->alias]);
  164. $this->_addToWhitelist($Model, array($left, $right));
  165. if (!$Model->id) {
  166. if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) {
  167. $parentNode = $Model->find('first', array(
  168. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  169. 'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive
  170. ));
  171. if (!$parentNode) {
  172. return false;
  173. }
  174. list($parentNode) = array_values($parentNode);
  175. $Model->data[$Model->alias][$left] = 0;
  176. $Model->data[$Model->alias][$right] = 0;
  177. } else {
  178. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  179. $Model->data[$Model->alias][$left] = $edge + 1;
  180. $Model->data[$Model->alias][$right] = $edge + 2;
  181. }
  182. } elseif (array_key_exists($parent, $Model->data[$Model->alias])) {
  183. if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) {
  184. $this->settings[$Model->alias]['__parentChange'] = true;
  185. }
  186. if (!$Model->data[$Model->alias][$parent]) {
  187. $Model->data[$Model->alias][$parent] = null;
  188. $this->_addToWhitelist($Model, $parent);
  189. } else {
  190. $values = $Model->find('first', array(
  191. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  192. 'fields' => array($Model->primaryKey, $parent, $left, $right), 'recursive' => $recursive)
  193. );
  194. if ($values === false) {
  195. return false;
  196. }
  197. list($node) = array_values($values);
  198. $parentNode = $Model->find('first', array(
  199. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  200. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  201. ));
  202. if (!$parentNode) {
  203. return false;
  204. }
  205. list($parentNode) = array_values($parentNode);
  206. if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  207. return false;
  208. } elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) {
  209. return false;
  210. }
  211. }
  212. }
  213. return true;
  214. }
  215. /**
  216. * Get the number of child nodes
  217. *
  218. * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
  219. * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
  220. *
  221. * @param Model $Model Model instance
  222. * @param integer|string|boolean $id The ID of the record to read or false to read all top level nodes
  223. * @param boolean $direct whether to count direct, or all, children
  224. * @return integer number of child nodes
  225. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCount
  226. */
  227. public function childCount(Model $Model, $id = null, $direct = false) {
  228. if (is_array($id)) {
  229. extract(array_merge(array('id' => null), $id));
  230. }
  231. if ($id === null && $Model->id) {
  232. $id = $Model->id;
  233. } elseif (!$id) {
  234. $id = null;
  235. }
  236. extract($this->settings[$Model->alias]);
  237. if ($direct) {
  238. return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id)));
  239. }
  240. if ($id === null) {
  241. return $Model->find('count', array('conditions' => $scope));
  242. } elseif ($Model->id === $id && isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) {
  243. $data = $Model->data[$Model->alias];
  244. } else {
  245. $data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive));
  246. if (!$data) {
  247. return 0;
  248. }
  249. $data = $data[$Model->alias];
  250. }
  251. return ($data[$right] - $data[$left] - 1) / 2;
  252. }
  253. /**
  254. * Get the child nodes of the current model
  255. *
  256. * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
  257. * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
  258. *
  259. * @param Model $Model Model instance
  260. * @param integer|string $id The ID of the record to read
  261. * @param boolean $direct whether to return only the direct, or all, children
  262. * @param string|array $fields Either a single string of a field name, or an array of field names
  263. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
  264. * @param integer $limit SQL LIMIT clause, for calculating items per page.
  265. * @param integer $page Page number, for accessing paged data
  266. * @param integer $recursive The number of levels deep to fetch associated records
  267. * @return array Array of child nodes
  268. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::children
  269. */
  270. public function children(Model $Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
  271. if (is_array($id)) {
  272. extract(array_merge(array('id' => null), $id));
  273. }
  274. $overrideRecursive = $recursive;
  275. if ($id === null && $Model->id) {
  276. $id = $Model->id;
  277. } elseif (!$id) {
  278. $id = null;
  279. }
  280. extract($this->settings[$Model->alias]);
  281. if (!is_null($overrideRecursive)) {
  282. $recursive = $overrideRecursive;
  283. }
  284. if (!$order) {
  285. $order = $Model->alias . '.' . $left . ' asc';
  286. }
  287. if ($direct) {
  288. $conditions = array($scope, $Model->escapeField($parent) => $id);
  289. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  290. }
  291. if (!$id) {
  292. $conditions = $scope;
  293. } else {
  294. $result = array_values((array)$Model->find('first', array(
  295. 'conditions' => array($scope, $Model->escapeField() => $id),
  296. 'fields' => array($left, $right),
  297. 'recursive' => $recursive
  298. )));
  299. if (empty($result) || !isset($result[0])) {
  300. return array();
  301. }
  302. $conditions = array($scope,
  303. $Model->escapeField($right) . ' <' => $result[0][$right],
  304. $Model->escapeField($left) . ' >' => $result[0][$left]
  305. );
  306. }
  307. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  308. }
  309. /**
  310. * A convenience method for returning a hierarchical array used for HTML select boxes
  311. *
  312. * @param Model $Model Model instance
  313. * @param string|array $conditions SQL conditions as a string or as an array('field' =>'value',...)
  314. * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
  315. * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
  316. * @param string $spacer The character or characters which will be repeated
  317. * @param integer $recursive The number of levels deep to fetch associated records
  318. * @return array An associative array of records, where the id is the key, and the display field is the value
  319. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList
  320. */
  321. public function generateTreeList(Model $Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) {
  322. $overrideRecursive = $recursive;
  323. extract($this->settings[$Model->alias]);
  324. if (!is_null($overrideRecursive)) {
  325. $recursive = $overrideRecursive;
  326. }
  327. if ($keyPath == null && $valuePath == null && $Model->hasField($Model->displayField)) {
  328. $fields = array($Model->primaryKey, $Model->displayField, $left, $right);
  329. } else {
  330. $fields = null;
  331. }
  332. if ($keyPath == null) {
  333. $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
  334. }
  335. if ($valuePath == null) {
  336. $valuePath = array('%s%s', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
  337. } elseif (is_string($valuePath)) {
  338. $valuePath = array('%s%s', '{n}.tree_prefix', $valuePath);
  339. } else {
  340. $valuePath[0] = '{' . (count($valuePath) - 1) . '}' . $valuePath[0];
  341. $valuePath[] = '{n}.tree_prefix';
  342. }
  343. $order = $Model->alias . '.' . $left . ' asc';
  344. $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
  345. $stack = array();
  346. foreach ($results as $i => $result) {
  347. $count = count($stack);
  348. while ($stack && ($stack[$count - 1] < $result[$Model->alias][$right])) {
  349. array_pop($stack);
  350. $count--;
  351. }
  352. $results[$i]['tree_prefix'] = str_repeat($spacer, $count);
  353. $stack[] = $result[$Model->alias][$right];
  354. }
  355. if (empty($results)) {
  356. return array();
  357. }
  358. return Hash::combine($results, $keyPath, $valuePath);
  359. }
  360. /**
  361. * Get the parent node
  362. *
  363. * reads the parent id and returns this node
  364. *
  365. * @param Model $Model Model instance
  366. * @param integer|string $id The ID of the record to read
  367. * @param string|array $fields
  368. * @param integer $recursive The number of levels deep to fetch associated records
  369. * @return array|boolean Array of data for the parent node
  370. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode
  371. */
  372. public function getParentNode(Model $Model, $id = null, $fields = null, $recursive = null) {
  373. if (is_array($id)) {
  374. extract(array_merge(array('id' => null), $id));
  375. }
  376. $overrideRecursive = $recursive;
  377. if (empty ($id)) {
  378. $id = $Model->id;
  379. }
  380. extract($this->settings[$Model->alias]);
  381. if (!is_null($overrideRecursive)) {
  382. $recursive = $overrideRecursive;
  383. }
  384. $parentId = $Model->find('first', array('conditions' => array($Model->primaryKey => $id), 'fields' => array($parent), 'recursive' => -1));
  385. if ($parentId) {
  386. $parentId = $parentId[$Model->alias][$parent];
  387. $parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive));
  388. return $parent;
  389. }
  390. return false;
  391. }
  392. /**
  393. * Get the path to the given node
  394. *
  395. * @param Model $Model Model instance
  396. * @param integer|string $id The ID of the record to read
  397. * @param string|array $fields Either a single string of a field name, or an array of field names
  398. * @param integer $recursive The number of levels deep to fetch associated records
  399. * @return array Array of nodes from top most parent to current node
  400. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPath
  401. */
  402. public function getPath(Model $Model, $id = null, $fields = null, $recursive = null) {
  403. if (is_array($id)) {
  404. extract(array_merge(array('id' => null), $id));
  405. }
  406. $overrideRecursive = $recursive;
  407. if (empty ($id)) {
  408. $id = $Model->id;
  409. }
  410. extract($this->settings[$Model->alias]);
  411. if (!is_null($overrideRecursive)) {
  412. $recursive = $overrideRecursive;
  413. }
  414. $result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive));
  415. if ($result) {
  416. $result = array_values($result);
  417. } else {
  418. return null;
  419. }
  420. $item = $result[0];
  421. $results = $Model->find('all', array(
  422. 'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]),
  423. 'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive
  424. ));
  425. return $results;
  426. }
  427. /**
  428. * Reorder the node without changing the parent.
  429. *
  430. * If the node is the last child, or is a top level node with no subsequent node this method will return false
  431. *
  432. * @param Model $Model Model instance
  433. * @param integer|string $id The ID of the record to move
  434. * @param integer|boolean $number how many places to move the node or true to move to last position
  435. * @return boolean true on success, false on failure
  436. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDown
  437. */
  438. public function moveDown(Model $Model, $id = null, $number = 1) {
  439. if (is_array($id)) {
  440. extract(array_merge(array('id' => null), $id));
  441. }
  442. if (!$number) {
  443. return false;
  444. }
  445. if (empty ($id)) {
  446. $id = $Model->id;
  447. }
  448. extract($this->settings[$Model->alias]);
  449. list($node) = array_values($Model->find('first', array(
  450. 'conditions' => array($scope, $Model->escapeField() => $id),
  451. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  452. )));
  453. if ($node[$parent]) {
  454. list($parentNode) = array_values($Model->find('first', array(
  455. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  456. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  457. )));
  458. if (($node[$right] + 1) == $parentNode[$right]) {
  459. return false;
  460. }
  461. }
  462. $nextNode = $Model->find('first', array(
  463. 'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)),
  464. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive)
  465. );
  466. if ($nextNode) {
  467. list($nextNode) = array_values($nextNode);
  468. } else {
  469. return false;
  470. }
  471. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  472. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  473. $this->_sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]);
  474. $this->_sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge);
  475. if (is_int($number)) {
  476. $number--;
  477. }
  478. if ($number) {
  479. $this->moveDown($Model, $id, $number);
  480. }
  481. return true;
  482. }
  483. /**
  484. * Reorder the node without changing the parent.
  485. *
  486. * If the node is the first child, or is a top level node with no previous node this method will return false
  487. *
  488. * @param Model $Model Model instance
  489. * @param integer|string $id The ID of the record to move
  490. * @param integer|boolean $number how many places to move the node, or true to move to first position
  491. * @return boolean true on success, false on failure
  492. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUp
  493. */
  494. public function moveUp(Model $Model, $id = null, $number = 1) {
  495. if (is_array($id)) {
  496. extract(array_merge(array('id' => null), $id));
  497. }
  498. if (!$number) {
  499. return false;
  500. }
  501. if (empty ($id)) {
  502. $id = $Model->id;
  503. }
  504. extract($this->settings[$Model->alias]);
  505. list($node) = array_values($Model->find('first', array(
  506. 'conditions' => array($scope, $Model->escapeField() => $id),
  507. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  508. )));
  509. if ($node[$parent]) {
  510. list($parentNode) = array_values($Model->find('first', array(
  511. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  512. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  513. )));
  514. if (($node[$left] - 1) == $parentNode[$left]) {
  515. return false;
  516. }
  517. }
  518. $previousNode = $Model->find('first', array(
  519. 'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)),
  520. 'fields' => array($Model->primaryKey, $left, $right),
  521. 'recursive' => $recursive
  522. ));
  523. if ($previousNode) {
  524. list($previousNode) = array_values($previousNode);
  525. } else {
  526. return false;
  527. }
  528. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  529. $this->_sync($Model, $edge - $previousNode[$left] + 1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]);
  530. $this->_sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  531. $this->_sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge);
  532. if (is_int($number)) {
  533. $number--;
  534. }
  535. if ($number) {
  536. $this->moveUp($Model, $id, $number);
  537. }
  538. return true;
  539. }
  540. /**
  541. * Recover a corrupted tree
  542. *
  543. * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data
  544. * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode
  545. * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
  546. * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
  547. *
  548. * @todo Could be written to be faster, *maybe*. Ideally using a subquery and putting all the logic burden on the DB.
  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->primaryKey => array_flip($missingParents)));
  583. } else {
  584. $Model->updateAll(array($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. if ($path == null || count($path) < 2) {
  605. $parentId = null;
  606. } else {
  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 == 0) {
  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->alias}.{$Model->primaryKey} <> ";
  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->alias . '.' . $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->alias . '.' . $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->alias}.{$field} {$conditions}");
  931. }
  932. if (($scope != '1 = 1' && $scope !== true) && $scope) {
  933. $conditions[] = $scope;
  934. }
  935. if ($created) {
  936. $conditions['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  937. }
  938. $Model->updateAll(array($Model->alias . '.' . $field => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
  939. $Model->recursive = $ModelRecursive;
  940. }
  941. }