2 // +-----------------------------------------------------------------------+
3 // | Copyright (c) 2002-2003, Richard Heyes, Harald Radi |
4 // | All rights reserved. |
6 // | Redistribution and use in source and binary forms, with or without |
7 // | modification, are permitted provided that the following conditions |
10 // | o Redistributions of source code must retain the above copyright |
11 // | notice, this list of conditions and the following disclaimer. |
12 // | o Redistributions in binary form must reproduce the above copyright |
13 // | notice, this list of conditions and the following disclaimer in the |
14 // | documentation and/or other materials provided with the distribution.|
15 // | o The names of the authors may not be used to endorse or promote |
16 // | products derived from this software without specific prior written |
19 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
20 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
21 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
22 // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
23 // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
24 // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
25 // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
26 // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
27 // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
28 // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
29 // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
31 // +-----------------------------------------------------------------------+
32 // | Author: Richard Heyes <richard@phpguru.org> |
33 // | Harald Radi <harald.radi@nme.at> |
34 // +-----------------------------------------------------------------------+
41 * A simple couple of PHP classes and some not so simple
42 * Jabbascript which produces a tree menu. In IE this menu
43 * is dynamic, with branches being collapsable. In IE5+ the
44 * status of the collapsed/open branches persists across page
45 * refreshes.In any other browser the tree is static. Code is
46 * based on work of Harald Radi.
50 * After installing the package, copy the example php script to
51 * your servers document root. Also place the TreeMenu.js and the
52 * images folder in the same place. Running the script should
53 * then produce the tree.
55 * Thanks go to Chip Chapin (http://www.chipchapin.com) for many
56 * excellent ideas and improvements.
58 * @author Richard Heyes <richard@php.net>
59 * @author Harald Radi <harald.radi@nme.at>
61 * @package HTML_TreeMenu
67 * Indexed array of subnodes
77 function __construct()
79 // Not much to do here :(
83 * This function adds an item to the the tree.
86 * @param object $node The node to add. This object should be
87 * a HTML_TreeNode object.
88 * @return object Returns a reference to the new node inside
91 function &addItem(&$node)
93 $this->items
[] = &$node;
94 return $this->items
[count($this->items
) - 1];
98 * Import method for creating HTML_TreeMenu objects/structures
99 * out of existing tree objects/structures. Currently supported
100 * are Wolfram Kriesings' PEAR Tree class, and Richard Heyes' (me!)
101 * Tree class (available here: http://www.phpguru.org/). This
102 * method is intended to be used statically, eg:
103 * $treeMenu = &HTML_TreeMenu::createFromStructure($myTreeStructureObj);
105 * @param array $params An array of parameters that determine
106 * how the import happens. This can consist of:
107 * structure => The tree structure
108 * type => The type of the structure, currently
109 * can be either 'heyes' or 'kriesing'
110 * nodeOptions => Default options for each node
112 * @return object The resulting HTML_TreeMenu object
114 function createFromStructure($params)
116 if (!isset($params['nodeOptions'])) {
117 $params['nodeOptions'] = array();
120 switch (@$params['type']) {
123 * Wolfram Kriesings' PEAR Tree class
126 $className = strtolower(get_class($params['structure']->dataSourceClass
));
127 $isXMLStruct = strpos($className, '_xml') !== false ?
true : false;
129 // Get the entire tree, the $nodes are sorted like in the tree view
130 // from top to bottom, so we can easily put them in the nodes
131 $nodes = $params['structure']->getNode();
133 // Make a new menu and fill it with the values from the tree
134 $treeMenu = new HTML_TreeMenu();
135 $curNode[0] = &$treeMenu; // we need the current node as the reference to the
137 foreach ($nodes as $aNode) {
141 // In an XML, all the attributes are saved in an array, but since they might be
142 // used as the parameters, we simply extract them here if we handle an XML-structure
143 if ($isXMLStruct && sizeof($aNode['attributes'])) {
144 foreach ($aNode['attributes'] as $key => $val) {
145 if (!$aNode[$key]) { // dont overwrite existing values
151 // Process all the data that are saved in $aNode and put them in the data and/or events array
152 foreach ($aNode as $key => $val) {
153 if (!is_array($val)) {
154 // Dont get the recursive data in here! they are always arrays
155 if (substr($key, 0, 2) == 'on') { // get the events
156 $events[$key] = $val;
159 // 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
164 // Normally the text is in 'name' in the Tree class, so we check both but 'text' is used if found
165 $data['text'] = $aNode['text'] ?
$aNode['text'] : $aNode['name'];
167 // Add the item to the proper node
168 $thisNode = &$curNode[$aNode['level']]->addItem(new HTML_TreeNode($data, $events));
169 $curNode[$aNode['level']+
1] = &$thisNode;
174 * Richard Heyes' (me!) second (array based) Tree class
177 // Need to create a HTML_TreeMenu object ?
178 if (!isset($params['treeMenu'])) {
179 $treeMenu = new HTML_TreeMenu();
182 $treeMenu = &$params['treeMenu'];
183 $parentID = $params['parentID'];
186 // Loop thru the trees nodes
187 foreach ($params['structure']->getChildren($parentID) as $nodeID) {
188 $data = $params['structure']->getData($nodeID);
189 $parentNode = &$treeMenu->addItem(new HTML_TreeNode(array_merge($params['nodeOptions'], $data)));
192 if ($params['structure']->hasChildren($nodeID)) {
193 $recurseParams['type'] = 'heyes_array';
194 $recurseParams['parentID'] = $nodeID;
195 $recurseParams['nodeOptions'] = $params['nodeOptions'];
196 $recurseParams['structure'] = &$params['structure'];
197 $recurseParams['treeMenu'] = &$parentNode;
198 HTML_TreeMenu
::createFromStructure($recurseParams);
204 * Richard Heyes' (me!) original OO based Tree class
208 // Need to create a HTML_TreeMenu object ?
209 if (!isset($params['treeMenu'])) {
210 $treeMenu = new HTML_TreeMenu();
212 $treeMenu = &$params['treeMenu'];
215 // Loop thru the trees nodes
216 foreach ($params['structure']->nodes
->nodes
as $node) {
217 $tag = $node->getTag();
218 $parentNode = &$treeMenu->addItem(new HTML_TreeNode(array_merge($params['nodeOptions'], $tag)));
221 if (!empty($node->nodes
->nodes
)) {
222 $recurseParams['structure'] = $node;
223 $recurseParams['nodeOptions'] = $params['nodeOptions'];
224 $recurseParams['treeMenu'] = &$parentNode;
225 HTML_TreeMenu
::createFromStructure($recurseParams);
235 * Creates a treeMenu from XML. The structure of your XML should be
239 * <node text="First node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
240 * <node text="Second node" icon="folder.gif" expandedIcon="folder-expanded.gif">
241 * <node text="Sub node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
243 * <node text="Third node" icon="folder.gif" expandedIcon="folder-expanded.gif">
246 * Any of the options you can supply to the HTML_TreeNode constructor can be supplied as
247 * attributes to the <node> tag. If there are no subnodes for a particular node, you can
248 * use the XML shortcut <node ... /> instead of <node ... ></node>. The $xml argument can
249 * be either the XML as a string, or an pre-created XML_Tree object. Also, this method
250 * REQUIRES my own Tree class to work (http://phpguru.org/tree.html). If this has not
251 * been include()ed or require()ed this method will die().
253 * @param mixed $xml This can be either a string containing the XML, or an XML_Tree object
254 * (the PEAR::XML_Tree package).
255 * @return object The HTML_TreeMenu object
257 function createFromXML($xml)
259 if (!class_exists('Tree')) {
260 die('Could not find Tree class');
263 // Supplied $xml is a string
264 if (is_string($xml)) {
265 require_once('XML/Tree.php');
266 $xmlTree = new XML_Tree();
267 $xmlTree->getTreeFromString($xml);
269 // Supplied $xml is an XML_Tree object
274 // Now process the XML_Tree object, setting the XML attributes
275 // to be the tag data (with out the XML tag name or contents).
276 $treeStructure = Tree
::createFromXMLTree($xmlTree, true);
277 $treeStructure->nodes
->traverse(create_function('&$node', '$tagData = $node->getTag(); $node->setTag($tagData["attributes"]);'));
280 return HTML_TreeMenu
::createFromStructure(array('structure' => $treeStructure));
286 * HTML_TreeNode class
288 * This class is supplementary to the above and provides a way to
289 * add nodes to the tree. A node can have other nodes added to it.
291 * @author Richard Heyes <richard@php.net>
292 * @author Harald Radi <harald.radi@nme.at>
294 * @package HTML_TreeMenu
299 * The text for this node.
305 * The link for this node.
311 * The icon for this node.
317 * The icon to show when expanded for this node.
323 * The css class for this node
329 * The link target for this node
335 * Indexed array of subnodes
341 * Whether this node is expanded or not
347 * Whether this node is dynamic or not
353 * Should this node be made visible?
359 * The parent node. Null if top level
365 * Unique ID of this node
368 //commented out because it was causing Documents page to not show
369 //because of this redeclaration of $parent. I do not know what the
370 // author's intention was in using this name twice or if it was a mistake
375 * Javascript event handlers;
384 * @param array $options An array of options which you can pass to change
385 * the way this node looks/acts. This can consist of:
386 * o text The title of the node, defaults to blank
387 * o link The link for the node, defaults to blank
388 * o icon The icon for the node, defaults to blank
389 * o expandedIcon The icon to show when the node is expanded
390 * o cssClass The CSS class for this node, defaults to blank
391 * o expanded The default expanded status of this node, defaults to false
392 * This doesn't affect non dynamic presentation types
393 * o linkTarget Target for the links. Defaults to linkTarget of the
394 * HTML_TreeMenu_Presentation.
395 * o isDynamic If this node is dynamic or not. Only affects
396 * certain presentation types.
397 * o ensureVisible If true this node will be made visible despite the expanded
398 * settings, and client side persistence. Will not affect
399 * some presentation styles, such as Listbox. Default is false
400 * @param array $events An array of javascript events and the corresponding event handlers.
401 * Additionally to the standard javascript events you can specify handlers
402 * for the 'onexpand', 'oncollapse' and 'ontoggle' events which will be fired
403 * whenever a node is collapsed and/or expanded.
405 function __construct($options = array(), $events = array())
410 $this->expandedIcon
= '';
411 $this->cssClass
= '';
412 $this->expanded
= false;
413 $this->isDynamic
= true;
414 $this->ensureVisible
= false;
415 $this->linkTarget
= null;
418 $this->parent
= null;
419 $this->events
= $events;
421 foreach ($options as $option => $value) {
422 $this->$option = $value;
427 * Allows setting of various parameters after the initial
428 * constructor call. Possible options you can set are:
436 * ie The same options as in the constructor
439 * @param string $option Option to set
440 * @param string $value Value to set the option to
442 function setOption($option, $value)
444 $this->$option = $value;
448 * Adds a new subnode to this node.
451 * @param object $node The new node
453 function &addItem(&$node)
455 $node->parent
= &$this;
456 $this->items
[] = &$node;
459 * If the subnode has ensureVisible set it needs
460 * to be handled, and all parents set accordingly.
462 if ($node->ensureVisible
) {
463 $this->_ensureVisible();
466 return $this->items
[count($this->items
) - 1];
470 * Private function to handle ensureVisible stuff
474 function _ensureVisible()
476 $this->ensureVisible
= true;
477 $this->expanded
= true;
479 if (!is_null($this->parent
)) {
480 $this->parent
->_ensureVisible();
487 * HTML_TreeMenu_Presentation class
489 * Base class for other presentation classes to
492 class HTML_TreeMenu_Presentation
495 * The TreeMenu structure
501 * Base constructor simply sets the menu object
503 * @param object $structure The menu structure
505 function __construct(&$structure)
507 $this->menu
= &$structure;
511 * Prints the HTML generated by the toHTML() method.
512 * toHTML() must therefore be defined by the derived
516 * @param array Options to set. Any options taken by
517 * the presentation class can be specified
520 function printMenu($options = array())
522 foreach ($options as $option => $value) {
523 $this->$option = $value;
526 echo $this->toHTML();
532 * HTML_TreeMenu_DHTML class
534 * This class is a presentation class for the tree structure
535 * created using the TreeMenu/TreeNode. It presents the
536 * traditional tree, static for browsers that can't handle
539 class HTML_TreeMenu_DHTML
extends HTML_TreeMenu_Presentation
542 * Dynamic status of the treemenu. If true (default) this has no effect. If
543 * false it will override all dynamic status vars and set the menu to be
544 * fully expanded an non-dynamic.
555 * Target for the links generated
561 * Whether to use clientside persistence or not
564 var $userPersistence;
567 * The default CSS class for the nodes
572 * Whether to skip first level branch images
575 var $noTopLevelImages;
578 * Constructor, takes the tree structure as
579 * an argument and an array of options which
581 * o images - The path to the images folder. Defaults to "images"
582 * o linkTarget - The target for the link. Defaults to "_self"
583 * o defaultClass - The default CSS class to apply to a node. Default is none.
584 * o usePersistence - Whether to use clientside persistence. This persistence
585 * is achieved using cookies. Default is true.
586 * o noTopLevelImages - Whether to skip displaying the first level of images if
587 * there is multiple top level branches.
588 * o maxDepth - The maximum depth of indentation. Useful for ensuring
589 * deeply nested trees don't go way off to the right of your
590 * page etc. Defaults to no limit.
592 * And also a boolean for whether the entire tree is dynamic or not.
593 * This overrides any perNode dynamic settings.
595 * @param object $structure The menu structure
596 * @param array $options Array of options
597 * @param bool $isDynamic Whether the tree is dynamic or not
599 function __construct(&$structure, $options = array(), $isDynamic = true)
601 parent
::__construct($structure);
602 $this->isDynamic
= $isDynamic;
605 $this->images
= 'images';
606 $this->maxDepth
= 0; // No limit
607 $this->linkTarget
= '_self';
608 $this->defaultClass
= '';
609 $this->usePersistence
= true;
610 $this->noTopLevelImages
= false;
612 foreach ($options as $option => $value) {
613 $this->$option = $value;
618 * Returns the HTML for the menu. This method can be
619 * used instead of printMenu() to use the menu system
620 * with a template system.
623 * @return string The HTML for the menu
628 $menuObj = 'objTreeMenu_' . ++
$count;
631 $html .= '<script language="javascript" type="text/javascript">' . "\n\t";
633 '%s = new TreeMenu("%s", "%s", "%s", "%s", %s, %s);',
639 $this->usePersistence ?
'true' : 'false',
640 $this->noTopLevelImages ?
'true' : 'false'
646 * Loop through subnodes
648 if (isset($this->menu
->items
)) {
649 for ($i=0; $i<count($this->menu
->items
); $i++
) {
650 $html .= $this->_nodeToHTML($this->menu
->items
[$i], $menuObj);
654 $html .= sprintf("\n\t%s.drawMenu();", $menuObj);
655 $html .= sprintf("\n\t%s.writeOutput();", $menuObj);
657 if ($this->usePersistence
&& $this->isDynamic
) {
658 $html .= sprintf("\n\t%s.resetBranches();", $menuObj);
661 $html .= "\n</script>";
667 * Prints a node of the menu
671 function _nodeToHTML($nodeObj, $prefix, $return = 'newNode', $currentDepth = 0, $maxDepthPrefix = null)
673 $prefix = empty($maxDepthPrefix) ?
$prefix : $maxDepthPrefix;
675 $expanded = $this->isDynamic ?
($nodeObj->expanded ?
'true' : 'false') : 'true';
676 $isDynamic = $this->isDynamic ?
($nodeObj->isDynamic ?
'true' : 'false') : 'false';
678 "\t %s = %s.addItem(new TreeNode('%s', %s, %s, %s, %s, '%s', '%s', %s));\n",
681 str_replace("'", "\\'", $nodeObj->text
),
682 !empty($nodeObj->icon
) ?
"'" . $nodeObj->icon
. "'" : 'null',
683 !empty($nodeObj->link
) ?
"'" . attr($nodeObj->link
) . "'" : 'null',
687 $nodeObj->linkTarget
,
688 !empty($nodeObj->expandedIcon
) ?
"'" . $nodeObj->expandedIcon
. "'" : 'null'
691 foreach ($nodeObj->events
as $event => $handler) {
693 "\t %s.setEvent('%s', '%s');\n",
696 str_replace(array("\r", "\n", "'"), array('\r', '\n', "\'"), $handler)
700 if ($this->maxDepth
> 0 and $currentDepth == $this->maxDepth
) {
701 $maxDepthPrefix = $prefix;
705 * Loop through subnodes
707 if (!empty($nodeObj->items
)) {
708 for ($i=0; $i<count($nodeObj->items
); $i++
) {
709 $html .= $this->_nodeToHTML($nodeObj->items
[$i], $return, $return . '_' . ($i +
1), $currentDepth +
1, $maxDepthPrefix);
715 } // End class HTML_TreeMenu_DHTML
719 * HTML_TreeMenu_Listbox class
721 * This class presents the menu as a listbox
723 class HTML_TreeMenu_Listbox
extends HTML_TreeMenu_Presentation
726 * The text that is displayed in the first option
732 * The character used for indentation
738 * How many of the indent chars to use
739 * per indentation level
745 * Target for the links generated
753 * @param object $structure The menu structure
754 * @param array $options Options whic affect the display of the listbox.
755 * These can consist of:
756 * o promoText The text that appears at the the top of the listbox
757 * Defaults to "Select..."
758 * o indentChar The character to use for indenting the nodes
759 * Defaults to " "
760 * o indentNum How many of the indentChars to use per indentation level
762 * o linkTarget Target for the links. Defaults to "_self"
763 * o submitText Text for the submit button. Defaults to "Go"
765 function __construct($structure, $options = array())
767 parent
::__construct($structure);
769 $this->promoText
= null;
770 $this->indentChar
= ' ';
771 $this->indentNum
= 2;
772 $this->linkTarget
= '_self';
773 $this->submitText
= 'Go';
775 foreach ($options as $option => $value) {
776 $this->$option = $value;
781 * Returns the HTML generated
789 * Loop through subnodes
791 if (isset($this->menu
->items
)) {
792 for ($i=0; $i<count($this->menu
->items
); $i++
) {
793 $nodeHTML .= $this->_nodeToHTML($this->menu
->items
[$i]);
797 if ($this->promoText
) {
798 return sprintf('<option value="">%s</option>%s', $this->promoText
, $nodeHTML);
805 * Returns HTML for a single node
809 function _nodeToHTML($node, $prefix = '')
811 $html = sprintf('<option value="%s">%s%s</option>', $node->id
, $prefix, $node->text
);
814 * Loop through subnodes
816 if (isset($node->items
)) {
817 for ($i=0; $i<count($node->items
); $i++
) {
818 $html .= $this->_nodeToHTML($node->items
[$i], $prefix . str_repeat($this->indentChar
, $this->indentNum
));
824 } // End class HTML_TreeMenu_Listbox