<?php
namespace dbtext\storage;

use dbtext\text\Group;
use dbtext\text\Text;
use n2n\context\RequestScoped;
use n2n\core\container\TransactionManager;
use n2n\persistence\orm\EntityManager;

class DbtextDao implements RequestScoped {
	/**
	 * @var EntityManager $em;
	 */
	private $em;
	/**
	 * @var TransactionManager $tm
	 */
	private $tm;

	/**
	 * @param EntityManager $em
	 */
	private function _init(EntityManager $em, TransactionManager $tm) {
		$this->em = $em;
		$this->tm = $tm;
	}

	/**
	 * @param string $namespace
	 * @param string $key
	 */
	public function insertKey(string $namespace, string $key, array $args = null) {
		$tx = $this->tm->createTransaction();

		if (0 < (int) $this->em->createCriteria()
				->select('COUNT(1)')
				->from(Text::getClass(), 't')
				->where(array('t.key' => $key, 't.group.namespace' => $namespace))->endClause()
				->toQuery()->fetchSingle()) {
			$tx->commit();
			return;
		}

		$text = new Text($key, $this->getOrCreateGroup($namespace), $args);
		$this->em->persist($text);
		$tx->commit();
	}

	public function persistText(Text $text) {
		$this->em->persist($text);
	}

	/**
	 * @param string $namespace
	 */
	public function getGroupData(string $namespace) {
		$result = $this->em->createNqlCriteria('
				SELECT  t.key, t.textTs.n2nLocale, t.textTs.str, t.placeholdersJson
				FROM Text t
				WHERE t.group.namespace = :ns',
				array('ns' => $namespace))->toQuery()->fetchArray();

		if (empty($result)) {
			return new GroupData($namespace);
		}
		$data[GroupData::TEXTS_KEY] = $this->formGroupDataResult($result);
		$data[GroupData::PLACEHOLDER_JSON_KEY] = $this->formPlaceholdersFromResult($result);

		return new GroupData($namespace, $data);
	}

	/**
	 * Gets group if exists.
	 * If Category does not exist a new one is created.
	 *
	 * @param string $namespace
	 * @return Group
	 */
	private function getOrCreateGroup(string $namespace): Group {
		$group = $this->em->find(Group::getClass(), $namespace);

		if (null !== $group) {
			return $group;
		}

		$group = new Group($namespace);
		$t = $this->tm->createTransaction();
		$this->em->persist($group);
		$t->commit();
		return $group;
	}

	public function changePlaceholders(string $key, string $ns, array $args) {
		$tx = $this->tm->createTransaction();

		/**
		 * @var Text $text
		 */
		$text = $this->em->createSimpleCriteria(Text::getClass(),
				array('key' => $key, 'group' => $this->em->find(Group::getClass(), $ns)))->toQuery()->fetchSingle();

		if ($text !== null) {
			$text->setPlaceholders($args);
			$this->em->persist($text);
		}

		$tx->commit();
	}

	/**
	 * @param array $result
	 * @return array
	 */
	private function formGroupDataResult(array $result) {
		$formedResult = array();

		foreach ($result as $i => $item) {
			if (!isset($formedResult[$item[0]])) {
				$formedResult[$item[0]] = array();
			}

			if ($item[2] === null) continue;

			$formedResult[$item[0]][(string) $item[1]] = $item[2];
		}

		return $formedResult;
	}

	/**
	 * @param array $result
	 * @return array
	 */
	private function formPlaceholdersFromResult(array $result) {
		$formedResult = array();

		foreach ($result as $i => $item) {
			if (!isset($formedResult[$item[0]])) {
				$formedResult[$item[0]] = array();
			}

			$formedResult[$item[0]] = json_decode($item[3]);
		}

		return $formedResult;
	}
}


<?php
namespace dbtext;

use dbtext\model\DbtextService;
use n2n\impl\web\ui\view\html\HtmlView;
use n2n\web\ui\UiComponent;
use n2n\impl\web\ui\view\html\HtmlBuilderMeta;
use n2n\web\ui\Raw;
use n2n\l10n\N2nLocale;

/**
 *
Use this html builder for easy access to {@see TextService} in html views.

 *
 *
Example usage

 *

 *	<?php
 *		use dbtext\DbtextHtmlBuilder;
 *
 *		$dbtextHtml = new DbtextHtmlBuilder($view);
 *	?>
 *	<p>
 *		<?php $dbtextHtml->t('greetings') ?>
 *	</p>
 *

 */
class DbtextHtmlBuilder {
	/**
	 * @var HtmlView $view
	 */
	private $view;

	/**
	 * @var DbtextService $textService
	 */
	private $textService;

	/**
	 * @var DbtextHtmlBuilderMeta
	 */
	private $meta;

	/**
	 * @param HtmlView $view
	 * @param string[] $namespaces
	 * @param N2nLocale[] $n2nLocales
	 */
	public function __construct(HtmlView $view, array $namespaces = array(), array $n2nLocales = array()) {
		$this->view = $view;
		$this->textService = $view->lookup(DbtextService::class);

		if (empty($namespaces)) {
			$namespaces[] = $this->view->getModuleNamespace();
		}

		if (empty($n2nLocales)) {
			$n2nLocales[] = $this->view->getN2nLocale();
		}

		$this->meta = new DbtextHtmlBuilderMeta($namespaces, $n2nLocales);
	}

	/**
	 * Outputs {@see self::getT()}
	 * Use as follows
	 *
	 * @param string $key
	 * @param array $args
	 */
	public function t(string $key, array $args = null, array $replacements = null, string ...$namespaces) {
		$this->view->out($this->view->getHtmlBuilder()->escBr($this->getT($key, $args, $replacements, ...$namespaces)));
	}

	/**
	 * Uses {@see TextService::t()} to return translated text as an {@see UiComponent}.
	 *
	 * <p>
	 * <?php $textHtml->t('intro_text') ?>
	 * </p>
	 *
	 * @param string $key
	 * @param array|null $args
	 * @param array|null $replacements
	 * @param string[] ...$namespaces
	 * @return Raw
	 */
	public function getT(string $key, array $args = null, array $replacements = null, string ...$namespaces) {
		if (empty($namespaces)) {
			$namespaces = $this->meta->getNamespaces();
		}

		$translatedText = $this->textService->t($namespaces, $key, $args, ...$this->meta->getN2nLocales());
		$replacedText = HtmlBuilderMeta::replace($translatedText, $replacements, $this->view);
		return new Raw($replacedText);
	}

	/**
	 * Use for easy access to a textblock formatted by printf rules.
	 *
	 * <p>
	 * <?php $textHtml->tf('intro_text') ?>
	 * </p>
	 *
	 * @param string $key
	 * @param string[] $args
	 * @param string[] $replacements
	 * @param string ...$namespaces
	 */
	public function tf(string $key, array $args = null, array $replacements = null, string ...$namespaces) {
		$this->view->out($this->getTf($key, $args, $replacements, ...$namespaces));
	}

