TreeBehavior.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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 (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP Project
  18. * @package Cake.Model.Behavior
  19. * @since CakePHP v 1.2.0.4487
  20. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  21. */
  22. App::uses('ModelBehavior', 'Model');
  23. /**
  24. * Tree Behavior.
  25. *
  26. * Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
  27. *
  28. * @see http://en.wikipedia.org/wiki/Tree_traversal
  29. * @package Cake.Model.Behavior
  30. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
  31. */
  32. class TreeBehavior extends ModelBehavior {
  33. /**
  34. * Errors
  35. *
  36. * @var array
  37. */
  38. public $errors = array();
  39. /**
  40. * Defaults
  41. *
  42. * @var array
  43. */
  44. protected $_defaults = array(
  45. 'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght',
  46. 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1
  47. );
  48. /**
  49. * Used to preserve state between delete callbacks.
  50. *
  51. * @var array
  52. */
  53. protected $_deletedRow = array();
  54. /**
  55. * Initiate Tree behavior
  56. *
  57. * @param Model $Model instance of model
  58. * @param array $config array of configuration settings.
  59. * @return void
  60. */
  61. public function setup(Model $Model, $config = array()) {
  62. if (isset($config[0])) {
  63. $config['type'] = $config[0];
  64. unset($config[0]);
  65. }
  66. $settings = array_merge($this->_defaults, $config);
  67. if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
  68. $data = $Model->getAssociated($settings['scope']);
  69. $Parent = $Model->{$settings['scope']};
  70. $settings['scope'] = $Model->escapeField($data['foreignKey']) . ' = ' . $Parent->escapeField();
  71. $settings['recursive'] = 0;
  72. }
  73. $this->settings[$Model->alias] = $settings;
  74. }
  75. /**
  76. * After save method. Called after all saves
  77. *
  78. * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  79. * parameters to be saved.
  80. *
  81. * @param Model $Model Model instance.
  82. * @param boolean $created indicates whether the node just saved was created or updated
  83. * @return boolean true on success, false on failure
  84. */
  85. public function afterSave(Model $Model, $created) {
  86. extract($this->settings[$Model->alias]);
  87. if ($created) {
  88. if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) {
  89. return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created);
  90. }
  91. } elseif ($this->settings[$Model->alias]['__parentChange']) {
  92. $this->settings[$Model->alias]['__parentChange'] = false;
  93. return $this->_setParent($Model, $Model->data[$Model->alias][$parent]);
  94. }
  95. }
  96. /**
  97. * Runs before a find() operation
  98. *
  99. * @param Model $Model Model using the behavior
  100. * @param array $query Query parameters as set by cake
  101. * @return array
  102. */
  103. public function beforeFind(Model $Model, $query) {
  104. if ($Model->findQueryType === 'threaded' && !isset($query['parent'])) {
  105. $query['parent'] = $this->settings[$Model->alias]['parent'];
  106. }
  107. return $query;
  108. }
  109. /**
  110. * Stores the record about to be deleted.
  111. *
  112. * This is used to delete child nodes in the afterDelete.
  113. *
  114. * @param Model $Model Model instance
  115. * @param boolean $cascade
  116. * @return boolean
  117. */
  118. public function beforeDelete(Model $Model, $cascade = true) {
  119. extract($this->settings[$Model->alias]);
  120. $data = $Model->find('first', array(
  121. 'conditions' => array($Model->escapeField($Model->primaryKey) => $Model->id),
  122. 'fields' => array($Model->escapeField($left), $Model->escapeField($right)),
  123. 'recursive' => -1));
  124. if ($data) {
  125. $this->_deletedRow[$Model->alias] = current($data);
  126. }
  127. return true;
  128. }
  129. /**
  130. * After delete method.
  131. *
  132. * Will delete the current node and all children using the deleteAll method and sync the table
  133. *
  134. * @param Model $Model Model instance
  135. * @return boolean true to continue, false to abort the delete
  136. */
  137. public function afterDelete(Model $Model) {
  138. extract($this->settings[$Model->alias]);
  139. $data = $this->_deletedRow[$Model->alias];
  140. $this->_deletedRow[$Model->alias] = null;
  141. if (!$data[$right] || !$data[$left]) {
  142. return true;
  143. }
  144. $diff = $data[$right] - $data[$left] + 1;
  145. if ($diff > 2) {
  146. if (is_string($scope)) {
  147. $scope = array($scope);
  148. }
  149. $scope[][$Model->escapeField($left) . " BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1);
  150. $Model->deleteAll($scope);
  151. }
  152. $this->_sync($Model, $diff, '-', '> ' . $data[$right]);
  153. return true;
  154. }
  155. /**
  156. * Before save method. Called before all saves
  157. *
  158. * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  159. * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
  160. * this method bypassing the setParent logic.
  161. *
  162. * @since 1.2
  163. * @param Model $Model Model instance
  164. * @return boolean true to continue, false to abort the save
  165. */
  166. public function beforeSave(Model $Model) {
  167. extract($this->settings[$Model->alias]);
  168. $this->_addToWhitelist($Model, array($left, $right));
  169. if (!$Model->id || !$Model->exists()) {
  170. if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) {
  171. $parentNode = $Model->find('first', array(
  172. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  173. 'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive
  174. ));
  175. if (!$parentNode) {
  176. return false;
  177. }
  178. list($parentNode) = array_values($parentNode);
  179. $Model->data[$Model->alias][$left] = 0;
  180. $Model->data[$Model->alias][$right] = 0;
  181. } else {
  182. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  183. $Model->data[$Model->alias][$left] = $edge + 1;
  184. $Model->data[$Model->alias][$right] = $edge + 2;
  185. }
  186. } elseif (array_key_exists($parent, $Model->data[$Model->alias])) {
  187. if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) {
  188. $this->settings[$Model->alias]['__parentChange'] = true;
  189. }
  190. if (!$Model->data[$Model->alias][$parent]) {
  191. $Model->data[$Model->alias][$parent] = null;
  192. $this->_addToWhitelist($Model, $parent);
  193. } else {
  194. $values = $Model->find('first', array(
  195. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  196. 'fields' => array($Model->primaryKey, $parent, $left, $right), 'recursive' => $recursive)
  197. );
  198. if ($values === false) {
  199. return false;
  200. }
  201. list($node) = array_values($values);
  202. $parentNode = $Model->find('first', array(
  203. 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),
  204. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  205. ));
  206. if (!$parentNode) {
  207. return false;
  208. }
  209. list($parentNode) = array_values($parentNode);
  210. if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  211. return false;
  212. } elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) {
  213. return false;
  214. }
  215. }
  216. }
  217. return true;
  218. }
  219. /**
  220. * Get the number of child nodes
  221. *
  222. * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
  223. * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
  224. *
  225. * @param Model $Model Model instance
  226. * @param integer|string|boolean $id The ID of the record to read or false to read all top level nodes
  227. * @param boolean $direct whether to count direct, or all, children
  228. * @return integer number of child nodes
  229. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCount
  230. */
  231. public function childCount(Model $Model, $id = null, $direct = false) {
  232. if (is_array($id)) {
  233. extract(array_merge(array('id' => null), $id));
  234. }
  235. if ($id === null && $Model->id) {
  236. $id = $Model->id;
  237. } elseif (!$id) {
  238. $id = null;
  239. }
  240. extract($this->settings[$Model->alias]);
  241. if ($direct) {
  242. return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id)));
  243. }
  244. if ($id === null) {
  245. return $Model->find('count', array('conditions' => $scope));
  246. } elseif ($Model->id === $id && isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) {
  247. $data = $Model->data[$Model->alias];
  248. } else {
  249. $data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive));
  250. if (!$data) {
  251. return 0;
  252. }
  253. $data = $data[$Model->alias];
  254. }
  255. return ($data[$right] - $data[$left] - 1) / 2;
  256. }
  257. /**
  258. * Get the child nodes of the current model
  259. *
  260. * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
  261. * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
  262. *
  263. * @param Model $Model Model instance
  264. * @param integer|string $id The ID of the record to read
  265. * @param boolean $direct whether to return only the direct, or all, children
  266. * @param string|array $fields Either a single string of a field name, or an array of field names
  267. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
  268. * @param integer $limit SQL LIMIT clause, for calculating items per page.
  269. * @param integer $page Page number, for accessing paged data
  270. * @param integer $recursive The number of levels deep to fetch associated records
  271. * @return array Array of child nodes
  272. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::children
  273. */
  274. public function children(Model $Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
  275. if (is_array($id)) {
  276. extract(array_merge(array('id' => null), $id));
  277. }
  278. $overrideRecursive = $recursive;
  279. if ($id === null && $Model->id) {
  280. $id = $Model->id;
  281. } elseif (!$id) {
  282. $id = null;
  283. }
  284. extract($this->settings[$Model->alias]);
  285. if ($overrideRecursive !== null) {
  286. $recursive = $overrideRecursive;
  287. }
  288. if (!$order) {
  289. $order = $Model->escapeField($left) . " asc";
  290. }
  291. if ($direct) {
  292. $conditions = array($scope, $Model->escapeField($parent) => $id);
  293. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  294. }
  295. if (!$id) {
  296. $conditions = $scope;
  297. } else {
  298. $result = array_values((array)$Model->find('first', array(
  299. 'conditions' => array($scope, $Model->escapeField() => $id),
  300. 'fields' => array($left, $right),
  301. 'recursive' => $recursive
  302. )));
  303. if (empty($result) || !isset($result[0])) {
  304. return array();
  305. }
  306. $conditions = array($scope,
  307. $Model->escapeField($right) . ' <' => $result[0][$right],
  308. $Model->escapeField($left) . ' >' => $result[0][$left]
  309. );
  310. }
  311. return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  312. }
  313. /**
  314. * A convenience method for returning a hierarchical array used for HTML select boxes
  315. *
  316. * @param Model $Model Model instance
  317. * @param string|array $conditions SQL conditions as a string or as an array('field' =>'value',...)
  318. * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
  319. * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
  320. * @param string $spacer The character or characters which will be repeated
  321. * @param integer $recursive The number of levels deep to fetch associated records
  322. * @return array An associative array of records, where the id is the key, and the display field is the value
  323. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList
  324. */
  325. public function generateTreeList(Model $Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) {
  326. $overrideRecursive = $recursive;
  327. extract($this->settings[$Model->alias]);
  328. if ($overrideRecursive !== null) {
  329. $recursive = $overrideRecursive;
  330. }
  331. $fields = null;
  332. if (!$keyPath && !$valuePath && $Model->hasField($Model->displayField)) {
  333. $fields = array($Model->primaryKey, $Model->displayField, $left, $right);
  334. }
  335. if (!$keyPath) {
  336. $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
  337. }
  338. if (!$valuePath) {
  339. $valuePath = array('%s%s', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
  340. } elseif (is_string($valuePath)) {
  341. $valuePath = array('%s%s', '{n}.tree_prefix', $valuePath);
  342. } else {
  343. array_unshift($valuePath, '%s' . $valuePath[0], '{n}.tree_prefix');
  344. }
  345. $conditions = (array)$conditions;
  346. if ($scope) {
  347. $conditions[] = $scope;
  348. }
  349. $order = $Model->escapeField($left) . " asc";
  350. $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
  351. $stack = array();
  352. foreach ($results as $i => $result) {
  353. $count = count($stack);
  354. while ($stack && ($stack[$count - 1] < $result[$Model->alias][$right])) {
  355. array_pop($stack);
  356. $count--;
  357. }
  358. $results[$i]['tree_prefix'] = str_repeat($spacer, $count);
  359. $stack[] = $result[$Model->alias][$right];
  360. }
  361. if (empty($results)) {
  362. return array();
  363. }
  364. return Hash::combine($results, $keyPath, $valuePath);
  365. }
  366. /**
  367. * Get the parent node
  368. *
  369. * reads the parent id and returns this node
  370. *
  371. * @param Model $Model Model instance
  372. * @param integer|string $id The ID of the record to read
  373. * @param string|array $fields
  374. * @param integer $recursive The number of levels deep to fetch associated records
  375. * @return array|boolean Array of data for the parent node
  376. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode
  377. */
  378. public function getParentNode(Model $Model, $id = null, $fields = null, $recursive = null) {
  379. if (is_array($id)) {
  380. extract(array_merge(array('id' => null), $id));
  381. }
  382. $overrideRecursive = $recursive;
  383. if (empty($id)) {
  384. $id = $Model->id;
  385. }
  386. extract($this->settings[$Model->alias]);
  387. if ($overrideRecursive !== null) {
  388. $recursive = $overrideRecursive;
  389. }
  390. $parentId = $Model->find('first', array('conditions' => array($Model->primaryKey => $id), 'fields' => array($parent), 'recursive' => -1));
  391. if ($parentId) {
  392. $parentId = $parentId[$Model->alias][$parent];
  393. $parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive));
  394. return $parent;
  395. }
  396. return false;
  397. }
  398. /**
  399. * Get the path to the given node
  400. *
  401. * @param Model $Model Model instance
  402. * @param integer|string $id The ID of the record to read
  403. * @param string|array $fields Either a single string of a field name, or an array of field names
  404. * @param integer $recursive The number of levels deep to fetch associated records
  405. * @return array Array of nodes from top most parent to current node
  406. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPath
  407. */
  408. public function getPath(Model $Model, $id = null, $fields = null, $recursive = null) {
  409. if (is_array($id)) {
  410. extract(array_merge(array('id' => null), $id));
  411. }
  412. $overrideRecursive = $recursive;
  413. if (empty($id)) {
  414. $id = $Model->id;
  415. }
  416. extract($this->settings[$Model->alias]);
  417. if ($overrideRecursive !== null) {
  418. $recursive = $overrideRecursive;
  419. }
  420. $result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive));
  421. if ($result) {
  422. $result = array_values($result);
  423. } else {
  424. return null;
  425. }
  426. $item = $result[0];
  427. $results = $Model->find('all', array(
  428. 'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]),
  429. 'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive
  430. ));
  431. return $results;
  432. }
  433. /**
  434. * Reorder the node without changing the parent.
  435. *
  436. * If the node is the last child, or is a top level node with no subsequent node this method will return false
  437. *
  438. * @param Model $Model Model instance
  439. * @param integer|string $id The ID of the record to move
  440. * @param integer|boolean $number how many places to move the node or true to move to last position
  441. * @return boolean true on success, false on failure
  442. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDown
  443. */
  444. public function moveDown(Model $Model, $id = null, $number = 1) {
  445. if (is_array($id)) {
  446. extract(array_merge(array('id' => null), $id));
  447. }
  448. if (!$number) {
  449. return false;
  450. }
  451. if (empty($id)) {
  452. $id = $Model->id;
  453. }
  454. extract($this->settings[$Model->alias]);
  455. list($node) = array_values($Model->find('first', array(
  456. 'conditions' => array($scope, $Model->escapeField() => $id),
  457. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  458. )));
  459. if ($node[$parent]) {
  460. list($parentNode) = array_values($Model->find('first', array(
  461. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  462. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  463. )));
  464. if (($node[$right] + 1) == $parentNode[$right]) {
  465. return false;
  466. }
  467. }
  468. $nextNode = $Model->find('first', array(
  469. 'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)),
  470. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive)
  471. );
  472. if ($nextNode) {
  473. list($nextNode) = array_values($nextNode);
  474. } else {
  475. return false;
  476. }
  477. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  478. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  479. $this->_sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]);
  480. $this->_sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge);
  481. if (is_int($number)) {
  482. $number--;
  483. }
  484. if ($number) {
  485. $this->moveDown($Model, $id, $number);
  486. }
  487. return true;
  488. }
  489. /**
  490. * Reorder the node without changing the parent.
  491. *
  492. * If the node is the first child, or is a top level node with no previous node this method will return false
  493. *
  494. * @param Model $Model Model instance
  495. * @param integer|string $id The ID of the record to move
  496. * @param integer|boolean $number how many places to move the node, or true to move to first position
  497. * @return boolean true on success, false on failure
  498. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUp
  499. */
  500. public function moveUp(Model $Model, $id = null, $number = 1) {
  501. if (is_array($id)) {
  502. extract(array_merge(array('id' => null), $id));
  503. }
  504. if (!$number) {
  505. return false;
  506. }
  507. if (empty($id)) {
  508. $id = $Model->id;
  509. }
  510. extract($this->settings[$Model->alias]);
  511. list($node) = array_values($Model->find('first', array(
  512. 'conditions' => array($scope, $Model->escapeField() => $id),
  513. 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive
  514. )));
  515. if ($node[$parent]) {
  516. list($parentNode) = array_values($Model->find('first', array(
  517. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  518. 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive
  519. )));
  520. if (($node[$left] - 1) == $parentNode[$left]) {
  521. return false;
  522. }
  523. }
  524. $previousNode = $Model->find('first', array(
  525. 'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)),
  526. 'fields' => array($Model->primaryKey, $left, $right),
  527. 'recursive' => $recursive
  528. ));
  529. if ($previousNode) {
  530. list($previousNode) = array_values($previousNode);
  531. } else {
  532. return false;
  533. }
  534. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  535. $this->_sync($Model, $edge - $previousNode[$left] + 1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]);
  536. $this->_sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
  537. $this->_sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge);
  538. if (is_int($number)) {
  539. $number--;
  540. }
  541. if ($number) {
  542. $this->moveUp($Model, $id, $number);
  543. }
  544. return true;
  545. }
  546. /**
  547. * Recover a corrupted tree
  548. *
  549. * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data
  550. * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode
  551. * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
  552. * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
  553. *
  554. * @param Model $Model Model instance
  555. * @param string $mode parent or tree
  556. * @param string|integer $missingParentAction 'return' to do nothing and return, 'delete' to
  557. * delete, or the id of the parent to set as the parent_id
  558. * @return boolean true on success, false on failure
  559. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recover
  560. */
  561. public function recover(Model $Model, $mode = 'parent', $missingParentAction = null) {
  562. if (is_array($mode)) {
  563. extract(array_merge(array('mode' => 'parent'), $mode));
  564. }
  565. extract($this->settings[$Model->alias]);
  566. $Model->recursive = $recursive;
  567. if ($mode === 'parent') {
  568. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  569. 'className' => $Model->name,
  570. 'foreignKey' => $parent,
  571. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  572. ))));
  573. $missingParents = $Model->find('list', array(
  574. 'recursive' => 0,
  575. 'conditions' => array($scope, array(
  576. 'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null
  577. ))
  578. ));
  579. $Model->unbindModel(array('belongsTo' => array('VerifyParent')));
  580. if ($missingParents) {
  581. if ($missingParentAction === 'return') {
  582. foreach ($missingParents as $id => $display) {
  583. $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')';
  584. }
  585. return false;
  586. } elseif ($missingParentAction === 'delete') {
  587. $Model->deleteAll(array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)), false);
  588. } else {
  589. $Model->updateAll(array($Model->escapeField($parent) => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
  590. }
  591. }
  592. $this->_recoverByParentId($Model);
  593. } else {
  594. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  595. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  596. $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]);
  597. $parentId = null;
  598. if (count($path) > 1) {
  599. $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
  600. }
  601. $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
  602. }
  603. }
  604. return true;
  605. }
  606. /**
  607. * _recoverByParentId
  608. *
  609. * Recursive helper function used by recover
  610. *
  611. * @param Model $Model
  612. * @param integer $counter
  613. * @param mixed $parentId
  614. * @return integer $counter
  615. */
  616. protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = null) {
  617. $params = array(
  618. 'conditions' => array(
  619. $this->settings[$Model->alias]['parent'] => $parentId
  620. ),
  621. 'fields' => array($Model->primaryKey),
  622. 'page' => 1,
  623. 'limit' => 100,
  624. 'order' => array($Model->primaryKey)
  625. );
  626. $scope = $this->settings[$Model->alias]['scope'];
  627. if ($scope && ($scope !== '1 = 1' && $scope !== true)) {
  628. $conditions[] = $scope;
  629. }
  630. $children = $Model->find('all', $params);
  631. $hasChildren = (bool)$children;
  632. if (!is_null($parentId)) {
  633. if ($hasChildren) {
  634. $Model->updateAll(
  635. array($this->settings[$Model->alias]['left'] => $counter),
  636. array($Model->escapeField() => $parentId)
  637. );
  638. $counter++;
  639. } else {
  640. $Model->updateAll(
  641. array(
  642. $this->settings[$Model->alias]['left'] => $counter,
  643. $this->settings[$Model->alias]['right'] => $counter + 1
  644. ),
  645. array($Model->escapeField() => $parentId)
  646. );
  647. $counter += 2;
  648. }
  649. }
  650. while ($children) {
  651. foreach ($children as $row) {
  652. $counter = $this->_recoverByParentId($Model, $counter, $row[$Model->alias][$Model->primaryKey]);
  653. }
  654. if (count($children) !== $params['limit']) {
  655. break;
  656. }
  657. $params['page']++;
  658. $children = $Model->find('all', $params);
  659. }
  660. if (!is_null($parentId) && $hasChildren) {
  661. $Model->updateAll(
  662. array($this->settings[$Model->alias]['right'] => $counter),
  663. array($Model->escapeField() => $parentId)
  664. );
  665. $counter++;
  666. }
  667. return $counter;
  668. }
  669. /**
  670. * Reorder method.
  671. *
  672. * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
  673. * This method does not change the parent of any node.
  674. *
  675. * Requires a valid tree, by default it verifies the tree before beginning.
  676. *
  677. * Options:
  678. *
  679. * - 'id' id of record to use as top node for reordering
  680. * - 'field' Which field to use in reordering defaults to displayField
  681. * - 'order' Direction to order either DESC or ASC (defaults to ASC)
  682. * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
  683. *
  684. * @param Model $Model Model instance
  685. * @param array $options array of options to use in reordering.
  686. * @return boolean true on success, false on failure
  687. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder
  688. */
  689. public function reorder(Model $Model, $options = array()) {
  690. $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options);
  691. extract($options);
  692. if ($verify && !$this->verify($Model)) {
  693. return false;
  694. }
  695. $verify = false;
  696. extract($this->settings[$Model->alias]);
  697. $fields = array($Model->primaryKey, $field, $left, $right);
  698. $sort = $field . ' ' . $order;
  699. $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
  700. $cacheQueries = $Model->cacheQueries;
  701. $Model->cacheQueries = false;
  702. if ($nodes) {
  703. foreach ($nodes as $node) {
  704. $id = $node[$Model->alias][$Model->primaryKey];
  705. $this->moveDown($Model, $id, true);
  706. if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
  707. $this->reorder($Model, compact('id', 'field', 'order', 'verify'));
  708. }
  709. }
  710. }
  711. $Model->cacheQueries = $cacheQueries;
  712. return true;
  713. }
  714. /**
  715. * Remove the current node from the tree, and reparent all children up one level.
  716. *
  717. * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
  718. * after the children are reparented.
  719. *
  720. * @param Model $Model Model instance
  721. * @param integer|string $id The ID of the record to remove
  722. * @param boolean $delete whether to delete the node after reparenting children (if any)
  723. * @return boolean true on success, false on failure
  724. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree
  725. */
  726. public function removeFromTree(Model $Model, $id = null, $delete = false) {
  727. if (is_array($id)) {
  728. extract(array_merge(array('id' => null), $id));
  729. }
  730. extract($this->settings[$Model->alias]);
  731. list($node) = array_values($Model->find('first', array(
  732. 'conditions' => array($scope, $Model->escapeField() => $id),
  733. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  734. 'recursive' => $recursive
  735. )));
  736. if ($node[$right] == $node[$left] + 1) {
  737. if ($delete) {
  738. return $Model->delete($id);
  739. }
  740. $Model->id = $id;
  741. return $Model->saveField($parent, null);
  742. } elseif ($node[$parent]) {
  743. list($parentNode) = array_values($Model->find('first', array(
  744. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  745. 'fields' => array($Model->primaryKey, $left, $right),
  746. 'recursive' => $recursive
  747. )));
  748. } else {
  749. $parentNode[$right] = $node[$right] + 1;
  750. }
  751. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  752. $Model->updateAll(
  753. array($parent => $db->value($node[$parent], $parent)),
  754. array($Model->escapeField($parent) => $node[$Model->primaryKey])
  755. );
  756. $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
  757. $this->_sync($Model, 2, '-', '> ' . ($node[$right]));
  758. $Model->id = $id;
  759. if ($delete) {
  760. $Model->updateAll(
  761. array(
  762. $Model->escapeField($left) => 0,
  763. $Model->escapeField($right) => 0,
  764. $Model->escapeField($parent) => null
  765. ),
  766. array($Model->escapeField() => $id)
  767. );
  768. return $Model->delete($id);
  769. }
  770. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  771. if ($node[$right] == $edge) {
  772. $edge = $edge - 2;
  773. }
  774. $Model->id = $id;
  775. return $Model->save(
  776. array($left => $edge + 1, $right => $edge + 2, $parent => null),
  777. array('callbacks' => false, 'validate' => false)
  778. );
  779. }
  780. /**
  781. * Check if the current tree is valid.
  782. *
  783. * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
  784. *
  785. * @param Model $Model Model instance
  786. * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
  787. * [incorrect left/right index,node id], message)
  788. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify
  789. */
  790. public function verify(Model $Model) {
  791. extract($this->settings[$Model->alias]);
  792. if (!$Model->find('count', array('conditions' => $scope))) {
  793. return true;
  794. }
  795. $min = $this->_getMin($Model, $scope, $left, $recursive);
  796. $edge = $this->_getMax($Model, $scope, $right, $recursive);
  797. $errors = array();
  798. for ($i = $min; $i <= $edge; $i++) {
  799. $count = $Model->find('count', array('conditions' => array(
  800. $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
  801. )));
  802. if ($count != 1) {
  803. if (!$count) {
  804. $errors[] = array('index', $i, 'missing');
  805. } else {
  806. $errors[] = array('index', $i, 'duplicate');
  807. }
  808. }
  809. }
  810. $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0));
  811. if ($node) {
  812. $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
  813. }
  814. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  815. 'className' => $Model->name,
  816. 'foreignKey' => $parent,
  817. 'fields' => array($Model->primaryKey, $left, $right, $parent)
  818. ))));
  819. foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) {
  820. if ($instance[$Model->alias][$left] === null || $instance[$Model->alias][$right] === null) {
  821. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  822. 'has invalid left or right values');
  823. } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
  824. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  825. 'left and right values identical');
  826. } elseif ($instance[$Model->alias][$parent]) {
  827. if (!$instance['VerifyParent'][$Model->primaryKey]) {
  828. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  829. 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
  830. } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
  831. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  832. 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  833. } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
  834. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  835. 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  836. }
  837. } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
  838. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
  839. }
  840. }
  841. if ($errors) {
  842. return $errors;
  843. }
  844. return true;
  845. }
  846. /**
  847. * Sets the parent of the given node
  848. *
  849. * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
  850. * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
  851. * method could be private, since calling save with parent_id set also calls setParent
  852. *
  853. * @param Model $Model Model instance
  854. * @param integer|string $parentId
  855. * @param boolean $created
  856. * @return boolean true on success, false on failure
  857. */
  858. protected function _setParent(Model $Model, $parentId = null, $created = false) {
  859. extract($this->settings[$Model->alias]);
  860. list($node) = array_values($Model->find('first', array(
  861. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  862. 'fields' => array($Model->primaryKey, $parent, $left, $right),
  863. 'recursive' => $recursive
  864. )));
  865. $edge = $this->_getMax($Model, $scope, $right, $recursive, $created);
  866. if (empty($parentId)) {
  867. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  868. $this->_sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
  869. } else {
  870. $values = $Model->find('first', array(
  871. 'conditions' => array($scope, $Model->escapeField() => $parentId),
  872. 'fields' => array($Model->primaryKey, $left, $right),
  873. 'recursive' => $recursive
  874. ));
  875. if ($values === false) {
  876. return false;
  877. }
  878. $parentNode = array_values($values);
  879. if (empty($parentNode) || empty($parentNode[0])) {
  880. return false;
  881. }
  882. $parentNode = $parentNode[0];
  883. if (($Model->id == $parentId)) {
  884. return false;
  885. } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  886. return false;
  887. }
  888. if (empty($node[$left]) && empty($node[$right])) {
  889. $this->_sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
  890. $result = $Model->save(
  891. array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
  892. array('validate' => false, 'callbacks' => false)
  893. );
  894. $Model->data = $result;
  895. } else {
  896. $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  897. $diff = $node[$right] - $node[$left] + 1;
  898. if ($node[$left] > $parentNode[$left]) {
  899. if ($node[$right] < $parentNode[$right]) {
  900. $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  901. $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  902. } else {
  903. $this->_sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
  904. $this->_sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
  905. }
  906. } else {
  907. $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  908. $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  909. }
  910. }
  911. }
  912. return true;
  913. }
  914. /**
  915. * get the maximum index value in the table.
  916. *
  917. * @param Model $Model
  918. * @param string $scope
  919. * @param string $right
  920. * @param integer $recursive
  921. * @param boolean $created
  922. * @return integer
  923. */
  924. protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $created = false) {
  925. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  926. if ($created) {
  927. if (is_string($scope)) {
  928. $scope .= " AND " . $Model->escapeField() . " <> ";
  929. $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
  930. } else {
  931. $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  932. }
  933. }
  934. $name = $Model->escapeField($right);
  935. list($edge) = array_values($Model->find('first', array(
  936. 'conditions' => $scope,
  937. 'fields' => $db->calculate($Model, 'max', array($name, $right)),
  938. 'recursive' => $recursive,
  939. 'callbacks' => false
  940. )));
  941. return (empty($edge[$right])) ? 0 : $edge[$right];
  942. }
  943. /**
  944. * get the minimum index value in the table.
  945. *
  946. * @param Model $Model
  947. * @param string $scope
  948. * @param string $left
  949. * @param integer $recursive
  950. * @return integer
  951. */
  952. protected function _getMin(Model $Model, $scope, $left, $recursive = -1) {
  953. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  954. $name = $Model->escapeField($left);
  955. list($edge) = array_values($Model->find('first', array(
  956. 'conditions' => $scope,
  957. 'fields' => $db->calculate($Model, 'min', array($name, $left)),
  958. 'recursive' => $recursive,
  959. 'callbacks' => false
  960. )));
  961. return (empty($edge[$left])) ? 0 : $edge[$left];
  962. }
  963. /**
  964. * Table sync method.
  965. *
  966. * Handles table sync operations, Taking account of the behavior scope.
  967. *
  968. * @param Model $Model
  969. * @param integer $shift
  970. * @param string $dir
  971. * @param array $conditions
  972. * @param boolean $created
  973. * @param string $field
  974. * @return void
  975. */
  976. protected function _sync(Model $Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
  977. $ModelRecursive = $Model->recursive;
  978. extract($this->settings[$Model->alias]);
  979. $Model->recursive = $recursive;
  980. if ($field === 'both') {
  981. $this->_sync($Model, $shift, $dir, $conditions, $created, $left);
  982. $field = $right;
  983. }
  984. if (is_string($conditions)) {
  985. $conditions = array($Model->escapeField($field) . " {$conditions}");
  986. }
  987. if (($scope !== '1 = 1' && $scope !== true) && $scope) {
  988. $conditions[] = $scope;
  989. }
  990. if ($created) {
  991. $conditions['NOT'][$Model->escapeField()] = $Model->id;
  992. }
  993. $Model->updateAll(array($Model->escapeField($field) => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
  994. $Model->recursive = $ModelRecursive;
  995. }
  996. }