<?php
/*
EasyGUI XP is free software released under the terms of the following BSD license.

Copyright (c) 2005,2006 Gaetan Lauff (glauff@plansoft.de)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer. 

- Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution.

- Neither the name of the developer nor the names of its contributors may 
be used to endorse or promote products derived from this software without 
specific prior written permission. 

THIS SOFTWARE 
IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

class EK_SimpleXML
{
	/**
	 * XML Parser Resource
	 *
	 * @var resource
	 */
	var $parser;
	
	/**
	 * Iteration
	 *
	 * @var integer
	 */
	var $iter = 0; 
	
	/**
	 * XML Path
	 *
	 * @var string
	 */
	var $path = array();
	
	/**
	 * The transformed XML
	 *
	 * @var array
	 */
	var $xml = array();
	
	/**
	 * Elements for getElementByTagName Method
	 *
	 * @var array
	 */
	var $elements = array();
	
	/**
	 * Constructor
	 *
	 * @return EK_SimpleXML
	 */
	function EK_SimpleXML() {
		;
	}
	
	/**
	 * Sets internal XML
	 *
	 * @param string $XML
	 */
	function setXML($XML)
	{
		$this->parser = xml_parser_create();
		
		xml_set_object($this->parser, $this);
		
		xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
		xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
		
		xml_set_element_handler($this->parser, "handleTagStart", "handleTagEnd");
		xml_set_character_data_handler($this->parser, "handleTagCData");
		
		xml_parse($this->parser, $XML);
		xml_parser_free($this->parser);
		
		//$this->xml = $this->xml['childNodes'];
	}
	
	/**
	 * Returns the current xml array
	 *
	 * @return array
	 */
	function getXML() 
	{
		return $this->xml;
	}
	
	/**
	 * Returns an attribute from a specific section inside the xml array
	 *
	 * @param string $section
	 * @param string $attribute
	 * @param string $default
	 * @return string
	 */
	function getAttribute( &$section, $attribute, $default = null)
	{
		$val = null;
	
		if (is_array( $section ) ) {
			if ( isset( $section[$attribute])) {
				$val = $section[$attribute];
			} elseif ( isset ( $section['attributes'] ) ) {
				if ( isset($section['attributes'][$attribute]) ) {
					$val = $section['attributes'][$attribute];
				}
			} elseif ( isset( $section[0]['attributes'] ) ) {
				if ( isset( $section[0]['attributes'][$attribute])) {
					$val = $section[0]['attributes'][$attribute];
				}
			}
		}
		
		if (empty($val) && !empty($default)) {
			return EK_Common::getValue( $default );
		}
		
		return EK_Common::getValue( $val );
	}
	
	/**
	 * Returns all elements of a given tag Name starting from a specific node
	 *
	 * @param string $tagName
	 * @param array $node
	 * @return array
	 */
	function getElementsByTagName( $tagName, $node = null )
	{
		$this->elements = array();
		
		if ( is_null( $node ) ) {
			$node = $this->xml;
		}
		
		$this->_getElementsByTagName( $tagName, $node );
		
		return $this->elements;
	}
	
	/**
	 * Is called recursivly to get all Elements of a given tagName
	 *
	 * @param string $tagName
	 * @param array $node
	 * @access private
	 */
	function _getElementsByTagName( $tagName, $node = null ) 
	{
		if ( array_key_exists( 'tagName', $node ) && $tagName == $node['tagName'] ) {
			$this->elements[] = $node;
		}
		
		if ( array_key_exists( 'childNodes', $node ) ) {
			foreach ( $node['childNodes'] as $nextNode ) {
				$this->_getElementsByTagName( $tagName, $nextNode );
			}
		}	
	}
	
	/**
	 * Returns all child nodes descending a given node
	 *
	 * @param array $node
	 * @return array
	 */
	function childNodes( $node ) 
	{
		$childNodes = array();
		
		if ( array_key_exists( 'childNodes', $node[0] ) ) {
			foreach ( $node[0]['childNodes'] as $childNode ) {
				$childNodes[] = $childNode;
			}
		} elseif ( array_key_exists( 'childNodes', $node ) ) {
			foreach ( $node['childNodes'] as $childNode ) {
				$childNodes[] = $childNode;
			}
		}
		
		return $childNodes;
	}
	
	/**
	 * Returns an evaluation path
	 *
	 * @return string
	 */
	function getEvalPath()
	{
		return '$this->xml[' . "'" . implode("']['", $this->path) . "'" . ']';
	} 
	
	/**
	 * Handles all starting tags
	 *
	 * @param resource $parser
	 * @param string $tag
	 * @param array $attributes
	 */
	function handleTagStart($parser, $tag, $attributes)
	{
		array_push($this->path, 'childNodes');
		array_push($this->path, ($this->iter++));
		
		$e = $this->getEvalPath();
		eval ($e . "['tagName'] = \$tag;");
		if ($attributes !== array())
		{
		   eval ($e . "['attributes'] = \$attributes;");
		} 
	} 
	
	/**
	 * Handles all character parsed Data
	 *
	 * @param resource $parser
	 * @param string $cdata
	 */
	function handleTagCData($parser, $cdata)
	{
		$e = $this->getEvalPath();
		eval ($e . "['value'] = \$cdata;");
	} 
	
	/**
	 * Handles all closing tags
	 *
	 * @param resource $parser
	 * @param string $tag
	 */
	function handleTagEnd($parser, $tag)
	{
		array_pop($this->path);
		array_pop($this->path);
	} 
} 