	/**
	 * Use for easy access to a UiComponent with textblock formatted by printf rules.
	 *
	 * @param string $key
	 * @param string[] $args
	 * @param string[] $replacements
	 * @param string ...$namespaces
	 * @return UiComponent
	 */
	public function getTf(string $key, array $args = null, array $replacements = null, string ...$namespaces) {
		if (empty($namespaces)) {
			$namespaces = $this->meta->getNamespaces();
		}

		$translatedText = $this->textService->tf($namespaces, $key, $args, ...$this->meta->getN2nLocales());
		$replacedText = HtmlBuilderMeta::replace($translatedText, $replacements, $this->view);
		return new Raw($replacedText);
	}

	/**
	 * @return \dbtext\DbtextHtmlBuilderMeta
	 */
	public function meta() {
		return $this->meta;
	}
}


<?php
namespace dbtext;

use n2n\l10n\N2nLocale;

class DbtextHtmlBuilderMeta {
	/**
	 * @var string[] $namespaces
	 */
	private $namespaces;

	/**
	 * @var N2nLocale[] $n2nLocales
	 */
	private $n2nLocales;

	/**
	 * @param string[] $namespaces
	 * @param N2nLocale[] $n2nLocales
	 */
	public function __construct(array $namespaces = array(), array $n2nLocales = array()) {
		$this->namespaces = $namespaces;
		$this->n2nLocales = $n2nLocales;
	}

	/**
	 * Use this method to add namespaces where textblock keys will be searched.
	 *
	 * @param string $namespace
	 * @param bool $prepend
	 */
	public function assignNamespace(string $namespace, $prepend = false) {
		if ($prepend) {
			array_unshift($this->namespaces, $namespace);
			return;
		}

		array_push($this->namespaces, $namespace);
	}

	/**
	 * @param string[] ...$namespaces
	 */
	public function assignNamespaces(string ...$namespaces) {
		$this->namespaces = $namespaces;
	}

	/**
	 * @param N2nLocale $n2nLocale
	 * @param bool $prepend
	 */
	public function assignN2nLocale(N2nLocale $n2nLocale, $prepend = false) {
		if ($prepend) {
			array_unshift($this->n2nLocales, $n2nLocale);
			return;
		}

		array_push($this->n2nLocales, $n2nLocale);
	}

	/**
	 * @param N2nLocale[] ...$n2nLocales
	 */
	public function assignN2nLocales(N2nLocale ...$n2nLocales) {
		$this->n2nLocales = $n2nLocales;
	}

	public function getNamespaces() {
		return $this->namespaces;
	}

	public function getN2nLocales() {
		return $this->n2nLocales;
	}
}


<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pQuery;

/**
 * Converts a document into tokens
 *
 * Can convert any string into tokens. The base class only supports
 * identifier/whitespace tokens. For more tokens, the class can be
 * easily extended.
 *
 * Use like:
 *
 * <?php
 *  $a = new TokenizerBase('hello word');
 *  while ($a->next() !== $a::TOK_NULL) {
 *    echo $a->token, ': ',$a->getTokenString(), "
\n";
 *  }
 * ?>
 *
 *
 * @internal The tokenizer works with a character map that connects a certain
 * character to a certain function/token. This class is build with speed in mind.
 */
class TokenizerBase {

	/**
	 * NULL Token, used at end of document (parsing should stop after this token)
	 */
	const TOK_NULL = 0;
	/**
	 * Unknown token, used at unidentified character
	 */
	const TOK_UNKNOWN = 1;
	/**
	 * Whitespace token, used with whitespace
	 */
	const TOK_WHITESPACE = 2;
	/**
	 * Identifier token, used with identifiers
	 */
	const TOK_IDENTIFIER = 3;

	/**
	 * The document that is being tokenized
	 * @var string
	 * @internal Public for faster access!
	 * @see setDoc()
	 * @see getDoc()
	 * @access private
	 */
	var $doc = '';

	/**
	 * The size of the document (length of string)
	 * @var int
	 * @internal Public for faster access!
	 * @see $doc
	 * @access private
	 */
	var $size = 0;

	/**
	 * Current (character) position in the document
	 * @var int
	 * @internal Public for faster access!
	 * @see setPos()
	 * @see getPos()
	 * @access private
	 */
	var $pos = 0;

	/**
	 * Current (Line/Column) position in document
	 * @var array (Current_Line, Line_Starting_Pos)
	 * @internal Public for faster access!
	 * @see getLinePos()
	 * @access private
	 */
	var $line_pos = array(0, 0);

	/**
	 * Current token
	 * @var int
	 * @internal Public for faster access!
	 * @see getToken()
	 * @access private
	 */
	var $token = self::TOK_NULL;

	/**
	 * Start position of token. If NULL, then current position is used.
	 * @var int
	 * @internal Public for faster access!
	 * @see getTokenString()
	 * @access private
	 */
	var $token_start = null;

	/**
	 * List with all the character that can be considered as whitespace
	 * @var array|string
	 * @internal Variable is public + associated array for faster access!
	 * @internal array(' ' => true) will recognize space (' ') as whitespace
	 * @internal String will be converted to array in constructor
	 * @internal Result token will be {@link self::TOK_WHITESPACE};
	 * @see setWhitespace()
	 * @see getWhitespace()
	 * @access private
	 */
	var $whitespace = " \t\n\r\0\x0B";

	/**
	 * List with all the character that can be considered as identifier
	 * @var array|string
	 * @internal Variable is public + associated array for faster access!
	 * @internal array('a' => true) will recognize 'a' as identifier
	 * @internal String will be converted to array in constructor
	 * @internal Result token will be {@link self::TOK_IDENTIFIER};
	 * @see setIdentifiers()
	 * @see getIdentifiers()
	 * @access private
	 */
	var $identifiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_';

	/**
	 * All characters that should be mapped to a token/function that cannot be considered as whitespace or identifier
	 * @var array
	 * @internal Variable is public + associated array for faster access!
	 * @internal array('a' => 'parse_a') will call $this->parse_a() if it matches the character 'a'
	 * @internal array('a' => self::TOK_A) will set token to TOK_A if it matches the character 'a'
	 * @see mapChar()
	 * @see unmapChar()
	 * @access private
	 */
	var $custom_char_map = array();

	/**
	 * Automatically built character map. Built using {@link $identifiers}, {@link $whitespace} and {@link $custom_char_map}
	 * @var array
	 * @internal Public for faster access!
	 * @access private
	 */
	var $char_map = array();

	/**
	 * All errors found while parsing the document
	 * @var array
	 * @see addError()
	 */
	var $errors = array();

	/**
	 * Class constructor
	 * @param string $doc Document to be tokenized
	 * @param int $pos Position to start parsing
	 * @see setDoc()
	 * @see setPos()
	 */
	function __construct($doc = '', $pos = 0) {
		$this->setWhitespace($this->whitespace);
		$this->setIdentifiers($this->identifiers);

		$this->setDoc($doc, $pos);
	}

