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);
205 * Richard Heyes' (me!) original OO based Tree class
209 // Need to create a HTML_TreeMenu object ?
210 if (!isset($params['treeMenu'])) {
211 $treeMenu = new HTML_TreeMenu();
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)));
222 if (!empty($node->nodes
->nodes
)) {
223 $recurseParams['structure'] = $node;
224 $recurseParams['nodeOptions'] = $params['nodeOptions'];
225 $recurseParams['treeMenu'] = &$parentNode;
226 HTML_TreeMenu
::createFromStructure($recurseParams);
237 * Creates a treeMenu from XML. The structure of your XML should be
241 * <node text="First node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
242 * <node text="Second node" icon="folder.gif" expandedIcon="folder-expanded.gif">
243 * <node text="Sub node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
245 * <node text="Third node" icon="folder.gif" expandedIcon="folder-expanded.gif">
248 * Any of the options you can supply to the HTML_TreeNode constructor can be supplied as
249 * attributes to the <node> tag. If there are no subnodes for a particular node, you can
250 * use the XML shortcut <node ... /> instead of <node ... ></node>. The $xml argument can
251 * be either the XML as a string, or an pre-created XML_Tree object. Also, this method
252 * REQUIRES my own Tree class to work (http://phpguru.org/tree.html). If this has not
253 * been include()ed or require()ed this method will die().
255 * @param mixed $xml This can be either a string containing the XML, or an XML_Tree object
256 * (the PEAR::XML_Tree package).
257 * @return object The HTML_TreeMenu object
259 function createFromXML($xml)
261 if (!class_exists('Tree')) {
262 die('Could not find Tree class');
265 // Supplied $xml is a string
266 if (is_string($xml)) {
267 require_once('XML/Tree.php');
268 $xmlTree = new XML_Tree();
269 $xmlTree->getTreeFromString($xml);
271 // Supplied $xml is an XML_Tree object
276 // Now process the XML_Tree object, setting the XML attributes
277 // to be the tag data (with out the XML tag name or contents).
278 $treeStructure = Tree
::createFromXMLTree($xmlTree, true);
279 $treeStructure->nodes
->traverse(create_function('&$node', '$tagData = $node->getTag(); $node->setTag($tagData["attributes"]);'));
282 return HTML_TreeMenu
::createFromStructure(array('structure' => $treeStructure));
288 * HTML_TreeNode class
290 * This class is supplementary to the above and provides a way to
291 * add nodes to the tree. A node can have other nodes added to it.
293 * @author Richard Heyes <richard@php.net>
294 * @author Harald Radi <harald.radi@nme.at>
296 * @package HTML_TreeMenu
301 * The text for this node.
307 * The link for this node.
313 * The icon for this node.
319 * The icon to show when expanded for this node.
325 * The css class for this node
331 * The link target for this node
337 * Indexed array of subnodes
343 * Whether this node is expanded or not
349 * Whether this node is dynamic or not
355 * Should this node be made visible?
361 * The parent node. Null if top level
367 * Unique ID of this node
370 //commented out because it was causing Documents page to not show
371 //because of this redeclaration of $parent. I do not know what the
372 // author's intention was in using this name twice or if it was a mistake
377 * Javascript event handlers;
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())
412 $this->expandedIcon
= '';
413 $this->cssClass
= '';
414 $this->expanded
= false;
415 $this->isDynamic
= true;
416 $this->ensureVisible
= false;
417 $this->linkTarget
= 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:
438 * ie The same options as in the constructor
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.
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
476 function _ensureVisible()
478 $this->ensureVisible
= true;
479 $this->expanded
= true;
481 if (!is_null($this->parent
)) {
482 $this->parent
->_ensureVisible();
489 * HTML_TreeMenu_Presentation class
491 * Base class for other presentation classes to
494 class HTML_TreeMenu_Presentation
497 * The TreeMenu structure
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
518 * @param array Options to set. Any options taken by
519 * the presentation class can be specified
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
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.
557 * Target for the links generated
563 * Whether to use clientside persistence or not
566 var $userPersistence;
569 * The default CSS class for the nodes
574 * Whether to skip first level branch images
577 var $noTopLevelImages;
580 * Constructor, takes the tree structure as
581 * an argument and an array of options which
583 * o images - The path to the images folder. Defaults to "images"
584 * o linkTarget - The target for the link. Defaults to "_self"
585 * o defaultClass - The default CSS class to apply to a node. Default is none.
586 * o usePersistence - Whether to use clientside persistence. This persistence
587 * is achieved using cookies. Default is true.
588 * o noTopLevelImages - Whether to skip displaying the first level of images if
589 * there is multiple top level branches.
590 * o maxDepth - The maximum depth of indentation. Useful for ensuring
591 * deeply nested trees don't go way off to the right of your
592 * page etc. Defaults to no limit.
594 * And also a boolean for whether the entire tree is dynamic or not.
595 * This overrides any perNode dynamic settings.
597 * @param object $structure The menu structure
598 * @param array $options Array of options
599 * @param bool $isDynamic Whether the tree is dynamic or not
601 function __construct(&$structure, $options = array(), $isDynamic = true)
603 parent
::__construct($structure);
604 $this->isDynamic
= $isDynamic;
607 $this->images
= 'images';
608 $this->maxDepth
= 0; // No limit
609 $this->linkTarget
= '_self';
610 $this->defaultClass
= '';
611 $this->usePersistence
= true;
612 $this->noTopLevelImages
= false;
614 foreach ($options as $option => $value) {
615 $this->$option = $value;
620 * Returns the HTML for the menu. This method can be
621 * used instead of printMenu() to use the menu system
622 * with a template system.
625 * @return string The HTML for the menu
630 $menuObj = 'objTreeMenu_' . ++
$count;
633 $html .= '<script language="javascript" type="text/javascript">' . "\n\t";
634 $html .= sprintf('%s = new TreeMenu("%s", "%s", "%s", "%s", %s, %s);',
640 $this->usePersistence ?
'true' : 'false',
641 $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);
660 $html .= "\n</script>";
666 * Prints a node of the menu
670 function _nodeToHTML($nodeObj, $prefix, $return = 'newNode', $currentDepth = 0, $maxDepthPrefix = null)
672 $prefix = empty($maxDepthPrefix) ?
$prefix : $maxDepthPrefix;
674 $expanded = $this->isDynamic ?
($nodeObj->expanded ?
'true' : 'false') : 'true';
675 $isDynamic = $this->isDynamic ?
($nodeObj->isDynamic ?
'true' : 'false') : 'false';
676 $html = sprintf("\t %s = %s.addItem(new TreeNode('%s', %s, %s, %s, %s, '%s', '%s', %s));\n",
679 str_replace("'", "\\'", $nodeObj->text
),
680 !empty($nodeObj->icon
) ?
"'" . $nodeObj->icon
. "'" : 'null',
681 !empty($nodeObj->link
) ?
"'" . attr($nodeObj->link
) . "'" : 'null',
685 $nodeObj->linkTarget
,
686 !empty($nodeObj->expandedIcon
) ?
"'" . $nodeObj->expandedIcon
. "'" : 'null');
688 foreach ($nodeObj->events
as $event => $handler) {
689 $html .= sprintf("\t %s.setEvent('%s', '%s');\n",
692 str_replace(array("\r", "\n", "'"), array('\r', '\n', "\'"), $handler));
695 if ($this->maxDepth
> 0 AND $currentDepth == $this->maxDepth
) {
696 $maxDepthPrefix = $prefix;
700 * Loop through subnodes
702 if (!empty($nodeObj->items
)) {
703 for ($i=0; $i<count($nodeObj->items
); $i++
) {
704 $html .= $this->_nodeToHTML($nodeObj->items
[$i], $return, $return . '_' . ($i +
1), $currentDepth +
1, $maxDepthPrefix);
710 } // End class HTML_TreeMenu_DHTML
714 * HTML_TreeMenu_Listbox class
716 * This class presents the menu as a listbox
718 class HTML_TreeMenu_Listbox
extends HTML_TreeMenu_Presentation
721 * The text that is displayed in the first option
727 * The character used for indentation
733 * How many of the indent chars to use
734 * per indentation level
740 * Target for the links generated
748 * @param object $structure The menu structure
749 * @param array $options Options whic affect the display of the listbox.
750 * These can consist of:
751 * o promoText The text that appears at the the top of the listbox
752 * Defaults to "Select..."
753 * o indentChar The character to use for indenting the nodes
754 * Defaults to " "
755 * o indentNum How many of the indentChars to use per indentation level
757 * o linkTarget Target for the links. Defaults to "_self"
758 * o submitText Text for the submit button. Defaults to "Go"
760 function __construct($structure, $options = array())
762 parent
::__construct($structure);
764 $this->promoText
= null;
765 $this->indentChar
= ' ';
766 $this->indentNum
= 2;
767 $this->linkTarget
= '_self';
768 $this->submitText
= 'Go';
770 foreach ($options as $option => $value) {
771 $this->$option = $value;
776 * Returns the HTML generated
784 * Loop through subnodes
786 if (isset($this->menu
->items
)) {
787 for ($i=0; $i<count($this->menu
->items
); $i++
) {
788 $nodeHTML .= $this->_nodeToHTML($this->menu
->items
[$i]);
792 if ($this->promoText
) {
793 return sprintf('<option value="">%s</option>%s', $this->promoText
, $nodeHTML);
801 * Returns HTML for a single node
805 function _nodeToHTML($node, $prefix = '')
807 $html = sprintf('<option value="%s">%s%s</option>', $node->id
, $prefix, $node->text
);
810 * Loop through subnodes
812 if (isset($node->items
)) {
813 for ($i=0; $i<count($node->items
); $i++
) {
814 $html .= $this->_nodeToHTML($node->items
[$i], $prefix . str_repeat($this->indentChar
, $this->indentNum
));
820 } // End class HTML_TreeMenu_Listbox