Guest User

Codeigniter Nest Set Library

a guest
Feb 17th, 2011
2,069
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 32.87 KB | None | 0 0
  1. <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3.  * File: libraries/Nested_set.php
  4.  *
  5.  * An implementation of Joe Celko's Nested Sets as a Code Igniter model.
  6.  *
  7.  * Updated by intel352 for unlimited root trees, also added ability to define
  8.  * primary key column and parent column. Use of parent column can help lighten
  9.  * the load of having a strict nested set model. It takes more of a hybrid approach.
  10.  *
  11.  * @package  Nested_sets
  12.  * @author    Thunder <[email protected]>, intel352 <[email protected]>
  13.  * @copyright   Copyright (c) 2007 Thunder; Copyright (c) 2008 intel352
  14.  */
  15.  
  16.  
  17. /**
  18.  * @package Nested_set
  19.  * @author  Thunder <[email protected]>, intel352 <[email protected]>
  20.  * @version 1.2
  21.  * @copyright Copyright (c) 2007 Thunder; Copyright (c) 2008 intel352
  22.  * @todo    Keep semi-persistent model of data retrieved, to reduce query access of the same data.
  23.  *          Need to convert this to a generic TREE class, supporting nested and adjacent, a la cakephp
  24.  */
  25. class Nested_set {
  26.  
  27.     private $table_name;
  28.     private $left_column_name;
  29.     private $right_column_name;
  30.     private $primary_key_column_name;
  31.     private $parent_column_name;
  32.     private $db;
  33.  
  34.     /**
  35.      * Constructor
  36.      *
  37.      * @access  public
  38.      */
  39.     public function __construct()   {
  40.         $CI =& get_instance(); // to access CI resources, use $CI instead of $this
  41.         $this->db =& $CI->db;
  42.     }
  43.  
  44.     // -------------------------------------------------------------------------
  45.     //  OBJECT INITIALISATION METHODS
  46.     //
  47.     //  For setting instance properties
  48.     //
  49.     // -------------------------------------------------------------------------
  50.  
  51.     /**
  52.      * On initialising the instance, this method should be called to set the
  53.      * database table name that we're dealing and also to identify the names
  54.      * of the left and right value columns used to form the tree structure.
  55.      * Typically, this would be done automatically by the model class that
  56.      * extends this "base" class (eg. a Categories class would set the table_name
  57.      * to "categories", a Site_structure class would set the table_name to
  58.      * "pages" etc)
  59.      *
  60.      * @param string $table_name The name of the db table to use
  61.      * @param string $left_column_name The name of the field representing the left identifier
  62.      * @param string $right_column_name The name of the field representing the right identifier
  63.      * @param string $primary_key_column_name The name of the primary identifier field
  64.      * @param string $parent_column_name The name of the parent column field
  65.      */
  66.     public function setControlParams($table_name, $left_column_name = 'lft', $right_column_name = 'rgt', $primary_key_column_name = 'id', $parent_column_name = 'parent_id') {
  67.         $this->table_name = $table_name;
  68.         $this->left_column_name = $left_column_name;
  69.         $this->right_column_name = $right_column_name;
  70.         $this->primary_key_column_name = $primary_key_column_name;
  71.         $this->parent_column_name = $parent_column_name;
  72.     }
  73.  
  74.     /**
  75.     * Used to identify the primary key of the table in use. Commonly, this will
  76.     * be an auto_incrementing ID column (eg CategoryId)
  77.     *
  78.     * @param string $primary_key_name
  79.     */
  80.     public function setPrimaryKeyColumn($primary_key_name) {
  81.         $this->primary_key_column_name = $primary_key_name;
  82.     }
  83.  
  84.  
  85.     // -------------------------------------------------------------------------
  86.     //  NODE MANIPULATION FUNCTIONS
  87.     //
  88.     //  Methods to add/remove nodes in your tree
  89.     //
  90.     // -------------------------------------------------------------------------
  91.  
  92.  
  93.     /**
  94.      * Adds the first entry to the table
  95.      * @param    $extrafields  An array of field->value pairs for the database record
  96.      * @return  $node an array of left and right values
  97.      * @deprecated
  98.      */
  99.     public function initialiseRoot($extrafields = array()) {
  100.         return $this->insertNewTree($extrafields);
  101.     }
  102.  
  103.     /**
  104.      * Adds the first entry to the table
  105.      * @param    $extrafields  An array of field->value pairs for the database record
  106.      * @return  $node an array of left and right values
  107.      */
  108.     public function insertNewTree($extrafields = array()) {
  109.  
  110.         $this->db->select_max($this->right_column_name, 'lft');
  111.         $query = $this->db->get($this->table_name);
  112.         $result = $query->row_array();
  113.  
  114.         $node = array(
  115.         $this->parent_column_name => 0,
  116.         $this->left_column_name  => $result['lft'] + 1,
  117.         $this->right_column_name => $result['lft'] + 2,
  118.         );
  119.  
  120.         $this->_setNewNode($node, $extrafields);
  121.  
  122.         return $this->getNodeWhereLeft($node[$this->left_column_name]);
  123.     }
  124.  
  125.     /**
  126.      * inserts a new node as the first child of the supplied parent node
  127.      * @param array $parentNode The node array of the parent to use
  128.      * @param array $extrafields An associative array of fieldname=>value for the other fields in the recordset
  129.      * @return array $childNode An associative array representing the new node
  130.      */
  131.     public function insertNewChild($parentNode, $extrafields = array()) {
  132.         $childNode[$this->parent_column_name]   =   $parentNode[$this->primary_key_column_name];
  133.         $childNode[$this->left_column_name]     =   $parentNode[$this->left_column_name]+1;
  134.         $childNode[$this->right_column_name]    =   $parentNode[$this->left_column_name]+2;
  135.  
  136.         $this->_modifyNode($childNode[$this->left_column_name], 2);
  137.         $this->_setNewNode($childNode, $extrafields);
  138.  
  139.         return $this->getNodeWhereLeft($childNode[$this->left_column_name]);
  140.     }
  141.  
  142.     /**
  143.      * Same as insertNewChild except the new node is added as the last child
  144.      * @param array $parentNode The node array of the parent to use
  145.      * @param array $extrafields An associative array of fieldname=>value for the other fields in the recordset
  146.      * @return array $childNode An associative array representing the new node
  147.      */
  148.     public function appendNewChild($parentNode, $extrafields = array()) {
  149.         $childNode[$this->parent_column_name]   =   $parentNode[$this->primary_key_column_name];
  150.         $childNode[$this->left_column_name]     =   $parentNode[$this->right_column_name];
  151.         $childNode[$this->right_column_name]    =   $parentNode[$this->right_column_name]+1;
  152.  
  153.         $this->_modifyNode($childNode[$this->left_column_name], 2);
  154.         $this->_setNewNode($childNode, $extrafields);
  155.  
  156.         return $this->getNodeWhereLeft($childNode[$this->left_column_name]);
  157.     }
  158.     /**
  159.      * Adds a new node to the left of the supplied focusNode
  160.      * @param array $focusNode The node to use as the position marker
  161.      * @param array $extrafields An associative array of node attributes
  162.      * @return array $siblingNode The new node
  163.      */
  164.     public function insertSibling($focusNode, $extrafields) {
  165.         $siblingNode[$this->parent_column_name] =   $focusNode[$this->parent_column_name];
  166.         $siblingNode[$this->left_column_name]   =   $focusNode[$this->left_column_name];
  167.         $siblingNode[$this->right_column_name]  =   $focusNode[$this->left_column_name]+1;
  168.  
  169.         $this->_modifyNode($siblingNode[$this->left_column_name], 2);
  170.         $this->_setNewNode($siblingNode, $extrafields);
  171.  
  172.         return $this->getNodeWhereLeft($siblingNode[$this->left_column_name]);
  173.     }
  174.  
  175.     /**
  176.      * Adds a new node to the right of the supplied focusNode
  177.      * @param array $focusNode The node to use as the position marker
  178.      * @param array $extrafields An associative array of node attributes
  179.      * @return array $siblingNode The New Node
  180.      */
  181.     public function appendSibling($focusNode, $extrafields) {
  182.         $siblingNode[$this->parent_column_name] =   $focusNode[$this->parent_column_name];
  183.         $siblingNode[$this->left_column_name]   =   $focusNode[$this->right_column_name]+1;
  184.         $siblingNode[$this->right_column_name]  =   $focusNode[$this->right_column_name]+2;
  185.  
  186.         $this->_modifyNode($siblingNode[$this->left_column_name], 2);
  187.         $this->_setNewNode($siblingNode, $extrafields);
  188.  
  189.         return $this->getNodeWhereLeft($siblingNode[$this->left_column_name]);
  190.     }
  191.  
  192.  
  193.     /**
  194.      * Empties the table currently in use - use with extreme caution!
  195.      *
  196.      * @return boolean
  197.      */
  198.     public function deleteTree() {
  199.         return $this->db->delete($this->table_name);
  200.     }
  201.  
  202.     /**
  203.      * Deletes the given node (and any children) from the tree table
  204.      * @param array $node The node to remove from the tree
  205.      * @return array $newnode The node that replaced the deleted node
  206.      */
  207.     public function deleteNode($node) {
  208.         $leftanchor     =   $node[$this->left_column_name];
  209.         $leftcol        =   $this->left_column_name;
  210.         $rightcol       =   $this->right_column_name;
  211.         $leftval        =   $node[$this->left_column_name];
  212.         $rightval       =   $node[$this->right_column_name];
  213.  
  214.         $where = array(
  215.         $leftcol . ' >=' => $leftval,
  216.         $rightcol . ' <=' => $rightval,
  217.         );
  218.         $this->db->delete($this->table_name, $where);
  219.  
  220.         $this->_modifyNode($node[$this->right_column_name]+1, $node[$this->left_column_name] -$node[$this->right_column_name] - 1);
  221.  
  222.         return $this->getNodeWhere($leftcol . ' < ' . $leftanchor . ' ORDER BY ' . $leftcol  . ' DESC');
  223.     }
  224.  
  225.     // -------------------------------------------------------------------------
  226.     //  MODIFY/REORGANISE TREE
  227.     //
  228.     //  Methods to move nodes around the tree. Method names should be
  229.     //  relatively self-explanatory! Hopefully ;)
  230.     //
  231.     // -------------------------------------------------------------------------
  232.  
  233.     /**
  234.      * Moves the given node to make it the next sibling of "target"
  235.      * @param array $node The node to move
  236.      * @param array $target The node to use as the position marker
  237.      * @return array $newpos The new left and right values of the node moved
  238.      */
  239.     public function setNodeAsNextSibling($node, $target) {
  240.         $this->_setParent($node, $target[$this->parent_column_name]);
  241.         return $this->_moveSubtree($node, $target[$this->right_column_name]+1);
  242.     }
  243.  
  244.     /**
  245.      * Moves the given node to make it the prior sibling of "target"
  246.      * @param array $node The node to move
  247.      * @param array $target The node to use as the position marker
  248.      * @return array $newpos The new left and right values of the node moved
  249.      */
  250.     public function setNodeAsPrevSibling($node, $target) {
  251.         $this->_setParent($node, $target[$this->parent_column_name]);
  252.         return $this->_moveSubtree($node, $target[$this->left_column_name]);
  253.     }
  254.  
  255.     /**
  256.      * Moves the given node to make it the first child of "target"
  257.      * @param array $node The node to move
  258.      * @param array $target The node to use as the position marker
  259.      * @return array $newpos The new left and right values of the node moved
  260.      */
  261.     public function setNodeAsFirstChild($node, $target) {
  262.         $this->_setParent($node, $target[$this->primary_key_column_name]);
  263.         return $this->_moveSubtree($node, $target[$this->left_column_name]+1);
  264.     }
  265.  
  266.     /**
  267.      * Moves the given node to make it the last child of "target"
  268.      * @param array $node The node to move
  269.      * @param array $target The node to use as the position marker
  270.      * @return array $newpos The new left and right values of the node moved
  271.      */
  272.     public function setNodeAsLastChild($node, $target) {
  273.         $this->_setParent($node, $target[$this->primary_key_column_name]);
  274.         return $this->_moveSubtree($node, $target[$this->right_column_name]);
  275.     }
  276.  
  277.     // -------------------------------------------------------------------------
  278.     //  QUERY METHODS
  279.     //
  280.     //  Selecting nodes from the tree
  281.     //
  282.     // -------------------------------------------------------------------------
  283.  
  284.     /**
  285.      * Selects the first node to match the given where clause argument
  286.      * @param mixed $whereArg Any valid SQL to follow the WHERE keyword in an SQL statement
  287.      * @return array $resultNode The node returned from the query
  288.      */
  289.     public function getNodeWhere($whereArg = '"1"="1"') {
  290.         $resultNode[$this->left_column_name]    =   $resultNode[$this->right_column_name]   =   0;
  291.  
  292.         $query = $this->db->get_where($this->table_name, $whereArg);
  293.  
  294.         $resultNode = array();
  295.         if($query->num_rows() > 0)
  296.         {
  297.             $result = $query->result_array();
  298.             $resultNode = array_shift($result); // assumes CI standard $row[0] = first row
  299.         }
  300.  
  301.         return $resultNode;
  302.     }
  303.  
  304.     /**
  305.      * Gets an array of nodes
  306.      *
  307.      * @param mixed $whereArg String or array of where arguments
  308.      * @param string $orderArg Orderby argument
  309.      * @param integer $limit_start Number of rows to retrieve
  310.      * @param mixed $limit_offset Row to start retrieving from
  311.      * @return array Returns array of nodes found
  312.      */
  313.     public function getNodesWhere($whereArg = '"1"="1"', $orderArg = '', $limit_start = 0, $limit_offset = null) {
  314.         $resultNode[$this->left_column_name]    =   $resultNode[$this->right_column_name]   =   0;
  315.  
  316.         if($orderArg) {
  317.             $this->db->orderby($orderArg);
  318.         }
  319.         if($limit_start || $limit_offset) {
  320.             $this->db->limit($limit_offset, $limit_start);
  321.         }
  322.         $query = $this->db->get_where($this->table_name, $whereArg);
  323.  
  324.         $resultNodes = array();
  325.         if($query->num_rows() > 0)
  326.         {
  327.             $resultNodes = $query->result_array();
  328.         }
  329.  
  330.         return $resultNodes;
  331.     }
  332.  
  333.     /**
  334.      * Returns the node identified by the given left value
  335.      * @param integer $leftval The left value to use to select the node
  336.      * @return array $resultNode The node returned
  337.      */
  338.     public function getNodeWhereLeft($leftval) {
  339.         return $this->getNodeWhere($this->left_column_name . ' = ' . $leftval);
  340.     }
  341.  
  342.     /**
  343.      * Returns the node identified by the given right value
  344.      * @param integer $rightval The right value to use to select the node
  345.      * @return array $resultNode The node returned
  346.      */
  347.     public function getNodeWhereRight($rightval) {
  348.         return $this->getNodeWhere($this->right_column_name . ' = ' . $rightval);
  349.     }
  350.  
  351.     /**
  352.      * Returns the root nodes
  353.      * @return array $resultNode The node returned
  354.      */
  355.     public function getRootNodes() {
  356.         return $this->getNodesWhere($this->parent_column_name . ' = 0 ');
  357.     }
  358.  
  359.     /**
  360.      * Returns the node with the appropriate primary key field value.
  361.      * Typically, this will be an auto_incrementing primary key column
  362.      * such as categoryid
  363.      * @param mixed $primarykey The value to look up in the primary key index
  364.      * @return array $resultNode The node returned
  365.      */
  366.     public function getNodeFromId($primarykey) {
  367.         // Test if we've set the primary key column name property
  368.         if(empty($this->primary_key_column_name)) return false;
  369.  
  370.         return $this->getNodeWhere($this->primary_key_column_name . ' = "' . $primarykey . '"');
  371.     }
  372.  
  373.     /**
  374.      * Returns the first child node of the given parentNode
  375.      * @param array $parentNode The parent node to use
  376.      * @return array $resultNode The first child of the parent node supplied
  377.      */
  378.     public function getFirstChild($parentNode) {
  379.         return $this->getNodeWhere($this->left_column_name . ' = ' . ($parentNode[$this->left_column_name]+1));
  380.     }
  381.  
  382.     /**
  383.      * Returns the last child node of the given parentNode
  384.      * @param array $parentNode The parent node to use
  385.      * @return array $resultNode the last child of the parent node supplied
  386.      */
  387.     public function getLastChild($parentNode) {
  388.         return $this->getNodeWhere($this->right_column_name . ' = ' . ($parentNode[$this->right_column_name]-1));
  389.     }
  390.  
  391.     /**
  392.      * Returns the node that is the immediately prior sibling of the given node
  393.      * @param array $currNode The node to use as the initial focus of enquiry
  394.      * @return array $resultNode The node returned
  395.      */
  396.     public function getPrevSibling($currNode) {
  397.         return $this->getNodeWhere($this->right_column_name . ' = ' . ($currNode[$this->left_column_name]-1));
  398.     }
  399.  
  400.     /**
  401.      * Returns the node that is the next sibling of the given node
  402.      * @param array $currNode The node to use as the initial focus of enquiry
  403.      * @return array $resultNode The node returned
  404.      */
  405.     public function getNextSibling($currNode) {
  406.         return $this->getNodeWhere($this->left_column_name . ' = ' . ($currNode[$this->right_column_name]+1));
  407.     }
  408.  
  409.     /**
  410.      * Returns the node that represents the parent of the given node
  411.      * @param array $currNode The node to use as the initial focus of enquiry
  412.      * @return array $resultNode the node returned
  413.      */
  414.     public function getAncestor($currNode) {
  415.         return $this->getNodeWhere($this->primary_key_column_name . ' = "' . $currNode[$this->parent_column_name] . '"');
  416.     }
  417.  
  418.  
  419.     // -------------------------------------------------------------------------
  420.     //  NODE TEST METHODS
  421.     //
  422.     //  Boolean tests for nodes
  423.     //
  424.     // -------------------------------------------------------------------------
  425.  
  426.  
  427.     /**
  428.      * Returns true or false
  429.      * (in reality, it checks to see if the given left and
  430.      * right values _appear_ to be valid not necessarily that they _are_ valid)
  431.      * @param array $node The node to test
  432.      * @return boolean
  433.      */
  434.     public function checkIsValidNode($node) {
  435.         return (empty($node) ? false : ($node[$this->left_column_name] < $node[$this->right_column_name]) );
  436.     }
  437.  
  438.     /**
  439.      * Tests whether the given node has an ancestor
  440.      * (effectively the opposite of isRoot yes|no)
  441.      * @param array $node The node to test
  442.      * @return boolean
  443.      */
  444.     public function checkNodeHasAncestor($node) {
  445.         return $this->checkIsValidNode($this->getAncestor($node));
  446.     }
  447.  
  448.     /**
  449.      * Tests whether the given node has a prior sibling or not
  450.      * @param array $node
  451.      * @return boolean
  452.      */
  453.     public function checkNodeHasPrevSibling($node) {
  454.         return $this->checkIsValidNode($this->getPrevSibling($node));
  455.     }
  456.  
  457.     /**
  458.      * Test to see if node has siblings after itself
  459.      * @param array $node The node to test
  460.      * @return boolean
  461.      */
  462.     public function checkNodeHasNextSibling($node) {
  463.         return $this->checkIsValidNode($this->getNextSibling($node));
  464.     }
  465.  
  466.     /**
  467.      * Test to see if node has children
  468.      * @param array $node The node to test
  469.      * @return boolean
  470.      */
  471.     public function checkNodeHasChildren($node) {
  472.         return (($node[$this->right_column_name] - $node[$this->left_column_name]) > 1);
  473.     }
  474.  
  475.     /**
  476.      * Test to see if the given node is also a root node
  477.      * @param array $node The node to test
  478.      * @return boolean
  479.      */
  480.     public function checkNodeIsRoot($node) {
  481.         return ($node[$this->parent_column_name] == 0);
  482.     }
  483.  
  484.     /**
  485.      * Test to see if the given node is a leaf node (ie has no children)
  486.      * @param array $node The node to test
  487.      * @return boolean
  488.      */
  489.     public function checkNodeIsLeaf($node) {
  490.         return (($node[$this->right_column_name] - $node[$this->left_column_name]) == 1);
  491.     }
  492.  
  493.     /**
  494.      * Test to see if the first given node is a child of the second given node
  495.      * @param array $testNode the node to test for child status
  496.      * @param array $controlNode the node to use as the parent or ancestor
  497.      * @return boolean
  498.      */
  499.     public function checkNodeIsChild($testNode, $controlNode) {
  500.         return ($testNode[$this->parent_column_name] == $controlNode[$this->primary_key_column_name]);
  501.     }
  502.  
  503.     /**
  504.      * Test to determine whether testNode is infact also controlNode (is A === B)
  505.      * @param array $testNode The node to test
  506.      * @param array $controlNode The node prototype to use for the comparison
  507.      * @return boolean
  508.      */
  509.     public function checkNodeIsEqual($testNode, $controlNode) {
  510.         return (($testNode[$this->left_column_name]==$controlNode[$this->left_column_name]) and ($testNode[$this->right_column_name]==$controlNode[$this->right_column_name]));
  511.     }
  512.  
  513.     /**
  514.      * Combination method of IsChild and IsEqual
  515.      * @param array $testNode The node to test
  516.      * @param array $controlNode The node prototype to use for the comparison
  517.      * @return boolean
  518.      */
  519.     public function checkNodeIsChildOrEqual($testNode, $controlNode) {
  520.         return (($testNode[$this->left_column_name]>=$controlNode[$this->left_column_name]) and ($testNode[$this->right_column_name]<=$controlNode[$this->right_column_name]));
  521.     }
  522.  
  523.  
  524.     // -------------------------------------------------------------------------
  525.     //  TREE QUERY METHODS
  526.     //
  527.     //  Query the tree itself
  528.     //
  529.     // -------------------------------------------------------------------------
  530.  
  531.     /**
  532.      * Returns the number of descendents that a node has
  533.      * @param array $node The node to query
  534.      * @return integer The number of descendents
  535.      */
  536.     public function getNumberOfChildren($node) {
  537.         return (($node[$this->right_column_name] - $node[$this->left_column_name] - 1) / 2);
  538.     }
  539.  
  540.     /**
  541.      * Returns the tree level for the given node (assuming root node is at level 0)
  542.      * @param array $node The node to query
  543.      * @return integer The level of the supplied node
  544.      */
  545.     public function getNodeLevel($node) {
  546.         $leftcol    =      $this->left_column_name;
  547.         $rightcol   =      $this->right_column_name;
  548.         $leftval    = (int) $node[$leftcol];
  549.         $rightval   = (int) $node[$rightcol];
  550.  
  551.         $this->db->where($leftcol . ' <', $leftval);
  552.         $this->db->where($rightcol . ' >', $rightval);
  553.  
  554.         return $this->db->count_all($this->table_name);
  555.     }
  556.  
  557.     /**
  558.      * Returns an array of the tree starting from the supplied node
  559.      * @param array $node The node to use as the starting point (typically root)
  560.      * @param boolean $direct When true, will retrieve only immediate children using parent col
  561.      * @return array $tree_handle The tree represented as an array to assist with
  562.      *                          the other tree traversal operations
  563.      */
  564.     public function getTreePreorder($node, $direct=false) {
  565.         $leftcol    =      $this->left_column_name;
  566.         $rightcol   =      $this->right_column_name;
  567.         $leftval    = (int) $node[$leftcol];
  568.         $rightval   = (int) $node[$rightcol];
  569.  
  570.         $primarykeycol  =       $this->primary_key_column_name;
  571.         $parentcol      =       $this->parent_column_name;
  572.         $primarykeyval  = (int) $node[$primarykeycol];
  573.  
  574.         if( $direct ) {
  575.             $this->db->where($parentcol, $primarykeyval);
  576.         }else{
  577.             $this->db->where($leftcol . ' >=', $leftval);
  578.             $this->db->where($rightcol . ' <=', $rightval);
  579.         }
  580.         $this->db->order_by($leftcol, 'asc');
  581.         $query = $this->db->get($this->table_name);
  582.  
  583.         $treeArray = array();
  584.  
  585.         if($query->num_rows() > 0) {
  586.             foreach($query->result_array() AS $result) {
  587.                 $treeArray[] = $result;
  588.             }
  589.         }
  590.  
  591.         $retArray = array(  'result_array'  =>    $treeArray,
  592.         'prev_left'  =>   $node[$leftcol],
  593.         'prev_right'    =>    $node[$rightcol],
  594.         'level'      =>   -2);
  595.  
  596.         return $retArray;
  597.     }
  598.  
  599.     /**
  600.      * Returns the next element from the tree and updates the tree_handle with the
  601.      * new positions
  602.      * @param array $tree_handle Passed by reference to allow for modifications
  603.      * @return array The next node in the tree
  604.      */
  605.     public function getTreeNext($tree_handle) {
  606.         $leftcol    =   $this->left_column_name;
  607.         $rightcol   =   $this->right_column_name;
  608.  
  609.         if(!empty($tree_handle['result_array'])) {
  610.             if($row = array_shift($tree_handle['result_array'])) {
  611.  
  612.                 $tree_handle['level']+= $tree_handle['prev_left'] - $row[$leftcol] + 2;
  613.                 // store current node
  614.                 $tree_handle['prev_left']  = $row[$leftcol];
  615.                 $tree_handle['prev_right'] = $row[$rightcol];
  616.                 $tree_handle['row'] = $row;
  617.  
  618.                 return array(   $leftcol  =>  $row[$leftcol],
  619.                 $rightcol =>  $row[$rightcol]
  620.                 );
  621.             }
  622.         }
  623.  
  624.         return FALSE;
  625.     }
  626.  
  627.     /**
  628.      * Returns the given attribute (database field) for the current node in $tree_handle
  629.      * @param array $tree_handle The tree as an array
  630.      * @param string $attribute A string containing the fieldname to retrieve
  631.      * @return string The value requested
  632.      */
  633.     public function getTreeAttribute($tree_handle,$attribute) {
  634.         return $tree_handle['row'][$attribute];
  635.     }
  636.  
  637.     /**
  638.      * Returns the current node of the tree contained in $tree_handle
  639.      * @param array $tree_handle The tree as an array
  640.      * @return array The left and right values of the current node
  641.      */
  642.     public function getTreeCurrent($tree_handle) {
  643.         return  array(
  644.         $this->left_column_name     =>  $tree_handle['prev_left'],
  645.         $this->right_column_name    =>  $tree_handle['prev_right'],
  646.         );
  647.     }
  648.  
  649.     /**
  650.      * Returns the current level from the tree
  651.      * @param array $tree_handle The tree as an array
  652.      * @return integer The integer value of the current level
  653.      */
  654.     public function getTreeLevel($tree_handle) {
  655.         return $tree_handle['level'];
  656.     }
  657.  
  658.     /**
  659.      * Find the path of a given node
  660.      * @param array $node The node to start with
  661.      * @param boolean $includeSelf Wheter or not to include given node in result
  662.      * @param boolean $returnAsArray Wheter or not to return array or unordered list
  663.      * @return array or unordered list
  664.      */
  665.     public function getPath($node, $includeSelf=FALSE, $returnAsArray=FALSE) {
  666.        
  667.         if(empty($node)) return FALSE;
  668.        
  669.         $leftcol    =      $this->left_column_name;
  670.         $rightcol   =      $this->right_column_name;
  671.         $leftval    = (int) $node[$leftcol];
  672.         $rightval   = (int) $node[$rightcol];
  673.        
  674.         if($includeSelf)
  675.         {
  676.             $this->db->where($leftcol . ' <= ' . $leftval . ' AND ' . $rightcol . ' >= ' . $rightval);
  677.         }
  678.         else
  679.         {
  680.             $this->db->where($leftcol . ' < ' . $leftval . ' AND ' . $rightcol . ' > ' . $rightval);
  681.         }
  682.        
  683.         $this->db->order_by($leftcol);
  684.         $query = $this->db->get($this->table_name);
  685.  
  686.         if($query->num_rows() > 0)
  687.         {
  688.             if($returnAsArray)
  689.             {
  690.                 return $query->result_array();
  691.             }
  692.             else
  693.             {
  694.                 return $this->buildCrumbs($query->result_array());
  695.             }
  696.         }
  697.        
  698.         return FALSE;
  699.     }
  700.  
  701.     function buildCrumbs($crumbData)
  702.     {
  703.         $retVal = '';
  704.  
  705.         $retVal = '<ul id="breadcrumbs">';
  706.  
  707.         // $retVal.= '<li><a href="http://localhost/2ndsea/index.php/shop/" name="shop">Index</a></li>';
  708.  
  709.         foreach ($crumbData as $itemId)
  710.         {
  711.             if($itemId['id'] > 1) $retVal .= '<span class="divider">></span>';
  712.  
  713.             $retVal .= '<li>' . anchor(
  714.                 'shop/category/' . $itemId['id'],
  715.                 $itemId['short_desc'],
  716.                 array(
  717.                     'name' => $itemId['name'])
  718.                 );
  719.                
  720.             $retVal .= '</li>';
  721.         }
  722.  
  723.         $retVal .= '</ul>';
  724.  
  725.         return $retVal;
  726.     }
  727.  
  728.  
  729.     // -------------------------------------------------------------------------
  730.     //   NODE FIELD QUERIES
  731.     //
  732.     // -------------------------------------------------------------------------
  733.  
  734.     /**
  735.      * Queries the database for the value of the given field
  736.      * @param array $node The node to be queried
  737.      * @param string $fieldname The name of the field to query
  738.      * @return string $retval The value of the field for the node looked up
  739.      */
  740.     public function getNodeAttribute($node, $fieldname) {
  741.         $leftcol    =       $this->left_column_name;
  742.         $leftval    = (int) $node[$leftcol];
  743.  
  744.         $this->db->where($leftcol, $leftval);
  745.         $query = $this->db->get($this->table_name);
  746.  
  747.         if($query->num_rows() > 0) {
  748.             $res = $query->result();
  749.             return $res->$fieldname;
  750.         } else {
  751.             return '';
  752.         }
  753.     }
  754.  
  755.     /**
  756.      * Renders the fields for each node starting at the given node
  757.      * @param array $node The node to start with
  758.      * @param array $fields The fields to display for each node
  759.      * @return string Sample HTML render of tree
  760.      */
  761.     public function getSubTreeAsHTML($nodes, $fields = array()) {
  762.         if(isset($nodes[0]) && !is_array($nodes[0])) {
  763.             $nodes = array($nodes);
  764.         }
  765.  
  766.         $retVal = '';
  767.         foreach($nodes AS $node) {
  768.             $tree_handle = $this->getTreePreorder($node);
  769.  
  770.             while($this->getTreeNext($tree_handle))
  771.             {
  772.                 // print indentation
  773.                 $retVal .= (str_repeat('&nbsp;', $this->getTreeLevel($tree_handle)*4));
  774.  
  775.                 // print requested fields
  776.                 $field = reset($fields);
  777.                 while($field){
  778.                     $retVal .= $tree_handle['row'][$field] . "\n";
  779.                     $field = next($fields);
  780.                 }
  781.                 $retVal .= "<br />\n";
  782.  
  783.             }
  784.         }
  785.  
  786.         return $retVal;
  787.     }
  788.  
  789.     /**
  790.      * Renders the tree starting from given node
  791.      * @param array $node The node to start with
  792.      * @return string Unordered HTML list of the tree
  793.      */
  794.     public function getSubTree($node) {
  795.        
  796.         if(empty($node)) return FALSE;
  797.            
  798.         $tree_handle = $this->getTreePreorder($node);
  799.        
  800.         $menuData = array(
  801.             'items' => array(),
  802.             'parents' => array()
  803.         );
  804.        
  805.         foreach ($tree_handle['result_array'] as $menuItem)
  806.         {
  807.             $menuData['items'][$menuItem['id']] = $menuItem;
  808.             $menuData['parents'][$menuItem['parent_id']][] = $menuItem['id'];
  809.         }
  810.  
  811.         return $menuData;
  812.         // return $this->buildMenu($node['parent_id'], $menuData);
  813.     }
  814.    
  815.     function buildMenu($parentId, $menuData, $depth=0)
  816.     {
  817.         $retVal = '';
  818.  
  819.         if (isset($menuData['parents'][$parentId]))
  820.         {
  821.             $retVal = '<ul>';
  822.    
  823.             foreach ($menuData['parents'][$parentId] as $itemId)
  824.             {
  825.            
  826.                 $retVal .= '<li class="depth-' . $depth . '">' . anchor(
  827.                     'shop/category/' . $menuData['items'][$itemId]['id'],
  828.                     $menuData['items'][$itemId]['short_desc'],
  829.                     array(
  830.                         // 'title' => $menuData['items'][$itemId]['short_desc']
  831.                         'class' => 'id-' . $itemId['id']
  832.                     )
  833.                 );
  834.  
  835.                 $retVal .= $this->buildMenu($itemId, $menuData, $depth+1);
  836.  
  837.                 $retVal .= '</li>';
  838.             }
  839.    
  840.             $retVal .= '</ul>';
  841.         }
  842.  
  843.         return $retVal;
  844.     }
  845.  
  846.  
  847.     /**
  848.      * Renders the entire tree as per getSubTreeAsHTML starting from root
  849.      * @param array $fields An array of the fields to display
  850.      */
  851.     public function getTreeAsHTML($fields=array()) {
  852.         return $this->getSubTreeAsHTML($this->getRootNodes(), $fields);
  853.     }
  854.  
  855.     // -------------------------------------------------------------------------
  856.     //  INTERNALS
  857.     //
  858.     //  Private, internal methods
  859.     //
  860.     // -------------------------------------------------------------------------
  861.  
  862.     /**
  863.      *  _setNewNode
  864.      *
  865.      *  Inserts a new node into the tree
  866.      *
  867.      *  @param array $node An array containing the left and right values to use
  868.      *  @param array $extrafields An associative array of field names to values for \
  869.      *                        additional columns in tree table (eg CategoryName etc)
  870.      *
  871.      *  @return boolean True/False dependent upon the success of the operation
  872.      *  @access private
  873.      */
  874.     private function _setNewNode($node, $extrafields) {
  875.         $parentcol  =       $this->parent_column_name;
  876.         $leftcol    =       $this->left_column_name;
  877.         $rightcol   =       $this->right_column_name;
  878.         $parentval  = (int) $node[$parentcol];
  879.         $leftval    = (int) $node[$leftcol];
  880.         $rightval   = (int) $node[$rightcol];
  881.  
  882.         $data = array(
  883.             $parentcol => $parentval,
  884.             $leftcol => $leftval,
  885.             $rightcol => $rightval,
  886.         );
  887.         if(is_array($extrafields) && !empty($extrafields)) $data = array_merge($data, $extrafields);
  888.  
  889.         $result = $this->db->insert($this->table_name, $data);
  890.  
  891.         if(!$result) {
  892.             log_message('error', 'Node addition failed for ' . $leftval . ' - ' . $rightval);
  893.         }
  894.  
  895.         return $result;
  896.     }
  897.  
  898.     /**
  899.      * Sets the parent for the specified node
  900.      *
  901.      * @param array $node The child node
  902.      * @param integer $parent_id The id of the parent node
  903.      * @access private
  904.      */
  905.     private function _setParent($node, $parent_id) {
  906.         $primarykeycol  =   $this->primary_key_column_name;
  907.         $parentcol      =   $this->parent_column_name;
  908.         $primarykeyval  =   (int) $node[$primarykeycol];
  909.         $parentval      =   (int) $node[$parentcol];
  910.  
  911.         if($parentval != $parent_id) {
  912.             $data = array(
  913.                 $parentcol => $parent_id,
  914.             );
  915.  
  916.             $this->db->where($primarykeycol, $primarykeyval);
  917.             $this->db->update($this->table_name, $data);
  918.         }
  919.     }
  920.  
  921.     /**
  922.      * The method that performs moving/renumbering operations
  923.      *
  924.      * @param array $node The node to move
  925.      * @param array $targetValue Position integer to use as the target
  926.      * @return array $newpos The new left and right values of the node moved
  927.      * @access private
  928.      */
  929.     private function _moveSubtree($node, $targetValue) {
  930.         $sizeOfTree = $node[$this->right_column_name] - $node[$this->left_column_name] + 1;
  931.         $this->_modifyNode($targetValue, $sizeOfTree);
  932.  
  933.         if($node[$this->left_column_name] >= $targetValue)
  934.         {
  935.             $node[$this->left_column_name] += $sizeOfTree;
  936.             $node[$this->right_column_name] += $sizeOfTree;
  937.         }
  938.  
  939.         $newpos = $this->_modifyNodeRange($node[$this->left_column_name], $node[$this->right_column_name], $targetValue - $node[$this->left_column_name]);
  940.  
  941.         $this->_modifyNode($node[$this->right_column_name]+1, - $sizeOfTree);
  942.  
  943.         if($node[$this->left_column_name] <= $targetValue)
  944.         {
  945.             $newpos[$this->left_column_name] -= $sizeOfTree;
  946.             $newpos[$this->right_column_name] -= $sizeOfTree;
  947.         }
  948.  
  949.         return $newpos;
  950.     }
  951.  
  952.     /**
  953.      * _modifyNode
  954.      *
  955.      * Adds $changeVal to all left and right values that are greater than or
  956.      * equal to $node_int
  957.      *
  958.      * @param integer $node_int The value to start the shift from
  959.      * @param integer $changeVal unsigned integer value for change
  960.      * @access private
  961.      */
  962.     private function _modifyNode($node_int, $changeVal) {
  963.         $leftcol    =   $this->left_column_name;
  964.         $rightcol   =   $this->right_column_name;
  965.  
  966.         $this->db->set($leftcol, $leftcol . '+' . (int) $changeVal, FALSE);
  967.         $this->db->where($leftcol . ' >=', (int) $node_int);
  968.         $this->db->update($this->table_name);
  969.  
  970.         $this->db->set($rightcol, $rightcol . '+' . (int) $changeVal, FALSE);
  971.         $this->db->where($rightcol . ' >=', (int) $node_int);
  972.         $this->db->update($this->table_name);
  973.     }
  974.  
  975.     /**
  976.      * _modifyNodeRange
  977.      *
  978.      * @param integer $lowerbound integer value of lowerbound of range to move
  979.      * @param integer $upperbound integer value of upperbound of range to move
  980.      * @param integer $changeVal unsigned integer of change amount
  981.      * @return array Returns array of the new left & right column values
  982.      * @access private
  983.      */
  984.     private function _modifyNodeRange($lowerbound, $upperbound, $changeVal) {
  985.         $leftcol    =   $this->left_column_name;
  986.         $rightcol   =   $this->right_column_name;
  987.  
  988.         $this->db->set($leftcol, $leftcol . '+' . (int) $changeVal, FALSE);
  989.         $this->db->where($leftcol . ' >=', (int) $lowerbound);
  990.         $this->db->where($leftcol . ' <=', (int) $upperbound);
  991.         $this->db->update($this->table_name);
  992.  
  993.         $this->db->set($rightcol, $rightcol . '+' . (int) $changeVal, FALSE);
  994.         $this->db->where($rightcol . ' >=', (int) $lowerbound);
  995.         $this->db->where($rightcol . ' <=', (int) $upperbound);
  996.         $this->db->update($this->table_name);
  997.  
  998.         $retArray = array(
  999.         $this->left_column_name  =>  $lowerbound+$changeVal,
  1000.         $this->right_column_name =>  $upperbound+$changeVal
  1001.         );
  1002.         return $retArray;
  1003.     }
  1004.  
  1005. }
  1006.  
  1007. ?>
Advertisement
Add Comment
Please, Sign In to add comment