	#php4 PHP4 class constructor compatibility
	#function TokenizerBase($doc = '', $pos = 0) {return $this->__construct($doc, $pos);}
	#php4e

	/**
	 * Sets target document
	 * @param string $doc Document to be tokenized
	 * @param int $pos Position to start parsing
	 * @see getDoc()
	 * @see setPos()
	 */
	function setDoc($doc, $pos = 0) {
		$this->doc = $doc;
		$this->size = strlen($doc);
		$this->setPos($pos);
	}

	/**
	 * Returns target document
	 * @return string
	 * @see setDoc()
	 */
	function getDoc() {
		return $this->doc;
	}

	/**
	 * Sets position in document
	 * @param int $pos
	 * @see getPos()
	 */
	function setPos($pos = 0) {
		$this->pos = $pos - 1;
		$this->line_pos = array(0, 0);
		$this->next();
	}

	/**
	 * Returns current position in document (Index)
	 * @return int
	 * @see setPos()
	 */
	function getPos() {
		return $this->pos;
	}

	/**
	 * Returns current position in document (Line/Char)
	 * @return array array(Line, Column)
	 */
	function getLinePos() {
		return array($this->line_pos[0], $this->pos - $this->line_pos[1]);
	}

	/**
	 * Returns current token
	 * @return int
	 * @see $token
	 */
	function getToken() {
		return $this->token;
	}

	/**
	 * Returns current token as string
	 * @param int $start_offset Offset from token start
	 * @param int $end_offset Offset from token end
	 * @return string
	 */
	function getTokenString($start_offset = 0, $end_offset = 0) {
		$token_start = ((is_int($this->token_start)) ? $this->token_start : $this->pos) + $start_offset;
		$len = $this->pos - $token_start + 1 + $end_offset;
		return (($len > 0) ? substr($this->doc, $token_start, $len) : '');
	}

	/**
	 * Sets characters to be recognized as whitespace
	 *
	 * Used like: setWhitespace('ab') or setWhitespace(array('a' => true, 'b', 'c'));
	 * @param string|array $ws
	 * @see getWhitespace();
	 */
	function setWhitespace($ws) {
		if (is_array($ws)) {
			$this->whitespace = array_fill_keys(array_values($ws), true);
			$this->buildCharMap();
		} else {
			$this->setWhiteSpace(str_split($ws));
		}
	}

	/**
	 * Returns whitespace characters as string/array
	 * @param bool $as_string Should the result be a string or an array?
	 * @return string|array
	 * @see setWhitespace()
	 */
	function getWhitespace($as_string = true) {
		$ws = array_keys($this->whitespace);
		return (($as_string) ? implode('', $ws) : $ws);
	}

	/**
	 * Sets characters to be recognized as identifier
	 *
	 * Used like: setIdentifiers('ab') or setIdentifiers(array('a' => true, 'b', 'c'));
	 * @param string|array $ident
	 * @see getIdentifiers();
	 */
	function setIdentifiers($ident) {
		if (is_array($ident)) {
			$this->identifiers = array_fill_keys(array_values($ident), true);
			$this->buildCharMap();
		} else {
			$this->setIdentifiers(str_split($ident));
		}
	}

	/**
	 * Returns identifier characters as string/array
	 * @param bool $as_string Should the result be a string or an array?
	 * @return string|array
	 * @see setIdentifiers()
	 */
	function getIdentifiers($as_string = true) {
		$ident = array_keys($this->identifiers);
		return (($as_string) ? implode('', $ident) : $ident);
	}

	/**
	 * Maps a custom character to a token/function
	 *
	 * Used like: mapChar('a', self::{@link TOK_IDENTIFIER}) or mapChar('a', 'parse_identifier');
	 * @param string $char Character that should be mapped. If set, it will be overridden
	 * @param int|string $map If function name, then $this->function will be called, otherwise token is set to $map
	 * @see unmapChar()
	 */
	function mapChar($char, $map) {
		$this->custom_char_map[$char] = $map;
		$this->buildCharMap();
	}

	/**
	 * Removes a char mapped with {@link mapChar()}
	 * @param string $char Character that should be unmapped
	 * @see mapChar()
	 */
	function unmapChar($char) {
		unset($this->custom_char_map[$char]);
		$this->buildCharMap();
	}

	/**
	 * Builds the {@link $map_char} array
	 * @internal Builds single array that maps all characters. Gets called if {@link $whitespace}, {@link $identifiers} or {@link $custom_char_map} get modified
	 */
	protected function buildCharMap() {
		$this->char_map = $this->custom_char_map;
		if (is_array($this->whitespace)) {
			foreach($this->whitespace as $w => $v) {
				$this->char_map[$w] = 'parse_whitespace';
			}
		}
		if (is_array($this->identifiers)) {
			foreach($this->identifiers as $i => $v) {
				$this->char_map[$i] = 'parse_identifier';
			}
		}
	}

	/**
	 * Add error to the array and appends current position
	 * @param string $error
	 */
	function addError($error) {
		$this->errors[] = htmlentities($error.' at '.($this->line_pos[0] + 1).', '.($this->pos - $this->line_pos[1] + 1).'!');
	}

