PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/cake/libs/model/behaviors/tree.php

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