PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

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