	/**
	 * Parse line breaks and increase line number
	 * @internal Gets called to process line breaks
	 */
	protected function parse_linebreak() {
		if($this->doc[$this->pos] === "\r") {
			++$this->line_pos[0];
			if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === "\n")) {
				++$this->pos;
			}
			$this->line_pos[1] = $this->pos;
		} elseif($this->doc[$this->pos] === "\n") {
			++$this->line_pos[0];
			$this->line_pos[1] = $this->pos;
		}
	}

	/**
	 * Parse whitespace
	 * @return int Token
	 * @internal Gets called with {@link $whitespace} characters
	 */
	protected function parse_whitespace() {
		$this->token_start = $this->pos;

		while(++$this->pos < $this->size) {
			if (!isset($this->whitespace[$this->doc[$this->pos]])) {
				break;
			} else {
				$this->parse_linebreak();
			}
		}

		--$this->pos;
		return self::TOK_WHITESPACE;
	}

	/**
	 * Parse identifiers
	 * @return int Token
	 * @internal Gets called with {@link $identifiers} characters
	 */
	protected function parse_identifier() {
		$this->token_start = $this->pos;

		while((++$this->pos < $this->size) && isset($this->identifiers[$this->doc[$this->pos]])) {}

		--$this->pos;
		return self::TOK_IDENTIFIER;
	}

	/**
	 * Continues to the next token
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next() {
		$this->token_start = null;

		if (++$this->pos < $this->size) {
			if (isset($this->char_map[$this->doc[$this->pos]])) {
				if (is_string($this->char_map[$this->doc[$this->pos]])) {
					return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
				} else {
					return ($this->token = $this->char_map[$this->doc[$this->pos]]);
				}
			} else {
				return ($this->token = self::TOK_UNKNOWN);
			}
		} else {
			return ($this->token = self::TOK_NULL);
		}
	}

	/**
	 * Finds the next token, but skips whitespace
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next_no_whitespace() {
		$this->token_start = null;

		while (++$this->pos < $this->size) {
			if (!isset($this->whitespace[$this->doc[$this->pos]])) {
				if (isset($this->char_map[$this->doc[$this->pos]])) {
					if (is_string($this->char_map[$this->doc[$this->pos]])) {
						return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
					} else {
						return ($this->token = $this->char_map[$this->doc[$this->pos]]);
					}
				} else {
					return ($this->token = self::TOK_UNKNOWN);
				}
			} else {
				$this->parse_linebreak();
			}
		}

		return ($this->token = self::TOK_NULL);
	}

	/**
	 * Finds the next token using stop characters.
	 *
	 * Used like: next_search('abc') or next_search(array('a' => true, 'b' => true, 'c' => true));
	 * @param string|array $characters Characters to search for
	 * @param bool $callback Should the function check the charmap after finding a character?
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next_search($characters, $callback = true) {
		$this->token_start = $this->pos;
		if (!is_array($characters)) {
			$characters = array_fill_keys(str_split($characters), true);
		}

		while(++$this->pos < $this->size) {
			if (isset($characters[$this->doc[$this->pos]])) {
				if ($callback && isset($this->char_map[$this->doc[$this->pos]])) {
					if (is_string($this->char_map[$this->doc[$this->pos]])) {
						return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
					} else {
						return ($this->token = $this->char_map[$this->doc[$this->pos]]);
					}
				} else {
					return ($this->token = self::TOK_UNKNOWN);
				}
			} else {
				$this->parse_linebreak();
			}
		}

		return ($this->token = self::TOK_NULL);
	}

	/**
	 * Finds the next token by searching for a string
	 * @param string $needle The needle that's being searched for
	 * @param bool $callback Should the function check the charmap after finding the needle?
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next_pos($needle, $callback = true) {
		$this->token_start = $this->pos;
		if (($this->pos < $this->size) && (($p = stripos($this->doc, $needle, $this->pos + 1)) !== false)) {

			$len = $p - $this->pos - 1;
			if ($len > 0) {
				$str = substr($this->doc, $this->pos + 1, $len);

				if (($l = strrpos($str, "\n")) !== false) {
					++$this->line_pos[0];
					$this->line_pos[1] = $l + $this->pos + 1;

					$len -= $l;
					if ($len > 0) {
						$str = substr($str, 0, -$len);
						$this->line_pos[0] += substr_count($str, "\n");
					}
				}
			}

			$this->pos = $p;
			if ($callback && isset($this->char_map[$this->doc[$this->pos]])) {
				if (is_string($this->char_map[$this->doc[$this->pos]])) {
					return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
				} else {
					return ($this->token = $this->char_map[$this->doc[$this->pos]]);
				}
			} else {
				return ($this->token = self::TOK_UNKNOWN);
			}
		} else {
			$this->pos = $this->size;
			return ($this->token = self::TOK_NULL);
		}
	}

	/**
	 * Expect a specific token or character. Adds error if token doesn't match.
	 * @param string|int $token Character or token to expect
	 * @param bool|int $do_next Go to next character before evaluating. 1 for next char, true to ignore whitespace
	 * @param bool|int $try_next Try next character if current doesn't match. 1 for next char, true to ignore whitespace
	 * @param bool|int $next_on_match Go to next character after evaluating. 1 for next char, true to ignore whitespace
	 * @return bool
	 */
	protected function expect($token, $do_next = true, $try_next = false, $next_on_match = 1) {
		if ($do_next) {
			if ($do_next === 1) {
				$this->next();
			} else {
				$this->next_no_whitespace();
			}
		}

		if (is_int($token)) {
			if (($this->token !== $token) && ((!$try_next) || ((($try_next === 1) && ($this->next() !== $token)) || (($try_next === true) && ($this->next_no_whitespace() !== $token))))) {
				$this->addError('Unexpected "'.$this->getTokenString().'"');
				return false;
			}
		} else {
			if (($this->doc[$this->pos] !== $token) && ((!$try_next) || (((($try_next === 1) && ($this->next() !== self::TOK_NULL)) || (($try_next === true) && ($this->next_no_whitespace() !== self::TOK_NULL))) && ($this->doc[$this->pos] !== $token)))) {
				$this->addError('Expected "'.$token.'", but found "'.$this->getTokenString().'"');
				return false;
			}
		}

		if ($next_on_match) {
			if ($next_on_match === 1) {
				$this->next();
			} else {
				$this->next_no_whitespace();
			}
		}
		return true;
	}
}

?>


<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pQuery;

/**
 * Parses a HTML document
 *
 * Functionality can be extended by overriding functions or adjusting the tag map.
 * Document may contain small errors, the parser will try to recover and resume parsing.
 */
class HtmlParserBase extends TokenizerBase {

	/**
	 * Tag open token, used for "<"
	 */
	const TOK_TAG_OPEN = 100;
	/**
	 * Tag close token, used for ">"
	 */
	const TOK_TAG_CLOSE = 101;
	/**
	 * Forward slash token, used for "/"
	 */
	const TOK_SLASH_FORWARD = 103;
	/**
	 * Backslash token, used for "\"
	 */
	const TOK_SLASH_BACKWARD = 104;
	/**
	 * String token, used for attribute values (" and ')
	 */
	const TOK_STRING = 104;
	/**
	 * Equals token, used for "="
	 */
	const TOK_EQUALS = 105;

	/**
	 * Sets HTML identifiers, tags/attributes are considered identifiers
	 * @see TokenizerBase::$identifiers
	 * @access private
	 */
	var $identifiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890:-_!?%';

	/**
	 * Status of the parser (tagname, closing tag, etc)
	 * @var array
	 */
	var $status = array();

	/**
	 * Map characters to match their tokens
	 * @see TokenizerBase::$custom_char_map
	 * @access private
	 */
	var $custom_char_map = array(
		'<' => self::TOK_TAG_OPEN,
		'>' => self::TOK_TAG_CLOSE,
		"'" => 'parse_string',
		'"' => 'parse_string',
		'/' => self::TOK_SLASH_FORWARD,
		'\\' => self::TOK_SLASH_BACKWARD,
		'=' => self::TOK_EQUALS
	);

	function __construct($doc = '', $pos = 0) {
		parent::__construct($doc, $pos);
		$this->parse_all();
	}

	#php4 PHP4 class constructor compatibility
	#function HtmlParserBase($doc = '', $pos = 0) {return $this->__construct($doc, $pos);}
	#php4e

	/**
	 Callback functions for certain tags
	 @var array (TAG_NAME => FUNCTION_NAME)
	 @internal Function should be a method in the class
	 @internal Tagname should be lowercase and is everything after <, e.g. "?php" or "!doctype"
	 @access private
	 */
	var $tag_map = array(
		'!doctype' => 'parse_doctype',
		'?' => 'parse_php',
		'?php' => 'parse_php',
		'%' => 'parse_asp',
		'style' => 'parse_style',
		'script' => 'parse_script'
	);

