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.79 2004/04/02 00:15:05 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.79 $
  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.  
  946.         $this->_verifyUserValues('createRootNode()'$values);
  947.         // If they specified an id, see if the parent is valid
  948.         if (!$first && ($id && !$parent $this->pickNode($idtrue))) {
  949.             $epr = array('createRootNode()'$id);
  950.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  951.         elseif ($first && $id{
  952.             // No notice for now.  But these 2 params don't make sense together
  953.             $epr = array('createRootNode()''[id] AND [first] were passed - that doesn\'t make sense');
  954.             // $this->_raiseError(NESE_ERROR_WRONG_MPARAM, E_USER_WARNING, $epr);
  955.         elseif (!$first && !$id{
  956.             // If no id was specified, then determine order
  957.             $parent = array();
  958.             if ($pos == NESE_MOVE_BEFORE{
  959.                 $parent['norder'= 1;
  960.             elseif ($pos == NESE_MOVE_AFTER{
  961.                 // Put it at the end of the tree
  962.                 $qry sprintf('SELECT MAX(%s) FROM %s WHERE %s=1',
  963.                     $this->flparams['norder'],
  964.                     $this->node_table,
  965.                     $this->flparams['l']);
  966.                 $tmp_order $this->db->getOne($qry);
  967.                 // If null, then it's the first one
  968.                 $parent['norder'is_null($tmp_order? 0 : $tmp_order;
  969.             }
  970.         }
  971.         // Try to aquire a table lock
  972.         if (PEAR::isError($lock $this->_setLock())) {
  973.             return $lock;
  974.         }
  975.  
  976.         $sql = array();
  977.         $addval = array();
  978.         $addval[$this->flparams['level']] = 1;
  979.         // Shall we delete the existing tree (reinit)
  980.         if ($first{
  981.             $dsql sprintf('DELETE FROM %s'$this->node_table);
  982.             $this->db->query($dsql);
  983.             $this->_dropSequence($this->sequence_table);
  984.             // New order of the new node will be 1
  985.             $addval[$this->flparams['norder']] = 1;
  986.         else {
  987.             // Let's open a gap for the new node
  988.             if ($pos == NESE_MOVE_AFTER{
  989.                 $addval[$this->flparams['norder']] $parent['norder'+ 1;
  990.                 $sql[sprintf('UPDATE %s SET %s=%s+1 WHERE %s=1 AND %s > %s',
  991.                     $this->node_table,
  992.                     $this->flparams['norder']$this->flparams['norder'],
  993.                     $this->flparams['l'],
  994.                     $this->flparams['norder']$parent['norder']);
  995.             elseif ($pos == NESE_MOVE_BEFORE{
  996.                 $addval[$this->flparams['norder']] $parent['norder'];
  997.                 $sql[sprintf('UPDATE %s SET %s=%s+1 WHERE %s=1 AND %s >= %s',
  998.                     $this->node_table,
  999.                     $this->flparams['norder']$this->flparams['norder'],
  1000.                     $this->flparams['l'],
  1001.                     $this->flparams['norder']$parent['norder']);
  1002.             }
  1003.         }
  1004.  
  1005.         if (isset($this->flparams['parent'])) {
  1006.             $addval[$this->flparams['parent']] = 0;
  1007.         }
  1008.         // Sequence of node id (equals to root id in this case
  1009.         if (!$this->_dumbmode || !$node_id = isset($values[$this->flparams['id']]|| !isset($values[$this->flparams['rootid']])) {
  1010.             $addval[$this->flparams['rootid']] $node_id $addval[$this->flparams['id']] $this->db->nextId($this->sequence_table);
  1011.         else {
  1012.             $node_id $values[$this->flparams['id']];
  1013.         }
  1014.         // Left/Right values for rootnodes
  1015.         $addval[$this->flparams['l']] = 1;
  1016.         $addval[$this->flparams['r']] = 2;
  1017.         // Transform the node data hash to a query
  1018.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1019.             $this->_releaseLock();
  1020.             return false;
  1021.         }
  1022.         // Insert the new node
  1023.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1024.         foreach ($sql as $qry{
  1025.             $res $this->db->query($qry);
  1026.             $this->_testFatalAbort($res__FILE____LINE__);
  1027.         }
  1028.         // EVENT (nodeCreate)
  1029.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1030.             $this->triggerEvent('nodeCreate'$this->pickNode($node_id));
  1031.         }
  1032.         $this->_releaseLock();
  1033.         return $node_id;
  1034.     }
  1035.     // }}}
  1036.     // {{{ createSubNode()
  1037.     /**
  1038.      * Creates a subnode
  1039.      *
  1040.      * <pre>
  1041.      * +-- root1
  1042.      * |
  1043.      * +-\ root2 [target]
  1044.      * | |
  1045.      * | |-- subnode1 [new]
  1046.      * |
  1047.      * +-- root3
  1048.      * </pre>
  1049.      *
  1050.      * @param integer $id Parent node ID
  1051.      * @param array $values Hash with param => value pairs of the node (see $this->params)
  1052.      * @access public
  1053.      * @return mixed The node id or false on error
  1054.      */
  1055.     function createSubNode($id$values{
  1056.         if ($this->debug{
  1057.             $this->_debugMessage('createSubNode($id, $values)');
  1058.         }
  1059.         // invalid parent id, bail out
  1060.         if (!($thisnode $this->pickNode($idtrue))) {
  1061.             $epr = array('createSubNode()'$id);
  1062.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1063.         }
  1064.         // Try to aquire a table lock
  1065.         if (PEAR::isError($lock $this->_setLock())) {
  1066.             return $lock;
  1067.         }
  1068.  
  1069.         $this->_verifyUserValues('createRootNode()'$values);
  1070.         // Get the children of the target node
  1071.         $children $this->getChildren($idtrue);
  1072.         // We have children here
  1073.         if ($thisnode['r']-1 != $thisnode['l']{
  1074.             // Get the last child
  1075.             $last array_pop($children);
  1076.             // What we have to do is virtually an insert of a node after the last child
  1077.             // So we don't have to proceed creating a subnode
  1078.             $newNode $this->createRightNode($last['id']$values);
  1079.             $this->_releaseLock();
  1080.             return $newNode;
  1081.         }
  1082.  
  1083.         $sql = array();
  1084.         $sql[sprintf('UPDATE %s SET
  1085.                 %s=CASE WHEN %s>%s THEN %s+2 ELSE %s END,
  1086.                 %s=CASE WHEN (%s>%s OR %s>=%s) THEN %s+2 ELSE %s END
  1087.                 WHERE %s=%s',
  1088.             $this->node_table,
  1089.             $this->flparams['l'],
  1090.             $this->flparams['l']$thisnode['l'],
  1091.             $this->flparams['l']$this->flparams['l'],
  1092.             $this->flparams['r'],
  1093.             $this->flparams['l']$thisnode['l'],
  1094.             $this->flparams['r']$thisnode['r'],
  1095.             $this->flparams['r']$this->flparams['r'],
  1096.             $this->flparams['rootid']$thisnode['rootid']);
  1097.         $addval = array();
  1098.         if (isset($this->flparams['parent'])) {
  1099.             $addval[$this->flparams['parent']] $thisnode['id'];
  1100.         }
  1101.  
  1102.         $addval[$this->flparams['l']] $thisnode['r'];
  1103.         $addval[$this->flparams['r']] $thisnode['r'+ 1;
  1104.         $addval[$this->flparams['rootid']] $thisnode['rootid'];
  1105.         $addval[$this->flparams['norder']] = 1;
  1106.         $addval[$this->flparams['level']] $thisnode['level'+ 1;
  1107.         if (!$this->_dumbmode || !$node_id = isset($values[$this->flparams['id']])) {
  1108.             $node_id $addval[$this->flparams['id']] $this->db->nextId($this->sequence_table);
  1109.         else {
  1110.             $node_id $values[$this->flparams['id']];
  1111.         }
  1112.  
  1113.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1114.             $this->_releaseLock();
  1115.             return false;
  1116.         }
  1117.  
  1118.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1119.         foreach ($sql as $qry{
  1120.             $res $this->db->query($qry);
  1121.             $this->_testFatalAbort($res__FILE____LINE__);
  1122.         }
  1123.         // EVENT (NodeCreate)
  1124.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1125.             $thisnode $this->pickNode($node_id);
  1126.             $this->triggerEvent('nodeCreate'$this->pickNode($id));
  1127.         }
  1128.         $this->_releaseLock();
  1129.         return $node_id;
  1130.     }
  1131.     // }}}
  1132.     // {{{ createLeftNode()
  1133.     /**
  1134.      * Creates a node before a given node
  1135.      * <pre>
  1136.      * +-- root1
  1137.      * |
  1138.      * +-\ root2
  1139.      * | |
  1140.      * | |-- subnode2 [new]
  1141.      * | |-- subnode1 [target]
  1142.      * | |-- subnode3
  1143.      * |
  1144.      * +-- root3
  1145.      * </pre>
  1146.      *
  1147.      * @param int $id Target node ID
  1148.      * @param array $values Hash with param => value pairs of the node (see $this->params)
  1149.      * @param bool $returnID Tell the method to return a node id instead of an object.
  1150.      *                                    ATTENTION: That the method defaults to return an object instead of the node id
  1151.      *                                    has been overseen and is basically a bug. We have to keep this to maintain BC.
  1152.      *                                    You will have to set $returnID to true to make it behave like the other creation methods.
  1153.      *                                    This flaw will get fixed with the next major version.
  1154.      * @access public
  1155.      * @return mixed The node id or false on error
  1156.      */
  1157.     function createLeftNode($id$values{
  1158.         if ($this->debug{
  1159.             $this->_debugMessage('createLeftNode($target, $values)');
  1160.         }
  1161.  
  1162.         $this->_verifyUserValues('createLeftode()'$values);
  1163.         // invalid target node, bail out
  1164.         if (!($thisnode $this->pickNode($idtrue))) {
  1165.             $epr = array('createLeftNode()'$id);
  1166.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1167.         }
  1168.  
  1169.         if (PEAR::isError($lock $this->_setLock())) {
  1170.             return $lock;
  1171.         }
  1172.         // If the target node is a rootnode we virtually want to create a new root node
  1173.         if ($thisnode['rootid'== $thisnode['id']{
  1174.             return $this->createRootNode($values$idfalseNESE_MOVE_BEFORE);
  1175.         }
  1176.  
  1177.         $addval = array();
  1178.         $parent $this->getParent($idtrue);
  1179.         if (isset($this->flparams['parent'])) {
  1180.             $addval[$this->flparams['parent']] $parent['id'];
  1181.         }
  1182.  
  1183.         $sql = array();
  1184.         $sql[sprintf('UPDATE %s SET %s=%s+1
  1185.                         WHERE %s=%s AND %s>=%s AND %s=%s AND %s BETWEEN %s AND %s',
  1186.             $this->node_table,
  1187.             $this->flparams['norder']$this->flparams['norder'],
  1188.             $this->flparams['rootid']$thisnode['rootid'],
  1189.             $this->flparams['norder']$thisnode['norder'],
  1190.             $this->flparams['level']$thisnode['level'],
  1191.             $this->flparams['l']$parent['l']$parent['r']);
  1192.         // Update all nodes which have dependent left and right values
  1193.         $sql[sprintf('UPDATE %s SET
  1194.                 %s=CASE WHEN %s>=%s THEN %s+2 ELSE %s END,
  1195.                 %s=CASE WHEN (%s>=%s OR %s>=%s) THEN %s+2 ELSE %s END
  1196.                 WHERE %s=%s',
  1197.             $this->node_table,
  1198.             $this->flparams['l'],
  1199.             $this->flparams['l']$thisnode['l'],
  1200.             $this->flparams['l']$this->flparams['l'],
  1201.             $this->flparams['r'],
  1202.             $this->flparams['r']$thisnode['r'],
  1203.             $this->flparams['l']$thisnode['l'],
  1204.             $this->flparams['r']$this->flparams['r'],
  1205.             $this->flparams['rootid']$thisnode['rootid']);
  1206.         $addval[$this->flparams['norder']] $thisnode['norder'];
  1207.         $addval[$this->flparams['l']] $thisnode['l'];
  1208.         $addval[$this->flparams['r']] $thisnode['l'+ 1;
  1209.         $addval[$this->flparams['rootid']] $thisnode['rootid'];
  1210.         $addval[$this->flparams['level']] $thisnode['level'];
  1211.         if (!$this->_dumbmode || !$node_id = isset($values[$this->flparams['id']])) {
  1212.             $node_id $addval[$this->flparams['id']] $this->db->nextId($this->sequence_table);
  1213.         else {
  1214.             $node_id $values[$this->flparams['id']];
  1215.         }
  1216.  
  1217.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1218.             $this->_releaseLock();
  1219.             return false;
  1220.         }
  1221.         // Insert the new node
  1222.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1223.         foreach ($sql as $qry{
  1224.             $res $this->db->query($qry);
  1225.             $this->_testFatalAbort($res__FILE____LINE__);
  1226.         }
  1227.         // EVENT (NodeCreate)
  1228.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1229.             $this->triggerEvent('nodeCreate'$this->pickNode($id));
  1230.         }
  1231.         $this->_releaseLock();
  1232.         return $node_id;
  1233.     }
  1234.     // }}}
  1235.     // {{{ createRightNode()
  1236.     /**
  1237.      * Creates a node after a given node
  1238.      * <pre>
  1239.      * +-- root1
  1240.      * |
  1241.      * +-\ root2
  1242.      * | |
  1243.      * | |-- subnode1 [target]
  1244.      * | |-- subnode2 [new]
  1245.      * | |-- subnode3
  1246.      * |
  1247.      * +-- root3
  1248.      * </pre>
  1249.      *
  1250.      * @param int $id Target node ID
  1251.      * @param array $values Hash with param => value pairs of the node (see $this->params)
  1252.      * @param bool $returnID Tell the method to return a node id instead of an object.
  1253.      *                                    ATTENTION: That the method defaults to return an object instead of the node id
  1254.      *                                    has been overseen and is basically a bug. We have to keep this to maintain BC.
  1255.      *                                    You will have to set $returnID to true to make it behave like the other creation methods.
  1256.      *                                    This flaw will get fixed with the next major version.
  1257.      * @access public
  1258.      * @return mixed The node id or false on error
  1259.      */
  1260.     function createRightNode($id$values{
  1261.         if ($this->debug{
  1262.             $this->_debugMessage('createRightNode($target, $values)');
  1263.         }
  1264.  
  1265.         $this->_verifyUserValues('createRootNode()'$values);
  1266.         // invalid target node, bail out
  1267.         if (!($thisnode $this->pickNode($idtrue))) {
  1268.             $epr = array('createRightNode()'$id);
  1269.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1270.         }
  1271.  
  1272.         if (PEAR::isError($lock $this->_setLock())) {
  1273.             return $lock;
  1274.         }
  1275.         // If the target node is a rootnode we virtually want to create a new root node
  1276.         if ($thisnode['rootid'== $thisnode['id']{
  1277.             $nid $this->createRootNode($values$id);
  1278.             $this->_releaseLock();
  1279.             return $nid;
  1280.         }
  1281.  
  1282.         $addval = array();
  1283.         $parent $this->getParent($idtrue);
  1284.         if (isset($this->flparams['parent'])) {
  1285.             $addval[$this->flparams['parent']] $parent['id'];
  1286.         }
  1287.  
  1288.         $sql = array();
  1289.         $sql[sprintf('UPDATE %s SET %s=%s+1
  1290.                         WHERE %s=%s AND %s>%s AND %s=%s AND %s BETWEEN %s AND %s',
  1291.             $this->node_table,
  1292.             $this->flparams['norder']$this->flparams['norder'],
  1293.             $this->flparams['rootid']$thisnode['rootid'],
  1294.             $this->flparams['norder']$thisnode['norder'],
  1295.             $this->flparams['level']$thisnode['level'],
  1296.             $this->flparams['l']$parent['l']$parent['r']);
  1297.         // Update all nodes which have dependent left and right values
  1298.         $sql[sprintf('UPDATE %s SET
  1299.                 %s=CASE WHEN (%s>%s AND %s>%s) THEN %s+2 ELSE %s END,
  1300.                 %s=CASE WHEN %s>%s THEN %s+2 ELSE %s END
  1301.                 WHERE %s=%s',
  1302.             $this->node_table,
  1303.             $this->flparams['l'],
  1304.             $this->flparams['l']$thisnode['l'],
  1305.             $this->flparams['r']$thisnode['r'],
  1306.             $this->flparams['l']$this->flparams['l'],
  1307.             $this->flparams['r'],
  1308.             $this->flparams['r']$thisnode['r'],
  1309.             $this->flparams['r']$this->flparams['r'],
  1310.             $this->flparams['rootid']$thisnode['rootid']);
  1311.         $addval[$this->flparams['norder']] $thisnode['norder'+ 1;
  1312.         $addval[$this->flparams['l']] $thisnode['r'+ 1;
  1313.         $addval[$this->flparams['r']] $thisnode['r'+ 2;
  1314.         $addval[$this->flparams['rootid']] $thisnode['rootid'];
  1315.         $addval[$this->flparams['level']] $thisnode['level'];
  1316.         if (!$this->_dumbmode || !isset($values[$this->flparams['id']])) {
  1317.             $node_id $addval[$this->flparams['id']] $this->db->nextId($this->sequence_table);
  1318.         else {
  1319.             $node_id $values[$this->flparams['id']];
  1320.         }
  1321.  
  1322.         if (!$qr $this->_values2InsertQuery($values$addval)) {
  1323.             $this->_releaseLock();
  1324.             return false;
  1325.         }
  1326.         // Insert the new node
  1327.         $sql[sprintf('INSERT INTO %s (%s) VALUES (%s)'$this->node_tableimplode(', 'array_keys($qr))implode(', '$qr));
  1328.         foreach ($sql as $qry{
  1329.             $res $this->db->query($qry);
  1330.             $this->_testFatalAbort($res__FILE____LINE__);
  1331.         }
  1332.         // EVENT (NodeCreate)
  1333.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCreate'])) {
  1334.             $this->triggerEvent('nodeCreate'$this->pickNode($id));
  1335.         }
  1336.         $this->_releaseLock();
  1337.         return $node_id;
  1338.     }
  1339.     // }}}
  1340.     // {{{ deleteNode()
  1341.     /**
  1342.      * Deletes a node
  1343.      *
  1344.      * @param int $id ID of the node to be deleted
  1345.      * @access public
  1346.      * @return bool True if the delete succeeds
  1347.      */
  1348.     function deleteNode($id{
  1349.         if ($this->debug{
  1350.             $this->_debugMessage("deleteNode($id)");
  1351.         }
  1352.         // invalid target node, bail out
  1353.         if (!($thisnode $this->pickNode($idtrue))) {
  1354.             $epr = array('deleteNode()'$id);
  1355.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1356.         }
  1357.  
  1358.         if (PEAR::isError($lock $this->_setLock())) {
  1359.             return $lock;
  1360.         }
  1361.  
  1362.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeDelete'])) {
  1363.             // EVENT (NodeDelete)
  1364.             $this->triggerEvent('nodeDelete'$this->pickNode($id));
  1365.         }
  1366.  
  1367.         $parent $this->getParent($idtrue);
  1368.         $len $thisnode['r'$thisnode['l'+ 1;
  1369.         $sql = array();
  1370.         // Delete the node
  1371.         $sql[sprintf('DELETE FROM %s WHERE %s BETWEEN %s AND %s AND %s=%s',
  1372.             $this->node_table,
  1373.             $this->flparams['l']$thisnode['l']$thisnode['r'],
  1374.             $this->flparams['rootid']$thisnode['rootid']);
  1375.         if ($thisnode['id'!= $thisnode['rootid']{
  1376.             // The node isn't a rootnode so close the gap
  1377.             $sql[sprintf('UPDATE %s SET
  1378.                             %s=CASE WHEN %s>%s THEN %s-%s ELSE %s END,
  1379.                             %s=CASE WHEN %s>%s THEN %s-%s ELSE %s END
  1380.                             WHERE %s=%s AND (%s>%s OR %s>%s)',
  1381.                 $this->node_table,
  1382.                 $this->flparams['l'],
  1383.                 $this->flparams['l']$thisnode['l'],
  1384.                 $this->flparams['l']$len$this->flparams['l'],
  1385.                 $this->flparams['r'],
  1386.                 $this->flparams['r']$thisnode['l'],
  1387.                 $this->flparams['r']$len$this->flparams['r'],
  1388.                 $this->flparams['rootid']$thisnode['rootid'],
  1389.                 $this->flparams['l']$thisnode['l'],
  1390.                 $this->flparams['r']$thisnode['r']);
  1391.             // Re-order
  1392.             $sql[sprintf('UPDATE %s SET %s=%s-1
  1393.                     WHERE %s=%s AND %s=%s AND %s>%s AND %s BETWEEN %s AND %s',
  1394.                 $this->node_table,
  1395.                 $this->flparams['norder']$this->flparams['norder'],
  1396.                 $this->flparams['rootid']$thisnode['rootid'],
  1397.                 $this->flparams['level']$thisnode['level'],
  1398.                 $this->flparams['norder']$thisnode['norder'],
  1399.                 $this->flparams['l']$parent['l']$parent['r']);
  1400.         else {
  1401.             // A rootnode was deleted and we only have to close the gap inside the order
  1402.             $sql[sprintf('UPDATE %s SET %s=%s-1 WHERE %s=%s AND %s > %s',
  1403.                 $this->node_table,
  1404.                 $this->flparams['norder']$this->flparams['norder'],
  1405.                 $this->flparams['rootid']$this->flparams['id'],
  1406.                 $this->flparams['norder']$thisnode['norder']);
  1407.         }
  1408.  
  1409.         foreach ($sql as $qry{
  1410.             $res $this->db->query($qry);
  1411.             $this->_testFatalAbort($res__FILE____LINE__);
  1412.         }
  1413.         $this->_releaseLock();
  1414.         return true;
  1415.     }
  1416.     // }}}
  1417.     // {{{ updateNode()
  1418.     /**
  1419.      * Changes the payload of a node
  1420.      *
  1421.      * @param int $id Node ID
  1422.      * @param array $values Hash with param => value pairs of the node (see $this->params)
  1423.      * @param bool $_intermal Internal use only. Used to skip value validation. Leave this as it is.
  1424.      * @access public
  1425.      * @return bool True if the update is successful
  1426.      */
  1427.     function updateNode($id$values$_internal = false{
  1428.         if ($this->debug{
  1429.             $this->_debugMessage('updateNode($id, $values)');
  1430.         }
  1431.  
  1432.         if (PEAR::isError($lock $this->_setLock())) {
  1433.             return $lock;
  1434.         }
  1435.  
  1436.         if (!$_internal{
  1437.             $this->_verifyUserValues('createRootNode()'$values);
  1438.         }
  1439.  
  1440.         $eparams = array('values' => $values);
  1441.         if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeUpdate'])) {
  1442.             // EVENT (NodeUpdate)
  1443.             $this->triggerEvent('nodeUpdate'$this->pickNode($id)$eparams);
  1444.         }
  1445.  
  1446.         $addvalues = array();
  1447.         if (!$qr $this->_values2UpdateQuery($values$addvalues)) {
  1448.             $this->_releaseLock();
  1449.             return false;
  1450.         }
  1451.  
  1452.         $sql sprintf('UPDATE %s SET %s WHERE %s=%s',
  1453.             $this->node_table,
  1454.             $qr,
  1455.             $this->flparams['id']$id);
  1456.         $res $this->db->query($sql);
  1457.         $this->_testFatalAbort($res__FILE____LINE__);
  1458.         $this->_releaseLock();
  1459.         return true;
  1460.     }
  1461.     // }}}
  1462.     // +----------------------------------------------+
  1463.     // | Moving and copying                           |
  1464.     // |----------------------------------------------+
  1465.     // | [PUBLIC]                                     |
  1466.     // +----------------------------------------------+
  1467.     // {{{ moveTree()
  1468.     /**
  1469.      * Wrapper for node moving and copying
  1470.      *
  1471.      * @param int $id Source ID
  1472.      * @param int $target Target ID
  1473.      * @param constant $pos Position (use one of the NESE_MOVE_* constants)
  1474.      * @param bool $copy Shall we create a copy
  1475.      * @see _moveInsideLevel
  1476.      * @see _moveAcross
  1477.      * @see _moveRoot2Root
  1478.      * @access public
  1479.      * @return int ID of the moved node or false on error
  1480.      */
  1481.     function moveTree($id$targetid$pos$copy = false{
  1482.         if ($this->debug{
  1483.             $this->_debugMessage('moveTree($id, $target, $pos, $copy = false)');
  1484.         }
  1485.         if ($id == $targetid && !$copy{
  1486.             $epr = array('moveTree()');
  1487.             return $this->_raiseError(NESE_ERROR_RECURSIONPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  1488.         }
  1489.         // Get information about source and target
  1490.         if (!($source $this->pickNode($idtrue))) {
  1491.             $epr = array('moveTree()'$id);
  1492.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1493.         }
  1494.  
  1495.         if (!($target $this->pickNode($targetidtrue))) {
  1496.             $epr = array('moveTree()'$targetid);
  1497.             return $this->_raiseError(NESE_ERROR_NOT_FOUNDPEAR_ERROR_TRIGGERE_USER_ERROR$epr);
  1498.         }
  1499.  
  1500.         if (PEAR::isError($lock $this->_setLock(true))) {
  1501.             return $lock;
  1502.         }
  1503.  
  1504.         $this->_relations = array();
  1505.         // This operations don't need callbacks except the copy handler
  1506.         // which ignores this setting
  1507.         $this->_skipCallbacks = true;
  1508.         if (!$copy{
  1509.             // We have a recursion - let's stop
  1510.             if (($target['rootid'== $source['rootid']&&
  1511.                     (($source['l'<= $target['l']&&
  1512.                         ($source['r'>= $target['r']))) {
  1513.                 $this->_releaseLock(true);
  1514.                 $epr = array('moveTree()');
  1515.                 return $this->_raiseError(NESE_ERROR_RECURSIONPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  1516.             }
  1517.             // Insert/move before or after
  1518.             if (($source['rootid'== $source['id']&&
  1519.                     ($target['rootid'== $target['id']&& ($pos != NESE_MOVE_BELOW)) {
  1520.                 // We have to move a rootnode which is different from moving inside a tree
  1521.                 $nid $this->_moveRoot2Root($source$target$pos);
  1522.                 $this->_releaseLock(true);
  1523.                 return $nid;
  1524.             }
  1525.         elseif (($target['rootid'== $source['rootid']&&
  1526.                 (($source['l'$target['l']&&
  1527.                     ($source['r'$target['r']))) {
  1528.             $this->_releaseLock(true);
  1529.             $epr = array('moveTree()');
  1530.             return $this->_raiseError(NESE_ERROR_RECURSIONPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  1531.         }
  1532.         // We have to move between different levels and maybe subtrees - let's rock ;)
  1533.         $moveID $this->_moveAcross($source$target$postrue);
  1534.         $this->_moveCleanup($copy);
  1535.         $this->_releaseLock(true);
  1536.         if (!$copy{
  1537.             return $id;
  1538.         else {
  1539.             return $moveID;
  1540.         }
  1541.     }
  1542.     // }}}
  1543.     // {{{ _moveAcross()
  1544.     /**
  1545.      * Moves nodes and trees to other subtrees or levels
  1546.      *
  1547.      * <pre>
  1548.      * [+] <--------------------------------+
  1549.      * +-[\] root1 [target]                 |
  1550.      *        <-------------------------+      |p
  1551.      * +-\ root2                     |      |
  1552.      * | |                           |      |
  1553.      * | |-- subnode1 [target]       |      |B
  1554.      * | |-- subnode2 [new]          |S     |E
  1555.      * | |-- subnode3                |U     |F
  1556.      * |                             |B     |O
  1557.      * +-\ root3                     |      |R
  1558.      *      |-- subnode 3.1             |      |E
  1559.      *      |-\ subnode 3.2 [source] >--+------+
  1560.      *        |-- subnode 3.2.1
  1561.      * </pre>
  1562.      *
  1563.      * @param object NodeCT $source   Source node
  1564.      * @param object NodeCT $target   Target node
  1565.      * @param string $pos Position [SUBnode/BEfore]
  1566.      * @param bool $copy Shall we create a copy
  1567.      * @access private
  1568.      * @see moveTree
  1569.      * @see _r_moveAcross
  1570.      * @see _moveCleanup
  1571.      */
  1572.     function _moveAcross($source$target$pos$first = false{
  1573.         if ($this->debug{
  1574.             $this->_debugMessage('_moveAcross($source, $target, $pos, $copy = false)');
  1575.         }
  1576.         // Get the current data from a node and exclude the id params which will be changed
  1577.         // because of the node move
  1578.         $values = array();
  1579.         foreach($this->params as $key => $val{
  1580.             if ($source[$val&& $val != 'parent' && !in_array($val$this->_requiredParams)) {
  1581.                 $values[$keytrim($source[$val]);
  1582.             }
  1583.         }
  1584.  
  1585.         switch ($pos{
  1586.             case NESE_MOVE_BEFORE:
  1587.                 $clone_id $this->createLeftNode($target['id']$values);
  1588.                 break;
  1589.             case NESE_MOVE_AFTER:
  1590.                 $clone_id $this->createRightNode($target['id']$values);
  1591.                 break;
  1592.             case NESE_MOVE_BELOW:
  1593.                 $clone_id $this->createSubNode($target['id']$values);
  1594.                 break;
  1595.         }
  1596.  
  1597.         if ($first && isset($this->flparams['parent'])) {
  1598.             $t_parent $this->getParent($clone_idtruetruearray()false);
  1599.             $t_parent_id $t_parent['id'];
  1600.         elseif (isset($this->flparams['parent'])) {
  1601.             $t_parent_id $source['parent'];
  1602.         else {
  1603.             $t_parent_id = false;
  1604.         }
  1605.  
  1606.         $children $this->getChildren($source['id']truetruetrue);
  1607.         if ($children{
  1608.             $pos NESE_MOVE_BELOW;
  1609.             $sclone_id $clone_id;
  1610.             // Recurse through the child nodes
  1611.             foreach($children AS $cid => $child{
  1612.                 $sclone $this->pickNode($sclone_idtrue);
  1613.                 $sclone_id $this->_moveAcross($child$sclone$pos);
  1614.                 $pos NESE_MOVE_AFTER;
  1615.             }
  1616.         }
  1617.  
  1618.         $this->_relations[$source['id']]['clone'$clone_id;
  1619.         $this->_relations[$source['id']]['parent'$t_parent_id;
  1620.         return $clone_id;
  1621.     }
  1622.     // }}}
  1623.     // {{{ _moveCleanup()
  1624.     /**
  1625.      * Deletes the old subtree (node) and writes the node id's into the cloned tree
  1626.      *
  1627.      * @param array $relations Hash in der Form $h[alteid]=neueid
  1628.      * @param array $copy Are we in copy mode?
  1629.      * @access private
  1630.      */
  1631.     function _moveCleanup($copy = false{
  1632.         $relations $this->_relations;
  1633.         if ($this->debug{
  1634.             $this->_debugMessage('_moveCleanup($relations, $copy = false)');
  1635.         }
  1636.  
  1637.         $deletes = array();
  1638.         $updates = array();
  1639.         $pupdates = array();
  1640.         $tb $this->node_table;
  1641.         $fid $this->flparams['id'];
  1642.         $froot $this->flparams['rootid'];
  1643.         foreach($relations AS $key => $val{
  1644.             $cloneid $val['clone'];
  1645.             $parentID $val['parent'];
  1646.             $clone $this->pickNode($cloneid);
  1647.             if ($copy{
  1648.                 // EVENT (NodeCopy)
  1649.                 $eparams = array('clone' => $clone);
  1650.                 if (!$this->_skipCallbacks && isset($this->_hasListeners['nodeCopy'])) {
  1651.                     $this->triggerEvent('nodeCopy'$this->pickNode($key)$eparams);
  1652.                 }
  1653.                 continue;
  1654.             }
  1655.             // No callbacks here because the node itself doesn't get changed
  1656.             // Only it's position
  1657.             // If one needs a callback here please let me know
  1658.             if (!empty($parentID)) {
  1659.                 $sql sprintf('UPDATE %s SET %s=%s WHERE %s=%s',
  1660.                     $this->node_table,
  1661.                     $this->flparams['parent'],
  1662.                     $parentID,
  1663.                     $fid,
  1664.                     $key);
  1665.                 $pupdates[$sql;
  1666.             }
  1667.  
  1668.             $deletes[$key;
  1669.             // It's isn't a rootnode
  1670.             if ($clone->id != $clone->rootid{
  1671.                 $sql sprintf('UPDATE %s SET %s=%s WHERE %s=%s',
  1672.                     $this->node_table,
  1673.                     $fid$key,
  1674.                     $fid$cloneid);
  1675.                 $updates[$sql;
  1676.             else {
  1677.                 $sql sprintf('UPDATE %s SET %s=%s, %s=%s WHERE %s=%s',
  1678.                     $this->node_table,
  1679.                     $fid$key,
  1680.                     $froot$cloneid,
  1681.                     $fid$cloneid);
  1682.                 $updates[$sql;
  1683.                 $orootid $clone->rootid;
  1684.                 $sql sprintf('UPDATE %s SET %s=%s WHERE %s=%s',
  1685.                     $tb,
  1686.                     $froot$key,
  1687.                     $froot$orootid);
  1688.                 $updates[$sql;
  1689.             }
  1690.             $this->_skipCallbacks = false;
  1691.         }
  1692.  
  1693.         if (!empty($deletes)) {
  1694.             foreach ($deletes as $delete{
  1695.                 $this->deleteNode($delete);
  1696.             }
  1697.         }
  1698.  
  1699.         if (!empty($updates)) {
  1700.             for($i = 0;$i count($updates);$i++{
  1701.                 $res $this->db->query($updates[$i]);
  1702.                 $this->_testFatalAbort($res__FILE____LINE__);
  1703.             }
  1704.         }
  1705.  
  1706.         if (!empty($pupdates)) {
  1707.             for($i = 0;$i count($pupdates);$i++{
  1708.                 $res $this->db->query($pupdates[$i]);
  1709.                 $this->_testFatalAbort($res__FILE____LINE__);
  1710.             }
  1711.         }
  1712.  
  1713.         return true;
  1714.     }
  1715.     // }}}
  1716.     // {{{ _moveRoot2Root()
  1717.     /**
  1718.      * Moves rootnodes
  1719.      *
  1720.      * <pre>
  1721.      * +-- root1
  1722.      * |
  1723.      * +-\ root2
  1724.      * | |
  1725.      * | |-- subnode1 [target]
  1726.      * | |-- subnode2 [new]
  1727.      * | |-- subnode3
  1728.      * |
  1729.      * +-\ root3
  1730.      *     [|]  <-----------------------+
  1731.      *      |-- subnode 3.1 [target]    |
  1732.      *      |-\ subnode 3.2 [source] >--+
  1733.      *        |-- subnode 3.2.1
  1734.      * </pre>
  1735.      *
  1736.      * @param object NodeCT $source    Source
  1737.      * @param object NodeCT $target    Target
  1738.      * @param string $pos BEfore | AFter
  1739.      * @access private
  1740.      * @see moveTree
  1741.      */
  1742.     function _moveRoot2Root($source$target$pos{
  1743.         if ($this->debug{
  1744.             $this->_debugMessage('_moveRoot2Root($source, $target, $pos, $copy)');
  1745.         }
  1746.         if (PEAR::isError($lock $this->_setLock())) {
  1747.             return $lock;
  1748.         }
  1749.  
  1750.         $tb $this->node_table;
  1751.         $fid $this->flparams['id'];
  1752.         $froot $this->flparams['rootid'];
  1753.         $freh $this->flparams['norder'];
  1754.         $s_order $source['norder'];
  1755.         $t_order $target['norder'];
  1756.         $s_id $source['id'];
  1757.         $t_id $target['id'];
  1758.         if ($s_order $t_order{
  1759.             if ($pos == NESE_MOVE_BEFORE{
  1760.                 $sql = "UPDATE $tb SET $freh=$freh-1
  1761.                         WHERE $freh BETWEEN $s_order AND $t_order AND
  1762.                             $fid!=$t_id AND
  1763.                             $fid!=$s_id AND
  1764.                             $froot=$fid";
  1765.                 $res $this->db->query($sql);
  1766.                 $this->_testFatalAbort($res__FILE____LINE__);
  1767.                 $sql = "UPDATE $tb SET $freh=$t_order -1 WHERE $fid=$s_id";
  1768.                 $res $this->db->query($sql);
  1769.                 $this->_testFatalAbort($res__FILE____LINE__);
  1770.             elseif ($pos == NESE_MOVE_AFTER{
  1771.                 $sql = "UPDATE $tb SET $freh=$freh-1
  1772.                         WHERE $freh BETWEEN $s_order AND $t_order AND
  1773.                             $fid!=$s_id AND
  1774.                             $froot=$fid";
  1775.                 $res $this->db->query($sql);
  1776.                 $this->_testFatalAbort($res__FILE____LINE__);
  1777.                 $sql = "UPDATE $tb SET $freh=$t_order WHERE $fid=$s_id";
  1778.                 $res $this->db->query($sql);
  1779.                 $this->_testFatalAbort($res__FILE____LINE__);
  1780.             }
  1781.         }
  1782.  
  1783.         if ($s_order $t_order{
  1784.             if ($pos == NESE_MOVE_BEFORE{
  1785.                 $sql = "UPDATE $tb SET $freh=$freh+1
  1786.                         WHERE $freh BETWEEN $t_order AND $s_order AND
  1787.                             $fid != $s_id AND
  1788.                             $froot=$fid";
  1789.                 $res $this->db->query($sql);
  1790.                 $this->_testFatalAbort($res__FILE____LINE__);
  1791.                 $sql = "UPDATE $tb SET $freh=$t_order WHERE $fid=$s_id";
  1792.                 $res $this->db->query($sql);
  1793.                 $this->_testFatalAbort($res__FILE____LINE__);
  1794.             elseif ($pos == NESE_MOVE_AFTER{
  1795.                 $sql = "UPDATE $tb SET $freh=$freh+1
  1796.                         WHERE $freh BETWEEN $t_order AND $s_order AND
  1797.                         $fid!=$t_id AND
  1798.                         $fid!=$s_id AND
  1799.                         $froot=$fid";
  1800.                 $res $this->db->query($sql);
  1801.                 $this->_testFatalAbort($res__FILE____LINE__);
  1802.                 $sql = "UPDATE $tb SET $freh=$t_order+1 WHERE $fid = $s_id";
  1803.                 $res $this->db->query($sql);
  1804.                 $this->_testFatalAbort($res__FILE____LINE__);
  1805.             }
  1806.         }
  1807.         $this->_releaseLock();
  1808.         return $s_id;
  1809.     }
  1810.     // }}}
  1811.     // +-----------------------+
  1812.     // | Helper methods        |
  1813.     // +-----------------------+
  1814.     // {{{ _secSort()
  1815.     /**
  1816.      * Callback for uasort used to sort siblings
  1817.      *
  1818.      * @access private
  1819.      */
  1820.     function _secSort($node1$node2{
  1821.         // Within the same level?
  1822.         if ($node1['level'!= $node2['level']{
  1823.             return strnatcmp($node1['l']$node2['l']);
  1824.         }
  1825.         // Are they siblings?
  1826.         $p1 $this->getParent($node1);
  1827.         $p2 $this->getParent($node2);
  1828.         if ($p1['id'!= $p2['id']{
  1829.             return strnatcmp($node1['l']$node2['l']);
  1830.         }
  1831.         // Same field value? Use the lft value then
  1832.         $field $this->params[$this->secondarySort];
  1833.         if ($node1[$field== $node2[$field]{
  1834.             return strnatcmp($node1['l']$node2[l]);
  1835.         }
  1836.         // Compare between siblings with different field value
  1837.         return strnatcmp($node1[$field]$node2[$field]);
  1838.     }
  1839.     // }}}
  1840.     // {{{ _addSQL()
  1841.     /**
  1842.      * Adds a specific type of SQL to a query string
  1843.      *
  1844.      * @param array $addSQL The array of SQL strings to add.  Example value:
  1845.      *                   $addSQL = array(
  1846.      *                   'cols' => 'tb2.col2, tb2.col3',         // Additional tables/columns
  1847.      *                   'join' => 'LEFT JOIN tb1 USING(STRID)', // Join statement
  1848.          *                                       'where' => 'A='B' AND C='D',                    // Where statement without 'WHERE' OR 'AND' in front
  1849.      *                   'append' => 'GROUP by tb1.STRID');      // Group condition
  1850.      * @param string $type The type of SQL.  Can be 'cols', 'join', or 'append'.
  1851.      * @access private
  1852.      * @return string The SQL, properly formatted
  1853.      */
  1854.     function _addSQL($addSQL$type$prefix = false{
  1855.         if (!isset($addSQL[$type])) {
  1856.             return '';
  1857.         }
  1858.  
  1859.         switch ($type{
  1860.             case 'cols':
  1861.                 return ', ' $addSQL[$type];
  1862.             case 'where':
  1863.                 return $prefix ' (' $addSQL[$type')';
  1864.             default:
  1865.                 return $addSQL[$type];
  1866.         }
  1867.     }
  1868.     // }}}
  1869.     // {{{ _getSelectFields()
  1870.     /**
  1871.      * Gets the select fields based on the params
  1872.      *
  1873.      * @param bool $aliasFields Should we alias the fields so they are the names of the
  1874.      *                 parameter keys, or leave them as is?
  1875.      * @access private
  1876.      * @return string A string of query fields to select
  1877.      */
  1878.     function _getSelectFields($aliasFields{
  1879.         $queryFields = array();
  1880.         foreach ($this->params as $key => $val{
  1881.             $tmp_field $this->node_table . '.' $key;
  1882.             if ($aliasFields{
  1883.                 $tmp_field .= ' AS ' $this->_quoteIdentifier($val);
  1884.             }
  1885.             $queryFields[$tmp_field;
  1886.         }
  1887.  
  1888.         $fields implode(', '$queryFields);
  1889.         return $fields;
  1890.     }
  1891.     // }}}
  1892.     // {{{ _processResultSet()
  1893.     /**
  1894.      * Processes a DB result set by checking for a DB error and then transforming the result
  1895.      * into a set of DB_NestedSet_Node objects or leaving it as an array.
  1896.      *
  1897.      * @param string $sql The sql query to be done
  1898.      * @param bool $keepAsArray Keep the result as an array or transform it into a set of
  1899.      *                 DB_NestedSet_Node objects?
  1900.      * @param bool $fieldsAreAliased Are the fields aliased?
  1901.      * @access private
  1902.      * @return mixed False on error or the transformed node set.
  1903.      */
  1904.     function _processResultSet($sql$keepAsArray$fieldsAreAliased{
  1905.         $result $this->db->getAll($sql);
  1906.         if ($this->_testFatalAbort($result__FILE____LINE__)) {
  1907.             return false;
  1908.         }
  1909.  
  1910.         $nodes = array();
  1911.         $idKey $fieldsAreAliased 'id' $this->flparams['id'];
  1912.         foreach ($result as $row{
  1913.             $node_id $row[$idKey];
  1914.             if ($keepAsArray{
  1915.                 $nodes[$node_id$row;
  1916.             else {
  1917.                 // Create an instance of the node container
  1918.                 $nodes[$node_idnew DB_NestedSet_Node($row);
  1919.             }
  1920.         }
  1921.         return $nodes;
  1922.     }
  1923.     // }}}
  1924.     // {{{ _testFatalAbort()
  1925.     /**
  1926.      * Error Handler
  1927.      *
  1928.      * Tests if a given ressource is a PEAR error object
  1929.      * ans raises a fatal error in case of an error object
  1930.      *
  1931.      * @param object PEAR::Error $errobj     The object to test
  1932.      * @param string $file The filename wher the error occured
  1933.      * @param int $line The line number of the error
  1934.      * @return void 
  1935.      * @access private
  1936.      */
  1937.     function _testFatalAbort($errobj$file$line{
  1938.         if (!$this->_isDBError($errobj)) {
  1939.             return false;
  1940.         }
  1941.  
  1942.         if ($this->debug{
  1943.             $this->_debugMessage('_testFatalAbort($errobj, $file, $line)');
  1944.         }
  1945.         if ($this->debug{
  1946.             $message $errobj->getUserInfo();
  1947.             $code $errobj->getCode();
  1948.             $msg = "$message ($code) in file $file at line $line";
  1949.         else {
  1950.             $msg $errobj->getMessage();
  1951.             $code $errobj->getCode();
  1952.         }
  1953.  
  1954.         PEAR::raiseError($msg$codePEAR_ERROR_TRIGGERE_USER_ERROR);
  1955.     }
  1956.     // }}}
  1957.     // {{{ __raiseError()
  1958.     /**
  1959.      *
  1960.      * @access private
  1961.      */
  1962.     function _raiseError($code$mode$option$epr = array()) {
  1963.         $message vsprintf($this->_getMessage($code)$epr);
  1964.         return PEAR::raiseError($message$code$mode$option);
  1965.     }
  1966.     // }}}
  1967.     // {{{ addListener()
  1968.     /**
  1969.      * Add an event listener
  1970.      *
  1971.      * Adds an event listener and returns an ID for it
  1972.      *
  1973.      * @param string $event The ivent name
  1974.      * @param string $listener The listener object
  1975.      * @return string 
  1976.      * @access public
  1977.      */
  1978.     function addListener($event$listener{
  1979.         $listenerID uniqid('el');
  1980.         $this->eventListeners[$event][$listenerID$listener;
  1981.         $this->_hasListeners[$event= true;
  1982.         return $listenerID;
  1983.     }
  1984.     // }}}
  1985.     // {{{ removeListener()
  1986.     /**
  1987.      * Removes an event listener
  1988.      *
  1989.      * Removes the event listener with the given ID
  1990.      *
  1991.      * @param string $event The ivent name
  1992.      * @param string $listenerID The listener's ID
  1993.      * @return bool 
  1994.      * @access public
  1995.      */
  1996.     function removeListener($event$listenerID{
  1997.         unset($this->eventListeners[$event][$listenerID]);
  1998.         if (!isset($this->eventListeners[$event]|| !is_array($this->eventListeners[$event]||
  1999.                 count($this->eventListeners[$event]== 0{
  2000.             unset($this->_hasListeners[$event]);
  2001.         }
  2002.         return true;
  2003.     }
  2004.     // }}}
  2005.     // {{{ triggerEvent()
  2006.     /**
  2007.      * Triggers and event an calls the event listeners
  2008.      *
  2009.      * @param string $event The Event that occured
  2010.      * @param object node $node A Reference to the node object which was subject to changes
  2011.      * @param array $eparams A associative array of params which may be needed by the handler
  2012.      * @return bool 
  2013.      * @access public
  2014.      */
  2015.     function triggerEvent($event$node$eparams = false{
  2016.         if ($this->_skipCallbacks || !isset($this->_hasListeners[$event])) {
  2017.             return false;
  2018.         }
  2019.  
  2020.         foreach($this->eventListeners[$eventas $key => $val{
  2021.             if (!method_exists($val'callEvent')) {
  2022.                 return new PEAR_Error($this->_getMessage(NESE_ERROR_NOHANDLER)NESE_ERROR_NOHANDLER);
  2023.             }
  2024.  
  2025.             $val->callEvent($event$node$eparams);
  2026.         }
  2027.  
  2028.         return true;
  2029.     }
  2030.     // }}}
  2031.     // {{{ apiVersion()
  2032.     function apiVersion({
  2033.         return array('package:' => $this->_packagename,
  2034.             'majorversion' => $this->_majorversion,
  2035.             'minorversion' => $this->_minorversion,
  2036.             'version' => sprintf('%s.%s'$this->_majorversion$this->_minorversion),
  2037.             'revision' => str_replace('$'''"$Revision: 1.79 $")
  2038.             );
  2039.     }
  2040.     // }}}
  2041.     // {{{ setAttr()
  2042.     /**
  2043.      * Sets an object attribute
  2044.      *
  2045.      * @param array $attr An associative array with attributes
  2046.      * @return bool 
  2047.      * @access public
  2048.      */
  2049.     function setAttr($attr{
  2050.         static $hasSetSequence;
  2051.         if (!isset($hasSetSequence)) {
  2052.             $hasSetSequence = false;
  2053.         }
  2054.  
  2055.         if (!is_array($attr|| count($attr== 0{
  2056.             return false;
  2057.         }
  2058.  
  2059.         foreach ($attr as $key => $val{
  2060.             $this->$key $val;
  2061.             if ($key == 'sequence_table'{
  2062.                 $hasSetSequence = true;
  2063.             }
  2064.             // only update sequence to reflect new table if they haven't set it manually
  2065.             if (!$hasSetSequence && $key == 'node_table'{
  2066.                 $this->sequence_table = $this->node_table . '_' $this->flparams['id'];
  2067.             }
  2068.             if ($key == 'cache' && is_object($val)) {
  2069.                 $this->_caching = true;
  2070.                 $GLOBALS['DB_NestedSet'$this;
  2071.             }
  2072.         }
  2073.  
  2074.         return true;
  2075.     }
  2076.     // }}}
  2077.     // {{{ setsortMode()
  2078.     /**
  2079.      * This enables you to set specific options for each output method
  2080.      *
  2081.      * @param constant $sortMode 
  2082.      * @access public
  2083.      * @return Current sortMode
  2084.      */
  2085.     function setsortMode($sortMode = false{
  2086.         if ($sortMode && in_array($sortMode$this->_sortModes)) {
  2087.             $this->_sortMode $sortMode;
  2088.         else {
  2089.             return $this->_sortMode;
  2090.         }
  2091.         return $this->_sortMode;
  2092.     }
  2093.     // }}}
  2094.     // {{{ setDbOption()
  2095.     /**
  2096.      * Sets a db option.  Example, setting the sequence table format
  2097.      *
  2098.      * @var string $option The option to set
  2099.      * @var string $val The value of the option
  2100.      * @access public
  2101.      * @return void 
  2102.      */
  2103.     function setDbOption($option$val{
  2104.         $this->db->setOption($option$val);
  2105.     }
  2106.     // }}}
  2107.     // {{{ testLock()
  2108.     /**
  2109.      * Tests if a database lock is set
  2110.      *
  2111.      * @access public
  2112.      */
  2113.     function testLock({
  2114.         if ($this->debug{
  2115.             $this->_debugMessage('testLock()');
  2116.         }
  2117.  
  2118.         if ($lockID $this->_structureTableLock{
  2119.             return $lockID;
  2120.         }
  2121.         $this->_lockGC();
  2122.         $sql sprintf('SELECT lockID FROM %s WHERE lockTable=%s',
  2123.             $this->lock_table,
  2124.             $this->_quote($this->node_table)) ;
  2125.         $res $this->db->query($sql);
  2126.         $this->_testFatalAbort($res__FILE____LINE__);
  2127.         if ($this->_numRows($res)) {
  2128.             return new PEAR_Error($this->_getMessage(NESE_ERROR_TBLOCKED)NESE_ERROR_TBLOCKED);
  2129.         }
  2130.  
  2131.         return false;
  2132.     }
  2133.     // }}}
  2134.     // {{{ _setLock()
  2135.     /**
  2136.      *
  2137.      * @access private
  2138.      */
  2139.     function _setLock($exclusive = false{
  2140.         $lock $this->testLock();
  2141.         if (PEAR::isError($lock)) {
  2142.             return $lock;
  2143.         }
  2144.  
  2145.         if ($this->debug{
  2146.             $this->_debugMessage('_setLock()');
  2147.         }
  2148.         if ($this->_caching{
  2149.             @$this->cache->flush('function_cache');
  2150.             $this->_caching = false;
  2151.             $this->_restcache = true;
  2152.         }
  2153.  
  2154.         if (!$lockID $this->_structureTableLock{
  2155.             $lockID $this->_structureTableLock uniqid('lck-');
  2156.             $sql sprintf('INSERT INTO %s (lockID, lockTable, lockStamp) VALUES (%s, %s, %s)',
  2157.                 $this->lock_table,
  2158.                 $this->_quote($lockID)$this->_quote($this->node_table)time());
  2159.         else {
  2160.             $sql sprintf('UPDATE %s SET lockStamp=%s WHERE lockID=%s AND lockTable=%s',
  2161.                 $this->lock_table,
  2162.                 time(),
  2163.                 $this->_quote($lockID)$this->_quote($this->node_table));
  2164.         }
  2165.  
  2166.         if ($exclusive{
  2167.             $this->_lockExclusive = true;
  2168.         }
  2169.  
  2170.         $res $this->db->query($sql);
  2171.         $this->_testFatalAbort($res__FILE____LINE__);
  2172.         return $lockID;
  2173.     }
  2174.     // }}}
  2175.     // {{{ _releaseLock()
  2176.     /**
  2177.      *
  2178.      * @access private
  2179.      */
  2180.     function _releaseLock($exclusive = false{
  2181.         if ($this->debug{
  2182.             $this->_debugMessage('_releaseLock()');
  2183.         }
  2184.  
  2185.         if ($exclusive{
  2186.             $this->_lockExclusive = false;
  2187.         }
  2188.  
  2189.         if ((!$lockID $this->_structureTableLock|| $this->_lockExclusive{
  2190.             return false;
  2191.         }
  2192.  
  2193.         $tb $this->lock_table;
  2194.         $stb $this->node_table;
  2195.         $sql = "DELETE FROM $tb
  2196.                 WHERE lockTable=" . $this->_quote($stb" AND
  2197.                     lockID=" $this->_quote($lockID);
  2198.         $res $this->db->query($sql);
  2199.         $this->_testFatalAbort($res__FILE____LINE__);
  2200.         $this->_structureTableLock = false;
  2201.         if ($this->_restcache{
  2202.             $this->_caching = true;
  2203.             $this->_restcache = false;
  2204.         }
  2205.         return true;
  2206.     }
  2207.     // }}}
  2208.     // {{{ _lockGC()
  2209.     /**
  2210.      *
  2211.      * @access private
  2212.      */
  2213.     function _lockGC({
  2214.         if ($this->debug{
  2215.             $this->_debugMessage('_lockGC()');
  2216.         }
  2217.         $tb $this->lock_table;
  2218.         $stb $this->node_table;
  2219.         $lockTTL time($this->lockTTL;
  2220.         $sql = "DELETE FROM $tb
  2221.                 WHERE lockTable=" . $this->_quote($stb. " AND
  2222.                     lockStamp < $lockTTL";
  2223.         $res $this->db->query($sql);
  2224.         $this->_testFatalAbort($res__FILE____LINE__);
  2225.     }
  2226.     // }}}
  2227.     // {{{ _values2UpdateQuery()
  2228.     /**
  2229.      *
  2230.      * @access private
  2231.      */
  2232.     function _values2UpdateQuery($values$addval = false{
  2233.         if ($this->debug{
  2234.             $this->_debugMessage('_values2UpdateQuery($values, $addval = false)');
  2235.         }
  2236.         if (is_array($addval)) {
  2237.             $values $values $addval;
  2238.         }
  2239.  
  2240.         $arq = array();
  2241.         foreach($values AS $key => $val{
  2242.             $k $this->_quoteIdentifier(trim($key));
  2243.  
  2244.             // To be used with the next major version
  2245.             // $iv = in_array($this->params[$k], $this->_quotedParams) ? $this->_quote($v) : $v;
  2246.             $iv $this->_quote(trim($val));
  2247.             $arq[= "$k=$iv";
  2248.         }
  2249.  
  2250.         if (!is_array($arq|| count($arq== 0{
  2251.             return false;
  2252.         }
  2253.  
  2254.         $query implode(', '$arq);
  2255.         return $query;
  2256.     }
  2257.     // }}}
  2258.     // {{{ _values2UpdateQuery()
  2259.     /**
  2260.      *
  2261.      * @access private
  2262.      */
  2263.     function _values2InsertQuery($values$addval = false{
  2264.         if ($this->debug{
  2265.             $this->_debugMessage('_values2InsertQuery($values, $addval = false)');
  2266.         }
  2267.         if (is_array($addval)) {
  2268.             $values $values $addval;
  2269.         }
  2270.  
  2271.         $arq = array();
  2272.         foreach($values AS $key => $val{
  2273.             $k $this->_quoteIdentifier(trim($key));
  2274.  
  2275.             // To be used with the next major version
  2276.             // $iv = in_array($this->params[$k], $this->_quotedParams) ? $this->_quote($v) : $v;
  2277.             $iv $this->_quote(trim($val));
  2278.             $arq[$k$iv;
  2279.         }
  2280.  
  2281.         if (!is_array($arq|| count($arq== 0{
  2282.             return false;
  2283.         }
  2284.  
  2285.         return $arq;
  2286.     }
  2287.     // }}}
  2288.     // {{{ _verifyUserValues()
  2289.     /**
  2290.      * Clean values from protected or unknown columns
  2291.      *
  2292.      * @var string $caller The calling method
  2293.      * @var string $values The values array
  2294.      * @access private
  2295.      * @return void 
  2296.      */
  2297.     function _verifyUserValues($caller$values{
  2298.         if ($this->_dumbmode{
  2299.             return true;
  2300.         }
  2301.         foreach($values as $field => $value{
  2302.             if (!isset($this->params[$field])) {
  2303.                 $epr = array($callersprintf('Unknown column/param \'%s\''$field));
  2304.                 $this->_raiseError(NESE_ERROR_WRONG_MPARAMPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  2305.                 unset($values[$field]);
  2306.             else {
  2307.                 $flip $this->params[$field];
  2308.                 if (in_array($flip$this->_requiredParams)) {
  2309.                     $epr = array($callersprintf('\'%s\' is autogenerated and can\'t be passed - it will be ignored'$field));
  2310.                     $this->_raiseError(NESE_ERROR_WRONG_MPARAMPEAR_ERROR_RETURNE_USER_NOTICE$epr);
  2311.                     unset($values[$field]);
  2312.                 }
  2313.             }
  2314.         }
  2315.     }
  2316.     // }}}
  2317.     // {{{ _debugMessage()
  2318.     /**
  2319.      *
  2320.      * @access private
  2321.      */
  2322.     function _debugMessage($msg{
  2323.         if ($this->debug{
  2324.             list($usec$secexplode(' 'microtime());
  2325.             $time ((float)$usec + (float)$sec);
  2326.             echo "$time::Debug:: $msg<br />\n";
  2327.         }
  2328.     }
  2329.     // }}}
  2330.     // {{{ _getMessage()
  2331.     /**
  2332.      *
  2333.      * @access private
  2334.      */
  2335.     function _getMessage($code{
  2336.         if ($this->debug{
  2337.             $this->_debugMessage('_getMessage($code)');
  2338.         }
  2339.         return isset($this->messages[$code]$this->messages[$code$this->messages[NESE_MESSAGE_UNKNOWN];
  2340.     }
  2341.     // }}}
  2342.     // {{{ convertTreeModel()
  2343.     /**
  2344.      * Convert a <1.3 tree into a 1.3 tree format
  2345.      *
  2346.      * This will convert the tree into a format needed for some new features in
  2347.      * 1.3. Your <1.3 tree will still work without converting but some new features
  2348.      * like preorder sorting won't work as expected.
  2349.      *
  2350.      * <pre>
  2351.      * Usage:
  2352.      * - Create a new node table (tb_nodes2) from the current node table (tb_nodes1) (only copy the structure).
  2353.      * - Create a nested set instance of the 'old' set (NeSe1) and one of the new set (NeSe2)
  2354.      * - Now you have 2 identical objects where only node_table differs
  2355.      * - Call DB_NestedSet::convertTreeModel(&$orig, &$copy);
  2356.      * - After that you have a cleaned up copy of tb_nodes1 inside tb_nodes2
  2357.      * </pre>
  2358.      *
  2359.      * @param object DB_NestedSet $orig  Nested set we want to copy
  2360.      * @param object DB_NestedSet $copy  Object where the new tree is copied to
  2361.      * @param integer $_parent ID of the parent node (private)
  2362.      * @static
  2363.      * @access public
  2364.      * @return bool True uns success
  2365.      */
  2366.     function convertTreeModel($orig$copy$_parent = false{
  2367.         static $firstSet;
  2368.         $isRoot = false;
  2369.         if (!$_parent{
  2370.             if (!is_object($orig|| !is_object($copy)) {
  2371.                 return false;
  2372.             }
  2373.             if ($orig->node_table == $copy->node_table{
  2374.                 return false;
  2375.             }
  2376.             $copy->_dumbmode = true;
  2377.             $orig->sortMode = NESE_SORT_LEVEL;
  2378.             $copy->sortMode = NESE_SORT_LEVEL;
  2379.             $sibl $orig->getRootNodes(true);
  2380.             $isRoot = true;
  2381.         else {
  2382.             $sibl $orig->getChildren($_parenttrue);
  2383.         }
  2384.  
  2385.         if (empty($sibl)) {
  2386.             return false;
  2387.         }
  2388.  
  2389.         foreach($sibl AS $sid => $sibling{
  2390.             unset($sibling['l']);
  2391.             unset($sibling['r']);
  2392.             unset($sibling['norder']);
  2393.             $values = array();
  2394.             foreach($sibling AS $key => $val{
  2395.                 if (!isset($copy->flparams[$key])) {
  2396.                     continue;
  2397.                 }
  2398.                 $values[$copy->flparams[$key]] $val;
  2399.             }
  2400.  
  2401.             if (!$firstSet{
  2402.                 $psid $copy->createRootNode($valuesfalsetrue);
  2403.                 $firstSet = true;
  2404.             elseif ($isRoot{
  2405.                 $psid $copy->createRightNode($psid$values);
  2406.             else {
  2407.                 $copy->createSubNode($_parent$values);
  2408.             }
  2409.  
  2410.             DB_NestedSet::convertTreeModel($orig$copy$sid);
  2411.         }
  2412.         return true;
  2413.     }
  2414.     // }}}
  2415. }
  2416. // {{{ DB_NestedSet_Node:: class
  2417. /**
  2418.  * Generic class for node objects
  2419.  *
  2420.  * @autor Daniel Khan <dk@webcluster.at>;
  2421.  * @version $Revision: 1.79 $
  2422.  * @package DB_NestedSet
  2423.  * @access private
  2424.  */
  2425.  
  2426. class DB_NestedSet_Node {
  2427.     // {{{ constructor
  2428.     /**
  2429.      * Constructor
  2430.      */
  2431.     function DB_NestedSet_Node($data{
  2432.         if (!is_array($data|| count($data== 0{
  2433.             return new PEAR_ERROR($dataNESE_ERROR_PARAM_MISSING);
  2434.         }
  2435.  
  2436.         $this->setAttr($data);
  2437.         return true;
  2438.     }
  2439.     // }}}
  2440.     // {{{ setAttr()
  2441.     function setAttr($data{
  2442.         if (!is_array($data|| count($data== 0{
  2443.             return false;
  2444.         }
  2445.  
  2446.         foreach ($data as $key => $val{
  2447.             $this->$key $val;
  2448.         }
  2449.     }
  2450.     // }}}
  2451. }
  2452. // }}}
  2453. ?>

Documentation generated on Mon, 11 Mar 2019 10:14:33 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.