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

/libraries/joomla/table/nested.php

http://github.com/joomla/joomla-platform
PHP | 1641 lines | 897 code | 230 blank | 514 comment | 103 complexity | 7a70055daf9c7a7b09cbe0eba960a802 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * @package Joomla.Platform
  4. * @subpackage Table
  5. *
  6. * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
  7. * @license GNU General Public License version 2 or later; see LICENSE
  8. */
  9. defined('JPATH_PLATFORM') or die;
  10. /**
  11. * Table class supporting modified pre-order tree traversal behavior.
  12. *
  13. * @package Joomla.Platform
  14. * @subpackage Table
  15. * @link http://docs.joomla.org/JTableNested
  16. * @since 11.1
  17. */
  18. class JTableNested extends JTable
  19. {
  20. /**
  21. * Object property holding the primary key of the parent node. Provides
  22. * adjacency list data for nodes.
  23. *
  24. * @var integer
  25. * @since 11.1
  26. */
  27. public $parent_id;
  28. /**
  29. * Object property holding the depth level of the node in the tree.
  30. *
  31. * @var integer
  32. * @since 11.1
  33. */
  34. public $level;
  35. /**
  36. * Object property holding the left value of the node for managing its
  37. * placement in the nested sets tree.
  38. *
  39. * @var integer
  40. * @since 11.1
  41. */
  42. public $lft;
  43. /**
  44. * Object property holding the right value of the node for managing its
  45. * placement in the nested sets tree.
  46. *
  47. * @var integer
  48. * @since 11.1
  49. */
  50. public $rgt;
  51. /**
  52. * Object property holding the alias of this node used to constuct the
  53. * full text path, forward-slash delimited.
  54. *
  55. * @var string
  56. * @since 11.1
  57. */
  58. public $alias;
  59. /**
  60. * Object property to hold the location type to use when storing the row.
  61. * Possible values are: ['before', 'after', 'first-child', 'last-child'].
  62. *
  63. * @var string
  64. * @since 11.1
  65. */
  66. protected $_location;
  67. /**
  68. * Object property to hold the primary key of the location reference node to
  69. * use when storing the row. A combination of location type and reference
  70. * node describes where to store the current node in the tree.
  71. *
  72. * @var integer
  73. * @since 11.1
  74. */
  75. protected $_location_id;
  76. /**
  77. * An array to cache values in recursive processes.
  78. *
  79. * @var array
  80. * @since 11.1
  81. */
  82. protected $_cache = array();
  83. /**
  84. * Debug level
  85. *
  86. * @var integer
  87. * @since 11.1
  88. */
  89. protected $_debug = 0;
  90. /**
  91. * Sets the debug level on or off
  92. *
  93. * @param integer $level 0 = off, 1 = on
  94. *
  95. * @return void
  96. *
  97. * @since 11.1
  98. */
  99. public function debug($level)
  100. {
  101. $this->_debug = (int) $level;
  102. }
  103. /**
  104. * Method to get an array of nodes from a given node to its root.
  105. *
  106. * @param integer $pk Primary key of the node for which to get the path.
  107. * @param boolean $diagnostic Only select diagnostic data for the nested sets.
  108. *
  109. * @return mixed An array of node objects including the start node.
  110. *
  111. * @since 11.1
  112. * @throws RuntimeException on database error
  113. */
  114. public function getPath($pk = null, $diagnostic = false)
  115. {
  116. $k = $this->_tbl_key;
  117. $pk = (is_null($pk)) ? $this->$k : $pk;
  118. // Get the path from the node to the root.
  119. $query = $this->_db->getQuery(true);
  120. $select = ($diagnostic) ? 'p.' . $k . ', p.parent_id, p.level, p.lft, p.rgt' : 'p.*';
  121. $query->select($select)
  122. ->from($this->_tbl . ' AS n, ' . $this->_tbl . ' AS p')
  123. ->where('n.lft BETWEEN p.lft AND p.rgt')
  124. ->where('n.' . $k . ' = ' . (int) $pk)
  125. ->order('p.lft');
  126. $this->_db->setQuery($query);
  127. return $this->_db->loadObjectList();
  128. }
  129. /**
  130. * Method to get a node and all its child nodes.
  131. *
  132. * @param integer $pk Primary key of the node for which to get the tree.
  133. * @param boolean $diagnostic Only select diagnostic data for the nested sets.
  134. *
  135. * @return mixed Boolean false on failure or array of node objects on success.
  136. *
  137. * @since 11.1
  138. * @throws RuntimeException on database error.
  139. */
  140. public function getTree($pk = null, $diagnostic = false)
  141. {
  142. $k = $this->_tbl_key;
  143. $pk = (is_null($pk)) ? $this->$k : $pk;
  144. // Get the node and children as a tree.
  145. $query = $this->_db->getQuery(true);
  146. $select = ($diagnostic) ? 'n.' . $k . ', n.parent_id, n.level, n.lft, n.rgt' : 'n.*';
  147. $query->select($select)
  148. ->from($this->_tbl . ' AS n, ' . $this->_tbl . ' AS p')
  149. ->where('n.lft BETWEEN p.lft AND p.rgt')
  150. ->where('p.' . $k . ' = ' . (int) $pk)
  151. ->order('n.lft');
  152. return $this->_db->setQuery($query)->loadObjectList();
  153. }
  154. /**
  155. * Method to determine if a node is a leaf node in the tree (has no children).
  156. *
  157. * @param integer $pk Primary key of the node to check.
  158. *
  159. * @return boolean True if a leaf node, false if not or null if the node does not exist.
  160. *
  161. * @note Since 12.1 this method returns null if the node does not exist.
  162. * @since 11.1
  163. * @throws RuntimeException on database error.
  164. */
  165. public function isLeaf($pk = null)
  166. {
  167. $k = $this->_tbl_key;
  168. $pk = (is_null($pk)) ? $this->$k : $pk;
  169. $node = $this->_getNode($pk);
  170. // Get the node by primary key.
  171. if (empty($node))
  172. {
  173. // Error message set in getNode method.
  174. return null;
  175. }
  176. // The node is a leaf node.
  177. return (($node->rgt - $node->lft) == 1);
  178. }
  179. /**
  180. * Method to set the location of a node in the tree object. This method does not
  181. * save the new location to the database, but will set it in the object so
  182. * that when the node is stored it will be stored in the new location.
  183. *
  184. * @param integer $referenceId The primary key of the node to reference new location by.
  185. * @param string $position Location type string. ['before', 'after', 'first-child', 'last-child']
  186. *
  187. * @return void
  188. *
  189. * @note Since 12.1 this method returns void and throws an InvalidArgumentException when an invalid position is passed.
  190. * @since 11.1
  191. * @throws InvalidArgumentException
  192. */
  193. public function setLocation($referenceId, $position = 'after')
  194. {
  195. // Make sure the location is valid.
  196. if (($position != 'before') && ($position != 'after') && ($position != 'first-child') && ($position != 'last-child'))
  197. {
  198. throw new InvalidArgumentException(sprintf('%s::setLocation(%d, *%s*)', get_class($this), $referenceId, $position));
  199. }
  200. // Set the location properties.
  201. $this->_location = $position;
  202. $this->_location_id = $referenceId;
  203. }
  204. /**
  205. * Method to move a row in the ordering sequence of a group of rows defined by an SQL WHERE clause.
  206. * Negative numbers move the row up in the sequence and positive numbers move it down.
  207. *
  208. * @param integer $delta The direction and magnitude to move the row in the ordering sequence.
  209. * @param string $where WHERE clause to use for limiting the selection of rows to compact the
  210. * ordering values.
  211. *
  212. * @return mixed Boolean true on success.
  213. *
  214. * @link http://docs.joomla.org/JTable/move
  215. * @since 11.1
  216. */
  217. public function move($delta, $where = '')
  218. {
  219. $k = $this->_tbl_key;
  220. $pk = $this->$k;
  221. $query = $this->_db->getQuery(true);
  222. $query->select($k);
  223. $query->from($this->_tbl);
  224. $query->where('parent_id = ' . $this->parent_id);
  225. if ($where)
  226. {
  227. $query->where($where);
  228. }
  229. $position = 'after';
  230. if ($delta > 0)
  231. {
  232. $query->where('rgt > ' . $this->rgt);
  233. $query->order('rgt ASC');
  234. $position = 'after';
  235. }
  236. else
  237. {
  238. $query->where('lft < ' . $this->lft);
  239. $query->order('lft DESC');
  240. $position = 'before';
  241. }
  242. $this->_db->setQuery($query);
  243. $referenceId = $this->_db->loadResult();
  244. if ($referenceId)
  245. {
  246. return $this->moveByReference($referenceId, $position, $pk);
  247. }
  248. else
  249. {
  250. return false;
  251. }
  252. }
  253. /**
  254. * Method to move a node and its children to a new location in the tree.
  255. *
  256. * @param integer $referenceId The primary key of the node to reference new location by.
  257. * @param string $position Location type string. ['before', 'after', 'first-child', 'last-child']
  258. * @param integer $pk The primary key of the node to move.
  259. *
  260. * @return boolean True on success.
  261. *
  262. * @link http://docs.joomla.org/JTableNested/moveByReference
  263. * @since 11.1
  264. * @throws RuntimeException on database error.
  265. */
  266. public function moveByReference($referenceId, $position = 'after', $pk = null)
  267. {
  268. // @codeCoverageIgnoreStart
  269. if ($this->_debug)
  270. {
  271. echo "\nMoving ReferenceId:$referenceId, Position:$position, PK:$pk";
  272. }
  273. // @codeCoverageIgnoreEnd
  274. $k = $this->_tbl_key;
  275. $pk = (is_null($pk)) ? $this->$k : $pk;
  276. // Get the node by id.
  277. if (!$node = $this->_getNode($pk))
  278. {
  279. // Error message set in getNode method.
  280. return false;
  281. }
  282. // Get the ids of child nodes.
  283. $query = $this->_db->getQuery(true);
  284. $query->select($k)
  285. ->from($this->_tbl)
  286. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  287. $children = $this->_db->setQuery($query)->loadColumn();
  288. // @codeCoverageIgnoreStart
  289. if ($this->_debug)
  290. {
  291. $this->_logtable(false);
  292. }
  293. // @codeCoverageIgnoreEnd
  294. // Cannot move the node to be a child of itself.
  295. if (in_array($referenceId, $children))
  296. {
  297. $e = new UnexpectedValueException(
  298. sprintf('%s::moveByReference(%d, %s, %d) parenting to child.', get_class($this), $referenceId, $position, $pk)
  299. );
  300. $this->setError($e);
  301. return false;
  302. }
  303. // Lock the table for writing.
  304. if (!$this->_lock())
  305. {
  306. return false;
  307. }
  308. /*
  309. * Move the sub-tree out of the nested sets by negating its left and right values.
  310. */
  311. $query = $this->_db->getQuery(true);
  312. $query->update($this->_tbl)
  313. ->set('lft = lft * (-1), rgt = rgt * (-1)')
  314. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  315. $this->_db->setQuery($query);
  316. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  317. /*
  318. * Close the hole in the tree that was opened by removing the sub-tree from the nested sets.
  319. */
  320. // Compress the left values.
  321. $query = $this->_db->getQuery(true);
  322. $query->update($this->_tbl)
  323. ->set('lft = lft - ' . (int) $node->width)
  324. ->where('lft > ' . (int) $node->rgt);
  325. $this->_db->setQuery($query);
  326. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  327. // Compress the right values.
  328. $query = $this->_db->getQuery(true);
  329. $query->update($this->_tbl)
  330. ->set('rgt = rgt - ' . (int) $node->width)
  331. ->where('rgt > ' . (int) $node->rgt);
  332. $this->_db->setQuery($query);
  333. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  334. // We are moving the tree relative to a reference node.
  335. if ($referenceId)
  336. {
  337. // Get the reference node by primary key.
  338. if (!$reference = $this->_getNode($referenceId))
  339. {
  340. // Error message set in getNode method.
  341. $this->_unlock();
  342. return false;
  343. }
  344. // Get the reposition data for shifting the tree and re-inserting the node.
  345. if (!$repositionData = $this->_getTreeRepositionData($reference, $node->width, $position))
  346. {
  347. // Error message set in getNode method.
  348. $this->_unlock();
  349. return false;
  350. }
  351. }
  352. // We are moving the tree to be the last child of the root node
  353. else
  354. {
  355. // Get the last root node as the reference node.
  356. $query = $this->_db->getQuery(true);
  357. $query->select($this->_tbl_key . ', parent_id, level, lft, rgt')
  358. ->from($this->_tbl)
  359. ->where('parent_id = 0')
  360. ->order('lft DESC');
  361. $this->_db->setQuery($query, 0, 1);
  362. $reference = $this->_db->loadObject();
  363. // @codeCoverageIgnoreStart
  364. if ($this->_debug)
  365. {
  366. $this->_logtable(false);
  367. }
  368. // @codeCoverageIgnoreEnd
  369. // Get the reposition data for re-inserting the node after the found root.
  370. if (!$repositionData = $this->_getTreeRepositionData($reference, $node->width, 'last-child'))
  371. {
  372. // Error message set in getNode method.
  373. $this->_unlock();
  374. return false;
  375. }
  376. }
  377. /*
  378. * Create space in the nested sets at the new location for the moved sub-tree.
  379. */
  380. // Shift left values.
  381. $query = $this->_db->getQuery(true);
  382. $query->update($this->_tbl)
  383. ->set('lft = lft + ' . (int) $node->width)
  384. ->where($repositionData->left_where);
  385. $this->_db->setQuery($query);
  386. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  387. // Shift right values.
  388. $query = $this->_db->getQuery(true);
  389. $query->update($this->_tbl)
  390. ->set('rgt = rgt + ' . (int) $node->width)
  391. ->where($repositionData->right_where);
  392. $this->_db->setQuery($query);
  393. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  394. /*
  395. * Calculate the offset between where the node used to be in the tree and
  396. * where it needs to be in the tree for left ids (also works for right ids).
  397. */
  398. $offset = $repositionData->new_lft - $node->lft;
  399. $levelOffset = $repositionData->new_level - $node->level;
  400. // Move the nodes back into position in the tree using the calculated offsets.
  401. $query = $this->_db->getQuery(true);
  402. $query->update($this->_tbl)
  403. ->set('rgt = ' . (int) $offset . ' - rgt')
  404. ->set('lft = ' . (int) $offset . ' - lft')
  405. ->set('level = level + ' . (int) $levelOffset)
  406. ->where('lft < 0');
  407. $this->_db->setQuery($query);
  408. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  409. // Set the correct parent id for the moved node if required.
  410. if ($node->parent_id != $repositionData->new_parent_id)
  411. {
  412. $query = $this->_db->getQuery(true);
  413. $query->update($this->_tbl);
  414. // Update the title and alias fields if they exist for the table.
  415. $fields = $this->getFields();
  416. if (property_exists($this, 'title') && $this->title !== null)
  417. {
  418. $query->set('title = ' . $this->_db->Quote($this->title));
  419. }
  420. if (array_key_exists('alias', $fields) && $this->alias !== null)
  421. {
  422. $query->set('alias = ' . $this->_db->Quote($this->alias));
  423. }
  424. $query->set('parent_id = ' . (int) $repositionData->new_parent_id)
  425. ->where($this->_tbl_key . ' = ' . (int) $node->$k);
  426. $this->_db->setQuery($query);
  427. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_MOVE_FAILED');
  428. }
  429. // Unlock the table for writing.
  430. $this->_unlock();
  431. // Set the object values.
  432. $this->parent_id = $repositionData->new_parent_id;
  433. $this->level = $repositionData->new_level;
  434. $this->lft = $repositionData->new_lft;
  435. $this->rgt = $repositionData->new_rgt;
  436. return true;
  437. }
  438. /**
  439. * Method to delete a node and, optionally, its child nodes from the table.
  440. *
  441. * @param integer $pk The primary key of the node to delete.
  442. * @param boolean $children True to delete child nodes, false to move them up a level.
  443. *
  444. * @return boolean True on success.
  445. *
  446. * @since 11.1
  447. */
  448. public function delete($pk = null, $children = true)
  449. {
  450. $k = $this->_tbl_key;
  451. $pk = (is_null($pk)) ? $this->$k : $pk;
  452. // Lock the table for writing.
  453. if (!$this->_lock())
  454. {
  455. // Error message set in lock method.
  456. return false;
  457. }
  458. // If tracking assets, remove the asset first.
  459. if ($this->_trackAssets)
  460. {
  461. $name = $this->_getAssetName();
  462. $asset = JTable::getInstance('Asset');
  463. // Lock the table for writing.
  464. if (!$asset->_lock())
  465. {
  466. // Error message set in lock method.
  467. return false;
  468. }
  469. if ($asset->loadByName($name))
  470. {
  471. // Delete the node in assets table.
  472. if (!$asset->delete(null, $children))
  473. {
  474. $this->setError($asset->getError());
  475. $asset->_unlock();
  476. return false;
  477. }
  478. $asset->_unlock();
  479. }
  480. else
  481. {
  482. $this->setError($asset->getError());
  483. $asset->_unlock();
  484. return false;
  485. }
  486. }
  487. // Get the node by id.
  488. $node = $this->_getNode($pk);
  489. if (empty($node))
  490. {
  491. // Error message set in getNode method.
  492. $this->_unlock();
  493. return false;
  494. }
  495. // Should we delete all children along with the node?
  496. if ($children)
  497. {
  498. // Delete the node and all of its children.
  499. $query = $this->_db->getQuery(true);
  500. $query->delete()
  501. ->from($this->_tbl)
  502. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  503. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  504. // Compress the left values.
  505. $query = $this->_db->getQuery(true);
  506. $query->update($this->_tbl)
  507. ->set('lft = lft - ' . (int) $node->width)
  508. ->where('lft > ' . (int) $node->rgt);
  509. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  510. // Compress the right values.
  511. $query = $this->_db->getQuery(true);
  512. $query->update($this->_tbl)
  513. ->set('rgt = rgt - ' . (int) $node->width)
  514. ->where('rgt > ' . (int) $node->rgt);
  515. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  516. }
  517. // Leave the children and move them up a level.
  518. else
  519. {
  520. // Delete the node.
  521. $query = $this->_db->getQuery(true);
  522. $query->delete()
  523. ->from($this->_tbl)
  524. ->where('lft = ' . (int) $node->lft);
  525. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  526. // Shift all node's children up a level.
  527. $query->clear()
  528. ->update($this->_tbl)
  529. ->set('lft = lft - 1')
  530. ->set('rgt = rgt - 1')
  531. ->set('level = level - 1')
  532. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  533. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  534. // Adjust all the parent values for direct children of the deleted node.
  535. $query->clear()
  536. ->update($this->_tbl)
  537. ->set('parent_id = ' . (int) $node->parent_id)
  538. ->where('parent_id = ' . (int) $node->$k);
  539. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  540. // Shift all of the left values that are right of the node.
  541. $query->clear()
  542. ->update($this->_tbl)
  543. ->set('lft = lft - 2')
  544. ->where('lft > ' . (int) $node->rgt);
  545. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  546. // Shift all of the right values that are right of the node.
  547. $query->clear()
  548. ->update($this->_tbl)
  549. ->set('rgt = rgt - 2')
  550. ->where('rgt > ' . (int) $node->rgt);
  551. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
  552. }
  553. // Unlock the table for writing.
  554. $this->_unlock();
  555. return true;
  556. }
  557. /**
  558. * Checks that the object is valid and able to be stored.
  559. *
  560. * This method checks that the parent_id is non-zero and exists in the database.
  561. * Note that the root node (parent_id = 0) cannot be manipulated with this class.
  562. *
  563. * @return boolean True if all checks pass.
  564. *
  565. * @since 11.1
  566. * @throws RuntimeException on database error.
  567. */
  568. public function check()
  569. {
  570. $this->parent_id = (int) $this->parent_id;
  571. // Set up a mini exception handler.
  572. try
  573. {
  574. // Check that the parent_id field is valid.
  575. if ($this->parent_id == 0)
  576. {
  577. throw new UnexpectedValueException(sprintf('Invalid `parent_id` [%d] in %s', $this->parent_id, get_class($this)));
  578. }
  579. $query = $this->_db->getQuery(true);
  580. $query->select('COUNT(' . $this->_tbl_key . ')')
  581. ->from($this->_tbl)
  582. ->where($this->_tbl_key . ' = ' . $this->parent_id);
  583. if (!$this->_db->setQuery($query)->loadResult())
  584. {
  585. throw new UnexpectedValueException(sprintf('Invalid `parent_id` [%d] in %s', $this->parent_id, get_class($this)));
  586. }
  587. }
  588. catch (UnexpectedValueException $e)
  589. {
  590. // Validation error - record it and return false.
  591. $this->setError($e);
  592. return false;
  593. }
  594. // @codeCoverageIgnoreStart
  595. catch (Exception $e)
  596. {
  597. // Database error - rethrow.
  598. throw $e;
  599. }
  600. // @codeCoverageIgnoreEnd
  601. return true;
  602. }
  603. /**
  604. * Method to store a node in the database table.
  605. *
  606. * @param boolean $updateNulls True to update null values as well.
  607. *
  608. * @return boolean True on success.
  609. *
  610. * @link http://docs.joomla.org/JTableNested/store
  611. * @since 11.1
  612. */
  613. public function store($updateNulls = false)
  614. {
  615. $k = $this->_tbl_key;
  616. // @codeCoverageIgnoreStart
  617. if ($this->_debug)
  618. {
  619. echo "\n" . get_class($this) . "::store\n";
  620. $this->_logtable(true, false);
  621. }
  622. // @codeCoverageIgnoreEnd
  623. /*
  624. * If the primary key is empty, then we assume we are inserting a new node into the
  625. * tree. From this point we would need to determine where in the tree to insert it.
  626. */
  627. if (empty($this->$k))
  628. {
  629. /*
  630. * We are inserting a node somewhere in the tree with a known reference
  631. * node. We have to make room for the new node and set the left and right
  632. * values before we insert the row.
  633. */
  634. if ($this->_location_id >= 0)
  635. {
  636. // Lock the table for writing.
  637. if (!$this->_lock())
  638. {
  639. // Error message set in lock method.
  640. return false;
  641. }
  642. // We are inserting a node relative to the last root node.
  643. if ($this->_location_id == 0)
  644. {
  645. // Get the last root node as the reference node.
  646. $query = $this->_db->getQuery(true);
  647. $query->select($this->_tbl_key . ', parent_id, level, lft, rgt')
  648. ->from($this->_tbl)
  649. ->where('parent_id = 0')
  650. ->order('lft DESC');
  651. $this->_db->setQuery($query, 0, 1);
  652. $reference = $this->_db->loadObject();
  653. // @codeCoverageIgnoreStart
  654. if ($this->_debug)
  655. {
  656. $this->_logtable(false);
  657. }
  658. // @codeCoverageIgnoreEnd
  659. }
  660. // We have a real node set as a location reference.
  661. else
  662. {
  663. // Get the reference node by primary key.
  664. if (!$reference = $this->_getNode($this->_location_id))
  665. {
  666. // Error message set in getNode method.
  667. $this->_unlock();
  668. return false;
  669. }
  670. }
  671. // Get the reposition data for shifting the tree and re-inserting the node.
  672. if (!($repositionData = $this->_getTreeRepositionData($reference, 2, $this->_location)))
  673. {
  674. // Error message set in getNode method.
  675. $this->_unlock();
  676. return false;
  677. }
  678. // Create space in the tree at the new location for the new node in left ids.
  679. $query = $this->_db->getQuery(true);
  680. $query->update($this->_tbl)
  681. ->set('lft = lft + 2')
  682. ->where($repositionData->left_where);
  683. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_STORE_FAILED');
  684. // Create space in the tree at the new location for the new node in right ids.
  685. $query = $this->_db->getQuery(true);
  686. $query->update($this->_tbl)
  687. ->set('rgt = rgt + 2')
  688. ->where($repositionData->right_where);
  689. $this->_runQuery($query, 'JLIB_DATABASE_ERROR_STORE_FAILED');
  690. // Set the object values.
  691. $this->parent_id = $repositionData->new_parent_id;
  692. $this->level = $repositionData->new_level;
  693. $this->lft = $repositionData->new_lft;
  694. $this->rgt = $repositionData->new_rgt;
  695. }
  696. else
  697. {
  698. // Negative parent ids are invalid
  699. $e = new UnexpectedValueException(sprintf('%s::store() used a negative _location_id', get_class($this)));
  700. $this->setError($e);
  701. return false;
  702. }
  703. }
  704. /*
  705. * If we have a given primary key then we assume we are simply updating this
  706. * node in the tree. We should assess whether or not we are moving the node
  707. * or just updating its data fields.
  708. */
  709. else
  710. {
  711. // If the location has been set, move the node to its new location.
  712. if ($this->_location_id > 0)
  713. {
  714. if (!$this->moveByReference($this->_location_id, $this->_location, $this->$k))
  715. {
  716. // Error message set in move method.
  717. return false;
  718. }
  719. }
  720. // Lock the table for writing.
  721. if (!$this->_lock())
  722. {
  723. // Error message set in lock method.
  724. return false;
  725. }
  726. }
  727. // Store the row to the database.
  728. if (!parent::store($updateNulls))
  729. {
  730. $this->_unlock();
  731. return false;
  732. }
  733. // @codeCoverageIgnoreStart
  734. if ($this->_debug)
  735. {
  736. $this->_logtable();
  737. }
  738. // @codeCoverageIgnoreEnd
  739. // Unlock the table for writing.
  740. $this->_unlock();
  741. return true;
  742. }
  743. /**
  744. * Method to set the publishing state for a node or list of nodes in the database
  745. * table. The method respects rows checked out by other users and will attempt
  746. * to checkin rows that it can after adjustments are made. The method will not
  747. * allow you to set a publishing state higher than any ancestor node and will
  748. * not allow you to set a publishing state on a node with a checked out child.
  749. *
  750. * @param mixed $pks An optional array of primary key values to update. If not
  751. * set the instance property value is used.
  752. * @param integer $state The publishing state. eg. [0 = unpublished, 1 = published]
  753. * @param integer $userId The user id of the user performing the operation.
  754. *
  755. * @return boolean True on success.
  756. *
  757. * @link http://docs.joomla.org/JTableNested/publish
  758. * @since 11.1
  759. */
  760. public function publish($pks = null, $state = 1, $userId = 0)
  761. {
  762. $k = $this->_tbl_key;
  763. // Sanitize input.
  764. JArrayHelper::toInteger($pks);
  765. $userId = (int) $userId;
  766. $state = (int) $state;
  767. // If $state > 1, then we allow state changes even if an ancestor has lower state
  768. // (for example, can change a child state to Archived (2) if an ancestor is Published (1)
  769. $compareState = ($state > 1) ? 1 : $state;
  770. // If there are no primary keys set check to see if the instance key is set.
  771. if (empty($pks))
  772. {
  773. if ($this->$k)
  774. {
  775. $pks = explode(',', $this->$k);
  776. }
  777. // Nothing to set publishing state on, return false.
  778. else
  779. {
  780. $e = new UnexpectedValueException(sprintf('%s::publish(%s, %d, %d) empty.', get_class($this), $pks, $state, $userId));
  781. $this->setError($e);
  782. return false;
  783. }
  784. }
  785. // Determine if there is checkout support for the table.
  786. $checkoutSupport = (property_exists($this, 'checked_out') || property_exists($this, 'checked_out_time'));
  787. // Iterate over the primary keys to execute the publish action if possible.
  788. foreach ($pks as $pk)
  789. {
  790. // Get the node by primary key.
  791. if (!$node = $this->_getNode($pk))
  792. {
  793. // Error message set in getNode method.
  794. return false;
  795. }
  796. // If the table has checkout support, verify no children are checked out.
  797. if ($checkoutSupport)
  798. {
  799. // Ensure that children are not checked out.
  800. $query = $this->_db->getQuery(true);
  801. $query->select('COUNT(' . $k . ')');
  802. $query->from($this->_tbl);
  803. $query->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  804. $query->where('(checked_out <> 0 AND checked_out <> ' . (int) $userId . ')');
  805. $this->_db->setQuery($query);
  806. // Check for checked out children.
  807. if ($this->_db->loadResult())
  808. {
  809. // TODO Convert to a conflict exception when available.
  810. $e = new RuntimeException(sprintf('%s::publish(%s, %d, %d) checked-out conflict.', get_class($this), $pks, $state, $userId));
  811. $this->setError($e);
  812. return false;
  813. }
  814. }
  815. // If any parent nodes have lower published state values, we cannot continue.
  816. if ($node->parent_id)
  817. {
  818. // Get any ancestor nodes that have a lower publishing state.
  819. $query = $this->_db->getQuery(true)->select('n.' . $k)->from($this->_db->quoteName($this->_tbl) . ' AS n')
  820. ->where('n.lft < ' . (int) $node->lft)->where('n.rgt > ' . (int) $node->rgt)->where('n.parent_id > 0')
  821. ->where('n.published < ' . (int) $compareState);
  822. // Just fetch one row (one is one too many).
  823. $this->_db->setQuery($query, 0, 1);
  824. $rows = $this->_db->loadColumn();
  825. if (!empty($rows))
  826. {
  827. $e = new UnexpectedValueException(
  828. sprintf('%s::publish(%s, %d, %d) ancestors have lower state.', get_class($this), $pks, $state, $userId)
  829. );
  830. $this->setError($e);
  831. return false;
  832. }
  833. }
  834. // Update and cascade the publishing state.
  835. $query = $this->_db->getQuery(true)->update($this->_db->quoteName($this->_tbl))->set('published = ' . (int) $state)
  836. ->where('(lft > ' . (int) $node->lft . ' AND rgt < ' . (int) $node->rgt . ')' . ' OR ' . $k . ' = ' . (int) $pk);
  837. $this->_db->setQuery($query)->execute();
  838. // If checkout support exists for the object, check the row in.
  839. if ($checkoutSupport)
  840. {
  841. $this->checkin($pk);
  842. }
  843. }
  844. // If the JTable instance value is in the list of primary keys that were set, set the instance.
  845. if (in_array($this->$k, $pks))
  846. {
  847. $this->published = $state;
  848. }
  849. $this->setError('');
  850. return true;
  851. }
  852. /**
  853. * Method to move a node one position to the left in the same level.
  854. *
  855. * @param integer $pk Primary key of the node to move.
  856. *
  857. * @return boolean True on success.
  858. *
  859. * @since 11.1
  860. * @throws RuntimeException on database error.
  861. */
  862. public function orderUp($pk)
  863. {
  864. $k = $this->_tbl_key;
  865. $pk = (is_null($pk)) ? $this->$k : $pk;
  866. // Lock the table for writing.
  867. if (!$this->_lock())
  868. {
  869. // Error message set in lock method.
  870. return false;
  871. }
  872. // Get the node by primary key.
  873. $node = $this->_getNode($pk);
  874. if (empty($node))
  875. {
  876. // Error message set in getNode method.
  877. $this->_unlock();
  878. return false;
  879. }
  880. // Get the left sibling node.
  881. $sibling = $this->_getNode($node->lft - 1, 'right');
  882. if (empty($sibling))
  883. {
  884. // Error message set in getNode method.
  885. $this->_unlock();
  886. return false;
  887. }
  888. try
  889. {
  890. // Get the primary keys of child nodes.
  891. $query = $this->_db->getQuery(true);
  892. $query->select($this->_tbl_key)
  893. ->from($this->_tbl)
  894. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  895. $children = $this->_db->setQuery($query)->loadColumn();
  896. // Shift left and right values for the node and its children.
  897. $query->clear()
  898. ->update($this->_tbl)
  899. ->set('lft = lft - ' . (int) $sibling->width)
  900. ->set('rgt = rgt - ' . (int) $sibling->width)
  901. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  902. $this->_db->setQuery($query)->execute();
  903. // Shift left and right values for the sibling and its children.
  904. $query->clear()
  905. ->update($this->_tbl)
  906. ->set('lft = lft + ' . (int) $node->width)
  907. ->set('rgt = rgt + ' . (int) $node->width)
  908. ->where('lft BETWEEN ' . (int) $sibling->lft . ' AND ' . (int) $sibling->rgt)
  909. ->where($this->_tbl_key . ' NOT IN (' . implode(',', $children) . ')');
  910. $this->_db->setQuery($query)->execute();
  911. }
  912. catch (RuntimeException $e)
  913. {
  914. $this->_unlock();
  915. throw $e;
  916. }
  917. // Unlock the table for writing.
  918. $this->_unlock();
  919. return true;
  920. }
  921. /**
  922. * Method to move a node one position to the right in the same level.
  923. *
  924. * @param integer $pk Primary key of the node to move.
  925. *
  926. * @return boolean True on success.
  927. *
  928. * @since 11.1
  929. * @throws RuntimeException on database error.
  930. */
  931. public function orderDown($pk)
  932. {
  933. $k = $this->_tbl_key;
  934. $pk = (is_null($pk)) ? $this->$k : $pk;
  935. // Lock the table for writing.
  936. if (!$this->_lock())
  937. {
  938. // Error message set in lock method.
  939. return false;
  940. }
  941. // Get the node by primary key.
  942. $node = $this->_getNode($pk);
  943. if (empty($node))
  944. {
  945. // Error message set in getNode method.
  946. $this->_unlock();
  947. return false;
  948. }
  949. $query = $this->_db->getQuery(true);
  950. // Get the right sibling node.
  951. $sibling = $this->_getNode($node->rgt + 1, 'left');
  952. if (empty($sibling))
  953. {
  954. // Error message set in getNode method.
  955. $query->_unlock($this->_db);
  956. $this->_locked = false;
  957. return false;
  958. }
  959. try
  960. {
  961. // Get the primary keys of child nodes.
  962. $query->clear()
  963. ->select($this->_tbl_key)
  964. ->from($this->_tbl)
  965. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  966. $this->_db->setQuery($query);
  967. $children = $this->_db->loadColumn();
  968. // Shift left and right values for the node and its children.
  969. $query->clear()
  970. ->update($this->_tbl)
  971. ->set('lft = lft + ' . (int) $sibling->width)
  972. ->set('rgt = rgt + ' . (int) $sibling->width)
  973. ->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
  974. $this->_db->setQuery($query)->execute();
  975. // Shift left and right values for the sibling and its children.
  976. $query->clear()
  977. ->update($this->_tbl)
  978. ->set('lft = lft - ' . (int) $node->width)
  979. ->set('rgt = rgt - ' . (int) $node->width)
  980. ->where('lft BETWEEN ' . (int) $sibling->lft . ' AND ' . (int) $sibling->rgt)
  981. ->where($this->_tbl_key . ' NOT IN (' . implode(',', $children) . ')');
  982. $this->_db->setQuery($query)->execute();
  983. }
  984. catch (RuntimeException $e)
  985. {
  986. $this->_unlock();
  987. throw $e;
  988. }
  989. // Unlock the table for writing.
  990. $this->_unlock();
  991. return true;
  992. }
  993. /**
  994. * Gets the ID of the root item in the tree
  995. *
  996. * @return mixed The primary id of the root row, or false if not found and the internal error is set.
  997. *
  998. * @since 11.1
  999. */
  1000. public function getRootId()
  1001. {
  1002. // Get the root item.
  1003. $k = $this->_tbl_key;
  1004. // Test for a unique record with parent_id = 0
  1005. $query = $this->_db->getQuery(true);
  1006. $query->select($k)
  1007. ->from($this->_tbl)
  1008. ->where('parent_id = 0');
  1009. $result = $this->_db->setQuery($query)->loadColumn();
  1010. if (count($result) == 1)
  1011. {
  1012. return $result[0];
  1013. }
  1014. // Test for a unique record with lft = 0
  1015. $query = $this->_db->getQuery(true);
  1016. $query->select($k)
  1017. ->from($this->_tbl)
  1018. ->where('lft = 0');
  1019. $result = $this->_db->setQuery($query)->loadColumn();
  1020. if (count($result) == 1)
  1021. {
  1022. return $result[0];
  1023. }
  1024. $fields = $this->getFields();
  1025. if (array_key_exists('alias', $fields))
  1026. {
  1027. // Test for a unique record alias = root
  1028. $query = $this->_db->getQuery(true);
  1029. $query->select($k)
  1030. ->from($this->_tbl)
  1031. ->where('alias = ' . $this->_db->quote('root'));
  1032. $result = $this->_db->setQuery($query)->loadColumn();
  1033. if (count($result) == 1)
  1034. {
  1035. return $result[0];
  1036. }
  1037. }
  1038. $e = new UnexpectedValueException(sprintf('%s::getRootId', get_class($this)));
  1039. $this->setError($e);
  1040. return false;
  1041. }
  1042. /**
  1043. * Method to recursively rebuild the whole nested set tree.
  1044. *
  1045. * @param integer $parentId The root of the tree to rebuild.
  1046. * @param integer $leftId The left id to start with in building the tree.
  1047. * @param integer $level The level to assign to the current nodes.
  1048. * @param string $path The path to the current nodes.
  1049. *
  1050. * @return integer 1 + value of root rgt on success, false on failure
  1051. *
  1052. * @link http://docs.joomla.org/JTableNested/rebuild
  1053. * @since 11.1
  1054. * @throws RuntimeException on database error.
  1055. */
  1056. public function rebuild($parentId = null, $leftId = 0, $level = 0, $path = '')
  1057. {
  1058. // If no parent is provided, try to find it.
  1059. if ($parentId === null)
  1060. {
  1061. // Get the root item.
  1062. $parentId = $this->getRootId();
  1063. if ($parentId === false)
  1064. {
  1065. return false;
  1066. }
  1067. }
  1068. // Build the structure of the recursive query.
  1069. if (!isset($this->_cache['rebuild.sql']))
  1070. {
  1071. $query = $this->_db->getQuery(true);
  1072. $query->select($this->_tbl_key . ', alias')
  1073. ->from($this->_tbl)
  1074. ->where('parent_id = %d');
  1075. // If the table has an ordering field, use that for ordering.
  1076. if (property_exists($this, 'ordering'))
  1077. {
  1078. $query->order('parent_id, ordering, lft');
  1079. }
  1080. else
  1081. {
  1082. $query->order('parent_id, lft');
  1083. }
  1084. $this->_cache['rebuild.sql'] = (string) $query;
  1085. }
  1086. // Make a shortcut to database object.
  1087. // Assemble the query to find all children of this node.
  1088. $this->_db->setQuery(sprintf($this->_cache['rebuild.sql'], (int) $parentId));
  1089. $children = $this->_db->loadObjectList();
  1090. // The right value of this node is the left value + 1
  1091. $rightId = $leftId + 1;
  1092. // Execute this function recursively over all children
  1093. foreach ($children as $node)
  1094. {
  1095. /*
  1096. * $rightId is the current right value, which is incremented on recursion return.
  1097. * Increment the level for the children.
  1098. * Add this item's alias to the path (but avoid a leading /)
  1099. */
  1100. $rightId = $this->rebuild($node->{$this->_tbl_key}, $rightId, $level + 1, $path . (empty($path) ? '' : '/') . $node->alias);
  1101. // If there is an update failure, return false to break out of the recursion.
  1102. if ($rightId === false)
  1103. {
  1104. return false;
  1105. }
  1106. }
  1107. // We've got the left value, and now that we've processed
  1108. // the children of this node we also know the right value.
  1109. $query = $this->_db->getQuery(true);
  1110. $query->update($this->_tbl)
  1111. ->set('lft = ' . (int) $leftId)
  1112. ->set('rgt = ' . (int) $rightId)
  1113. ->set('level = ' . (int) $level)
  1114. ->set('path = ' . $this->_db->quote($path))
  1115. ->where($this->_tbl_key . ' = ' . (int) $parentId);
  1116. $this->_db->setQuery($query)->execute();
  1117. // Return the right value of this node + 1.
  1118. return $rightId + 1;
  1119. }
  1120. /**
  1121. * Method to rebuild the node's path field from the alias values of the
  1122. * nodes from the current node to the root node of the tree.
  1123. *
  1124. * @param integer $pk Primary key of the node for which to get the path.
  1125. *
  1126. * @return boolean True on success.
  1127. *
  1128. * @link http://docs.joomla.org/JTableNested/rebuildPath
  1129. * @since 11.1
  1130. */
  1131. public function rebuildPath($pk = null)
  1132. {
  1133. $fields = $this->getFields();
  1134. // If there is no alias or path field, just return true.
  1135. if (!array_key_exists('alias', $fields) || !array_key_exists('path', $fields))
  1136. {
  1137. return true;
  1138. }
  1139. $k = $this->_tbl_key;
  1140. $pk = (is_null($pk)) ? $this->$k : $pk;
  1141. // Get the aliases for the path from the node to the root node.
  1142. $query = $this->_db->getQuery(true);
  1143. $query->select('p.alias');
  1144. $query->from($this->_tbl . ' AS n, ' . $this->_tbl . ' AS p');
  1145. $query->where('n.lft BETWEEN p.lft AND p.rgt');
  1146. $query->where('n.' . $this->_tbl_key . ' = ' . (int) $pk);
  1147. $query->order('p.lft');
  1148. $this->_db->setQuery($query);
  1149. $segments = $this->_db->loadColumn();
  1150. // Make sure to remove the root path if it exists in the list.
  1151. if ($segments[0] == 'root')
  1152. {
  1153. array_shift($segments);
  1154. }
  1155. // Build the path.
  1156. $path = trim(implode('/', $segments), ' /\\');
  1157. // Update the path field for the node.
  1158. $query = $this->_db->getQuery(true);
  1159. $query->update($this->_tbl);
  1160. $query->set('path = ' . $this->_db->quote($path));
  1161. $query->where($this->_tbl_key . ' = ' . (int) $pk);
  1162. $this->_db->setQuery($query)->execute();
  1163. // Update the current record's path to the new one:
  1164. $this->path = $path;
  1165. return true;
  1166. }
  1167. /**
  1168. * Method to update order of table rows
  1169. *
  1170. * @param array $idArray id numbers of rows to be reordered.
  1171. * @param array $lft_array lft values of rows to be reordered.
  1172. *
  1173. * @return integer 1 + value of root rgt on success, false on failure.
  1174. *
  1175. * @since 11.1
  1176. * @throws RuntimeException on database error.
  1177. */
  1178. public function saveorder($idArray = null, $lft_array = null)
  1179. {
  1180. try
  1181. {
  1182. $query = $this->_db->getQuery(true);
  1183. // Validate arguments
  1184. if (is_array($idArray) && is_array($lft_array) && count($idArray) == count($lft_array))
  1185. {
  1186. for ($i = 0, $count = count($idArray); $i < $count; $i++)
  1187. {
  1188. // Do an update to change the lft values in the table for each id
  1189. $query->clear()
  1190. ->update($this->_tbl)
  1191. ->where($this->_tbl_key . ' = ' . (int) $idArray[$i])
  1192. ->set('lft = ' . (int) $lft_array[$i]);
  1193. $this->_db->setQuery($query)->execute();
  1194. // @codeCoverageIgnoreStart
  1195. if ($this->_debug)
  1196. {
  1197. $this->_logtable();
  1198. }
  1199. // @codeCoverageIgnoreEnd
  1200. }
  1201. return $this->rebuild();
  1202. }
  1203. else
  1204. {
  1205. return false;
  1206. }
  1207. }
  1208. catch (Exception $e)
  1209. {
  1210. $this->_unlock();
  1211. throw $e;
  1212. }
  1213. }
  1214. /**
  1215. * Method to get nested set properties for a node in the tree.
  1216. *
  1217. * @param integer $id Value to look up the node by.
  1218. * @param string $key An optional key to look up the node by (parent | left | right).
  1219. * If omitted, the primary key of the table is used.
  1220. *
  1221. * @return mixed Boolean false on failure or node object on success.
  1222. *
  1223. * @since 11.1
  1224. * @throws RuntimeException on database error.
  1225. */
  1226. protected function _getNode($id, $key = null)
  1227. {
  1228. // Determine which key to get the node base on.
  1229. switch ($key)
  1230. {
  1231. case 'parent':
  1232. $k = 'parent_id';
  1233. break;
  1234. case 'left':
  1235. $k = 'lft';
  1236. break;
  1237. case 'right':
  1238. $k = 'rgt';
  1239. break;
  1240. default:
  1241. $k = $this->_tbl_key;
  1242. break;
  1243. }
  1244. // Get the node data.
  1245. $query = $this->_db->getQuery(true);
  1246. $query->select($this->_tbl_key . ', parent_id, level, lft, rgt')
  1247. ->from($this->_tbl)
  1248. ->where($k . ' = ' . (int) $id);
  1249. $row = $this->_db->setQuery($query, 0, 1)->loadObject();
  1250. // Check for no $row returned
  1251. if (empty($row))
  1252. {
  1253. $e = new UnexpectedValueException(sprintf('%s::_getNode(%d, %s) failed.', get_class($this), $id, $key));
  1254. $this->setError($e);
  1255. return false;
  1256. }
  1257. // Do some simple calculations.
  1258. $row->numChildren = (int) ($row->rgt - $row->lft - 1) / 2;
  1259. $row->width = (int) $row->rgt - $row->lft + 1;
  1260. return $row;
  1261. }
  1262. /**
  1263. * Method to get various data necessary to make room in the tree at a location
  1264. * for a node and its children. The returned data object includes conditions
  1265. * for SQL WHERE clauses for updating left and right id values to make room for
  1266. * the node as well as the new left and right ids for the node.
  1267. *
  1268. * @param object $referenceNode A node object with at least a 'lft' and 'rgt' with
  1269. * which to make room in the tree around for a new node.
  1270. * @param integer $nodeWidth The width of the node for which to make room in the tree.
  1271. * @param string $position The position relative to the reference node where the room
  1272. * should be made.
  1273. *
  1274. * @return mixed Boolean false on failure or data object on success.
  1275. *
  1276. * @since 11.1
  1277. */
  1278. protected function _getTreeRepositionData($referenceNode, $nodeWidth, $position = 'before')
  1279. {
  1280. // Make sure the reference an object with a left and right id.
  1281. if (!is_object($referenceNode) || !(isset($referenceNode->lft) && isset($referenceNode->rgt)))
  1282. {
  1283. return false;
  1284. }
  1285. // A valid node cannot have a width less than 2.
  1286. if ($nodeWidth < 2)
  1287. {
  1288. return false;
  1289. }
  1290. $k = $this->_tbl_key;
  1291. $data = new stdClass;
  1292. // Run the calculations and build the data object by reference position.
  1293. switch ($position)
  1294. {
  1295. case 'first-child':
  1296. $data->left_where = 'lft > ' . $referenceNode->lft;
  1297. $data->right_where = 'rgt >= ' . $referenceNode->lft;
  1298. $data->new_lft = $referenceNode->lft + 1;
  1299. $data->new_rgt = $referenceNode->lft + $nodeWidth;
  1300. $data->new_parent_id = $referenceNode->$k;
  1301. $data->new_level = $referenceNode->level + 1;
  1302. break;
  1303. case 'last-child':
  1304. $data->left_where = 'lft > ' . ($referenceNode->rgt);
  1305. $data->right_where = 'rgt >= ' . ($referenceNode->rgt);
  1306. $data->new_lft = $referenceNode->rgt;
  1307. $data->new_rgt = $referenceNode->rgt + $nodeWidth - 1;
  1308. $data->new_parent_id = $referenceNode->$k;
  1309. $data->new_level = $referenceNode->level + 1;
  1310. break;
  1311. case 'before':
  1312. $data->left_where = 'lft >= ' . $referenceNode->lft;
  1313. $data->right_where = 'rgt >= ' . $referenceNode->lft;
  1314. $data->new_lft = $referenceNode->lft;
  1315. $data->new_rgt = $referenceNode->lft + $nodeWidth - 1;
  1316. $data->new_parent_id = $referenceNode->parent_id;
  1317. $data->new_level = $referenceNode->level;
  1318. break;
  1319. default:
  1320. case 'after':
  1321. $data->left_where = 'lft > ' . $referenceNode->rgt;
  1322. $data->right_where = 'rgt > ' . $referenceNode->rgt;
  1323. $data->new_lft = $referenceNode->rgt + 1;
  1324. $data->new_rgt = $referenceNode->rgt + $nodeWidth;
  1325. $data->new_parent_id = $referenceNode->parent_id;
  1326. $data->new_level = $referenceNode->level;
  1327. break;
  1328. }
  1329. // @codeCoverageIgnoreStart
  1330. if ($this->_debug)
  1331. {
  1332. echo "\nRepositioning Data for $position" . "\n-----------------------------------" . "\nLeft Where: $data->left_where"
  1333. . "\nRight Where: $data->right_where" . "\nNew Lft: $data->new_lft" . "\nNew Rgt: $data->new_rgt"
  1334. . "\nNew Parent ID: $data->new_parent_id" . "\nNew Level: $data->new_level" . "\n";
  1335. }
  1336. // @codeCoverageIgnoreEnd
  1337. return $data;
  1338. }
  1339. /**
  1340. * Method to create a log table in the buffer optionally showing the query and/or data.
  1341. *
  1342. * @param boolean $showData True to show data
  1343. * @param boolean $showQuery True to show query
  1344. *
  1345. * @return void
  1346. *
  1347. * @codeCoverageIgnore
  1348. * @since 11.1
  1349. */
  1350. protected function _logtable($showData = true, $showQuery = true)
  1351. {
  1352. $sep = "\n" . str_pad('', 40, '-');
  1353. $buffer = '';
  1354. if ($showQuery)
  1355. {
  1356. $buffer .= "\n" . $this->_db->getQuery() . $sep;
  1357. }
  1358. if ($showData)
  1359. {
  1360. $query = $this->_db->getQuery(true);
  1361. $query->select($this->_tbl_key . ', parent_id, lft, rgt, level');
  1362. $query->from($this->_tbl);
  1363. $query->order($this->_tbl_key);
  1364. $this->_db->setQuery($query);
  1365. $rows = $this->_db->loadRowList();
  1366. $buffer .= sprintf("\n| %4s | %4s | %4s | %4s |", $this->_tbl_key, 'par', 'lft', 'rgt');
  1367. $buffer .= $sep;
  1368. foreach ($rows as $row)
  1369. {
  1370. $buffer .= sprintf("\n| %4s | %4s | %4s | %4s |", $row[0], $row[1], $row[2], $row[3]);
  1371. }
  1372. $buffer .= $sep;
  1373. }
  1374. echo $buffer;
  1375. }
  1376. /**
  1377. * Runs a query and unlocks the database on an error.
  1378. *
  1379. * @param mixed $query A string or JDatabaseQuery object.
  1380. * @param string $errorMessage Unused.
  1381. *
  1382. * @return boolean void
  1383. *
  1384. * @note Since 12.1 this method returns void and will rethrow the database exception.
  1385. * @since 11.1
  1386. * @throws RuntimeException on database error.
  1387. */
  1388. protected function _runQuery($query, $errorMessage)
  1389. {
  1390. // Prepare to catch an exception.
  1391. try
  1392. {
  1393. $this->_db->setQuery($query)->execute();
  1394. // @codeCoverageIgnoreStart
  1395. if ($this->_debug)
  1396. {
  1397. $this->_logtable();
  1398. }
  1399. // @codeCoverageIgnoreEnd
  1400. }
  1401. catch (Exception $e)
  1402. {
  1403. // Unlock the tables and rethrow.
  1404. $this->_unlock();
  1405. throw $e;
  1406. }
  1407. }
  1408. }