	/**
	 * Parse a HTML string (attributes)
	 * @internal Gets called with ' and "
	 * @return int
	 */
	protected function parse_string() {
		if ($this->next_pos($this->doc[$this->pos], false) !== self::TOK_UNKNOWN) {
			--$this->pos;
		}
		return self::TOK_STRING;
	}

	/**
	 * Parse text between tags
	 * @internal Gets called between tags, uses {@link $status}[last_pos]
	 * @internal Stores text in {@link $status}[text]
	 */
	function parse_text() {
		$len = $this->pos - 1 - $this->status['last_pos'];
		$this->status['text'] = (($len > 0) ? substr($this->doc, $this->status['last_pos'] + 1, $len) : '');
	}

	/**
	 * Parse comment tags
	 * @internal Gets called with HTML comments ("<!--")
	 * @internal Stores text in {@link $status}[comment]
	 * @return bool
	 */
	function parse_comment() {
		$this->pos += 3;
		if ($this->next_pos('-->', false) !== self::TOK_UNKNOWN) {
			$this->status['comment'] = $this->getTokenString(1, -1);
			--$this->pos;
		} else {
			$this->status['comment'] = $this->getTokenString(1, -1);
			$this->pos += 2;
		}
		$this->status['last_pos'] = $this->pos;

		return true;
	}

	/**
	 * Parse doctype tag
	 * @internal Gets called with doctype ("<!doctype")
	 * @internal Stores text in {@link $status}[dtd]
	 * @return bool
	 */
	function parse_doctype() {
		$start = $this->pos;
		if ($this->next_search('[>', false) === self::TOK_UNKNOWN)  {
			if ($this->doc[$this->pos] === '[') {
				if (($this->next_pos(']', false) !== self::TOK_UNKNOWN) || ($this->next_pos('>', false) !== self::TOK_UNKNOWN)) {
					$this->addError('Invalid doctype');
					return false;
				}
			}

			$this->token_start = $start;
			$this->status['dtd'] = $this->getTokenString(2, -1);
			$this->status['last_pos'] = $this->pos;
			return true;
		} else {
			$this->addError('Invalid doctype');
			return false;
		}
	}

	/**
	 * Parse cdata tag
	 * @internal Gets called with cdata ("<![cdata")
	 * @internal Stores text in {@link $status}[cdata]
	 * @return bool
	 */
	function parse_cdata() {
		if ($this->next_pos(']]>', false) === self::TOK_UNKNOWN) {
			$this->status['cdata'] = $this->getTokenString(9, -1);
			$this->status['last_pos'] = $this->pos + 2;
			return true;
		} else {
			$this->addError('Invalid cdata tag');
			return false;
		}
	}

	/**
	 * Parse php tags
	 * @internal Gets called with php tags ("<?php")
	 * @return bool
	 */
	function parse_php() {
		$start = $this->pos;
		if ($this->next_pos('?>', false) !== self::TOK_UNKNOWN) {
			$this->pos -= 2; //End of file
		}

		$len = $this->pos - 1 - $start;
		$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');
		$this->status['last_pos'] = ++$this->pos;
		return true;
	}

	/**
	 * Parse asp tags
	 * @internal Gets called with asp tags ("<%")
	 * @return bool
	 */
	function parse_asp() {
		$start = $this->pos;
		if ($this->next_pos('%>', false) !== self::TOK_UNKNOWN) {
			$this->pos -= 2; //End of file
		}

		$len = $this->pos - 1 - $start;
		$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');
		$this->status['last_pos'] = ++$this->pos;
		return true;
	}

	/**
	 * Parse style tags
	 * @internal Gets called with php tags ("<style>")
	 * @return bool
	 */
	function parse_style() {
		if ($this->parse_attributes() && ($this->token === self::TOK_TAG_CLOSE) && ($start = $this->pos) && ($this->next_pos('</style>', false) === self::TOK_UNKNOWN)) {
			$len = $this->pos - 1 - $start;
			$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');

			$this->pos += 7;
			$this->status['last_pos'] = $this->pos;
			return true;
		} else {
			$this->addError('No end for style tag found');
			return false;
		}
	}

	/**
	 * Parse script tags
	 * @internal Gets called with php tags ("<script>")
	 * @return bool
	 */
	function parse_script() {
		if ($this->parse_attributes() && ($this->token === self::TOK_TAG_CLOSE) && ($start = $this->pos) && ($this->next_pos('</script>', false) === self::TOK_UNKNOWN)) {
			$len = $this->pos - 1 - $start;
			$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');

			$this->pos += 8;
			$this->status['last_pos'] = $this->pos;
			return true;
		} else {
			$this->addError('No end for script tag found');
			return false;
		}
	}

	/**
	 * Parse conditional tags (+ all conditional tags inside)
	 * @internal Gets called with IE conditionals ("<![if]" and "<!--[if]")
	 * @internal Stores condition in {@link $status}[tag_condition]
	 * @return bool
	 */
	function parse_conditional() {
		if ($this->status['closing_tag']) {
			$this->pos += 8;
		} else {
			$this->pos += (($this->status['comment']) ? 5 : 3);
			if ($this->next_pos(']', false) !== self::TOK_UNKNOWN) {
				$this->addError('"]" not found in conditional tag');
				return false;
			}
			$this->status['tag_condition'] = $this->getTokenString(0, -1);
		}

		if ($this->next_no_whitespace() !== self::TOK_TAG_CLOSE) {
			$this->addError('No ">" tag found 2 for conditional tag');
			return false;
		}

		if ($this->status['comment']) {
			$this->status['last_pos'] = $this->pos;
			if ($this->next_pos('-->', false) !== self::TOK_UNKNOWN) {
				$this->addError('No ending tag found for conditional tag');
				$this->pos = $this->size - 1;

				$len = $this->pos - 1 - $this->status['last_pos'];
				$this->status['text'] = (($len > 0) ? substr($this->doc, $this->status['last_pos'] + 1, $len) : '');
			} else {
				$len = $this->pos - 10 - $this->status['last_pos'];
				$this->status['text'] = (($len > 0) ? substr($this->doc, $this->status['last_pos'] + 1, $len) : '');
				$this->pos += 2;
			}
		}

		$this->status['last_pos'] = $this->pos;
		return true;
	}

	/**
	 * Parse attributes (names + value)
	 * @internal Stores attributes in {@link $status}[attributes] (array(ATTR => VAL))
	 * @return bool
	 */
	function parse_attributes() {
		$this->status['attributes'] = array();

		while ($this->next_no_whitespace() === self::TOK_IDENTIFIER) {
			$attr = $this->getTokenString();
			if (($attr === '?') || ($attr === '%')) {
				//Probably closing tags
				break;
			}

			if ($this->next_no_whitespace() === self::TOK_EQUALS) {
				if ($this->next_no_whitespace() === self::TOK_STRING) {
					$val = $this->getTokenString(1, -1);
				} else {
					$this->token_start = $this->pos;
					if (!isset($stop)) {
						$stop = $this->whitespace;
						$stop['<'] = true;
						$stop['>'] = true;
					}

					while ((++$this->pos < $this->size) && (!isset($stop[$this->doc[$this->pos]]))) {
						// Do nothing.
					}
					--$this->pos;

					$val = $this->getTokenString();

					if (trim($val) === '') {
						$this->addError('Invalid attribute value');
						return false;
					}
				}
			} else {
				$val = $attr;
				$this->pos = (($this->token_start) ? $this->token_start : $this->pos) - 1;
			}

			$this->status['attributes'][$attr] = $val;
		}

		return true;
	}

