DB_NestedSet
[ class tree: DB_NestedSet ] [ index: DB_NestedSet ] [ all elements ]

Source for file NestedSet.php

Documentation is available at NestedSet.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PEAR :: DB_NestedSet                                                 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1997-2003 The PHP Group                                |
  6. // +----------------------------------------------------------------------+
  7. // | This source file is subject to version 2.0 of the PHP license,       |
  8. // | that is bundled with this package in the file LICENSE, and is        |
  9. // | available at through the world-wide-web at                           |
  10. // | http://www.php.net/license/2_02.txt.                                 |
  11. // | If you did not receive a copy of the PHP license and are unable to   |
  12. // | obtain it through the world-wide-web, please send a note to          |
  13. // | license@php.net so we can mail you a copy immediately.               |
  14. // +----------------------------------------------------------------------+
  15. // | Authors: Daniel Khan <dk@webcluster.at>                              |
  16. // |          Jason Rust  <jason@rustyparts.com>                          |
  17. // +----------------------------------------------------------------------+
  18. // $Id: NestedSet.php,v 1.83 2004/07/25 11:55:22 datenpunk Exp $
  19. // CREDITS:
  20. // --------
  21. // - Thanks to Kristian Koehntopp for publishing an explanation of the Nested Set
  22. // technique and for the great work he did and does for the php community
  23. // - Thanks to Daniel T. Gorski for his great tutorial on www.develnet.org
  24. // - Thanks to my parents for ... just kidding :]
  25. require_once 'PEAR.php';
  26. // {{{ constants
  27. // Error and message codes
  28. define('NESE_ERROR_RECURSION''E100');
  29. define('NESE_ERROR_NODRIVER''E200');
  30. define('NESE_ERROR_NOHANDLER''E300');
  31. define('NESE_ERROR_TBLOCKED''E010');
  32. define('NESE_MESSAGE_UNKNOWN''E0');
  33. define('NESE_ERROR_NOTSUPPORTED''E1');
  34. define('NESE_ERROR_PARAM_MISSING''E400');
  35. define('NESE_ERROR_NOT_FOUND''E500');
  36. define('NESE_ERROR_WRONG_MPARAM''E2');
  37. // for moving a node before another
  38. define('NESE_MOVE_BEFORE''BE');
  39. // for moving a node after another
  40. define('NESE_MOVE_AFTER''AF');
  41. // for moving a node below another
  42. define('NESE_MOVE_BELOW''SUB');
  43. // Sortorders
  44. define('NESE_SORT_LEVEL''SLV');
  45. define('NESE_SORT_PREORDER''SPO');
  46. // }}}
  47. // {{{ DB_NestedSet:: class
  48. /**
  49. * DB_NestedSet is a class for handling nested sets
  50. *
  51. @author Daniel Khan <dk@webcluster.at>
  52. @package DB_NestedSet
  53. @version $Revision: 1.83 $
  54. @access public
  55. */
  56. // }}}
  57. class DB_NestedSet {
  58.     // {{{ properties
  59.     /**
  60.     *
  61.     * @var array The field parameters of the table with the nested set. Format: 'realFieldName' => 'fieldId'
  62.     * @access public
  63.     */
  64.     var $params = array('STRID' => 'id',
  65.     'ROOTID' => 'rootid',
  66.     'l' => 'l',
  67.     'r' => 'r',
  68.     'STREH' => 'norder',
  69.     'LEVEL' => 'level',
  70.     // 'parent'=>'parent', // Optional but very useful
  71.     'STRNA' => 'name'
  72.     );
  73.     // To be used with 2.0 - would be an api break atm
  74.     // var $quotedParams = array('name');
  75.     /**
  76.     *
  77.     * @var string The table with the actual tree data
  78.     * @access public
  79.     */
  80.     var $node_table = 'tb_nodes';
  81.  
  82.     /**
  83.     *
  84.     * @var string The table to handle locking
  85.     * @access public
  86.     */
  87.     var $lock_table = 'tb_locks';
  88.  
  89.     /**
  90.     *
  91.     * @var string The table used for sequences
  92.     * @access public
  93.     */
  94.     var $sequence_table;
  95.  
  96.     /**
  97.     * Secondary order field.  Normally this is the order field, but can be changed to
  98.     * something else (i.e. the name field so that the tree can be shown alphabetically)
  99.     *
  100.     * @var string 
  101.     * @access public
  102.     */
  103.     var $secondarySort;
  104.  
  105.     /**
  106.     * Used to store the secondary sort method set by the user while doing manipulative queries
  107.     *
  108.     * @var string 
  109.     * @access private
  110.     */
  111.     var $_userSecondarySort = false;
  112.  
  113.     /**
  114.     * The default sorting field - will be set to the table column inside the constructor
  115.     *
  116.     * @var string 
  117.     * @access private
  118.     */
  119.     var $_defaultSecondarySort 'norder';
  120.  
  121.     /**
  122.     *
  123.     * @var int The time to live of the lock
  124.     * @access public
  125.     */
  126.     var $lockTTL = 1;
  127.  
  128.     /**
  129.     *
  130.     * @var bool Enable debugging statements?
  131.     * @access public
  132.     */
  133.     var $debug = 0;
  134.  
  135.     /**
  136.     *
  137.     * @var bool Lock the structure of the table?
  138.     * @access private
  139.     */
  140.     var $_structureTableLock = false;
  141.  
  142.     /**
  143.     *
  144.     * @var bool Don't allow unlocking (used inside of moves)
  145.     * @access private
  146.     */
  147.     var $_lockExclusive = false;
  148.  
  149.     /**
  150.     *
  151.     * @var object cache Optional PEAR::Cache object
  152.     * @access public
  153.     */
  154.     var $cache = false;
  155.  
  156.     /**
  157.     * Specify the sortMode of the query methods
  158.     * NESE_SORT_LEVEL is the 'old' sorting method and sorts a tree by level
  159.     * all nodes of level 1, all nodes of level 2,...
  160.     * NESE_SORT_PREORDER will sort doing a preorder walk.
  161.     * So all children of node x will come right after it
  162.     * Note that moving a node within it's siblings will obviously not change the output
  163.     * in this mode
  164.     *
  165.     * @var constant Order method (NESE_SORT_LEVEL|NESE_SORT_PREORDER)
  166.     * @access private
  167.     */
  168.     var $_sortMode = NESE_SORT_LEVEL;
  169.  
  170.     /**
  171.     *
  172.     * @var array Available sortModes
  173.     * @access private
  174.     */
  175.     var $_sortModes = array(NESE_SORT_LEVELNESE_SORT_PREORDER);
  176.  
  177.     /**
  178.     *
  179.     * @var array An array of field ids that must exist in the table
  180.     * @access private
  181.     */
  182.     var $_requiredParams = array('id''rootid''l''r''norder''level');
  183.  
  184.     /**
  185.     *
  186.     * @var bool Skip the callback events?
  187.     * @access private
  188.     */
  189.     var $_skipCallbacks = false;
  190.  
  191.     /**
  192.     *
  193.     * @var bool Do we want to use caching
  194.     * @access private
  195.     */
  196.     var $_caching = false;
  197.  
  198.     /**
  199.     *
  200.     * @var array The above parameters flipped for easy access
  201.     * @access private
  202.     */
  203.     var $flparams = array();
  204.  
  205.     /**
  206.     *
  207.     * @var bool Temporary switch for cache
  208.     * @access private
  209.     */
  210.     var $_restcache = false;
  211.  
  212.     /**
  213.     * Used to determine the presence of listeners for an event in triggerEvent()
  214.     *
  215.     * If any event listeners are registered for an event, the event name will
  216.     * have a key set in this array, otherwise, it will not be set.
  217.     *
  218.     * @see triggerEvent
  219.     * @var arrayg 
  220.     * @access private
  221.     */
  222.     var $_hasListeners = array();
  223.  
  224.     /**
  225.     *
  226.     * @var string packagename
  227.     * @access private
  228.     */
  229.     var $_packagename 'DB_NestedSet';
  230.  
  231.     /**
  232.     *
  233.     * @var int Majorversion
  234.     * @access private
  235.     */
  236.     var $_majorversion = 1;
  237.  
  238.     /**
  239.     *
  240.     * @var string Minorversion
  241.     * @access private
  242.     */
  243.     var $_minorversion '3';
  244.  
  245.     /**
  246.     *
  247.     * @var array Used for mapping a cloned tree to the real tree for move_* operations
  248.     * @access private
  249.     */
  250.     var $_relations = array();
  251.  
  252.     /**
  253.     * Used for _internal_ tree conversion
  254.     *
  255.     * @var bool Turn off user param verification and id generation
  256.     * @access private
  257.     */
  258.     var $_dumbmode = false;
  259.  
  260.     /**
  261.     *
  262.     * @var array Map of error messages to their descriptions
  263.     */
  264.     var $messages = array(
  265.     NESE_ERROR_RECURSION => '%s: This operation would lead to a recursion',
  266.     NESE_ERROR_TBLOCKED => 'The structure Table is locked for another database operation, please retry.',
  267.     NESE_ERROR_NODRIVER => 'The selected database driver %s wasn\'t found',
  268.     NESE_ERROR_NOTSUPPORTED => 'Method not supported yet',
  269.     NESE_ERROR_NOHANDLER => 'Event handler not found',
  270.     NESE_ERROR_PARAM_MISSING => 'Parameter missing',
  271.     NESE_MESSAGE_UNKNOWN => 'Unknown error or message',
  272.     NESE_ERROR_NOT_FOUND => '%s: Node %s not found',
  273.     NESE_ERROR_WRONG_MPARAM => '%s: %s'
  274.     );
  275.  
  276.     /**
  277.     *
  278.     * @var array The array of event listeners
  279.     * @access private
  280.     */
  281.     var $eventListeners = array();
  282.     // }}}
  283.     // +---------------------------------------+
  284.     // | Base methods                          |
  285.     // +---------------------------------------+
  286.     // {{{ constructor
  287.     /**
  288.     * Constructor
  289.     *
  290.     * @param array $params Database column fields which should be returned
  291.     * @access private
  292.     * @return void 
  293.     */
  294.     function DB_NestedSet($params{
  295.         if ($this->debug{
  296.             $this->_debugMessage('DB_NestedSet()');
  297.         }
  298.         if (is_array($params&& count($params> 0{
  299.             $this->params = $params;
  300.         }
  301.  
  302.         $this->flparams array_flip($this->params);
  303.         $this->sequence_table = $this->node_table . '_' $this->flparams['id'];
  304.         $this->secondarySort = $this->flparams[$this->_defaultSecondarySort];
  305.         register_shutdown_function(array($this'_DB_NestedSet'));
  306.     }
  307.     // }}}
  308.     // {{{ destructor
  309.     /**
  310.     * PEAR Destructor
  311.     * Releases all locks
  312.     * Closes open database connections
  313.     *
  314.     * @access private
  315.     * @return void 
  316.     */
  317.     function _DB_NestedSet({
  318.         if ($this->debug{
  319.             $this->_debugMessage('_DB_NestedSet()');
  320.         }
  321.         $this->_releaseLock(true);
  322.     }
  323.     // }}}
  324.     // {{{ factory
  325.     /**
  326.     * Handles the returning of a concrete instance of DB_NestedSet based on the driver.
  327.     * If the class given by $driver allready exists it will be used.
  328.     * If not the driver will be searched inside the default path ./NestedSet/
  329.     *
  330.     * @param string $driver The driver, such as DB or MDB
  331.     * @param string $dsn The dsn for connecting to the database
  332.     * @param array $params The field name params for the node table
  333.     * @static
  334.     * @access public
  335.     * @return object The DB_NestedSet object
  336.     */
  337.     function factory($driver$dsn$params = array()) {
  338.         $classname 'DB_NestedSet_' $driver;
  339.         if (!class_exists($classname)) {
  340.             $driverpath dirname(__FILE__'/NestedSet/' $driver '.php';
  341.             if (!file_exists($driverpath|| !$driver{
  342.                 return PEAR::raiseError("factory(): The database driver '$driver' wasn't found"NESE_ERROR_NODRIVERPEAR_ERROR_TRIGGERE_USER_ERROR);
  343.             }
  344.             include_once($driverpath);
  345.         }
  346.         $c new $classname($dsn$params);
  347.         return $c;
  348.     }
  349.     // }}}
  350.     // +----------------------------------------------+
  351.     // | NestedSet manipulation and query methods     |
  352.     // |----------------------------------------------+
  353.     // | Querying the tree                            |
  354.     // +----------------------------------------------+
  355.     // {{{ getAllNodes()
  356.     /**
  357.     * Fetch the whole NestedSet
  358.     *
  359.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  360.     *                 a set of DB_NestedSet_Node objects?
  361.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  362.     *                 of the parameter keys, or leave them as is?
  363.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  364.     * @access public
  365.     * @return mixed False on error, or an array of nodes
  366.     */
  367.     function getAllNodes($keepAsArray = false$aliasFields = true$addSQL = array()) {
  368.         if ($this->debug{
  369.             $this->_debugMessage('getAllNodes()');
  370.         }
  371.  
  372.         if ($this->_sortMode == NESE_SORT_LEVEL{
  373.             $sql sprintf('SELECT %s %s FROM %s %s %s %s ORDER BY %s.%s, %s.%s ASC',
  374.             $this->_getSelectFields($aliasFields),
  375.             $this->_addSQL($addSQL'cols'),
  376.             $this->node_table,
  377.             $this->_addSQL($addSQL'join'),
  378.             $this->_addSQL($addSQL'where''WHERE'),
  379.             $this->_addSQL($addSQL'append'),
  380.             $this->node_table,
  381.             $this->flparams['level'],
  382.             $this->node_table,
  383.             $this->secondarySort);
  384.  
  385.         elseif ($this->_sortMode == NESE_SORT_PREORDER{
  386.             $nodeSet = array();
  387.             $rootnodes $this->getRootNodes(true);
  388.             foreach($rootnodes AS $rid => $rootnode{
  389.                 $nodeSet $nodeSet $this->getBranch($rootnode$keepAsArray$aliasFields$addSQL);
  390.             }
  391.             return $nodeSet;
  392.         }
  393.  
  394.         if (!$this->_caching{
  395.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  396.         else {
  397.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  398.         }
  399.  
  400.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  401.             // EVENT (nodeLoad)
  402.             foreach (array_keys($nodeSetas $key{
  403.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  404.             }
  405.         }
  406.         return $nodeSet;
  407.     }
  408.     // }}}
  409.     // {{{ getRootNodes()
  410.     /**
  411.     * Fetches the first level (the rootnodes) of the NestedSet
  412.     *
  413.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  414.     *                 a set of DB_NestedSet_Node objects?
  415.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  416.     *                 of the parameter keys, or leave them as is?
  417.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  418.     * @see _addSQL
  419.     * @access public
  420.     * @return mixed False on error, or an array of nodes
  421.     */
  422.     function getRootNodes($keepAsArray = false$aliasFields = true$addSQL = array()) {
  423.         if ($this->debug{
  424.             $this->_debugMessage('getRootNodes()');
  425.         }
  426.         $sql sprintf('SELECT %s %s FROM %s %s WHERE %s.%s=%s.%s %s %s ORDER BY %s.%s ASC',
  427.         $this->_getSelectFields($aliasFields),
  428.         $this->_addSQL($addSQL'cols'),
  429.         $this->node_table,
  430.         $this->_addSQL($addSQL'join'),
  431.         $this->node_table,
  432.         $this->flparams['id'],
  433.         $this->node_table,
  434.         $this->flparams['rootid'],
  435.         $this->_addSQL($addSQL'where''AND'),
  436.         $this->_addSQL($addSQL'append'),
  437.         $this->node_table,
  438.         $this->secondarySort);
  439.  
  440.         if (!$this->_caching{
  441.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  442.         else {
  443.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  444.         }
  445.  
  446.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  447.             // EVENT (nodeLoad)
  448.             foreach (array_keys($nodeSetas $key{
  449.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  450.             }
  451.         }
  452.         return $nodeSet;
  453.     }
  454.     // }}}
  455.     // {{{ getBranch()
  456.     /**
  457.     * Fetch the whole branch where a given node id is in
  458.     *
  459.     * @param int $id The node ID
  460.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  461.     *                 a set of DB_NestedSet_Node objects?
  462.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  463.     *                 of the parameter keys, or leave them as is?
  464.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  465.     * @see _addSQL
  466.     * @access public
  467.     * @return mixed False on error, or an array of nodes
  468.     */
  469.     function getBranch($id$keepAsArray = false$aliasFields = true$addSQL = array()) {
  470.         if ($this->debug{
  471.             $this->_debugMessage('getBranch($id)');
  472.         }
  473.         if (!($thisnode $this->pickNode($idtrue))) {
  474.             $epr = array('getBranch()'$id);
  475.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_NOTICE$epr);
  476.         }
  477.         if ($this->_sortMode == NESE_SORT_LEVEL{
  478.             $firstsort $this->flparams['level'];
  479.             $sql sprintf('SELECT %s %s FROM %s %s WHERE %s.%s=%s %s %s ORDER BY %s.%s, %s.%s ASC',
  480.             $this->_getSelectFields($aliasFields),
  481.             $this->_addSQL($addSQL'cols'),
  482.             $this->node_table,
  483.             $this->_addSQL($addSQL'join'),
  484.             $this->node_table,
  485.             $this->flparams['rootid'],
  486.             $thisnode['rootid'],
  487.             $this->_addSQL($addSQL'where''AND'),
  488.             $this->_addSQL($addSQL'append'),
  489.             $this->node_table,
  490.             $firstsort,
  491.             $this->node_table,
  492.             $this->secondarySort);
  493.         elseif ($this->_sortMode == NESE_SORT_PREORDER{
  494.             $firstsort $this->flparams['l'];
  495.             $sql sprintf('SELECT %s %s FROM %s %s WHERE %s.%s=%s %s %s ORDER BY %s.%s ASC',
  496.             $this->_getSelectFields($aliasFields),
  497.             $this->_addSQL($addSQL'cols'),
  498.             $this->node_table,
  499.             $this->_addSQL($addSQL'join'),
  500.             $this->node_table,
  501.             $this->flparams['rootid'],
  502.             $thisnode['rootid'],
  503.             $this->_addSQL($addSQL'where''AND'),
  504.             $this->_addSQL($addSQL'append'),
  505.             $this->node_table,
  506.             $firstsort);
  507.         }
  508.  
  509.         if (!$this->_caching{
  510.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  511.         else {
  512.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  513.         }
  514.  
  515.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  516.             // EVENT (nodeLoad)
  517.             foreach (array_keys($nodeSetas $key{
  518.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  519.             }
  520.         }
  521.         if ($this->_sortMode == NESE_SORT_PREORDER && ($this->params[$this->secondarySort!= $this->_defaultSecondarySort)) {
  522.             uasort($nodeSetarray($this'_secSort'));
  523.         }
  524.         return $nodeSet;
  525.     }
  526.     // }}}
  527.     // {{{ getParents()
  528.     /**
  529.     * Fetch the parents of a node given by id
  530.     *
  531.     * @param int $id The node ID
  532.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  533.     *                 a set of DB_NestedSet_Node objects?
  534.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  535.     *                 of the parameter keys, or leave them as is?
  536.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  537.     * @see _addSQL
  538.     * @access public
  539.     * @return mixed False on error, or an array of nodes
  540.     */
  541.     function getParents($id$keepAsArray = false$aliasFields = true$addSQL = array()) {
  542.         if ($this->debug{
  543.             $this->_debugMessage('getParents($id)');
  544.         }
  545.         if (!($child $this->pickNode($idtrue))) {
  546.             $epr = array('getParents()'$id);
  547.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_NOTICE$epr);
  548.         }
  549.  
  550.         $sql sprintf('SELECT %s %s FROM %s %s
  551.                         WHERE %s.%s=%s AND %s.%s<%s AND %s.%s<%s AND %s.%s>%s %s %s
  552.                         ORDER BY %s.%s ASC',
  553.         $this->_getSelectFields($aliasFields),
  554.         $this->_addSQL($addSQL'cols'),
  555.         $this->node_table,
  556.         $this->_addSQL($addSQL'join'),
  557.         $this->node_table,
  558.         $this->flparams['rootid'],
  559.         $child['rootid'],
  560.         $this->node_table,
  561.         $this->flparams['level'],
  562.         $child['level'],
  563.         $this->node_table,
  564.         $this->flparams['l'],
  565.         $child['l'],
  566.         $this->node_table,
  567.         $this->flparams['r'],
  568.         $child['r'],
  569.         $this->_addSQL($addSQL'where''AND'),
  570.         $this->_addSQL($addSQL'append'),
  571.         $this->node_table,
  572.         $this->flparams['level']);
  573.  
  574.         if (!$this->_caching{
  575.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  576.         else {
  577.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  578.         }
  579.  
  580.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  581.             // EVENT (nodeLoad)
  582.             foreach (array_keys($nodeSetas $key{
  583.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  584.             }
  585.         }
  586.         return $nodeSet;
  587.     }
  588.     // }}}
  589.     // {{{ getParent()
  590.     /**
  591.     * Fetch the immediate parent of a node given by id
  592.     *
  593.     * @param int $id The node ID
  594.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  595.     *                 a set of DB_NestedSet_Node objects?
  596.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  597.     *                 of the parameter keys, or leave them as is?
  598.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  599.     * @see _addSQL
  600.     * @access public
  601.     * @return mixed False on error, or the parent node
  602.     */
  603.     function getParent($id$keepAsArray = false$aliasFields = true$addSQL = array()$useDB = true{
  604.         if ($this->debug{
  605.             $this->_debugMessage('getParent($id)');
  606.         }
  607.         if (!($child $this->pickNode($idtrue))) {
  608.             $epr = array('getParent()'$id);
  609.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_NOTICE$epr);
  610.         }
  611.  
  612.         if ($child['id'== $child['rootid']{
  613.             return false;
  614.         }
  615.         // If parent node is set inside the db simply return it
  616.         if (isset($child['parent']&& !empty($child['parent']&& ($useDB == true)) {
  617.             return $this->pickNode($child['parent']$keepAsArray$aliasFields'id'$addSQL);
  618.         }
  619.  
  620.         $addSQL['where'sprintf('%s.%s = %s',
  621.         $this->node_table,
  622.         $this->flparams['level'],
  623.         $child['level']-1);
  624.  
  625.         $nodeSet $this->getParents($id$keepAsArray$aliasFields$addSQL);
  626.         if (!empty($nodeSet)) {
  627.             $keys array_keys($nodeSet);
  628.             return $nodeSet[$keys[0]];
  629.         else {
  630.             return false;
  631.         }
  632.     }
  633.     // }}}
  634.     // {{{ getSiblings()
  635.     /**
  636.     * Fetch all siblings of the node given by id
  637.     * Important: The node given by ID will also be returned
  638.     * Do a unset($array[$id]) on the result if you don't want that
  639.     *
  640.     * @param int $id The node ID
  641.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  642.     *                 a set of DB_NestedSet_Node objects?
  643.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  644.     *                 of the parameter keys, or leave them as is?
  645.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  646.     * @see _addSQL
  647.     * @access public
  648.     * @return mixed False on error, or the parent node
  649.     */
  650.     function getSiblings($id$keepAsArray = false$aliasFields = true$addSQL = array()) {
  651.         if ($this->debug{
  652.             $this->_debugMessage('getSiblings($id)');
  653.         }
  654.  
  655.         if (!($sibling $this->pickNode($idtrue))) {
  656.             $epr = array('getSibling()'$id);
  657.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_NOTICE$epr);
  658.         }
  659.  
  660.         $parent $this->getParent($siblingtrue);
  661.         return $this->getChildren($parent$keepAsArray$aliasFieldsfalse$addSQL);
  662.     }
  663.     // }}}
  664.     // {{{ getChildren()
  665.     /**
  666.     * Fetch the children _one level_ after of a node given by id
  667.     *
  668.     * @param int $id The node ID
  669.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  670.     *                 a set of DB_NestedSet_Node objects?
  671.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  672.     *                 of the parameter keys, or leave them as is?
  673.     * @param bool $forceNorder (optional) Force the result to be ordered by the norder
  674.     *                 param (as opposed to the value of secondary sort).  Used by the move and
  675.     *                 add methods.
  676.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  677.     * @see _addSQL
  678.     * @access public
  679.     * @return mixed False on error, or an array of nodes
  680.     */
  681.     function getChildren($id$keepAsArray = false$aliasFields = true$forceNorder = false$addSQL = array()) {
  682.         if ($this->debug{
  683.             $this->_debugMessage('getChildren($id)');
  684.         }
  685.  
  686.         if (!($parent $this->pickNode($idtrue))) {
  687.             $epr = array('getChildren()'$id);
  688.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_NOTICE$epr);
  689.         }
  690.         if (!$parent || $parent['l'== ($parent['r'- 1)) {
  691.             return false;
  692.         }
  693.  
  694.         $sql sprintf('SELECT %s %s FROM %s %s
  695.                         WHERE %s.%s=%s AND %s.%s=%s+1 AND %s.%s BETWEEN %s AND %s %s %s
  696.                         ORDER BY %s.%s ASC',
  697.         $this->_getSelectFields($aliasFields)$this->_addSQL($addSQL'cols'),
  698.         $this->node_table$this->_addSQL($addSQL'join'),
  699.         $this->node_table$this->flparams['rootid']$parent['rootid'],
  700.         $this->node_table$this->flparams['level']$parent['level'],
  701.         $this->node_table$this->flparams['l']$parent['l']$parent['r'],
  702.         $this->_addSQL($addSQL'where''AND'),
  703.         $this->_addSQL($addSQL'append'),
  704.         $this->node_table$this->secondarySort);
  705.         if (!$this->_caching{
  706.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  707.         else {
  708.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  709.         }
  710.  
  711.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  712.             // EVENT (nodeLoad)
  713.             foreach (array_keys($nodeSetas $key{
  714.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  715.             }
  716.         }
  717.         return $nodeSet;
  718.     }
  719.     // }}}
  720.     // {{{ getSubBranch()
  721.     /**
  722.     * Fetch all the children of a node given by id
  723.     *
  724.     * getChildren only queries the immediate children
  725.     * getSubBranch returns all nodes below the given node
  726.     *
  727.     * @param string $id The node ID
  728.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  729.     *                 a set of DB_NestedSet_Node objects?
  730.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  731.     *                 of the parameter keys, or leave them as is?
  732.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  733.     * @see _addSQL
  734.     * @access public
  735.     * @return mixed False on error, or an array of nodes
  736.     */
  737.     function getSubBranch($id$keepAsArray = false$aliasFields = true$addSQL = array()) {
  738.         if ($this->debug{
  739.             $this->_debugMessage('getSubBranch($id)');
  740.         }
  741.         if (!($parent $this->pickNode($idtrue))) {
  742.             $epr = array('getSubBranch()'$id);
  743.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDE_USER_NOTICE$epr);
  744.         }
  745.         if ($this->_sortMode == NESE_SORT_LEVEL{
  746.             $firstsort $this->flparams['level'];
  747.             $sql sprintf('SELECT %s %s FROM %s %s
  748.                     WHERE %s.%s BETWEEN %s AND %s AND %s.%s=%s AND %s.%s!=%s %s %s
  749.                     ORDER BY %s.%s, %s.%s ASC',
  750.             $this->_getSelectFields($aliasFields)$this->_addSQL($addSQL'cols'),
  751.             $this->node_table$this->_addSQL($addSQL'join'),
  752.             $this->node_table$this->flparams['l']$parent['l']$parent['r'],
  753.             $this->node_table$this->flparams['rootid']$parent['rootid'],
  754.             $this->node_table$this->flparams['id']$id$this->_addSQL($addSQL'where''AND')$this->_addSQL($addSQL'append'),
  755.             $this->node_table$firstsort,
  756.             $this->node_table$this->secondarySort);
  757.         elseif ($this->_sortMode == NESE_SORT_PREORDER{
  758.             $firstsort $this->flparams['l'];
  759.  
  760.             $sql sprintf('SELECT %s %s FROM %s %s
  761.                     WHERE %s.%s BETWEEN %s AND %s AND %s.%s=%s AND %s.%s!=%s %s %s
  762.                     ORDER BY %s.%s ASC',
  763.             $this->_getSelectFields($aliasFields)$this->_addSQL($addSQL'cols'),
  764.             $this->node_table,
  765.             $this->_addSQL($addSQL'join'),
  766.             $this->node_table,
  767.             $this->flparams['l'],
  768.             $parent['l'],
  769.             $parent['r'],
  770.             $this->node_table,
  771.             $this->flparams['rootid'],
  772.             $parent['rootid'],
  773.             $this->node_table,
  774.             $this->flparams['id'],
  775.             $id,
  776.             $this->_addSQL($addSQL'where''AND'),
  777.             $this->_addSQL($addSQL'append'),
  778.             $this->node_table,
  779.             $firstsort);
  780.         }
  781.  
  782.         if (!$this->_caching{
  783.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  784.         else {
  785.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  786.         }
  787.  
  788.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  789.             // EVENT (nodeLoad)
  790.             foreach (array_keys($nodeSetas $key{
  791.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  792.             }
  793.         }
  794.         if ($this->params[$this->secondarySort!= $this->_defaultSecondarySort{
  795.             uasort($nodeSetarray($this'_secSort'));
  796.         }
  797.         return $nodeSet;
  798.     }
  799.     // }}}
  800.     // {{{ pickNode()
  801.     /**
  802.     * Fetch the data of a node with the given id
  803.     *
  804.     * @param int $id The node id of the node to fetch
  805.     * @param bool $keepAsArray (optional) Keep the result as an array or transform it into
  806.     *                 a set of DB_NestedSet_Node objects?
  807.     * @param bool $aliasFields (optional) Should we alias the fields so they are the names
  808.     *                 of the parameter keys, or leave them as is?
  809.     * @param string $idfield (optional) Which field has to be compared with $id?
  810.     *                  This is can be used to pick a node by other values (e.g. it's name).
  811.     * @param array $addSQL (optional) Array of additional params to pass to the query.
  812.     * @see _addSQL
  813.     * @access public
  814.     * @return mixed False on error, or an array of nodes
  815.     */
  816.     function pickNode($id$keepAsArray = false$aliasFields = true$idfield 'id'$addSQL = array()) {
  817.         if ($this->debug{
  818.             $this->_debugMessage('pickNode($id)');
  819.         }
  820.  
  821.         if (is_object($id&& $id->id{
  822.             return $id;
  823.         elseif (is_array($id&& isset($id['id'])) {
  824.             return $id;
  825.         }
  826.  
  827.         if (!$id{
  828.             return false;
  829.         }
  830.  
  831.         $sql sprintf("SELECT %s %s FROM %s %s WHERE %s.%s=%s %s %s",
  832.         $this->_getSelectFields($aliasFields)$this->_addSQL($addSQL'cols'),
  833.         $this->node_table$this->_addSQL($addSQL'join'),
  834.         $this->node_table$this->flparams[$idfield]$this->_quote($id),
  835.         $this->_addSQL($addSQL'where''AND'),
  836.         $this->_addSQL($addSQL'append'));
  837.         if (!$this->_caching{
  838.             $nodeSet $this->_processResultSet($sql$keepAsArray$aliasFields);
  839.         else {
  840.             $nodeSet $this->cache->call('DB_NestedSet->_processResultSet'$sql$keepAsArray$aliasFields);
  841.         }
  842.  
  843.         $nsKey = false;
  844.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeLoad'])) {
  845.             // EVENT (nodeLoad)
  846.             foreach (array_keys($nodeSetas $key{
  847.                 $this->triggerEvent('nodeLoad'$nodeSet[$key]);
  848.                 $nsKey $key;
  849.             }
  850.         else {
  851.             foreach (array_keys($nodeSetas $key{
  852.                 $nsKey $key;
  853.             }
  854.         }
  855.  
  856.         if (is_array($nodeSet&& $idfield != 'id'{
  857.             $id $nsKey;
  858.         }
  859.  
  860.         return isset($nodeSet[$id]$nodeSet[$id: false;
  861.     }
  862.     // }}}
  863.     // {{{ isParent()
  864.     /**
  865.     * See if a given node is a parent of another given node
  866.     *
  867.     * A node is considered to be a parent if it resides above the child
  868.     * So it doesn't mean that the node has to be an immediate parent.
  869.     * To get this information simply compare the levels of the two nodes
  870.     * after you know that you have a parent relation.
  871.     *
  872.     * @param mixed $parent The parent node as array or object
  873.     * @param mixed $child The child node as array or object
  874.     * @access public
  875.     * @return bool True if it's a parent
  876.     */
  877.     function isParent($parent$child{
  878.         if ($this->debug{
  879.             $this->_debugMessage('isParent($parent, $child)');
  880.         }
  881.  
  882.         if (!isset($parent|| !isset($child)) {
  883.             return false;
  884.         }
  885.  
  886.         if (is_array($parent)) {
  887.             $p_rootid $parent['rootid'];
  888.             $p_l $parent['l'];
  889.             $p_r $parent['r'];
  890.         elseif (is_object($parent)) {
  891.             $p_rootid $parent->rootid;
  892.             $p_l $parent->l;
  893.             $p_r $parent->r;
  894.         }
  895.  
  896.         if (is_array($child)) {
  897.             $c_rootid $child['rootid'];
  898.             $c_l $child['l'];
  899.             $c_r $child['r'];
  900.         elseif (is_object($child)) {
  901.             $c_rootid $child->rootid;
  902.             $c_l $child->l;
  903.             $c_r $child->r;
  904.         }
  905.  
  906.         if (($p_rootid == $c_rootid&& ($p_l $c_l && $p_r $c_r)) {
  907.             return true;
  908.         }
  909.  
  910.         return false;
  911.     }
  912.     // }}}
  913.     // +----------------------------------------------+
  914.     // | NestedSet manipulation and query methods     |
  915.     // |----------------------------------------------+
  916.     // | insert / delete / update of nodes            |
  917.     // +----------------------------------------------+
  918.     // | [PUBLIC]                                     |
  919.     // +----------------------------------------------+
  920.     // {{{ createRootNode()
  921.     /**
  922.     * Creates a new root node.  If no id is specified then it is either
  923.     * added to the beginning/end of the tree based on the $pos.
  924.     * Optionally it deletes the whole tree and creates one initial rootnode
  925.     *
  926.     * <pre>
  927.     * +-- root1 [target]
  928.     * |
  929.     * +-- root2 [new]
  930.     * |
  931.     * +-- root3
  932.     * </pre>
  933.     *
  934.     * @param array $values Hash with param => value pairs of the node (see $this->params)
  935.     * @param integer $id ID of target node (the rootnode after which the node should be inserted)
  936.     * @param bool $first Danger: Deletes and (re)init's the hole tree - sequences are reset
  937.     * @param string $pos The position in which to insert the new node.
  938.     * @access public
  939.     * @return mixed The node id or false on error
  940.     */
  941.     function createRootNode($values$id = false$first = false$pos = NESE_MOVE_AFTER{
  942.         if ($this->debug{
  943.             $this->_debugMessage('createRootNode($values, $id = false, $first = false, $pos = \'AF\')');
  944.         }
  945.         // Try to aquire a table lock
  946.         if (PEAR::isError($lock $this->_setLock())) {
  947.             return $lock;
  948.         }
  949.         $this->_verifyUserValues('createRootNode()'$values);
  950.         // If they specified an id, see if the parent is valid
  951.         if (!$first && ($id && !$parent $this->pickNode($idtrue))) {
  952.             $epr = array('createRootNode()'$id);
  953.             $this->_releaseLock();
  954.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  955.         elseif ($first && $id{
  956.             // No notice for now.  But these 2 params don't make sense together
  957.             $epr = array('createRootNode()''[id] AND [first] were passed - that doesn\'t make sense');
  958.             // $this->_raiseError(NESE_ERROR_WRONG_MPARAM, E_USER_WARNING, $epr);
  959.         elseif (!$first && !$id{
  960.             // If no id was specified, then determine order
  961.             $parent = array();
  962.             if ($pos == NESE_MOVE_BEFORE{
  963.                 $parent['norder'= 1;
  964.             elseif ($pos == NESE_MOVE_AFTER{
  965.                 // Put it at the end of the tree
  966.                 $qry sprintf('SELECT MAX(%s) FROM %s WHERE %s=1',
  967.                 $this->flparams['norder'],
  968.                 $this->node_table,
  969.                 $this->flparams['l']);
  970.                 $tmp_order $this->_getOne($qry);
  971.                 // If null, then it's the first one
  972.                 $parent['norder'is_null($tmp_order? 0 : $tmp_order;
  973.             }
  974.         }
  975.  
  976.  
  977.         $sql = array();
  978.         $addval = array();
  979.         $addval[$this->flparams['level']] = 1;
  980.         // Shall we delete the existing tree (reinit)
  981.         if ($first{
  982.             $dsql sprintf('DELETE FROM %s'$this->node_table);
  983.             $this->_query($dsql);
  984.             $this->_dropSequence($this->sequence_table);
  985.             // New order of the new node will be 1
  986.             $addval[$this->flparams['norder']] = 1;
  987.         else {
  988.             // Let's open a gap for the new node
  989.             if ($pos == NESE_MOVE_AFTER{
  990.                 $addval[$this->flparams['norder']] $parent['norder'+ 1;
  991.                 $sql[sprintf('UPDATE %s SET %s=%s+1 WHERE %s=1 AND %s > %s',
  992.                 $this->node_table,
  993.                 $this->flparams['norder']$this->flparams['norder'],
  994.                 $this->flparams['l'],
  995.                 $this->flparams['norder']$parent['norder']);
  996.             elseif ($pos == NESE_MOVE_BEFORE{
  997.                 $addval[$this->flparams['norder']] $parent['norder'];
  998.                 $sql[sprintf('UPDATE %s SET %s=%s+1 WHERE %s=1 AND %s >= %s',
  999.                 $this->node_table,
  1000.                 $this->flparams['norder']$this->flparams['norder'],
  1001.                 $this->flparams['l'],
  1002.                 $this->flparams['norder']$parent['norder']);
  1003.             }
  1004.         }
  1005.  
  1006.         if (isset($this->flparams['parent'])) {
  1007.             $addval[$this->flparams['parent']] = 0;
  1008.         }
  1009.         // Sequence of node id (equals to root id in this case
  1010.         if (!$this->_dumbmode || !$node_id = isset($values[$this->flparams['id']]|| !isset($values[$this->flparams['rootid']])) {
  1011.             $addval[$this->flparams['rootid']] $node_id $addval[$this->flparams['id']] $this->_nextID($this->sequence_table);
  1012.         else {
  1013.             $node_id $values[$this->flparams['id']];
  1014.         }
  1015.         // Left/Right values for rootnodes
  1016.         $addval[$this->flparams['l']] = 1;
  1017.         $addval[$this->flparams['r']] = 2;
  1018.         // Transform the node data hash to a query
  1019.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1020.             $this->_releaseLock();
  1021.             return false;
  1022.         }
  1023.         // Insert the new node
  1024.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1025.         foreach ($sql as $qry{
  1026.             $res $this->_query($qry);
  1027.             $this->_testFatalAbort($res__FILE____LINE__);
  1028.         }
  1029.         // EVENT (nodeCreate)
  1030.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1031.             $thisnode $this->pickNode($node_id);
  1032.             $this->triggerEvent('nodeCreate'$thisnode);
  1033.         }
  1034.         $this->_releaseLock();
  1035.         return $node_id;
  1036.     }
  1037.     // }}}
  1038.     // {{{ createSubNode()
  1039.     /**
  1040.     * Creates a subnode
  1041.     *
  1042.     * <pre>
  1043.     * +-- root1
  1044.     * |
  1045.     * +-\ root2 [target]
  1046.     * | |
  1047.     * | |-- subnode1 [new]
  1048.     * |
  1049.     * +-- root3
  1050.     * </pre>
  1051.     *
  1052.     * @param integer $id Parent node ID
  1053.     * @param array $values Hash with param => value pairs of the node (see $this->params)
  1054.     * @access public
  1055.     * @return mixed The node id or false on error
  1056.     */
  1057.     function createSubNode($id$values{
  1058.         if ($this->debug{
  1059.             $this->_debugMessage('createSubNode($id, $values)');
  1060.         }
  1061.  
  1062.         // Try to aquire a table lock
  1063.         if (PEAR::isError($lock $this->_setLock())) {
  1064.             return $lock;
  1065.         }
  1066.  
  1067.         // invalid parent id, bail out
  1068.         if (!($thisnode $this->pickNode($idtrue))) {
  1069.             $epr = array('createSubNode()'$id);
  1070.             $this->_releaseLock();
  1071.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1072.         }
  1073.  
  1074.         $this->_verifyUserValues('createRootNode()'$values);
  1075.         // Get the children of the target node
  1076.         $children $this->getChildren($idtrue);
  1077.         // We have children here
  1078.         if ($thisnode['r']-1 != $thisnode['l']{
  1079.             // Get the last child
  1080.             $last array_pop($children);
  1081.             // What we have to do is virtually an insert of a node after the last child
  1082.             // So we don't have to proceed creating a subnode
  1083.             $newNode $this->createRightNode($last['id']$values);
  1084.             $this->_releaseLock();
  1085.             return $newNode;
  1086.         }
  1087.  
  1088.         $sql = array();
  1089.         $sql[sprintf('UPDATE %s SET
  1090.                 %s=CASE WHEN %s>%s THEN %s+2 ELSE %s END,
  1091.                 %s=CASE WHEN (%s>%s OR %s>=%s) THEN %s+2 ELSE %s END
  1092.                 WHERE %s=%s',
  1093.         $this->node_table,
  1094.         $this->flparams['l'],
  1095.         $this->flparams['l']$thisnode['l'],
  1096.         $this->flparams['l']$this->flparams['l'],
  1097.         $this->flparams['r'],
  1098.         $this->flparams['l']$thisnode['l'],
  1099.         $this->flparams['r']$thisnode['r'],
  1100.         $this->flparams['r']$this->flparams['r'],
  1101.         $this->flparams['rootid']$thisnode['rootid']);
  1102.         $addval = array();
  1103.         if (isset($this->flparams['parent'])) {
  1104.             $addval[$this->flparams['parent']] $thisnode['id'];
  1105.         }
  1106.  
  1107.         $addval[$this->flparams['l']] $thisnode['r'];
  1108.         $addval[$this->flparams['r']] $thisnode['r'+ 1;
  1109.         $addval[$this->flparams['rootid']] $thisnode['rootid'];
  1110.         $addval[$this->flparams['norder']] = 1;
  1111.         $addval[$this->flparams['level']] $thisnode['level'+ 1;
  1112.         if (!$this->_dumbmode || !$node_id = isset($values[$this->flparams['id']])) {
  1113.             $node_id $addval[$this->flparams['id']] $this->_nextID($this->sequence_table);
  1114.         else {
  1115.             $node_id $values[$this->flparams['id']];
  1116.         }
  1117.  
  1118.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1119.             $this->_releaseLock();
  1120.             return false;
  1121.         }
  1122.  
  1123.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1124.         foreach ($sql as $qry{
  1125.             $res $this->_query($qry);
  1126.             $this->_testFatalAbort($res__FILE____LINE__);
  1127.         }
  1128.         // EVENT (NodeCreate)
  1129.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1130.             $thisnode $this->pickNode($node_id);
  1131.             $this->triggerEvent('nodeCreate'$thisnode);
  1132.         }
  1133.         $this->_releaseLock();
  1134.         return $node_id;
  1135.     }
  1136.     // }}}
  1137.     // {{{ createLeftNode()
  1138.     /**
  1139.     * Creates a node before a given node
  1140.     * <pre>
  1141.     * +-- root1
  1142.     * |
  1143.     * +-\ root2
  1144.     * | |
  1145.     * | |-- subnode2 [new]
  1146.     * | |-- subnode1 [target]
  1147.     * | |-- subnode3
  1148.     * |
  1149.     * +-- root3
  1150.     * </pre>
  1151.     *
  1152.     * @param int $id Target node ID
  1153.     * @param array $values Hash with param => value pairs of the node (see $this->params)
  1154.     * @param bool $returnID Tell the method to return a node id instead of an object.
  1155.     *                                    ATTENTION: That the method defaults to return an object instead of the node id
  1156.     *                                    has been overseen and is basically a bug. We have to keep this to maintain BC.
  1157.     *                                    You will have to set $returnID to true to make it behave like the other creation methods.
  1158.     *                                    This flaw will get fixed with the next major version.
  1159.     * @access public
  1160.     * @return mixed The node id or false on error
  1161.     */
  1162.     function createLeftNode($id$values{
  1163.         if ($this->debug{
  1164.             $this->_debugMessage('createLeftNode($target, $values)');
  1165.         }
  1166.  
  1167.         if (PEAR::isError($lock $this->_setLock())) {
  1168.             return $lock;
  1169.         }
  1170.  
  1171.         $this->_verifyUserValues('createLeftode()'$values);
  1172.         // invalid target node, bail out
  1173.         if (!($thisnode $this->pickNode($idtrue))) {
  1174.             $epr = array('createLeftNode()'$id);
  1175.             $this->_releaseLock();
  1176.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1177.         }
  1178.  
  1179.  
  1180.         // If the target node is a rootnode we virtually want to create a new root node
  1181.         if ($thisnode['rootid'== $thisnode['id']{
  1182.             $this->_releaseLock();
  1183.             return $this->createRootNode($values$idfalseNESE_MOVE_BEFORE);
  1184.         }
  1185.  
  1186.         $addval = array();
  1187.         $parent $this->getParent($idtrue);
  1188.         if (isset($this->flparams['parent'])) {
  1189.             $addval[$this->flparams['parent']] $parent['id'];
  1190.         }
  1191.  
  1192.         $sql = array();
  1193.         $sql[sprintf('UPDATE %s SET %s=%s+1
  1194.                         WHERE %s=%s AND %s>=%s AND %s=%s AND %s BETWEEN %s AND %s',
  1195.         $this->node_table,
  1196.         $this->flparams['norder']$this->flparams['norder'],
  1197.         $this->flparams['rootid']$thisnode['rootid'],
  1198.         $this->flparams['norder']$thisnode['norder'],
  1199.         $this->flparams['level']$thisnode['level'],
  1200.         $this->flparams['l']$parent['l']$parent['r']);
  1201.         // Update all nodes which have dependent left and right values
  1202.         $sql[sprintf('UPDATE %s SET
  1203.                 %s=CASE WHEN %s>=%s THEN %s+2 ELSE %s END,
  1204.                 %s=CASE WHEN (%s>=%s OR %s>=%s) THEN %s+2 ELSE %s END
  1205.                 WHERE %s=%s',
  1206.         $this->node_table,
  1207.         $this->flparams['l'],
  1208.         $this->flparams['l']$thisnode['l'],
  1209.         $this->flparams['l']$this->flparams['l'],
  1210.         $this->flparams['r'],
  1211.         $this->flparams['r']$thisnode['r'],
  1212.         $this->flparams['l']$thisnode['l'],
  1213.         $this->flparams['r']$this->flparams['r'],
  1214.         $this->flparams['rootid']$thisnode['rootid']);
  1215.         $addval[$this->flparams['norder']] $thisnode['norder'];
  1216.         $addval[$this->flparams['l']] $thisnode['l'];
  1217.         $addval[$this->flparams['r']] $thisnode['l'+ 1;
  1218.         $addval[$this->flparams['rootid']] $thisnode['rootid'];
  1219.         $addval[$this->flparams['level']] $thisnode['level'];
  1220.         if (!$this->_dumbmode || !$node_id = isset($values[$this->flparams['id']])) {
  1221.             $node_id $addval[$this->flparams['id']] $this->_nextID($this->sequence_table);
  1222.         else {
  1223.             $node_id $values[$this->flparams['id']];
  1224.         }
  1225.  
  1226.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1227.             $this->_releaseLock();
  1228.             return false;
  1229.         }
  1230.         // Insert the new node
  1231.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1232.         foreach ($sql as $qry{
  1233.             $res $this->_query($qry);
  1234.             $this->_testFatalAbort($res__FILE____LINE__);
  1235.         }
  1236.         // EVENT (NodeCreate)
  1237.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1238.             $thisnode $this->pickNode($node_id);
  1239.             $this->triggerEvent('nodeCreate'$thisnode);
  1240.         }
  1241.         $this->_releaseLock();
  1242.         return $node_id;
  1243.     }
  1244.     // }}}
  1245.     // {{{ createRightNode()
  1246.     /**
  1247.     * Creates a node after a given node
  1248.     * <pre>
  1249.     * +-- root1
  1250.     * |
  1251.     * +-\ root2
  1252.     * | |
  1253.     * | |-- subnode1 [target]
  1254.     * | |-- subnode2 [new]
  1255.     * | |-- subnode3
  1256.     * |
  1257.     * +-- root3
  1258.     * </pre>
  1259.     *
  1260.     * @param int $id Target node ID
  1261.     * @param array $values Hash with param => value pairs of the node (see $this->params)
  1262.     * @param bool $returnID Tell the method to return a node id instead of an object.
  1263.     *                                    ATTENTION: That the method defaults to return an object instead of the node id
  1264.     *                                    has been overseen and is basically a bug. We have to keep this to maintain BC.
  1265.     *                                    You will have to set $returnID to true to make it behave like the other creation methods.
  1266.     *                                    This flaw will get fixed with the next major version.
  1267.     * @access public
  1268.     * @return mixed The node id or false on error
  1269.     */
  1270.     function createRightNode($id$values{
  1271.         if ($this->debug{
  1272.             $this->_debugMessage('createRightNode($target, $values)');
  1273.         }
  1274.  
  1275.         if (PEAR::isError($lock $this->_setLock())) {
  1276.             return $lock;
  1277.         }
  1278.  
  1279.         $this->_verifyUserValues('createRootNode()'$values);
  1280.         // invalid target node, bail out
  1281.         if (!($thisnode $this->pickNode($idtrue))) {
  1282.             $epr = array('createRightNode()'$id);
  1283.             $this->_releaseLock();
  1284.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1285.         }
  1286.  
  1287.  
  1288.         // If the target node is a rootnode we virtually want to create a new root node
  1289.         if ($thisnode['rootid'== $thisnode['id']{
  1290.             $nid $this->createRootNode($values$id);
  1291.             $this->_releaseLock();
  1292.             return $nid;
  1293.         }
  1294.  
  1295.         $addval = array();
  1296.         $parent $this->getParent($idtrue);
  1297.         if (isset($this->flparams['parent'])) {
  1298.             $addval[$this->flparams['parent']] $parent['id'];
  1299.         }
  1300.  
  1301.         $sql = array();
  1302.         $sql[sprintf('UPDATE %s SET %s=%s+1
  1303.                         WHERE %s=%s AND %s>%s AND %s=%s AND %s BETWEEN %s AND %s',
  1304.         $this->node_table,
  1305.         $this->flparams['norder']$this->flparams['norder'],
  1306.         $this->flparams['rootid']$thisnode['rootid'],
  1307.         $this->flparams['norder']$thisnode['norder'],
  1308.         $this->flparams['level']$thisnode['level'],
  1309.         $this->flparams['l']$parent['l']$parent['r']);
  1310.         // Update all nodes which have dependent left and right values
  1311.         $sql[sprintf('UPDATE %s SET
  1312.                 %s=CASE WHEN (%s>%s AND %s>%s) THEN %s+2 ELSE %s END,
  1313.                 %s=CASE WHEN %s>%s THEN %s+2 ELSE %s END
  1314.                 WHERE %s=%s',
  1315.         $this->node_table,
  1316.         $this->flparams['l'],
  1317.         $this->flparams['l']$thisnode['l'],
  1318.         $this->flparams['r']$thisnode['r'],
  1319.         $this->flparams['l']$this->flparams['l'],
  1320.         $this->flparams['r'],
  1321.         $this->flparams['r']$thisnode['r'],
  1322.         $this->flparams['r']$this->flparams['r'],
  1323.         $this->flparams['rootid']$thisnode['rootid']);
  1324.         $addval[$this->flparams['norder']] $thisnode['norder'+ 1;
  1325.         $addval[$this->flparams['l']] $thisnode['r'+ 1;
  1326.         $addval[$this->flparams['r']] $thisnode['r'+ 2;
  1327.         $addval[$this->flparams['rootid']] $thisnode['rootid'];
  1328.         $addval[$this->flparams['level']] $thisnode['level'];
  1329.         if (!$this->_dumbmode || !isset($values[$this->flparams['id']])) {
  1330.             $node_id $addval[$this->flparams['id']] $this->_nextID($this->sequence_table);
  1331.         else {
  1332.             $node_id $values[$this->flparams['id']];
  1333.         }
  1334.  
  1335.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1336.             $this->_releaseLock();
  1337.             return false;
  1338.         }
  1339.         // Insert the new node
  1340.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1341.         foreach ($sql as $qry{
  1342.             $res $this->_query($qry);
  1343.             $this->_testFatalAbort($res__FILE____LINE__);
  1344.         }
  1345.         // EVENT (NodeCreate)
  1346.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1347.             $thisnode $this->pickNode($node_id);
  1348.             $this->triggerEvent('nodeCreate'$thisnode);
  1349.         }
  1350.         $this->_releaseLock();
  1351.         return $node_id;
  1352.     }
  1353.     // }}}
  1354.     // {{{ deleteNode()
  1355.     /**
  1356.     * Deletes a node
  1357.     *
  1358.     * @param int $id ID of the node to be deleted
  1359.     * @access public
  1360.     * @return bool True if the delete succeeds
  1361.     */
  1362.     function deleteNode($id{
  1363.         if ($this->debug{
  1364.             $this->_debugMessage("deleteNode($id)");
  1365.         }
  1366.         if (PEAR::isError($lock $this->_setLock())) {
  1367.             return $lock;
  1368.         }
  1369.  
  1370.         // invalid target node, bail out
  1371.         if (!($thisnode $this->pickNode($idtrue))) {
  1372.             $epr = array('deleteNode()'$id);
  1373.             $this->_releaseLock();
  1374.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1375.         }
  1376.  
  1377.  
  1378.  
  1379.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeDelete'])) {
  1380.             // EVENT (NodeDelete)
  1381.             $this->triggerEvent('nodeDelete'$this->pickNode($id));
  1382.         }
  1383.  
  1384.         $parent $this->getParent($idtrue);
  1385.         $len $thisnode['r'$thisnode['l'+ 1;
  1386.         $sql = array();
  1387.         // Delete the node
  1388.         $sql[sprintf('DELETE FROM %s WHERE %s BETWEEN %s AND %s AND %s=%s',
  1389.         $this->node_table,
  1390.         $this->flparams['l']$thisnode['l']$thisnode['r'],
  1391.         $this->flparams['rootid']$thisnode['rootid']);
  1392.         if ($thisnode['id'!= $thisnode['rootid']{
  1393.             // The node isn't a rootnode so close the gap
  1394.             $sql[sprintf('UPDATE %s SET
  1395.                             %s=CASE WHEN %s>%s THEN %s-%s ELSE %s END,
  1396.                             %s=CASE WHEN %s>%s THEN %s-%s ELSE %s END
  1397.                             WHERE %s=%s AND (%s>%s OR %s>%s)',
  1398.             $this->node_table,
  1399.             $this->flparams['l'],
  1400.             $this->flparams['l']$thisnode['l'],
  1401.             $this->flparams['l']$len$this->flparams['l'],
  1402.             $this->flparams['r'],
  1403.             $this->flparams['r']$thisnode['l'],
  1404.             $this->flparams['r']$len$this->flparams['r'],
  1405.             $this->flparams['rootid']$thisnode['rootid'],
  1406.             $this->flparams['l']$thisnode['l'],
  1407.             $this->flparams['r']$thisnode['r']);
  1408.             // Re-order
  1409.             $sql[sprintf('UPDATE %s SET %s=%s-1
  1410.                     WHERE %s=%s AND %s=%s AND %s>%s AND %s BETWEEN %s AND %s',
  1411.             $this->node_table,
  1412.             $this->flparams['norder']$this->flparams['norder'],
  1413.             $this->flparams['rootid']$thisnode['rootid'],
  1414.             $this->flparams['level']$thisnode['level'],
  1415.             $this->flparams['norder']$thisnode['norder'],
  1416.             $this->flparams['l']$parent['l']$parent['r']);
  1417.         else {
  1418.             // A rootnode was deleted and we only have to close the gap inside the order
  1419.             $sql[sprintf('UPDATE %s SET %s=%s-1 WHERE %s=%s AND %s > %s',
  1420.             $this->node_table,
  1421.             $this->flparams['norder']$this->flparams['norder'],
  1422.             $this->flparams['rootid']$this->flparams['id'],
  1423.             $this->flparams['norder']$thisnode['norder']);
  1424.         }
  1425.  
  1426.         foreach ($sql as $qry{
  1427.             $res $this->_query($qry);
  1428.             $this->_testFatalAbort($res__FILE____LINE__);
  1429.         }
  1430.         $this->_releaseLock();
  1431.         return true;
  1432.     }
  1433.     // }}}
  1434.     // {{{ updateNode()
  1435.     /**
  1436.     * Changes the payload of a node
  1437.     *
  1438.     * @param int $id Node ID
  1439.     * @param array $values Hash with param => value pairs of the node (see $this->params)
  1440.     * @param bool $_intermal Internal use only. Used to skip value validation. Leave this as it is.
  1441.     * @access public
  1442.     * @return bool True if the update is successful
  1443.     */
  1444.     function updateNode($id$values$_internal = false{
  1445.         if ($this->debug{
  1446.             $this->_debugMessage('updateNode($id, $values)');
  1447.         }
  1448.  
  1449.         if (PEAR::isError($lock $this->_setLock())) {
  1450.             return $lock;
  1451.         }
  1452.  
  1453.         if (!$_internal{
  1454.             $this->_verifyUserValues('createRootNode()'$values);
  1455.         }
  1456.  
  1457.         $eparams = array('values' => $values);
  1458.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeUpdate'])) {
  1459.             // EVENT (NodeUpdate)
  1460.             $this->triggerEvent('nodeUpdate'$this->pickNode($id)$eparams);
  1461.         }
  1462.  
  1463.         $addvalues = array();
  1464.         if (!$qr $this->_values2UpdateQuery($values$addvalues)) {
  1465.             $this->_releaseLock();
  1466.             return false;
  1467.         }
  1468.  
  1469.         $sql sprintf('UPDATE %s SET %s WHERE %s=%s',
  1470.         $this->node_table,
  1471.         $qr,
  1472.         $this->flparams['id']$id);
  1473.         $res $this->_query($sql);
  1474.         $this->_testFatalAbort($res__FILE____LINE__);
  1475.         $this->_releaseLock();
  1476.         return true;
  1477.     }
  1478.     // }}}
  1479.     // +----------------------------------------------+
  1480.     // | Moving and copying                           |
  1481.     // |----------------------------------------------+
  1482.     // | [PUBLIC]                                     |
  1483.     // +----------------------------------------------+
  1484.     // {{{ moveTree()
  1485.     /**
  1486.     * Wrapper for node moving and copying
  1487.     *
  1488.     * @param int $id Source ID
  1489.     * @param int $target Target ID
  1490.     * @param constant $pos Position (use one of the NESE_MOVE_* constants)
  1491.     * @param bool $copy Shall we create a copy
  1492.     * @see _moveInsideLevel
  1493.     * @see _moveAcross
  1494.     * @see _moveRoot2Root
  1495.     * @access public
  1496.     * @return int ID of the moved node or false on error
  1497.     */
  1498.     function moveTree($id$targetid$pos$copy = false{
  1499.         if ($this->debug{
  1500.             $this->_debugMessage('moveTree($id, $target, $pos, $copy = false)');
  1501.         }
  1502.  
  1503.         if (PEAR::isError($lock $this->_setLock(true))) {
  1504.             return $lock;
  1505.         }
  1506.  
  1507.         if ($id == $targetid && !$copy{
  1508.             $epr = array('moveTree()');
  1509.             $this->_releaseLock();
  1510.             return $this->_raiseError(NESE_ERROR_RECURSIONPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  1511.         }
  1512.         // Get information about source and target
  1513.         if (!($source $this->pickNode($idtrue))) {
  1514.             $epr = array('moveTree()'$id);
  1515.             $this->_releaseLock();
  1516.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1517.         }
  1518.  
  1519.         if (!($target $this->pickNode($targetidtrue))) {
  1520.             $epr = array('moveTree()'$targetid);
  1521.             $this->_releaseLock();
  1522.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1523.         }
  1524.  
  1525.  
  1526.  
  1527.         $this->_relations = array();
  1528.         // This operations don't need callbacks except the copy handler
  1529.         // which ignores this setting
  1530.         $this->_skipCallbacks = true;
  1531.         if (!$copy{
  1532.             // We have a recursion - let's stop
  1533.             if (($target['rootid'== $source['rootid']&&
  1534.             (($source['l'<= $target['l']&&
  1535.             ($source['r'>= $target['r']))) {
  1536.                 $this->_releaseLock(true);
  1537.                 $epr = array('moveTree()');
  1538.                 return $this->_raiseError(NESE_ERROR_RECURSIONPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  1539.             }
  1540.             // Insert/move before or after
  1541.             if (($source['rootid'== $source['id']&&
  1542.             ($target['rootid'== $target['id']&& ($pos != NESE_MOVE_BELOW)) {
  1543.                 // We have to move a rootnode which is different from moving inside a tree
  1544.                 $nid $this->_moveRoot2Root($source$target$pos);
  1545.                 $this->_releaseLock(true);
  1546.                 return $nid;
  1547.             }
  1548.         elseif (($target['rootid'== $source['rootid']&&
  1549.         (($source['l'$target['l']&&
  1550.         ($source['r'$target['r']))) {
  1551.             $this->_releaseLock(true);
  1552.             $epr = array('moveTree()');
  1553.             return $this->_raiseError(NESE_ERROR_RECURSIONPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  1554.         }
  1555.         // We have to move between different levels and maybe subtrees - let's rock ;)
  1556.         $moveID $this->_moveAcross($source$target$postrue);
  1557.         $this->_moveCleanup($copy);
  1558.         $this->_releaseLock(true);
  1559.         if (!$copy{
  1560.             return $id;
  1561.         else {
  1562.             return $moveID;
  1563.         }
  1564.     }
  1565.     // }}}
  1566.     // {{{ _moveAcross()
  1567.     /**
  1568.     * Moves nodes and trees to other subtrees or levels
  1569.     *
  1570.     * <pre>
  1571.     * [+] <--------------------------------+
  1572.     * +-[\] root1 [target]                 |
  1573.     *        <-------------------------+      |p
  1574.     * +-\ root2                     |      |
  1575.     * | |                           |      |
  1576.     * | |-- subnode1 [target]       |      |B
  1577.     * | |-- subnode2 [new]          |S     |E
  1578.     * | |-- subnode3                |U     |F
  1579.     * |                             |B     |O
  1580.     * +-\ root3                     |      |R
  1581.     *      |-- subnode 3.1             |      |E
  1582.     *      |-\ subnode 3.2 [source] >--+------+
  1583.     *        |-- subnode 3.2.1
  1584.     * </pre>
  1585.     *
  1586.     * @param object NodeCT $source   Source node
  1587.     * @param object NodeCT $target   Target node
  1588.     * @param string $pos Position [SUBnode/BEfore]
  1589.     * @param bool $copy Shall we create a copy
  1590.     * @access private
  1591.     * @see moveTree
  1592.     * @see _r_moveAcross
  1593.     * @see _moveCleanup
  1594.     */
  1595.     function _moveAcross($source$target$pos$first = false{
  1596.         if ($this->debug{
  1597.             $this->_debugMessage('_moveAcross($source, $target, $pos, $copy = false)');
  1598.         }
  1599.         // Get the current data from a node and exclude the id params which will be changed
  1600.         // because of the node move
  1601.         $values = array();
  1602.         foreach($this->params as $key => $val{
  1603.             if ($source[$val&& $val != 'parent' && !in_array($val$this->_requiredParams)) {
  1604.                 $values[$keytrim($source[$val]);
  1605.             }
  1606.         }
  1607.  
  1608.         switch ($pos{
  1609.             case NESE_MOVE_BEFORE:
  1610.             $clone_id $this->createLeftNode($target['id']$values);
  1611.             break;
  1612.             case NESE_MOVE_AFTER:
  1613.             $clone_id $this->createRightNode($target['id']$values);
  1614.             break;
  1615.             case NESE_MOVE_BELOW:
  1616.             $clone_id $this->createSubNode($target['id']$values);
  1617.             break;
  1618.         }
  1619.  
  1620.         if ($first && isset($this->flparams['parent'])) {
  1621.             $t_parent $this->getParent($clone_idtruetruearray()false);
  1622.             $t_parent_id $t_parent['id'];
  1623.         elseif (isset($this->flparams['parent'])) {
  1624.             $t_parent_id $source['parent'];
  1625.         else {
  1626.             $t_parent_id = false;
  1627.         }
  1628.  
  1629.         $children $this->getChildren($source['id']truetruetrue);
  1630.         if ($children{
  1631.             $pos NESE_MOVE_BELOW;
  1632.             $sclone_id $clone_id;
  1633.             // Recurse through the child nodes
  1634.             foreach($children AS $cid => $child{
  1635.                 $sclone $this->pickNode($sclone_idtrue);
  1636.                 $sclone_id $this->_moveAcross($child$sclone$pos);
  1637.                 $pos NESE_MOVE_AFTER;
  1638.             }
  1639.         }
  1640.  
  1641.         $this->_relations[$source['id']]['clone'$clone_id;
  1642.         $this->_relations[$source['id']]['parent'$t_parent_id;
  1643.         return $clone_id;
  1644.     }
  1645.     // }}}
  1646.     // {{{ _moveCleanup()
  1647.     /**
  1648.     * Deletes the old subtree (node) and writes the node id's into the cloned tree
  1649.     *
  1650.     * @param array $relations Hash in der Form $h[alteid]=neueid
  1651.     * @param array $copy Are we in copy mode?
  1652.     * @access private
  1653.     */
  1654.     function _moveCleanup($copy = false{
  1655.         $relations $this->_relations;
  1656.         if ($this->debug{
  1657.             $this->_debugMessage('_moveCleanup($relations, $copy = false)');
  1658.         }
  1659.  
  1660.         $deletes = array();
  1661.         $updates = array();
  1662.         $pupdates = array();
  1663.         $tb $this->node_table;
  1664.         $fid $this->flparams['id'];
  1665.         $froot $this->flparams['rootid'];
  1666.         foreach($relations AS $key => $val{
  1667.             $cloneid $val['clone'];
  1668.             $parentID $val['parent'];
  1669.             $clone $this->pickNode($cloneid);
  1670.             if ($copy{
  1671.                 // EVENT (NodeCopy)
  1672.                 $eparams = array('clone' => $clone);
  1673.                 if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCopy'])) {
  1674.                     $this->triggerEvent('nodeCopy'$this->pickNode($key)$eparams);
  1675.                 }
  1676.                 continue;
  1677.             }
  1678.             // No callbacks here because the node itself doesn't get changed
  1679.             // Only it's position
  1680.             // If one needs a callback here please let me know
  1681.             if (!empty($parentID)) {
  1682.                 $sql sprintf('UPDATE %s SET %s=%s WHERE %s=%s',
  1683.                 $this->node_table,
  1684.                 $this->flparams['parent'],
  1685.                 $parentID,
  1686.                 $fid,
  1687.                 $key);
  1688.                 $pupdates[$sql;
  1689.             }
  1690.  
  1691.             $deletes[$key;
  1692.             // It's isn't a rootnode
  1693.             if ($clone->id != $clone->rootid{
  1694.                 $sql sprintf('UPDATE %s SET %s=%s WHERE %s=%s',
  1695.                 $this->node_table,
  1696.                 $fid$key,
  1697.                 $fid$cloneid);
  1698.                 $updates[$sql;
  1699.             else {
  1700.                 $sql sprintf('UPDATE %s SET %s=%s, %s=%s WHERE %s=%s',
  1701.                 $this->node_table,
  1702.                 $fid$key,
  1703.                 $froot$cloneid,
  1704.                 $fid$cloneid);
  1705.                 $updates[$sql;
  1706.                 $orootid $clone->rootid;
  1707.                 $sql sprintf('UPDATE %s SET %s=%s WHERE %s=%s',
  1708.                 $tb,
  1709.                 $froot$key,
  1710.                 $froot$orootid);
  1711.                 $updates[$sql;
  1712.             }
  1713.             $this->_skipCallbacks = false;
  1714.         }
  1715.  
  1716.         if (!empty($deletes)) {
  1717.             foreach ($deletes as $delete{
  1718.                 $this->deleteNode($delete);
  1719.             }
  1720.         }
  1721.  
  1722.         if (!empty($updates)) {
  1723.             for($i = 0;$i count($updates);$i++{
  1724.                 $res $this->_query($updates[$i]);
  1725.                 $this->_testFatalAbort($res__FILE____LINE__);
  1726.             }
  1727.         }
  1728.  
  1729.         if (!empty($pupdates)) {
  1730.             for($i = 0;$i count($pupdates);$i++{
  1731.                 $res $this->_query($pupdates[$i]);
  1732.                 $this->_testFatalAbort($res__FILE____LINE__);
  1733.             }
  1734.         }
  1735.  
  1736.         return true;
  1737.     }
  1738.     // }}}
  1739.     // {{{ _moveRoot2Root()
  1740.     /**
  1741.     * Moves rootnodes
  1742.     *
  1743.     * <pre>
  1744.     * +-- root1
  1745.     * |
  1746.     * +-\ root2
  1747.     * | |
  1748.     * | |-- subnode1 [target]
  1749.     * | |-- subnode2 [new]
  1750.     * | |-- subnode3
  1751.     * |
  1752.     * +-\ root3
  1753.     *     [|]  <-----------------------+
  1754.     *      |-- subnode 3.1 [target]    |
  1755.     *      |-\ subnode 3.2 [source] >--+
  1756.     *        |-- subnode 3.2.1
  1757.     * </pre>
  1758.     *
  1759.     * @param object NodeCT $source    Source
  1760.     * @param object NodeCT $target    Target
  1761.     * @param string $pos BEfore | AFter
  1762.     * @access private
  1763.     * @see moveTree
  1764.     */
  1765.     function _moveRoot2Root($source$target$pos{
  1766.         if ($this->debug{
  1767.             $this->_debugMessage('_moveRoot2Root($source, $target, $pos, $copy)');
  1768.         }
  1769.         if (PEAR::isError($lock $this->_setLock())) {
  1770.             return $lock;
  1771.         }
  1772.  
  1773.         $tb $this->node_table;
  1774.         $fid $this->flparams['id'];
  1775.         $froot $this->flparams['rootid'];
  1776.         $freh $this->flparams['norder'];
  1777.         $s_order $source['norder'];
  1778.         $t_order $target['norder'];
  1779.         $s_id $source['id'];
  1780.         $t_id $target['id'];
  1781.         if ($s_order $t_order{
  1782.             if ($pos == NESE_MOVE_BEFORE{
  1783.                 $sql = "UPDATE $tb SET $freh=$freh-1
  1784.                         WHERE $freh BETWEEN $s_order AND $t_order AND
  1785.                             $fid!=$t_id AND
  1786.                             $fid!=$s_id AND
  1787.                             $froot=$fid";
  1788.                 $res $this->_query($sql);
  1789.                 $this->_testFatalAbort($res__FILE____LINE__);
  1790.                 $sql = "UPDATE $tb SET $freh=$t_order -1 WHERE $fid=$s_id";
  1791.                 $res $this->_query($sql);
  1792.                 $this->_testFatalAbort($res__FILE____LINE__);
  1793.             elseif ($pos == NESE_MOVE_AFTER{
  1794.                 $sql = "UPDATE $tb SET $freh=$freh-1
  1795.                         WHERE $freh BETWEEN $s_order AND $t_order AND
  1796.                             $fid!=$s_id AND
  1797.                             $froot=$fid";
  1798.                 $res $this->_query($sql);
  1799.                 $this->_testFatalAbort($res__FILE____LINE__);
  1800.                 $sql = "UPDATE $tb SET $freh=$t_order WHERE $fid=$s_id";
  1801.                 $res $this->_query($sql);
  1802.                 $this->_testFatalAbort($res__FILE____LINE__);
  1803.             }
  1804.         }
  1805.  
  1806.         if ($s_order $t_order{
  1807.             if ($pos == NESE_MOVE_BEFORE{
  1808.                 $sql = "UPDATE $tb SET $freh=$freh+1
  1809.                         WHERE $freh BETWEEN $t_order AND $s_order AND
  1810.                             $fid != $s_id AND
  1811.                             $froot=$fid";
  1812.                 $res $this->_query($sql);
  1813.                 $this->_testFatalAbort($res__FILE____LINE__);
  1814.                 $sql = "UPDATE $tb SET $freh=$t_order WHERE $fid=$s_id";
  1815.                 $res $this->_query($sql);
  1816.                 $this->_testFatalAbort($res__FILE____LINE__);
  1817.             elseif ($pos == NESE_MOVE_AFTER{
  1818.                 $sql = "UPDATE $tb SET $freh=$freh+1
  1819.                         WHERE $freh BETWEEN $t_order AND $s_order AND
  1820.                         $fid!=$t_id AND
  1821.                         $fid!=$s_id AND
  1822.                         $froot=$fid";
  1823.                 $res $this->_query($sql);
  1824.                 $this->_testFatalAbort($res__FILE____LINE__);
  1825.                 $sql = "UPDATE $tb SET $freh=$t_order+1 WHERE $fid = $s_id";
  1826.                 $res $this->_query($sql);
  1827.                 $this->_testFatalAbort($res__FILE____LINE__);
  1828.             }
  1829.         }
  1830.         $this->_releaseLock();
  1831.         return $s_id;
  1832.     }
  1833.     // }}}
  1834.     // +-----------------------+
  1835.     // | Helper methods        |
  1836.     // +-----------------------+
  1837.     // {{{ _secSort()
  1838.     /**
  1839.     * Callback for uasort used to sort siblings
  1840.     *
  1841.     * @access private
  1842.     */
  1843.     function _secSort($node1$node2{
  1844.         // Within the same level?
  1845.         if ($node1['level'!= $node2['level']{
  1846.             return strnatcmp($node1['l']$node2['l']);
  1847.         }
  1848.         // Are they siblings?
  1849.         $p1 $this->getParent($node1);
  1850.         $p2 $this->getParent($node2);
  1851.         if ($p1['id'!= $p2['id']{
  1852.             return strnatcmp($node1['l']$node2['l']);
  1853.         }
  1854.         // Same field value? Use the lft value then
  1855.         $field $this->params[$this->secondarySort];
  1856.         if ($node1[$field== $node2[$field]{
  1857.             return strnatcmp($node1['l']$node2[l]);
  1858.         }
  1859.         // Compare between siblings with different field value
  1860.         return strnatcmp($node1[$field]$node2[$field]);
  1861.     }
  1862.     // }}}
  1863.     // {{{ _addSQL()
  1864.     /**
  1865.     * Adds a specific type of SQL to a query string
  1866.     *
  1867.     * @param array $addSQL The array of SQL strings to add.  Example value:
  1868.     *                   $addSQL = array(
  1869.     *                   'cols' => 'tb2.col2, tb2.col3',         // Additional tables/columns
  1870.     *                   'join' => 'LEFT JOIN tb1 USING(STRID)', // Join statement
  1871.     *                                       'where' => 'A='B' AND C='D',                    // Where statement without 'WHERE' OR 'AND' in front
  1872.     *                   'append' => 'GROUP by tb1.STRID');      // Group condition
  1873.     * @param string $type The type of SQL.  Can be 'cols', 'join', or 'append'.
  1874.     * @access private
  1875.     * @return string The SQL, properly formatted
  1876.     */
  1877.     function _addSQL($addSQL$type$prefix = false{
  1878.         if (!isset($addSQL[$type])) {
  1879.             return '';
  1880.         }
  1881.  
  1882.         switch ($type{
  1883.             case 'cols':
  1884.             return ', ' $addSQL[$type];
  1885.             case 'where':
  1886.             return $prefix ' (' $addSQL[$type')';
  1887.             default:
  1888.             return $addSQL[$type];
  1889.         }
  1890.     }
  1891.     // }}}
  1892.     // {{{ _getSelectFields()
  1893.     /**
  1894.     * Gets the select fields based on the params
  1895.     *
  1896.     * @param bool $aliasFields Should we alias the fields so they are the names of the
  1897.     *                 parameter keys, or leave them as is?
  1898.     * @access private
  1899.     * @return string A string of query fields to select
  1900.     */
  1901.     function _getSelectFields($aliasFields{
  1902.         $queryFields = array();
  1903.         foreach ($this->params as $key => $val{
  1904.             $tmp_field $this->node_table . '.' $key;
  1905.             if ($aliasFields{
  1906.                 $tmp_field .= ' AS ' $this->_quoteIdentifier($val);
  1907.             }
  1908.             $queryFields[$tmp_field;
  1909.         }
  1910.         $fields implode(', '$queryFields);
  1911.         return $fields;
  1912.     }
  1913.     // }}}
  1914.     // {{{ _processResultSet()
  1915.     /**
  1916.     * Processes a DB result set by checking for a DB error and then transforming the result
  1917.     * into a set of DB_NestedSet_Node objects or leaving it as an array.
  1918.     *
  1919.     * @param string $sql The sql query to be done
  1920.     * @param bool $keepAsArray Keep the result as an array or transform it into a set of
  1921.     *                 DB_NestedSet_Node objects?
  1922.     * @param bool $fieldsAreAliased Are the fields aliased?
  1923.     * @access private
  1924.     * @return mixed False on error or the transformed node set.
  1925.     */
  1926.     function _processResultSet($sql$keepAsArray$fieldsAreAliased{
  1927.         $result $this->_getAll($sql);
  1928.         if ($this->_testFatalAbort($result__FILE____LINE__)) {
  1929.             return false;
  1930.         }
  1931.  
  1932.         $nodes = array();
  1933.         $idKey $fieldsAreAliased 'id' $this->flparams['id'];
  1934.         foreach ($result as $row{
  1935.             $node_id $row[$idKey];
  1936.             if ($keepAsArray{
  1937.                 $nodes[$node_id$row;
  1938.             else {
  1939.                 // Create an instance of the node container
  1940.                 $nodes[$node_idnew DB_NestedSet_Node($row);
  1941.             }
  1942.         }
  1943.         return $nodes;
  1944.     }
  1945.     // }}}
  1946.     // {{{ _testFatalAbort()
  1947.     /**
  1948.     * Error Handler
  1949.     *
  1950.     * Tests if a given ressource is a PEAR error object
  1951.     * ans raises a fatal error in case of an error object
  1952.     *
  1953.     * @param object PEAR::Error $errobj     The object to test
  1954.     * @param string $file The filename wher the error occured
  1955.     * @param int $line The line number of the error
  1956.     * @return void 
  1957.     * @access private
  1958.     */
  1959.     function _testFatalAbort($errobj$file$line{
  1960.         if (!$this->_isDBError($errobj)) {
  1961.             return false;
  1962.         }
  1963.  
  1964.         if ($this->debug{
  1965.             $this->_debugMessage('_testFatalAbort($errobj, $file, $line)');
  1966.         }
  1967.         if ($this->debug{
  1968.             $message $errobj->getUserInfo();
  1969.             $code $errobj->getCode();
  1970.             $msg = "$message ($code) in file $file at line $line";
  1971.         else {
  1972.             $msg $errobj->getMessage();
  1973.             $code $errobj->getCode();
  1974.         }
  1975.  
  1976.         PEAR::raiseError($msg$codePEAR_ERROR_TRIGGERE_USER_ERROR);
  1977.     }
  1978.     // }}}
  1979.     // {{{ __raiseError()
  1980.     /**
  1981.     *
  1982.     * @access private
  1983.     */
  1984.     function _raiseError($code$mode$option$epr = array()) {
  1985.         $message vsprintf($this->_getMessage($code)$epr);
  1986.         return PEAR::raiseError($message$code$mode$option);
  1987.     }
  1988.     // }}}
  1989.     // {{{ addListener()
  1990.     /**
  1991.     * Add an event listener
  1992.     *
  1993.     * Adds an event listener and returns an ID for it
  1994.     * <pre>Known events are
  1995.     * nodeCreate
  1996.     * nodeDelete
  1997.     * nodeUpdate
  1998.     * nodeCopy
  1999.     * nodeLoad
  2000.     * </pre>
  2001.     * @param string $event The event name
  2002.     * @param string $listener The listener object
  2003.     * @return string 
  2004.     * @access public
  2005.     */
  2006.     function addListener($event$listener{
  2007.         $listenerID uniqid('el');
  2008.         $this->eventListeners[$event][$listenerID$listener;
  2009.         $this->_hasListeners[$event= true;
  2010.         return $listenerID;
  2011.     }
  2012.     // }}}
  2013.     // {{{ removeListener()
  2014.     /**
  2015.     * Removes an event listener
  2016.     *
  2017.     * Removes the event listener with the given ID
  2018.     *
  2019.     * @param string $event The ivent name
  2020.     * @param string $listenerID The listener's ID
  2021.     * @return bool 
  2022.     * @access public
  2023.     */
  2024.     function removeListener($event$listenerID{
  2025.         unset($this->eventListeners[$event][$listenerID]);
  2026.         if (!isset($this->eventListeners[$event]|| !is_array($this->eventListeners[$event]||
  2027.         count($this->eventListeners[$event]== 0{
  2028.             unset($this->_hasListeners[$event]);
  2029.         }
  2030.         return true;
  2031.     }
  2032.     // }}}
  2033.     // {{{ triggerEvent()
  2034.     /**
  2035.     * Triggers and event an calls the event listeners
  2036.     *
  2037.     * @param string $event The Event that occured
  2038.     * @param object node $node A Reference to the node object which was subject to changes
  2039.     * @param array $eparams A associative array of params which may be needed by the handler
  2040.     * @return bool 
  2041.     * @access public
  2042.     */
  2043.     function triggerEvent($event$node$eparams = false{
  2044.         if ($this->_skipCallbacks || !isset($this->_hasListeners[$event])) {
  2045.             return false;
  2046.         }
  2047.  
  2048.         foreach($this->eventListeners[$eventas $key => $val{
  2049.             if (!method_exists($val'callEvent')) {
  2050.                 return new PEAR_Error($this->_getMessage(NESE_ERROR_NOHANDLER)NESE_ERROR_NOHANDLER);
  2051.             }
  2052.  
  2053.             $val->callEvent($event$node$eparams);
  2054.         }
  2055.  
  2056.         return true;
  2057.     }
  2058.     // }}}
  2059.     // {{{ apiVersion()
  2060.     function apiVersion({
  2061.         return array('package:' => $this->_packagename,
  2062.         'majorversion' => $this->_majorversion,
  2063.         'minorversion' => $this->_minorversion,
  2064.         'version' => sprintf('%s.%s'$this->_majorversion$this->_minorversion),
  2065.         'revision' => str_replace('$'''"$Revision: 1.83 $")
  2066.         );
  2067.     }
  2068.     // }}}
  2069.     // {{{ setAttr()
  2070.     /**
  2071.     * Sets an object attribute
  2072.     *
  2073.     * @param array $attr An associative array with attributes
  2074.     * @return bool 
  2075.     * @access public
  2076.     */
  2077.     function setAttr($attr{
  2078.         static $hasSetSequence;
  2079.         if (!isset($hasSetSequence)) {
  2080.             $hasSetSequence = false;
  2081.         }
  2082.  
  2083.         if (!is_array($attr|| count($attr== 0{
  2084.             return false;
  2085.         }
  2086.  
  2087.         foreach ($attr as $key => $val{
  2088.             $this->$key $val;
  2089.             if ($key == 'sequence_table'{
  2090.                 $hasSetSequence = true;
  2091.             }
  2092.             // only update sequence to reflect new table if they haven't set it manually
  2093.             if (!$hasSetSequence && $key == 'node_table'{
  2094.                 $this->sequence_table = $this->node_table . '_' $this->flparams['id'];
  2095.             }
  2096.             if ($key == 'cache' && is_object($val)) {
  2097.                 $this->_caching = true;
  2098.                 $GLOBALS['DB_NestedSet'$this;
  2099.             }
  2100.         }
  2101.  
  2102.         return true;
  2103.     }
  2104.     // }}}
  2105.     // {{{ setsortMode()
  2106.     /**
  2107.     * This enables you to set specific options for each output method
  2108.     *
  2109.     * @param constant $sortMode 
  2110.     * @access public
  2111.     * @return Current sortMode
  2112.     */
  2113.     function setsortMode($sortMode = false{
  2114.         if ($sortMode && in_array($sortMode$this->_sortModes)) {
  2115.             $this->_sortMode $sortMode;
  2116.         else {
  2117.             return $this->_sortMode;
  2118.         }
  2119.         return $this->_sortMode;
  2120.     }
  2121.     // }}}
  2122.     // {{{ setDbOption()
  2123.     /**
  2124.     * Sets a db option.  Example, setting the sequence table format
  2125.     *
  2126.     * @var string $option The option to set
  2127.     * @var string $val The value of the option
  2128.     * @access public
  2129.     * @return void 
  2130.     */
  2131.     function setDbOption($option$val{
  2132.         $this->db->setOption($option$val);
  2133.     }
  2134.     // }}}
  2135.     // {{{ testLock()
  2136.     /**
  2137.     * Tests if a database lock is set
  2138.     *
  2139.     * @access public
  2140.     */
  2141.     function testLock({
  2142.         if ($this->debug{
  2143.             $this->_debugMessage('testLock()');
  2144.         }
  2145.  
  2146.         if ($lockID $this->_structureTableLock{
  2147.             return $lockID;
  2148.         }
  2149.         $this->_lockGC();
  2150.         $sql sprintf('SELECT lockID FROM %s WHERE lockTable=%s',
  2151.         $this->lock_table,
  2152.         $this->_quote($this->node_table)) ;
  2153.         $res $this->_query($sql);
  2154.         $this->_testFatalAbort($res__FILE____LINE__);
  2155.         if ($this->_numRows($res)) {
  2156.             return new PEAR_Error($this->_getMessage(NESE_ERROR_TBLOCKED)NESE_ERROR_TBLOCKED);
  2157.         }
  2158.  
  2159.         return false;
  2160.     }
  2161.     // }}}
  2162.     // {{{ _setLock()
  2163.     /**
  2164.     *
  2165.     * @access private
  2166.     */
  2167.     function _setLock($exclusive = false{
  2168.         $lock $this->testLock();
  2169.         if (PEAR::isError($lock)) {
  2170.             return $lock;
  2171.         }
  2172.  
  2173.         if ($this->debug{
  2174.             $this->_debugMessage('_setLock()');
  2175.         }
  2176.         if ($this->_caching{
  2177.             @$this->cache->flush('function_cache');
  2178.             $this->_caching = false;
  2179.             $this->_restcache = true;
  2180.         }
  2181.  
  2182.         if (!$lockID $this->_structureTableLock{
  2183.             $lockID $this->_structureTableLock uniqid('lck-');
  2184.             $sql sprintf('INSERT INTO %s (lockID, lockTable, lockStamp) VALUES (%s, %s, %s)',
  2185.             $this->lock_table,
  2186.             $this->_quote($lockID)$this->_quote($this->node_table)time());
  2187.         else {
  2188.             $sql sprintf('UPDATE %s SET lockStamp=%s WHERE lockID=%s AND lockTable=%s',
  2189.             $this->lock_table,
  2190.             time(),
  2191.             $this->_quote($lockID)$this->_quote($this->node_table));
  2192.         }
  2193.  
  2194.         if ($exclusive{
  2195.             $this->_lockExclusive = true;
  2196.         }
  2197.  
  2198.         $res $this->_query($sql);
  2199.         $this->_testFatalAbort($res__FILE____LINE__);
  2200.         return $lockID;
  2201.     }
  2202.     // }}}
  2203.     // {{{ _releaseLock()
  2204.     /**
  2205.     *
  2206.     * @access private
  2207.     */
  2208.     function _releaseLock($exclusive = false{
  2209.         if ($this->debug{
  2210.             $this->_debugMessage('_releaseLock()');
  2211.         }
  2212.  
  2213.         if ($exclusive{
  2214.             $this->_lockExclusive = false;
  2215.         }
  2216.  
  2217.         if ((!$lockID $this->_structureTableLock|| $this->_lockExclusive{
  2218.             return false;
  2219.         }
  2220.  
  2221.         $tb $this->lock_table;
  2222.         $stb $this->node_table;
  2223.         $sql = "DELETE FROM $tb
  2224.                 WHERE lockTable=" . $this->_quote($stb" AND
  2225.                     lockID=" $this->_quote($lockID);
  2226.         $res $this->_query($sql);
  2227.         $this->_testFatalAbort($res__FILE____LINE__);
  2228.         $this->_structureTableLock = false;
  2229.         if ($this->_restcache{
  2230.             $this->_caching = true;
  2231.             $this->_restcache = false;
  2232.         }
  2233.         return true;
  2234.     }
  2235.     // }}}
  2236.     // {{{ _lockGC()
  2237.     /**
  2238.     *
  2239.     * @access private
  2240.     */
  2241.     function _lockGC({
  2242.         if ($this->debug{
  2243.             $this->_debugMessage('_lockGC()');
  2244.         }
  2245.         $tb $this->lock_table;
  2246.         $stb $this->node_table;
  2247.         $lockTTL time($this->lockTTL;
  2248.         $sql = "DELETE FROM $tb
  2249.                 WHERE lockTable=" . $this->_quote($stb. " AND
  2250.                     lockStamp < $lockTTL";
  2251.         $res $this->_query($sql);
  2252.         $this->_testFatalAbort($res__FILE____LINE__);
  2253.     }
  2254.     // }}}
  2255.     // {{{ _values2UpdateQuery()
  2256.     /**
  2257.     *
  2258.     * @access private
  2259.     */
  2260.     function _values2UpdateQuery($values$addval = false{
  2261.         if ($this->debug{
  2262.             $this->_debugMessage('_values2UpdateQuery($values, $addval = false)');
  2263.         }
  2264.         if (is_array($addval)) {
  2265.             $values $values $addval;
  2266.         }
  2267.  
  2268.         $arq = array();
  2269.         foreach($values AS $key => $val{
  2270.             $k $this->_quoteIdentifier(trim($key));
  2271.  
  2272.             // To be used with the next major version
  2273.             // $iv = in_array($this->params[$k], $this->_quotedParams) ? $this->_quote($v) : $v;
  2274.             $iv $this->_quote(trim($val));
  2275.             $arq[= "$k=$iv";
  2276.         }
  2277.  
  2278.         if (!is_array($arq|| count($arq== 0{
  2279.             return false;
  2280.         }
  2281.  
  2282.         $query implode(', '$arq);
  2283.         return $query;
  2284.     }
  2285.     // }}}
  2286.     // {{{ _values2UpdateQuery()
  2287.     /**
  2288.     *
  2289.     * @access private
  2290.     */
  2291.     function _values2InsertQuery($values$addval = false{
  2292.         if ($this->debug{
  2293.             $this->_debugMessage('_values2InsertQuery($values, $addval = false)');
  2294.         }
  2295.         if (is_array($addval)) {
  2296.             $values $values $addval;
  2297.         }
  2298.  
  2299.         $arq = array();
  2300.         foreach($values AS $key => $val{
  2301.             $k $this->_quoteIdentifier(trim($key));
  2302.  
  2303.             // To be used with the next major version
  2304.             // $iv = in_array($this->params[$k], $this->_quotedParams) ? $this->_quote($v) : $v;
  2305.             $iv $this->_quote(trim($val));
  2306.             $arq[$k$iv;
  2307.         }
  2308.  
  2309.         if (!is_array($arq|| count($arq== 0{
  2310.             return false;
  2311.         }
  2312.  
  2313.         return $arq;
  2314.     }
  2315.     // }}}
  2316.     // {{{ _verifyUserValues()
  2317.     /**
  2318.     * Clean values from protected or unknown columns
  2319.     *
  2320.     * @var string $caller The calling method
  2321.     * @var string $values The values array
  2322.     * @access private
  2323.     * @return void 
  2324.     */
  2325.     function _verifyUserValues($caller$values{
  2326.         if ($this->_dumbmode{
  2327.             return true;
  2328.         }
  2329.         foreach($values as $field => $value{
  2330.             if (!isset($this->params[$field])) {
  2331.                 $epr = array($callersprintf('Unknown column/param \'%s\''$field));
  2332.                 $this->_raiseError(NESE_ERROR_WRONG_MPARAMPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  2333.                 unset($values[$field]);
  2334.             else {
  2335.                 $flip $this->params[$field];
  2336.                 if (in_array($flip$this->_requiredParams)) {
  2337.                     $epr = array($callersprintf('\'%s\' is autogenerated and can\'t be passed - it will be ignored'$field));
  2338.                     $this->_raiseError(NESE_ERROR_WRONG_MPARAMPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  2339.                     unset($values[$field]);
  2340.                 }
  2341.             }
  2342.         }
  2343.     }
  2344.     // }}}
  2345.     // {{{ _debugMessage()
  2346.     /**
  2347.     *
  2348.     * @access private
  2349.     */
  2350.     function _debugMessage($msg{
  2351.         if ($this->debug{
  2352.             list($usec$secexplode(' 'microtime());
  2353.             $time ((float)$usec + (float)$sec);
  2354.             echo "$time::Debug:: $msg<br />\n";
  2355.         }
  2356.     }
  2357.     // }}}
  2358.     // {{{ _getMessage()
  2359.     /**
  2360.     *
  2361.     * @access private
  2362.     */
  2363.     function _getMessage($code{
  2364.         if ($this->debug{
  2365.             $this->_debugMessage('_getMessage($code)');
  2366.         }
  2367.         return isset($this->messages[$code]$this->messages[$code$this->messages[NESE_MESSAGE_UNKNOWN];
  2368.     }
  2369.     // }}}
  2370.     // {{{ convertTreeModel()
  2371.     /**
  2372.     * Convert a <1.3 tree into a 1.3 tree format
  2373.     *
  2374.     * This will convert the tree into a format needed for some new features in
  2375.     * 1.3. Your <1.3 tree will still work without converting but some new features
  2376.     * like preorder sorting won't work as expected.
  2377.     *
  2378.     * <pre>
  2379.     * Usage:
  2380.     * - Create a new node table (tb_nodes2) from the current node table (tb_nodes1) (only copy the structure).
  2381.     * - Create a nested set instance of the 'old' set (NeSe1) and one of the new set (NeSe2)
  2382.     * - Now you have 2 identical objects where only node_table differs
  2383.     * - Call DB_NestedSet::convertTreeModel(&$orig, &$copy);
  2384.     * - After that you have a cleaned up copy of tb_nodes1 inside tb_nodes2
  2385.     * </pre>
  2386.     *
  2387.     * @param object DB_NestedSet $orig  Nested set we want to copy
  2388.     * @param object DB_NestedSet $copy  Object where the new tree is copied to
  2389.     * @param integer $_parent ID of the parent node (private)
  2390.     * @static
  2391.     * @access public
  2392.     * @return bool True uns success
  2393.     */
  2394.     function convertTreeModel($orig$copy$_parent = false{
  2395.         static $firstSet;
  2396.         $isRoot = false;
  2397.         if (!$_parent{
  2398.             if (!is_object($orig|| !is_object($copy)) {
  2399.                 return false;
  2400.             }
  2401.             if ($orig->node_table == $copy->node_table{
  2402.                 return false;
  2403.             }
  2404.             $copy->_dumbmode = true;
  2405.             $orig->sortMode = NESE_SORT_LEVEL;
  2406.             $copy->sortMode = NESE_SORT_LEVEL;
  2407.             $sibl $orig->getRootNodes(true);
  2408.             $isRoot = true;
  2409.         else {
  2410.             $sibl $orig->getChildren($_parenttrue);
  2411.         }
  2412.  
  2413.         if (empty($sibl)) {
  2414.             return false;
  2415.         }
  2416.  
  2417.         foreach($sibl AS $sid => $sibling{
  2418.             unset($sibling['l']);
  2419.             unset($sibling['r']);
  2420.             unset($sibling['norder']);
  2421.             $values = array();
  2422.             foreach($sibling AS $key => $val{
  2423.                 if (!isset($copy->flparams[$key])) {
  2424.                     continue;
  2425.                 }
  2426.                 $values[$copy->flparams[$key]] $val;
  2427.             }
  2428.  
  2429.             if (!$firstSet{
  2430.                 $psid $copy->createRootNode($valuesfalsetrue);
  2431.                 $firstSet = true;
  2432.             elseif ($isRoot{
  2433.                 $psid $copy->createRightNode($psid$values);
  2434.             else {
  2435.                 $copy->createSubNode($_parent$values);
  2436.             }
  2437.  
  2438.             DB_NestedSet::convertTreeModel($orig$copy$sid);
  2439.         }
  2440.         return true;
  2441.     }
  2442.     // }}}
  2443. }
  2444. // {{{ DB_NestedSet_Node:: class
  2445. /**
  2446. * Generic class for node objects
  2447. *
  2448. @autor Daniel Khan <dk@webcluster.at>;
  2449. @version $Revision: 1.83 $
  2450. @package DB_NestedSet
  2451. @access private
  2452. */
  2453.  
  2454. class DB_NestedSet_Node {
  2455.     // {{{ constructor
  2456.     /**
  2457.     * Constructor
  2458.     */
  2459.     function DB_NestedSet_Node($data{
  2460.         if (!is_array($data|| count($data== 0{
  2461.             return new PEAR_ERROR($dataNESE_ERROR_PARAM_MISSING);
  2462.         }
  2463.  
  2464.         $this->setAttr($data);
  2465.         return true;
  2466.     }
  2467.     // }}}
  2468.     // {{{ setAttr()
  2469.     function setAttr($data{
  2470.         if (!is_array($data|| count($data== 0{
  2471.             return false;
  2472.         }
  2473.  
  2474.         foreach ($data as $key => $val{
  2475.             $this->$key $val;
  2476.         }
  2477.     }
  2478.     // }}}
  2479. }
  2480. // }}}
  2481. ?>

Documentation generated on Mon, 11 Mar 2019 13:54:04 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.