/**
 * DOM XML Wrapper for EasyGUI XP
 *
 * This class wraps calls to the dom xml api for EasyGUI to be compatible with
 * php4 and php5. This class may be instatiated or the methods can be called
 * statically.
 * @author Gaetan Lauff	<glauff@plansoft.de>
 * @version $Id: class.ek_domxml.php 11 2006-02-17 16:30:49Z glauff $
 * @package util
 */
class EK_DOMXML_
{
	/**
	 * EK_DOMXML Constructor
	 *
	 * If Class is instantiated the constructor sets the needed constant to determine the php version
	 * If you would like to call the methods statically you have to make sure the constant EK_PHPVER is set.
	 * Example:
	 * <code>define('EK_PHPVER', 0x4300)</code>
	 *
	 * @return void
	 *
	 * @access public
	 */ 
	function EK_DOMXML()
	{
		if ( !defined( 'EK_PHPVER' ) ) {
			$_version = (float) PHP_VERSION;
			
			if ($_version >= 5.0) {
				define('EK_PHPVER',0x5000);
			} elseif ($_version > 4.299999)  {
				define('EK_PHPVER',0x4300);
			} else  {
				trigger_error( 'Incompatible PHP Version. Please use PHP Version greater 4.3', E_USER_ERROR );
			}
		}
	}
	
	/**
	 * Loads an XML File and returns th Root Element
	 *
	 * @param string	$file	Filename of document to load
	 * @return The root element of the XML Document.
	 * 
	 * @access public
	 */
	function loadDocument( $file ) {
		if ( EK_PHPVER >= 0x5000 ) {
			$domHandler = new DOMDocument();
			
			if (! $domHandler->load( $file ) ) {
				trigger_error('File ' . $file . ' not found !! Aborting ...', E_USER_ERROR );
			}
			
			return $domHandler->documentElement;
		}
		
		if ( !$domHandler = domxml_open_file( $file ) ) {
			trigger_error('File ' . $file . ' not found !! Aborting ...', E_USER_ERROR );
		}
		
		return $domHandler->document_element;
	}
		
	function getElementsByTagName( $tags, $values, $tagname )
	{
		$elements = array();
		
		foreach( $tags as $tag => $indices ) {
			switch( $tag ) {
				case $tagname:
					array_push($elements, $values[$indices[0]] );
				default:
					break;
			}
		}
	
		return $elements;
	}
	/**
	 * Get DOM Elements By Tag Name
	 * 
	 * @param 	object	$root		DOM XML Root Element
	 * @param 	string	$tagname	Tagname that is searched
	 *
	 * @access 	public
	 */
	function getElementsByTagName_( $root, $tagname )
	{
		print_r($root);
		
		if (EK_PHPVER >= 0x5000 ) {
			$element = $root->getElementsByTagName( $tagname );
			return $element->item(0);
		}
		
		$element = $root->get_elements_by_tagname( $tagname );
		
		if (!isset( $element[0] ) ) {
			return new DOMElement($tagname);
		}
		
		return $element[0];
	}
	
