Commit generated changelog for 7.0.2.1 (#7458)
[openemr.git] / library / classes / TreeMenu.php
blob13c32f03c2f599e2a8880f48d05009e5740af1d8
1 <?php
3 // +-----------------------------------------------------------------------+
4 // | Copyright (c) 2002-2003, Richard Heyes, Harald Radi |
5 // | All rights reserved. |
6 // | |
7 // | Redistribution and use in source and binary forms, with or without |
8 // | modification, are permitted provided that the following conditions |
9 // | are met: |
10 // | |
11 // | o Redistributions of source code must retain the above copyright |
12 // | notice, this list of conditions and the following disclaimer. |
13 // | o Redistributions in binary form must reproduce the above copyright |
14 // | notice, this list of conditions and the following disclaimer in the |
15 // | documentation and/or other materials provided with the distribution.|
16 // | o The names of the authors may not be used to endorse or promote |
17 // | products derived from this software without specific prior written |
18 // | permission. |
19 // | |
20 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
21 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
22 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
23 // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
24 // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
25 // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
26 // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
27 // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
28 // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
29 // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
30 // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
31 // | |
32 // +-----------------------------------------------------------------------+
33 // | Author: Richard Heyes <richard@phpguru.org> |
34 // | Harald Radi <harald.radi@nme.at> |
35 // +-----------------------------------------------------------------------+
37 // $Id$
39 /**
40 * HTML_TreeMenu Class
42 * A simple couple of PHP classes and some not so simple
43 * Jabbascript which produces a tree menu. In IE this menu
44 * is dynamic, with branches being collapsable. In IE5+ the
45 * status of the collapsed/open branches persists across page
46 * refreshes.In any other browser the tree is static. Code is
47 * based on work of Harald Radi.
49 * Usage.
51 * After installing the package, copy the example php script to
52 * your servers document root. Also place the TreeMenu.js and the
53 * images folder in the same place. Running the script should
54 * then produce the tree.
56 * Thanks go to Chip Chapin (http://www.chipchapin.com) for many
57 * excellent ideas and improvements.
59 * @author Richard Heyes <richard@php.net>
60 * @author Harald Radi <harald.radi@nme.at>
61 * @access public
62 * @package HTML_TreeMenu
65 class HTML_TreeMenu
67 /**
68 * Indexed array of subnodes
69 * @var array
71 var $items;
73 /**
74 * Constructor
76 * @access public
78 function __construct()
80 // Not much to do here :(
83 /**
84 * This function adds an item to the the tree.
86 * @access public
87 * @param object $node The node to add. This object should be
88 * a HTML_TreeNode object.
89 * @return object Returns a reference to the new node inside
90 * the tree.
92 function &addItem(&$node)
94 $this->items[] = &$node;
95 return $this->items[count($this->items) - 1];
98 /**
99 * Import method for creating HTML_TreeMenu objects/structures
100 * out of existing tree objects/structures. Currently supported
101 * are Wolfram Kriesings' PEAR Tree class, and Richard Heyes' (me!)
102 * Tree class (available here: http://www.phpguru.org/). This
103 * method is intended to be used statically, eg:
104 * $treeMenu = &HTML_TreeMenu::createFromStructure($myTreeStructureObj);
106 * @param array $params An array of parameters that determine
107 * how the import happens. This can consist of:
108 * structure => The tree structure
109 * type => The type of the structure, currently
110 * can be either 'heyes' or 'kriesing'
111 * nodeOptions => Default options for each node
113 * @return object The resulting HTML_TreeMenu object
115 function createFromStructure($params)
117 if (!isset($params['nodeOptions'])) {
118 $params['nodeOptions'] = array();
121 switch (@$params['type']) {
124 * Wolfram Kriesings' PEAR Tree class
126 case 'kriesing':
127 $className = strtolower(get_class($params['structure']->dataSourceClass));
128 $isXMLStruct = strpos($className, '_xml') !== false ? true : false;
130 // Get the entire tree, the $nodes are sorted like in the tree view
131 // from top to bottom, so we can easily put them in the nodes
132 $nodes = $params['structure']->getNode();
134 // Make a new menu and fill it with the values from the tree
135 $treeMenu = new HTML_TreeMenu();
136 $curNode[0] = &$treeMenu; // we need the current node as the reference to the
138 foreach ($nodes as $aNode) {
139 $events = array();
140 $data = array();
142 // In an XML, all the attributes are saved in an array, but since they might be
143 // used as the parameters, we simply extract them here if we handle an XML-structure
144 if ($isXMLStruct && sizeof($aNode['attributes'])) {
145 foreach ($aNode['attributes'] as $key => $val) {
146 if (!$aNode[$key]) { // dont overwrite existing values
147 $aNode[$key] = $val;
152 // Process all the data that are saved in $aNode and put them in the data and/or events array
153 foreach ($aNode as $key => $val) {
154 if (!is_array($val)) {
155 // Dont get the recursive data in here! they are always arrays
156 if (substr($key, 0, 2) == 'on') { // get the events
157 $events[$key] = $val;
160 // I put it in data too, so in case an options starts with 'on' its also passed to the node ... not too cool i know
161 $data[$key] = $val;
165 // Normally the text is in 'name' in the Tree class, so we check both but 'text' is used if found
166 $data['text'] = $aNode['text'] ? $aNode['text'] : $aNode['name'];
168 // Add the item to the proper node
169 $thisNode = &$curNode[$aNode['level']]->addItem(new HTML_TreeNode($data, $events));
170 $curNode[$aNode['level'] + 1] = &$thisNode;
172 break;
175 * Richard Heyes' (me!) second (array based) Tree class
177 case 'heyes_array':
178 // Need to create a HTML_TreeMenu object ?
179 if (!isset($params['treeMenu'])) {
180 $treeMenu = new HTML_TreeMenu();
181 $parentID = 0;
182 } else {
183 $treeMenu = &$params['treeMenu'];
184 $parentID = $params['parentID'];
187 // Loop thru the trees nodes
188 foreach ($params['structure']->getChildren($parentID) as $nodeID) {
189 $data = $params['structure']->getData($nodeID);
190 $parentNode = &$treeMenu->addItem(new HTML_TreeNode(array_merge($params['nodeOptions'], $data)));
192 // Recurse ?
193 if ($params['structure']->hasChildren($nodeID)) {
194 $recurseParams['type'] = 'heyes_array';
195 $recurseParams['parentID'] = $nodeID;
196 $recurseParams['nodeOptions'] = $params['nodeOptions'];
197 $recurseParams['structure'] = &$params['structure'];
198 $recurseParams['treeMenu'] = &$parentNode;
199 HTML_TreeMenu::createFromStructure($recurseParams);
202 break;
205 * Richard Heyes' (me!) original OO based Tree class
207 case 'heyes':
208 default:
209 // Need to create a HTML_TreeMenu object ?
210 if (!isset($params['treeMenu'])) {
211 $treeMenu = new HTML_TreeMenu();
212 } else {
213 $treeMenu = &$params['treeMenu'];
216 // Loop thru the trees nodes
217 foreach ($params['structure']->nodes->nodes as $node) {
218 $tag = $node->getTag();
219 $parentNode = &$treeMenu->addItem(new HTML_TreeNode(array_merge($params['nodeOptions'], $tag)));
221 // Recurse ?
222 if (!empty($node->nodes->nodes)) {
223 $recurseParams['structure'] = $node;
224 $recurseParams['nodeOptions'] = $params['nodeOptions'];
225 $recurseParams['treeMenu'] = &$parentNode;
226 HTML_TreeMenu::createFromStructure($recurseParams);
229 break;
232 return $treeMenu;
236 * Creates a treeMenu from XML. The structure of your XML should be
237 * like so:
239 * <treemenu>
240 * <node text="First node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
241 * <node text="Second node" icon="folder.gif" expandedIcon="folder-expanded.gif">
242 * <node text="Sub node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
243 * </node>
244 * <node text="Third node" icon="folder.gif" expandedIcon="folder-expanded.gif">
245 * </treemenu>
247 * Any of the options you can supply to the HTML_TreeNode constructor can be supplied as
248 * attributes to the <node> tag. If there are no subnodes for a particular node, you can
249 * use the XML shortcut <node ... /> instead of <node ... ></node>. The $xml argument can
250 * be either the XML as a string, or an pre-created XML_Tree object. Also, this method
251 * REQUIRES my own Tree class to work (http://phpguru.org/tree.html). If this has not
252 * been include()ed or require()ed this method will die().
254 * @param mixed $xml This can be either a string containing the XML, or an XML_Tree object
255 * (the PEAR::XML_Tree package).
256 * @return object The HTML_TreeMenu object
258 function createFromXML($xml)
260 if (!class_exists('Tree')) {
261 die('Could not find Tree class');
264 // Supplied $xml is a string
265 if (is_string($xml)) {
266 require_once('XML/Tree.php');
267 $xmlTree = new XML_Tree();
268 $xmlTree->getTreeFromString($xml);
270 // Supplied $xml is an XML_Tree object
271 } else {
272 $xmlTree = $xml;
275 // Now process the XML_Tree object, setting the XML attributes
276 // to be the tag data (with out the XML tag name or contents).
277 $treeStructure = Tree::createFromXMLTree($xmlTree, true);
278 $treeStructure->nodes->traverse(create_function('&$node', '$tagData = $node->getTag(); $node->setTag($tagData["attributes"]);'));
281 return HTML_TreeMenu::createFromStructure(array('structure' => $treeStructure));
283 } // HTML_TreeMenu
287 * HTML_TreeNode class
289 * This class is supplementary to the above and provides a way to
290 * add nodes to the tree. A node can have other nodes added to it.
292 * @author Richard Heyes <richard@php.net>
293 * @author Harald Radi <harald.radi@nme.at>
294 * @access public
295 * @package HTML_TreeMenu
297 class HTML_TreeNode
300 * The text for this node.
301 * @var string
303 var $text;
306 * The link for this node.
307 * @var string
309 var $link;
312 * The icon for this node.
313 * @var string
315 var $icon;
318 * The icon to show when expanded for this node.
319 * @var string
321 var $expandedIcon;
324 * The css class for this node
325 * @var string
327 var $cssClass;
330 * The link target for this node
331 * @var string
333 var $linkTarget;
336 * Indexed array of subnodes
337 * @var array
339 var $items;
342 * Whether this node is expanded or not
343 * @var bool
345 var $expanded;
348 * Whether this node is dynamic or not
349 * @var bool
351 var $isDynamic;
354 * Should this node be made visible?
355 * @var bool
357 var $ensureVisible;
360 * The parent node. Null if top level
361 * @var object
363 var $parent;
366 * Unique ID of this node
367 * @var int
369 //commented out because it was causing Documents page to not show
370 //because of this redeclaration of $parent. I do not know what the
371 // author's intention was in using this name twice or if it was a mistake
372 //var $parent;
375 * Javascript event handlers;
376 * @var array
378 var $events;
380 var $id;
383 * Constructor
385 * @access public
386 * @param array $options An array of options which you can pass to change
387 * the way this node looks/acts. This can consist of:
388 * o text The title of the node, defaults to blank
389 * o link The link for the node, defaults to blank
390 * o icon The icon for the node, defaults to blank
391 * o expandedIcon The icon to show when the node is expanded
392 * o cssClass The CSS class for this node, defaults to blank
393 * o expanded The default expanded status of this node, defaults to false
394 * This doesn't affect non dynamic presentation types
395 * o linkTarget Target for the links. Defaults to linkTarget of the
396 * HTML_TreeMenu_Presentation.
397 * o isDynamic If this node is dynamic or not. Only affects
398 * certain presentation types.
399 * o ensureVisible If true this node will be made visible despite the expanded
400 * settings, and client side persistence. Will not affect
401 * some presentation styles, such as Listbox. Default is false
402 * @param array $events An array of javascript events and the corresponding event handlers.
403 * Additionally to the standard javascript events you can specify handlers
404 * for the 'onexpand', 'oncollapse' and 'ontoggle' events which will be fired
405 * whenever a node is collapsed and/or expanded.
407 function __construct($options = array(), $events = array())
409 $this->text = '';
410 $this->link = '';
411 $this->icon = '';
412 $this->expandedIcon = '';
413 $this->cssClass = '';
414 $this->expanded = false;
415 $this->isDynamic = true;
416 $this->ensureVisible = false;
417 $this->linkTarget = null;
418 $this->id = null;
420 $this->parent = null;
421 $this->events = $events;
423 foreach ($options as $option => $value) {
424 $this->$option = $value;
429 * Allows setting of various parameters after the initial
430 * constructor call. Possible options you can set are:
431 * o text
432 * o link
433 * o icon
434 * o cssClass
435 * o expanded
436 * o isDynamic
437 * o ensureVisible
438 * ie The same options as in the constructor
440 * @access public
441 * @param string $option Option to set
442 * @param string $value Value to set the option to
444 function setOption($option, $value)
446 $this->$option = $value;
450 * Adds a new subnode to this node.
452 * @access public
453 * @param object $node The new node
455 function &addItem($node)
457 $node->parent = &$this;
458 $this->items[] = &$node;
461 * If the subnode has ensureVisible set it needs
462 * to be handled, and all parents set accordingly.
464 if ($node->ensureVisible) {
465 $this->_ensureVisible();
468 return $this->items[count($this->items) - 1];
472 * Private function to handle ensureVisible stuff
474 * @access private
476 function _ensureVisible()
478 $this->ensureVisible = true;
479 $this->expanded = true;
481 if (!is_null($this->parent)) {
482 $this->parent->_ensureVisible();
485 } // HTML_TreeNode
489 * HTML_TreeMenu_Presentation class
491 * Base class for other presentation classes to
492 * inherit from.
494 class HTML_TreeMenu_Presentation
497 * The TreeMenu structure
498 * @var object
500 var $menu;
503 * Base constructor simply sets the menu object
505 * @param object $structure The menu structure
507 function __construct(&$structure)
509 $this->menu = &$structure;
513 * Prints the HTML generated by the toHTML() method.
514 * toHTML() must therefore be defined by the derived
515 * class.
517 * @access public
518 * @param array Options to set. Any options taken by
519 * the presentation class can be specified
520 * here.
522 function printMenu($options = array())
524 foreach ($options as $option => $value) {
525 $this->$option = $value;
528 echo $this->toHTML();
534 * HTML_TreeMenu_DHTML class
536 * This class is a presentation class for the tree structure
537 * created using the TreeMenu/TreeNode. It presents the
538 * traditional tree, static for browsers that can't handle
539 * the DHTML.
541 class HTML_TreeMenu_DHTML extends HTML_TreeMenu_Presentation
544 * Dynamic status of the treemenu. If true (default) this has no effect. If
545 * false it will override all dynamic status vars and set the menu to be
546 * fully expanded an non-dynamic.
548 var $isDynamic;
551 * Path to the images
552 * @var string
554 var $images;
557 * Target for the links generated
558 * @var string
560 var $linkTarget;
563 * Whether to use clientside persistence or not
564 * @var bool
566 var $userPersistence;
569 * The default CSS class for the nodes
571 var $defaultClass;
574 * Whether to skip first level branch images
575 * @var bool
577 var $noTopLevelImages;
579 var $maxDepth;
580 var $usePersistence;
583 * Constructor, takes the tree structure as
584 * an argument and an array of options which
585 * can consist of:
586 * o images - The path to the images folder. Defaults to "images"
587 * o linkTarget - The target for the link. Defaults to "_self"
588 * o defaultClass - The default CSS class to apply to a node. Default is none.
589 * o usePersistence - Whether to use clientside persistence. This persistence
590 * is achieved using cookies. Default is true.
591 * o noTopLevelImages - Whether to skip displaying the first level of images if
592 * there is multiple top level branches.
593 * o maxDepth - The maximum depth of indentation. Useful for ensuring
594 * deeply nested trees don't go way off to the right of your
595 * page etc. Defaults to no limit.
597 * And also a boolean for whether the entire tree is dynamic or not.
598 * This overrides any perNode dynamic settings.
600 * @param object $structure The menu structure
601 * @param array $options Array of options
602 * @param bool $isDynamic Whether the tree is dynamic or not
604 function __construct(&$structure, $options = array(), $isDynamic = true)
606 parent::__construct($structure);
607 $this->isDynamic = $isDynamic;
609 // Defaults
610 $this->images = 'public/images';
611 $this->maxDepth = 0; // No limit
612 $this->linkTarget = '_self';
613 $this->defaultClass = '';
614 $this->usePersistence = true;
615 $this->noTopLevelImages = false;
617 foreach ($options as $option => $value) {
618 $this->$option = $value;
623 * Returns the HTML for the menu. This method can be
624 * used instead of printMenu() to use the menu system
625 * with a template system.
627 * @access public
628 * @return string The HTML for the menu
630 function toHTML()
632 static $count = 0;
633 $menuObj = 'objTreeMenu_' . ++$count;
635 $html = "\n";
636 $html .= '<script>' . "\n\t";
637 $html .= sprintf(
638 '%s = new TreeMenu("%s", "%s", "%s", "%s", %s, %s);',
639 $menuObj,
640 $this->images,
641 $menuObj,
642 $this->linkTarget,
643 $this->defaultClass,
644 $this->usePersistence ? 'true' : 'false',
645 $this->noTopLevelImages ? 'true' : 'false'
648 $html .= "\n";
651 * Loop through subnodes
653 if (isset($this->menu->items)) {
654 for ($i = 0; $i < count($this->menu->items); $i++) {
655 $html .= $this->_nodeToHTML($this->menu->items[$i], $menuObj);
659 $html .= sprintf("\n\t%s.drawMenu();", $menuObj);
660 $html .= sprintf("\n\t%s.writeOutput();", $menuObj);
662 if ($this->usePersistence && $this->isDynamic) {
663 $html .= sprintf("\n\t%s.resetBranches();", $menuObj);
666 $html .= "\n</script>";
668 return $html;
672 * Prints a node of the menu
674 * @access private
676 function _nodeToHTML($nodeObj, $prefix, $return = 'newNode', $currentDepth = 0, $maxDepthPrefix = null)
678 $prefix = empty($maxDepthPrefix) ? $prefix : $maxDepthPrefix;
680 $expanded = $this->isDynamic ? ($nodeObj->expanded ? 'true' : 'false') : 'true';
681 $isDynamic = $this->isDynamic ? ($nodeObj->isDynamic ? 'true' : 'false') : 'false';
682 $html = sprintf(
683 "\t %s = %s.addItem(new TreeNode(jsAttr(%s), jsAttr(%s), jsAttr(%s), %s, %s, '%s', '%s', jsAttr(%s)));\n",
684 $return,
685 $prefix,
686 js_escape($nodeObj->text),
687 !empty($nodeObj->icon) ? js_escape($nodeObj->icon) : 'null',
688 !empty($nodeObj->link) ? js_escape($nodeObj->link) : 'null',
689 $expanded,
690 $isDynamic,
691 $nodeObj->cssClass,
692 $nodeObj->linkTarget,
693 !empty($nodeObj->expandedIcon) ? js_escape($nodeObj->expandedIcon) : 'null'
696 foreach ($nodeObj->events as $event => $handler) {
697 $html .= sprintf(
698 "\t %s.setEvent('%s', '%s');\n",
699 $return,
700 $event,
701 str_replace(array("\r", "\n", "'"), array('\r', '\n', "\'"), $handler)
705 if ($this->maxDepth > 0 and $currentDepth == $this->maxDepth) {
706 $maxDepthPrefix = $prefix;
710 * Loop through subnodes
712 if (!empty($nodeObj->items)) {
713 for ($i = 0; $i < count($nodeObj->items); $i++) {
714 $html .= $this->_nodeToHTML($nodeObj->items[$i], $return, $return . '_' . ($i + 1), $currentDepth + 1, $maxDepthPrefix);
718 return $html;
720 } // End class HTML_TreeMenu_DHTML
724 * HTML_TreeMenu_Listbox class
726 * This class presents the menu as a listbox
728 class HTML_TreeMenu_Listbox extends HTML_TreeMenu_Presentation
731 * The text that is displayed in the first option
732 * @var string
734 var $promoText;
737 * The character used for indentation
738 * @var string
740 var $indentChar;
743 * How many of the indent chars to use
744 * per indentation level
745 * @var integer
747 var $indentNum;
750 * Target for the links generated
751 * @var string
753 var $linkTarget;
755 var $submitText;
758 * Constructor
760 * @param object $structure The menu structure
761 * @param array $options Options whic affect the display of the listbox.
762 * These can consist of:
763 * o promoText The text that appears at the the top of the listbox
764 * Defaults to "Select..."
765 * o indentChar The character to use for indenting the nodes
766 * Defaults to "&nbsp;"
767 * o indentNum How many of the indentChars to use per indentation level
768 * Defaults to 2
769 * o linkTarget Target for the links. Defaults to "_self"
770 * o submitText Text for the submit button. Defaults to "Go"
772 function __construct($structure, $options = array())
774 parent::__construct($structure);
776 $this->promoText = null;
777 $this->indentChar = '&nbsp;';
778 $this->indentNum = 2;
779 $this->linkTarget = '_self';
780 $this->submitText = 'Go';
782 foreach ($options as $option => $value) {
783 $this->$option = $value;
788 * Returns the HTML generated
790 function toHTML()
792 static $count = 0;
793 $nodeHTML = '';
796 * Loop through subnodes
798 if (isset($this->menu->items)) {
799 for ($i = 0; $i < count($this->menu->items); $i++) {
800 $nodeHTML .= $this->_nodeToHTML($this->menu->items[$i]);
804 if ($this->promoText) {
805 return sprintf('<option value="">%s</option>%s', text($this->promoText ?? ''), $nodeHTML);
806 } else {
807 return $nodeHTML;
812 * Returns HTML for a single node
814 * @access private
816 function _nodeToHTML($node, $prefix = '')
818 $html = sprintf('<option value="%s">%s%s</option>', attr($node->id), $prefix, text($node->text));
821 * Loop through subnodes
823 if (isset($node->items)) {
824 for ($i = 0; $i < count($node->items); $i++) {
825 $html .= $this->_nodeToHTML($node->items[$i], $prefix . str_repeat($this->indentChar, $this->indentNum));
829 return $html;
831 } // End class HTML_TreeMenu_Listbox