PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/code/ryzom/tools/server/www/webtt/cake/libs/model/behaviors/tree.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 977 lines | 640 code | 61 blank | 276 comment | 152 complexity | 1bd7d50343f99b9043542e4e27b58ebd MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  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 2006-2010, 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 2006-2010, 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 (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->alias,
  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. $Model->id = $array[$Model->alias][$Model->primaryKey];
  565. $lft = $count++;
  566. $rght = $count++;
  567. $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false));
  568. }
  569. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  570. $Model->create();
  571. $Model->id = $array[$Model->alias][$Model->primaryKey];
  572. $this->_setParent($Model, $array[$Model->alias][$parent]);
  573. }
  574. } else {
  575. $db =& ConnectionManager::getDataSource($Model->useDbConfig);
  576. foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
  577. $path = $this->getpath($Model, $array[$Model->alias][$Model->primaryKey]);
  578. if ($path == null || count($path) < 2) {
  579. $parentId = null;
  580. } else {
  581. $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
  582. }
  583. $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
  584. }
  585. }
  586. return true;
  587. }
  588. /**
  589. * Reorder method.
  590. *
  591. * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
  592. * This method does not change the parent of any node.
  593. *
  594. * Requires a valid tree, by default it verifies the tree before beginning.
  595. *
  596. * Options:
  597. *
  598. * - 'id' id of record to use as top node for reordering
  599. * - 'field' Which field to use in reordeing defaults to displayField
  600. * - 'order' Direction to order either DESC or ASC (defaults to ASC)
  601. * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
  602. *
  603. * @param AppModel $Model Model instance
  604. * @param array $options array of options to use in reordering.
  605. * @return boolean true on success, false on failure
  606. * @link http://book.cakephp.org/view/1355/reorder
  607. * @link http://book.cakephp.org/view/1629/Reorder
  608. */
  609. function reorder(&$Model, $options = array()) {
  610. $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options);
  611. extract($options);
  612. if ($verify && !$this->verify($Model)) {
  613. return false;
  614. }
  615. $verify = false;
  616. extract($this->settings[$Model->alias]);
  617. $fields = array($Model->primaryKey, $field, $left, $right);
  618. $sort = $field . ' ' . $order;
  619. $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
  620. $cacheQueries = $Model->cacheQueries;
  621. $Model->cacheQueries = false;
  622. if ($nodes) {
  623. foreach ($nodes as $node) {
  624. $id = $node[$Model->alias][$Model->primaryKey];
  625. $this->moveDown($Model, $id, true);
  626. if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
  627. $this->reorder($Model, compact('id', 'field', 'order', 'verify'));
  628. }
  629. }
  630. }
  631. $Model->cacheQueries = $cacheQueries;
  632. return true;
  633. }
  634. /**
  635. * Remove the current node from the tree, and reparent all children up one level.
  636. *
  637. * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
  638. * after the children are reparented.
  639. *
  640. * @param AppModel $Model Model instance
  641. * @param mixed $id The ID of the record to remove
  642. * @param boolean $delete whether to delete the node after reparenting children (if any)
  643. * @return boolean true on success, false on failure
  644. * @access public
  645. * @link http://book.cakephp.org/view/1354/removeFromTree
  646. */
  647. function removefromtree(&$Model, $id = null, $delete = false) {
  648. if (is_array($id)) {
  649. extract (array_merge(array('id' => null), $id));
  650. }
  651. extract($this->settings[$Model->alias]);
  652. list($node) = array_values($Model->find('first', array(
  653. 'conditions' => array($scope, $Model->escapeField() => $id),
  654. 'fields' => array($Model->primaryKey, $left, $right, $parent),
  655. 'recursive' => $recursive
  656. )));
  657. if ($node[$right] == $node[$left] + 1) {
  658. if ($delete) {
  659. return $Model->delete($id);
  660. } else {
  661. $Model->id = $id;
  662. return $Model->saveField($parent, null);
  663. }
  664. } elseif ($node[$parent]) {
  665. list($parentNode) = array_values($Model->find('first', array(
  666. 'conditions' => array($scope, $Model->escapeField() => $node[$parent]),
  667. 'fields' => array($Model->primaryKey, $left, $right),
  668. 'recursive' => $recursive
  669. )));
  670. } else {
  671. $parentNode[$right] = $node[$right] + 1;
  672. }
  673. $db =& ConnectionManager::getDataSource($Model->useDbConfig);
  674. $Model->updateAll(
  675. array($parent => $db->value($node[$parent], $parent)),
  676. array($Model->escapeField($parent) => $node[$Model->primaryKey])
  677. );
  678. $this->__sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
  679. $this->__sync($Model, 2, '-', '> ' . ($node[$right]));
  680. $Model->id = $id;
  681. if ($delete) {
  682. $Model->updateAll(
  683. array(
  684. $Model->escapeField($left) => 0,
  685. $Model->escapeField($right) => 0,
  686. $Model->escapeField($parent) => null
  687. ),
  688. array($Model->escapeField() => $id)
  689. );
  690. return $Model->delete($id);
  691. } else {
  692. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  693. if ($node[$right] == $edge) {
  694. $edge = $edge - 2;
  695. }
  696. $Model->id = $id;
  697. return $Model->save(
  698. array($left => $edge + 1, $right => $edge + 2, $parent => null),
  699. array('callbacks' => false)
  700. );
  701. }
  702. }
  703. /**
  704. * Check if the current tree is valid.
  705. *
  706. * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
  707. *
  708. * @param AppModel $Model Model instance
  709. * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
  710. * [incorrect left/right index,node id], message)
  711. * @access public
  712. * @link http://book.cakephp.org/view/1630/Verify
  713. */
  714. function verify(&$Model) {
  715. extract($this->settings[$Model->alias]);
  716. if (!$Model->find('count', array('conditions' => $scope))) {
  717. return true;
  718. }
  719. $min = $this->__getMin($Model, $scope, $left, $recursive);
  720. $edge = $this->__getMax($Model, $scope, $right, $recursive);
  721. $errors = array();
  722. for ($i = $min; $i <= $edge; $i++) {
  723. $count = $Model->find('count', array('conditions' => array(
  724. $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
  725. )));
  726. if ($count != 1) {
  727. if ($count == 0) {
  728. $errors[] = array('index', $i, 'missing');
  729. } else {
  730. $errors[] = array('index', $i, 'duplicate');
  731. }
  732. }
  733. }
  734. $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0));
  735. if ($node) {
  736. $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
  737. }
  738. $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
  739. 'className' => $Model->alias,
  740. 'foreignKey' => $parent,
  741. 'fields' => array($Model->primaryKey, $left, $right, $parent)
  742. ))));
  743. foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) {
  744. if (is_null($instance[$Model->alias][$left]) || is_null($instance[$Model->alias][$right])) {
  745. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  746. 'has invalid left or right values');
  747. } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
  748. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  749. 'left and right values identical');
  750. } elseif ($instance[$Model->alias][$parent]) {
  751. if (!$instance['VerifyParent'][$Model->primaryKey]) {
  752. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  753. 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
  754. } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
  755. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  756. 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  757. } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
  758. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
  759. 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
  760. }
  761. } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
  762. $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
  763. }
  764. }
  765. if ($errors) {
  766. return $errors;
  767. }
  768. return true;
  769. }
  770. /**
  771. * Sets the parent of the given node
  772. *
  773. * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
  774. * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
  775. * method could be private, since calling save with parent_id set also calls setParent
  776. *
  777. * @param AppModel $Model Model instance
  778. * @param mixed $parentId
  779. * @return boolean true on success, false on failure
  780. * @access protected
  781. */
  782. function _setParent(&$Model, $parentId = null, $created = false) {
  783. extract($this->settings[$Model->alias]);
  784. list($node) = array_values($Model->find('first', array(
  785. 'conditions' => array($scope, $Model->escapeField() => $Model->id),
  786. 'fields' => array($Model->primaryKey, $parent, $left, $right),
  787. 'recursive' => $recursive
  788. )));
  789. $edge = $this->__getMax($Model, $scope, $right, $recursive, $created);
  790. if (empty ($parentId)) {
  791. $this->__sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  792. $this->__sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
  793. } else {
  794. $values = $Model->find('first', array(
  795. 'conditions' => array($scope, $Model->escapeField() => $parentId),
  796. 'fields' => array($Model->primaryKey, $left, $right),
  797. 'recursive' => $recursive
  798. ));
  799. if ($values === false) {
  800. return false;
  801. }
  802. $parentNode = array_values($values);
  803. if (empty($parentNode) || empty($parentNode[0])) {
  804. return false;
  805. }
  806. $parentNode = $parentNode[0];
  807. if (($Model->id == $parentId)) {
  808. return false;
  809. } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
  810. return false;
  811. }
  812. if (empty ($node[$left]) && empty ($node[$right])) {
  813. $this->__sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
  814. $result = $Model->save(
  815. array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
  816. array('validate' => false, 'callbacks' => false)
  817. );
  818. $Model->data = $result;
  819. } else {
  820. $this->__sync($Model, $edge - $node[$left] +1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
  821. $diff = $node[$right] - $node[$left] + 1;
  822. if ($node[$left] > $parentNode[$left]) {
  823. if ($node[$right] < $parentNode[$right]) {
  824. $this->__sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  825. $this->__sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  826. } else {
  827. $this->__sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
  828. $this->__sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
  829. }
  830. } else {
  831. $this->__sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
  832. $this->__sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
  833. }
  834. }
  835. }
  836. return true;
  837. }
  838. /**
  839. * get the maximum index value in the table.
  840. *
  841. * @param AppModel $Model
  842. * @param string $scope
  843. * @param string $right
  844. * @return int
  845. * @access private
  846. */
  847. function __getMax($Model, $scope, $right, $recursive = -1, $created = false) {
  848. $db =& ConnectionManager::getDataSource($Model->useDbConfig);
  849. if ($created) {
  850. if (is_string($scope)) {
  851. $scope .= " AND {$Model->alias}.{$Model->primaryKey} <> ";
  852. $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
  853. } else {
  854. $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  855. }
  856. }
  857. $name = $Model->alias . '.' . $right;
  858. list($edge) = array_values($Model->find('first', array(
  859. 'conditions' => $scope,
  860. 'fields' => $db->calculate($Model, 'max', array($name, $right)),
  861. 'recursive' => $recursive
  862. )));
  863. return (empty($edge[$right])) ? 0 : $edge[$right];
  864. }
  865. /**
  866. * get the minimum index value in the table.
  867. *
  868. * @param AppModel $Model
  869. * @param string $scope
  870. * @param string $right
  871. * @return int
  872. * @access private
  873. */
  874. function __getMin($Model, $scope, $left, $recursive = -1) {
  875. $db =& ConnectionManager::getDataSource($Model->useDbConfig);
  876. $name = $Model->alias . '.' . $left;
  877. list($edge) = array_values($Model->find('first', array(
  878. 'conditions' => $scope,
  879. 'fields' => $db->calculate($Model, 'min', array($name, $left)),
  880. 'recursive' => $recursive
  881. )));
  882. return (empty($edge[$left])) ? 0 : $edge[$left];
  883. }
  884. /**
  885. * Table sync method.
  886. *
  887. * Handles table sync operations, Taking account of the behavior scope.
  888. *
  889. * @param AppModel $Model
  890. * @param integer $shift
  891. * @param string $direction
  892. * @param array $conditions
  893. * @param string $field
  894. * @access private
  895. */
  896. function __sync(&$Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
  897. $ModelRecursive = $Model->recursive;
  898. extract($this->settings[$Model->alias]);
  899. $Model->recursive = $recursive;
  900. if ($field == 'both') {
  901. $this->__sync($Model, $shift, $dir, $conditions, $created, $left);
  902. $field = $right;
  903. }
  904. if (is_string($conditions)) {
  905. $conditions = array("{$Model->alias}.{$field} {$conditions}");
  906. }
  907. if (($scope != '1 = 1' && $scope !== true) && $scope) {
  908. $conditions[] = $scope;
  909. }
  910. if ($created) {
  911. $conditions['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
  912. }
  913. $Model->updateAll(array($Model->alias . '.' . $field => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
  914. $Model->recursive = $ModelRecursive;
  915. }
  916. }