	/**
	 * Get a DOM Element Attributes Value
	 *
	 * @param 	object/array	$section		Section in which Value is searched
	 * @param 	string			$attribute		Attribute to search for
	 * @param 	mixed			$default		Default value that is returned in case attribute is not found
	 *
	 * @access 	public
	 */
	function getAttribute( &$section, $attribute, $default = null)
	{
		$val = null;
		
		if (is_array( $section ) ) {
			if ( isset( $section[$attribute])) {
				$val = $section[$attribute];
			} elseif ( isset( $section[0]['attributes'] ) ) {
				if ( isset( $section[0]['attributes'][$attribute])) {
					$val = $section[0]['attributes'][$attribute];
				}
			}
		} else {
			if (EK_PHPVER >= 0x5000 ) {
				$val = $section->getAttribute( $attribute );
			} else {
				$val = $section->get_attribute( $attribute );
			}
		}
		
		if (empty($val) && !empty($default)) {
			return EK_Common::getValue( $default );
		}
		
		return EK_Common::getValue( $val );
	}
	
	/**
	 * Returns an array of DOM Nodes without text elements
	 *
	 * @param 	object	$node	DOM XML Node
	 * @return 	array	An array of DOM Nodes
	 *
	 * @access 	public
	 */
	function childNodes( $node, $values = null, $tagname = null )
	{
		$nodes 		= array();
		
		if ( is_array( $node ) && !is_null( $values ) ) {
			foreach ( $node as $idx => $key ) {
				if( $idx == $tagname ) {
					$nodes[] = $values[$key];
				}
			}
		} else {
		
			if (EK_PHPVER >= 0x5000 ) {
				$childNodes = $node->childNodes;
				
				foreach ($childNodes as $element) {
					if ($element->nodeType == XML_ELEMENT_NODE) {
						$nodes[] = $element;
					}
				}
			} else { 
				$childNodes = $node->child_nodes();
			
				foreach ($childNodes as $element) {
					if ($element->node_type() == XML_ELEMENT_NODE) {
						$nodes[] = $element;
					}
				}
			}
		}
		
		return $nodes;
	}
	
	/**
	 * Returns an array of DOM Attributes
	 *
	 * key = attribute name
	 * val = attribute value
	 *
	 * @param 	object	$node	DOM XML Node
	 * @return 	array	An Array of DOM Attributes
	 *
	 * @access 	public
	 */
	function getAttributes( $node )
	{
		$attributes = array();
		
		if (EK_PHPVER >= 0x5000) {
			$attribs = $node->getAttributeNode();
			//print_r($attribs);
		} else {
			$attribs = $node->attributes();
		
			foreach ($attribs as $attr) {
				if ($attr->type == 2) {
					$attributes[$attr->name] = EK_Common::getValue( $attr->value );
				}
			}
		}
		
		return $attributes;
	}
	
	/**
	 * Appends a child to a specific Node in the Document Tree
	 *
	 * @param 	object	$node	DOM XML Node
	 * @param 	object	$child	DOM XML Node
	 *
	 * @return 	void
	 *
	 * @access 	public
	 */
	function appendChild( $node, $child )
	{
		if (EK_PHPVER >= 0x5000 ) {
			$node->appendChild( $child );
		} else {
			$node->append_child( $child );
		}
	}
	
	/**
	 * Creates a new Element in the document Tree
	 *
	 * @param 	object	$doc	Document Object
	 * @param 	object	$name	Name of new Node
	 *
	 * @return 	new Element
	 *
	 * @access public
	 */
	function createElement( $doc, $name )
	{
		if (EK_PHPVER >= 0x5000 ) {
			return $doc->createElement( $name );
		} else {
			return $doc->create_element( $name );
		}
	}
	
}
?>