<?php
/*
 * This file is part of the easy-CMS project.
 * easy-CMS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * easy-CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with easy-CMS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

include_once('config.inc.php');
include_once('classes/core/CoreObject.class.php');
include_once('classes/core/parser/XMLIterator.class.php');
include_once('classes/core/parser/tags/Tag.class.php');

/**
 * Parser for html contents.
 *
 * @access     public
 * @author	   Cedric Francoys <cedric.francoys@easy-cms.org>
 * @version	   HTMLParser.class, Sun Dec 19 10:46:03 CET 2004
 * @package	   Core
 * @subpackage Parser
 */
class HTMLParser extends CoreObject {
	/**
	 * @access private
	 * @var    string
	 */
	var $xhtml;

	/**
	 * @access private
	 * @var    array
	 */
	var $tagsTable;

	function HTMLParser(&$xhtml) {
		$this->xhtml = &$xhtml;
	}

	function &getXHTML() {
		return $this->xhtml;
	}

	function &getResult($langId) {
  // first pass : check for include directives (recursion)
  // <easy-cms:include file="" />
		$xmlIterator = &new XMLIterator($this->xhtml);
		$tag = &new Tag();
		return $this->parse($xmlIterator, $tag, $langId);
	}

	function &parse(&$xmlIterator, $tag, $langId, $evaluate=true, $level=0) {
		// obtain the current offset
		$offset = $xmlIterator->getOffset();
		// initialize the result string
		$result = '';
		while ($xmlIterator->hasNext()) {
			if(!($newTag = &$xmlIterator->next())) {
				continue;
			}
			if($evaluate){
				$result .= substr($xmlIterator->getXML(), $offset, $newTag->getOffset()-$offset);
			}
			// obtain the new offset (the position following the last read tag)
			$offset = $xmlIterator->getOffset();
			switch($newTag->getType()){
				case SINGLE_TAG :
					if($evaluate) {
						$result .= $newTag->evaluate($langId);
					}
					break;
				case OPEN_TAG :
					$eval = ($evaluate && $newTag->evaluate($langId));
					$res = &$this->parse($xmlIterator, $newTag, $langId, $eval, $level+1);
					if($evaluate){
						$result .= $res;
					}
					// obtain the new offset
					$offset = $xmlIterator->getOffset();
					break;
				case CLOSE_TAG :
					if(!strcmp($newTag->getName(), $tag->getName())) {
						return $result;
					}
					break;
			}
		}
		// add the chars between the last tag and the end of the string
		$result .= substr($xmlIterator->getXML(), $xmlIterator->getOffset());
		return $result;
	}
}
?>