TreeBehavior.php 39 KB

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