some assorted updates
[openemr.git] / library / classes / Tree.class.php
blob64b3da077f4bda4798cb08a6362a80e32786fa85
1 <?php
3 define("ROOT_TYPE_ID",1);
4 define("ROOT_TYPE_NAME",2);
6 /**
7 * class Tree
8 * This class is a clean implementation of a modified preorder tree traversal hierachy to relational model
9 * Don't use this class directly as it won't work, extend it and set the $this->_table variable, currently
10 * this class needs its own sequence per table. MPTT uses a lot of self referential parent child relationships
11 * and having ids that are more or less sequential makes human reading, fixing and reconstruction much easier.
14 class Tree {
17 * This is the name of the table this tree is stored in
18 * @var string
20 var $_table;
23 * This is a lookup table so that you can get a node name or parent id from its id
24 * @var array
26 var $_id_name;
29 * This is a db abstraction object compatible with ADODB
30 * @var object the constructor expects it to be available as $GLOBALS['adodb']['db']
32 var $_db;
35 * The constructor takes a value and a flag determining if the value is the id of a the desired root node or the name
36 * @param mixed $root name or id of desired root node
37 * @param int $root_type optional flag indicating if $root is a name or id, defaults to id
39 function Tree($root,$root_type = ROOT_TYPE_ID) {
40 $this->_db = $GLOBALS['adodb']['db'];
41 $this->_root = mysql_real_escape_string($root);
42 $this->_root_type = mysql_real_escape_string($root_type);
43 $this->load_tree();
46 function load_tree() {
47 $root = $this->_root;
48 $tree = array();
49 $tree_tmp = array();
51 //get the left and right value of the root node
52 $sql = "SELECT * FROM " . $this->_table . " WHERE id='".$root."'";
54 if ($this->root_type == ROOT_TYPE_NAME) {
55 $sql = "SELECT * FROM " . $this->_table . " WHERE name='".$root."'";
57 $result = $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
58 $row = array();
60 if($result && !$result->EOF) {
61 $row = $result->fields;
63 else {
64 $this->tree = array();
67 // start with an empty right stack
68 $right = array();
70 // now, retrieve all descendants of the root node
71 $sql = "SELECT * FROM " . $this->_table . " WHERE lft BETWEEN " . $row['lft'] . " AND " . $row['rght'] . " ORDER BY parent,name ASC;";
72 $result = $this->_db->Execute($sql);
73 $this->_id_name = array();
76 while ($result && !$result->EOF) {
77 $ar = array();
78 $row = $result->fields;
80 //create a lookup table of id to name for every node that will end up in this tree, this is used
81 //by the array building code below to find the chain of parents for each node
82 $this->_id_name[$row['id']] = array("id" => $row['id'], "name" => $row['name'], "parent" => $row['parent']);
84 // only check stack if there is one
85 if (count($right)>0) {
86 // check if we should remove a node from the stack
87 while ($right[count($right)-1]<$row['rght']) {
88 array_pop($right);
92 //set up necessary variables to then determine the chain of parents for each node
93 $parent = $row['parent'];
94 $loop = 0;
96 //this is a string that gets evaled below to create the array representing the tree
97 $ar_string = "[\"".($row['id']) ."\"] = \$row[\"value\"]";
99 //if parent is 0 then the node has no parents, the number of nodes in the id_name lookup always includes any nodes
100 //that could be the parent of any future node in the record set, the order is deterministic because of the algorithm
101 while($parent != 0 && $loop < count($this->_id_name)) {
102 $ar_string = "[\"" . ($this->_id_name[$parent]['id']) . "\"]" . $ar_string;
103 $loop++;
104 $parent = $this->_id_name[$parent]['parent'];
107 $ar_string = '$ar' . $ar_string . ";";
108 //echo $ar_string;
110 //now eval the string to create the tree array
111 //there must be a more efficient way to do this than eval?
112 eval($ar_string);
114 //merge the evaled array with all of the already exsiting tree elements,
115 //merge recursive is used so that no keys are replaced in other words a key
116 //with a specific value will not be replace but instead that value will be turned into an array
117 //consisting of the previous value and the new value
118 $tree = array_merge_n($tree,$ar);
120 // add this node to the stack
121 $right[] = $row['rght'];
122 $result->MoveNext();
125 $this->tree = $tree;
129 * This function completely rebuilds a tree starting from parent to ensure that all of its preorder values
130 * are integrous.
131 * Upside is that it fixes any kind of goofiness, downside is that it is recursive and consequently
132 * exponentially expensive with the size of the tree.
133 * On adds and deletes the tree does dynamic updates as appropriate to maintain integrity of the algorithm,
134 * however you can still force it to do goofy things and afterwards you will need this function to fix it.
135 * If you need to do a huge number of adds or deletes it will be much faster to act directly on the db and then
136 * call this to fix the mess than to use the add and delete functions.
137 * @param int $parent id of the node you would like to rebuild all nodes below
138 * @param int $left optional proper left value of the node you are rebuilding below, then used recursively
140 function rebuild_tree($parent, $left = null) {
142 //if no left is supplied assume the existing left is proper
143 if ($left == null) {
144 $sql = "SELECT lft FROM " . $this->_table . " WHERE id='" . $parent . "';";
145 $result = $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
147 if($result && !$result->EOF) {
148 $left = $result->fields['lft'];
150 else {
151 //the node you are rebuilding below if goofed up and you didn't supply a proper value
152 //nothing we can do so error
153 die("Error: The node you are rebuilding from could not be found, please supply an existing node id.");
156 // get all children of this node
157 $sql = "SELECT id FROM " . $this->_table . " WHERE parent='" . $parent . "' ORDER BY id;";
158 $result = $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
160 // the right value of this node is the left value + 1
161 $right = $left+1;
163 while ($result && !$result->EOF) {
164 $row = $result->fields;
165 // recursive execution of this function for each
166 // child of this node
167 // $right is the current right value, which is
168 // incremented by the rebuild_tree function
169 $right = $this->rebuild_tree($row['id'], $right);
170 $result->MoveNext();
173 // we've got the left value, and now that we've processed
174 // the children of this node we also know the right value
175 $sql = "UPDATE " . $this->_table . " SET lft=".$left.", rght=".$right." WHERE id='".$parent."';";
176 //echo $sql . "<br>";
177 $this->_db->Execute($sql) or die("Error: $sql" . $this->_db->ErrorMsg());
179 // return the right value of this node + 1
180 return $right+1;
185 * Call this to add a new node to the tree
186 * @param int $parent id of the node you would like the new node to have as its parent
187 * @param string $name the name of the new node, it will be used to reference its value in the tree array
188 * @param string $value optional value this node is to contain
189 * @return int id of newly added node
191 function add_node($parent_id,$name,$value="") {
193 $sql = "SELECT * from " . $this->_table . " where parent = '" . $parent_id . "' and name='" . $name . "'";
194 $result = $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
196 if ($result && !$result->EOF) {
197 die("You cannot add a node with the name '" . $name ."' because one already exists under parent " . $parent_id . "<br>");
200 $sql = "SELECT * from " . $this->_table . " where id = '" . $parent_id . "'";
201 $result = $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
203 $next_right = 0;
205 if ($result && !$result->EOF) {
206 $next_right = $result->fields['rght'];
209 $sql = "UPDATE " . $this->_table . " SET rght=rght+2 WHERE rght>=" . $next_right;
210 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
211 $sql = "UPDATE " . $this->_table . " SET lft=lft+2 WHERE lft>=" . $next_right;
212 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
214 $id = $this->_db->GenID($this->_table . "_seq");
215 $sql = "INSERT INTO " . $this->_table . " SET name='" . $name . "', value='" . $value . "', lft='" . $next_right . "', rght='" . ($next_right + 1) . "', parent='" . $parent_id . "', id='" . $id . "'";
216 $this->_db->Execute($sql) or die("Error: $sql :: " . $this->_db->ErrorMsg());
217 //$this->rebuild_tree(1,1);
218 $this->load_tree();
219 return $id;
223 * Call this to delete a node from the tree, the nodes children (and their children, etc) will become children
224 * of the deleted nodes parent
225 * @param int $id id of the node you want to delete
227 function delete_node($id) {
229 $sql = "SELECT * from " . $this->_table . " where id = '" . $id . "'";
230 //echo $sql . "<br>";
231 $result = $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
233 $left = 0;
234 $right = 1;
235 $new_parent = 0;
237 if ($result && !$result->EOF) {
238 $left = $result->fields['lft'];
239 $right = $result->fields['rght'];
240 $new_parent = $result->fields['parent'];
243 $sql = "UPDATE " . $this->_table . " SET rght=rght-2 WHERE rght>" . $right;
244 //echo $sql . "<br>";
245 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
247 $sql = "UPDATE " . $this->_table . " SET lft=lft-2 WHERE lft>" . $right;
248 //echo $sql . "<br>";
249 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
251 $sql = "UPDATE " . $this->_table . " SET lft=lft-1, rght=rght-1 WHERE lft>" . $left . " and rght < " . $right;
252 //echo $sql . "<br>";
253 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
255 //only update the childrens parent setting if the node has children
256 if ($right > ($left +1)) {
257 $sql = "UPDATE " . $this->_table . " SET parent='" . $new_parent . "' WHERE parent='" . $id . "'";
258 //echo $sql . "<br>";
259 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
262 $sql = "DELETE FROM " . $this->_table . " where id='" . $id . "'";
263 //echo $sql . "<br>";
264 $this->_db->Execute($sql) or die("Error: " . $this->_db->ErrorMsg());
265 $this->load_tree();
267 return true;
270 function get_node_info($id) {
271 if(!empty($this->_id_name[$id])) {
272 return $this->_id_name[$id];
274 else {
275 return array();
279 function get_node_name($id) {
280 if(!empty($this->_id_name[$id])) {
281 return $this->_id_name[$id]['name'];
283 else {
284 return false;
290 function array_merge_2(&$array, &$array_i) {
291 // For each element of the array (key => value):
292 foreach ($array_i as $k => $v) {
293 // If the value itself is an array, the process repeats recursively:
294 if (is_array($v)) {
295 if (!isset($array[$k])) {
296 $array[$k] = array();
298 array_merge_2($array[$k], $v);
300 // Else, the value is assigned to the current element of the resulting array:
301 } else {
302 if (isset($array[$k]) && is_array($array[$k])) {
303 $array[$k][0] = $v;
304 } else {
305 if (isset($array) && !is_array($array)) {
306 $temp = $array;
307 $array = array();
308 $array[0] = $temp;
310 $array[$k] = $v;
317 function array_merge_n() {
318 // Initialization of the resulting array:
319 $array = array();
321 // Arrays to be merged (function's arguments):
322 $arrays =& func_get_args();
324 // Merging of each array with the resulting one:
325 foreach ($arrays as $array_i) {
326 if (is_array($array_i)) {
327 array_merge_2($array, $array_i);
331 return $array;
336 $db = $GLOBALS['adodb']['db'];
337 $sql = "USE document;";
338 $db->Execute($sql);
339 $t = new Tree(1);
340 echo "<pre>";
341 print_r($t->tree);
342 //$nid = $t->add_node(0,"test node2","test value");
343 //$t->add_node($nid,"test child","another value");
344 //$t->add_node($nid,"test child");
345 print_r($t->tree);
346 echo "</pre>";