	/**
	 * Default callback for tags
	 * @internal Gets called after the tagname (<html*ENTERS_HERE* attribute="value">)
	 * @return bool
	 */
	function parse_tag_default() {
		if ($this->status['closing_tag']) {
			$this->status['attributes'] = array();
			$this->next_no_whitespace();
		} else {
			if (!$this->parse_attributes()) {
				return false;
			}
		}

		if ($this->token !== self::TOK_TAG_CLOSE) {
			if ($this->token === self::TOK_SLASH_FORWARD) {
				$this->status['self_close'] = true;
				$this->next();
			} elseif ((($this->status['tag_name'][0] === '?') && ($this->doc[$this->pos] === '?')) || (($this->status['tag_name'][0] === '%') && ($this->doc[$this->pos] === '%'))) {
				$this->status['self_close'] = true;
				$this->pos++;

				if (isset($this->char_map[$this->doc[$this->pos]]) && (!is_string($this->char_map[$this->doc[$this->pos]]))) {
					$this->token = $this->char_map[$this->doc[$this->pos]];
				} else {
					$this->token = self::TOK_UNKNOWN;
				}
			}/* else {
				$this->status['self_close'] = false;
			}*/
		}

		if ($this->token !== self::TOK_TAG_CLOSE) {
			$this->addError('Expected ">", but found "'.$this->getTokenString().'"');
			if ($this->next_pos('>', false) !== self::TOK_UNKNOWN) {
				$this->addError('No ">" tag found for "'.$this->status['tag_name'].'" tag');
				return false;
			}
		}

		return true;
	}

	/**
	 * Parse tag
	 * @internal Gets called after opening tag (<*ENTERS_HERE*html attribute="value">)
	 * @internal Stores information about the tag in {@link $status} (comment, closing_tag, tag_name)
	 * @return bool
	 */
	function parse_tag() {
		$start = $this->pos;
		$this->status['self_close'] = false;
		$this->parse_text();

		$next = (($this->pos + 1) < $this->size) ? $this->doc[$this->pos + 1] : '';
		if ($next === '!') {
			$this->status['closing_tag'] = false;

			if (substr($this->doc, $this->pos + 2, 2) === '--') {
				$this->status['comment'] = true;

				if (($this->doc[$this->pos + 4] === '[') && (strcasecmp(substr($this->doc, $this->pos + 5, 2), 'if') === 0)) {
					return $this->parse_conditional();
				} else {
					return $this->parse_comment();
				}
			} else {
				$this->status['comment'] = false;

				if ($this->doc[$this->pos + 2] === '[') {
					if (strcasecmp(substr($this->doc, $this->pos + 3, 2), 'if') === 0) {
						return $this->parse_conditional();
					} elseif (strcasecmp(substr($this->doc, $this->pos + 3, 5), 'endif') === 0) {
						$this->status['closing_tag'] = true;
						return $this->parse_conditional();
					} elseif (strcasecmp(substr($this->doc, $this->pos + 3, 5), 'cdata') === 0) {
						return $this->parse_cdata();
					}
				}
			}
		} elseif ($next === '/') {
			$this->status['closing_tag'] = true;
			++$this->pos;
		} else {
			$this->status['closing_tag'] = false;
		}

		if ($this->next() !== self::TOK_IDENTIFIER) {
			$this->addError('Tagname expected');
			//if ($this->next_pos('>', false) === self::TOK_UNKNOWN) {
				$this->status['last_pos'] = $start - 1;
				return true;
			//} else {
			//	return false;
			//}
		}

		$tag = $this->getTokenString();
		$this->status['tag_name'] = $tag;
		$tag = strtolower($tag);

		if (isset($this->tag_map[$tag])) {
			$res = $this->{$this->tag_map[$tag]}();
		} else {
			$res = $this->parse_tag_default();
		}

		$this->status['last_pos'] = $this->pos;
		return $res;
	}

	/**
	 * Parse full document
	 * @return bool
	 */
	function parse_all() {
		$this->errors = array();
		$this->status['last_pos'] = -1;

		if (($this->token === self::TOK_TAG_OPEN) || ($this->next_pos('<', false) === self::TOK_UNKNOWN)) {
			do {
				if (!$this->parse_tag()) {
					return false;
				}
			} while ($this->next_pos('<') !== self::TOK_NULL);
		}

		$this->pos = $this->size;
		$this->parse_text();

		return true;
	}
}

/**
 * Parses a HTML document into a HTML DOM
 */
class HtmlParser extends HtmlParserBase {

	/**
	 * Root object
	 * @internal If string, then it will create a new instance as root
	 * @var DomNode
	 */
	var $root = 'pQuery\\DomNode';

	/**
	 * Current parsing hierarchy
	 * @internal Root is always at index 0, current tag is at the end of the array
	 * @var array
	 * @access private
	 */
	var $hierarchy = array();

	/**
	 * Tags that don't need closing tags
	 * @var array
	 * @access private
	 */
	var	$tags_selfclose = array(
		'area'		=> true,
		'base'		=> true,
		'basefont'	=> true,
		'br'		=> true,
		'col'		=> true,
		'command'	=> true,
		'embed'		=> true,
		'frame'		=> true,
		'hr'		=> true,
		'img'		=> true,
		'input'		=> true,
		'ins'		=> true,
		'keygen'	=> true,
		'link'		=> true,
		'meta'		=> true,
		'param'		=> true,
		'source'	=> true,
		'track'		=> true,
		'wbr'		=> true
	);

	/**
	 * Class constructor
	 * @param string $doc Document to be tokenized
	 * @param int $pos Position to start parsing
	 * @param DomNode $root Root node, null to auto create
	 */
	function __construct($doc = '', $pos = 0, $root = null) {
		if ($root === null) {
			$root = new $this->root('~root~', null);
		}
		$this->root =& $root;

		parent::__construct($doc, $pos);
	}

	#php4 PHP4 class constructor compatibility
	#function HtmlParser($doc = '', $pos = 0, $root = null) {return $this->__construct($doc, $pos, $root);}
	#php4e

	/**
	 * Class magic invoke method, performs {@link select()}
	 * @return array
	 * @access private
	 */
	function __invoke($query = '*') {
		return $this->select($query);
	}

	/**
	 * Class magic toString method, performs {@link DomNode::toString()}
	 * @return string
	 * @access private
	 */
	function __toString() {
		return $this->root->getInnerText();
	}

	/**
	 * Performs a css select query on the root node
	 * @see DomNode::select()
	 * @return array
	 */
	function select($query = '*', $index = false, $recursive = true, $check_self = false) {
		return $this->root->select($query, $index, $recursive, $check_self);
	}

	/**
	 * Updates the current hierarchy status and checks for
	 * correct opening/closing of tags
	 * @param bool $self_close Is current tag self closing? Null to use {@link tags_selfclose}
	 * @internal This is were most of the nodes get added
	 * @access private
	 */
	protected function parse_hierarchy($self_close = null) {
		if ($self_close === null) {
			$this->status['self_close'] = ($self_close = isset($this->tags_selfclose[strtolower($this->status['tag_name'])]));
		}

		if ($self_close) {
			if ($this->status['closing_tag']) {

				//$c = end($this->hierarchy)->children
				$c = $this->hierarchy[count($this->hierarchy) - 1]->children;
				$found = false;
				for ($count = count($c), $i = $count - 1; $i >= 0; $i--) {
					if (strcasecmp($c[$i]->tag, $this->status['tag_name']) === 0) {
						for($ii = $i + 1; $ii < $count; $ii++) {
							$index = null; //Needs to be passed by ref
							$c[$i + 1]->changeParent($c[$i], $index);
						}
						$c[$i]->self_close = false;

						$found = true;
						break;
					}
				}

				if (!$found) {
					$this->addError('Closing tag "'.$this->status['tag_name'].'" which is not open');
				}

			} elseif ($this->status['tag_name'][0] === '?') {
				//end($this->hierarchy)->addXML($this->status['tag_name'], '', $this->status['attributes']);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[count($this->hierarchy) - 1]->addXML($this->status['tag_name'], '', $this->status['attributes'], $index);
			} elseif ($this->status['tag_name'][0] === '%') {
				//end($this->hierarchy)->addASP($this->status['tag_name'], '', $this->status['attributes']);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[count($this->hierarchy) - 1]->addASP($this->status['tag_name'], '', $this->status['attributes'], $index);
			} else {
				//end($this->hierarchy)->addChild($this->status);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
			}
		} elseif ($this->status['closing_tag']) {
			$found = false;
			for ($count = count($this->hierarchy), $i = $count - 1; $i >= 0; $i--) {
				if (strcasecmp($this->hierarchy[$i]->tag, $this->status['tag_name']) === 0) {

					for($ii = ($count - $i - 1); $ii >= 0; $ii--) {
						$e = array_pop($this->hierarchy);
						if ($ii > 0) {
							$this->addError('Closing tag "'.$this->status['tag_name'].'" while "'.$e->tag.'" is not closed yet');
						}
					}

					$found = true;
					break;
				}
			}

			if (!$found) {
				$this->addError('Closing tag "'.$this->status['tag_name'].'" which is not open');
			}

		} else {
			//$this->hierarchy[] = end($this->hierarchy)->addChild($this->status);
			$index = null; //Needs to be passed by ref
			$this->hierarchy[] = $this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
		}
	}

	function parse_cdata() {
		if (!parent::parse_cdata()) {return false;}

		//end($this->hierarchy)->addCDATA($this->status['cdata']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addCDATA($this->status['cdata'], $index);
		return true;
	}

	function parse_comment() {
		if (!parent::parse_comment()) {return false;}

		//end($this->hierarchy)->addComment($this->status['comment']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addComment($this->status['comment'], $index);
		return true;
	}

	function parse_conditional() {
		if (!parent::parse_conditional()) {return false;}

		if ($this->status['comment']) {
			//$e = end($this->hierarchy)->addConditional($this->status['tag_condition'], true);
			$index = null; //Needs to be passed by ref
			$e = $this->hierarchy[count($this->hierarchy) - 1]->addConditional($this->status['tag_condition'], true, $index);
			if ($this->status['text'] !== '') {
				$index = null; //Needs to be passed by ref
				$e->addText($this->status['text'], $index);
			}
		} else {
			if ($this->status['closing_tag']) {
				$this->parse_hierarchy(false);
			} else {
				//$this->hierarchy[] = end($this->hierarchy)->addConditional($this->status['tag_condition'], false);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[] = $this->hierarchy[count($this->hierarchy) - 1]->addConditional($this->status['tag_condition'], false, $index);
			}
		}

		return true;
	}

	function parse_doctype() {
		if (!parent::parse_doctype()) {return false;}

		//end($this->hierarchy)->addDoctype($this->status['dtd']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addDoctype($this->status['dtd'], $index);
		return true;
	}

	function parse_php() {
		if (!parent::parse_php()) {return false;}

		//end($this->hierarchy)->addXML('php', $this->status['text']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addXML('php', $this->status['text'], $index);
		return true;
	}

	function parse_asp() {
		if (!parent::parse_asp()) {return false;}

		//end($this->hierarchy)->addASP('', $this->status['text']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addASP('', $this->status['text'], $index);
		return true;
	}

	function parse_script() {
		if (!parent::parse_script()) {return false;}

		//$e = end($this->hierarchy)->addChild($this->status);
		$index = null; //Needs to be passed by ref
		$e = $this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
		if ($this->status['text'] !== '') {
			$index = null; //Needs to be passed by ref
			$e->addText($this->status['text'], $index);
		}
		return true;
	}

	function parse_style() {
		if (!parent::parse_style()) {return false;}

		//$e = end($this->hierarchy)->addChild($this->status);
		$index = null; //Needs to be passed by ref
		$e = $this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
		if ($this->status['text'] !== '') {
			$index = null; //Needs to be passed by ref
			$e->addText($this->status['text'], $index);
		}
		return true;
	}

	function parse_tag_default() {
		if (!parent::parse_tag_default()) {return false;}

		$this->parse_hierarchy(($this->status['self_close']) ? true : null);
		return true;
	}

	function parse_text() {
		parent::parse_text();
		if ($this->status['text'] !== '') {
			//end($this->hierarchy)->addText($this->status['text']);
			$index = null; //Needs to be passed by ref
			$this->hierarchy[count($this->hierarchy) - 1]->addText($this->status['text'], $index);
		}
	}

	function parse_all() {
		$this->hierarchy = array(&$this->root);
		return ((parent::parse_all()) ? $this->root : false);
	}
}

/**
 * HTML5 specific parser (adds support for omittable closing tags)
 */
class Html5Parser extends HtmlParser {

	/**
	 * Tags with ommitable closing tags
	 * @var array array('tag2' => 'tag1') will close tag1 if following (not child) tag is tag2
	 * @access private
	 */
	var $tags_optional_close = array(
		//Current tag	=> Previous tag
		'li' 			=> array('li' => true),
		'dt' 			=> array('dt' => true, 'dd' => true),
		'dd' 			=> array('dt' => true, 'dd' => true),
		'address' 		=> array('p' => true),
		'article' 		=> array('p' => true),
		'aside' 		=> array('p' => true),
		'blockquote' 	=> array('p' => true),
		'dir' 			=> array('p' => true),
		'div' 			=> array('p' => true),
		'dl' 			=> array('p' => true),
		'fieldset' 		=> array('p' => true),
		'footer' 		=> array('p' => true),
		'form' 			=> array('p' => true),
		'h1' 			=> array('p' => true),
		'h2' 			=> array('p' => true),
		'h3' 			=> array('p' => true),
		'h4' 			=> array('p' => true),
		'h5' 			=> array('p' => true),
		'h6' 			=> array('p' => true),
		'header' 		=> array('p' => true),
		'hgroup' 		=> array('p' => true),
		'hr' 			=> array('p' => true),
		'menu' 			=> array('p' => true),
		'nav' 			=> array('p' => true),
		'ol' 			=> array('p' => true),
		'p' 			=> array('p' => true),
		'pre' 			=> array('p' => true),
		'section' 		=> array('p' => true),
		'table' 		=> array('p' => true),
		'ul' 			=> array('p' => true),
		'rt'			=> array('rt' => true, 'rp' => true),
		'rp'			=> array('rt' => true, 'rp' => true),
		'optgroup'		=> array('optgroup' => true, 'option' => true),
		'option'		=> array('option'),
		'tbody'			=> array('thread' => true, 'tbody' => true, 'tfoot' => true),
		'tfoot'			=> array('thread' => true, 'tbody' => true),
		'tr'			=> array('tr' => true),
		'td'			=> array('td' => true, 'th' => true),
		'th'			=> array('td' => true, 'th' => true),
		'body'			=> array('head' => true)
	);

	protected function parse_hierarchy($self_close = null) {
		$tag_curr = strtolower($this->status['tag_name']);
		if ($self_close === null) {
			$this->status['self_close'] = ($self_close = isset($this->tags_selfclose[$tag_curr]));
		}

		if (! ($self_close || $this->status['closing_tag'])) {
			//$tag_prev = strtolower(end($this->hierarchy)->tag);
			$tag_prev = strtolower($this->hierarchy[count($this->hierarchy) - 1]->tag);
			if (isset($this->tags_optional_close[$tag_curr]) && isset($this->tags_optional_close[$tag_curr][$tag_prev])) {
				array_pop($this->hierarchy);
			}
		}

		return parent::parse_hierarchy($self_close);
	}
}

?>


<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

use pQuery\IQuery;

/**
 * A jQuery-like object for php.
 */
class pQuery implements ArrayAccess, IteratorAggregate, IQuery {
    /// Properties ///

    /**
     * @var IQuery[]
     */
    protected $nodes = array();

    /// Methods ///

    public function __construct($nodes = array()) {
        $this->nodes = $nodes;
    }

    public function addClass($classname) {
        foreach ($this->nodes as $node) {
            $node->addClass($classname);
        }
        return $this;
    }

    public function after($content) {
        foreach ($this->nodes as $node) {
            $node->after($content);
        }
        return $this;
    }

    public function append($content) {
        foreach ($this->nodes as $node) {
            $node->append($content);
        }
        return $this;
    }

    public function attr($name, $value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->attr($name);
            $node->attr($name, $value);
        }
        return $this;
    }

    public function before($content) {
        foreach ($this->nodes as $node) {
            $node->before($content);
        }
        return $this;
    }

    public function clear() {
        foreach ($this->nodes as $node) {
            $node->clear();
        }
        return $this;
    }

    /**
     * Get the count of matched elements.
     *
     * @return int Returns the count of matched elements.
     */
    public function count() {
        return count($this->nodes);
    }

    /**
     * Format/beautify a DOM.
     *
     * @param pQuery\DomNode $dom The dom to format.
     * @param array $options Extra formatting options. See {@link pQuery\HtmlFormatter::$options}.
     * @return bool Returns `true` on sucess and `false` on failure.
     */
//    public static function format($dom, $options = array()) {
//        $formatter = new pQuery\HtmlFormatter($options);
//        return $formatter->format($dom);
//    }

    public function getIterator() {
        return new ArrayIterator($this->nodes);
    }

    public function hasClass($classname) {
        foreach ($this->nodes as $node) {
            if ($node->hasClass($classname))
                return true;
        }
        return false;
    }

    public function html($value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->html();
            $node->html($value);
        }
        return $this;
    }

    public function offsetExists($offset) {
        return isset($this->nodes[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->nodes[$offset]) ? $this->nodes[$offset] : null;
    }

    public function offsetSet($offset, $value) {

        if (is_null($offset) || !isset($this->nodes[$offset])) {
            throw new \BadMethodCallException("You are not allowed to add new nodes to the pQuery object.");
        } else {
            $this->nodes[$offset]->replaceWith($value);
        }
    }

    public function offsetUnset($offset) {
        if (isset($this->nodes[$offset])) {
            $this->nodes[$offset]->remove();
            unset($this->nodes[$offset]);
        }
    }

    /**
     * Query a file or url.
     *
     * @param string $path The path to the url.
     * @param resource $context A context suitable to be passed into {@link file_get_contents}
     * @return pQuery\DomNode Returns the root dom node for the html file.
     */
    public static function parseFile($path, $context = null) {
        $html_str = file_get_contents($path, false, $context);
        return static::parseStr($html_str);
    }

    /**
     * Query a string of html.
     *
     * @param string $html
     * @return pQuery\DomNode Returns the root dom node for the html string.
     */
    public static function parseStr($html) {
        $parser = new pQuery\Html5Parser($html);
        return $parser->root;
    }

    public function prepend($content = null) {
        foreach ($this->nodes as $node) {
            $node->prepend($content);
        }
        return $this;
    }

    public function prop($name, $value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->prop($name);
            $node->prop($name, $value);
        }
        return $this;
    }

    public function remove($selector = null) {
        foreach ($this->nodes as $node) {
            $node->remove($selector);
        }
        if ($selector === null)
            $this->nodes = array();

        return $this;
    }

    public function removeAttr($name) {
        foreach ($this->nodes as $node) {
            $node->removeAttr($name);
        }
        return $this;
    }

    public function removeClass($classname) {
        foreach ($this->nodes as $node) {
            $node->removeClass($classname);
        }
        return $this;
    }

    public function replaceWith($content) {
        foreach ($this->nodes as &$node) {
            $node = $node->replaceWith($content);
        }
        return $this;
    }

    public function tagName($value = null) {
        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->tagName();
            $node->tagName($value);
        }
        return $this;
    }

    public function text($value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->text();
            $node->text($value);
        }
        return $this;
    }

    public function toggleClass($classname, $switch = null) {
        foreach ($this->nodes as $node) {
            $node->toggleClass($classname, $switch);
        }

        return $this;
    }

    public function unwrap() {
        foreach ($this->nodes as $node) {
            $node->unwrap();
        }
        return $this;
    }

    public function val($value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->val();
            $node->val($value);
        }
        return $this;
    }

    public function wrap($wrapping_element) {
        foreach ($this->nodes as $node) {
            $node->wrap($wrapping_element);
        }
        return $this;
    }

    public function wrapInner($wrapping_element) {
        foreach ($this->nodes as $node) {
            $node->wrapInner($wrapping_element);
        }
        return $this;
    }
}