summaryrefslogtreecommitdiff
path: root/lib/querypath/src/QueryPath/CSS
diff options
context:
space:
mode:
authoremkael <emkael@tlen.pl>2017-01-18 20:07:16 +0100
committeremkael <emkael@tlen.pl>2017-01-18 20:07:16 +0100
commit9a9c04512e5dcb77c7fe5d850e3f2a0250cc160e (patch)
treefed46b5f4c2ed3a050bb1a7ad7c6d0a3ea844d55 /lib/querypath/src/QueryPath/CSS
parentc5bcf8f74fb80b7e163663845b0d6e35cabface3 (diff)
* Motor Sport Magazine feed provider
Diffstat (limited to 'lib/querypath/src/QueryPath/CSS')
-rw-r--r--lib/querypath/src/QueryPath/CSS/DOMTraverser.php775
-rw-r--r--lib/querypath/src/QueryPath/CSS/DOMTraverser/PseudoClass.php421
-rw-r--r--lib/querypath/src/QueryPath/CSS/DOMTraverser/Util.php139
-rw-r--r--lib/querypath/src/QueryPath/CSS/EventHandler.php171
-rw-r--r--lib/querypath/src/QueryPath/CSS/InputStream.php57
-rw-r--r--lib/querypath/src/QueryPath/CSS/NotImplementedException.php15
-rw-r--r--lib/querypath/src/QueryPath/CSS/ParseException.php15
-rw-r--r--lib/querypath/src/QueryPath/CSS/Parser.php575
-rw-r--r--lib/querypath/src/QueryPath/CSS/QueryPathEventHandler.php1424
-rw-r--r--lib/querypath/src/QueryPath/CSS/Scanner.php306
-rw-r--r--lib/querypath/src/QueryPath/CSS/Selector.php144
-rw-r--r--lib/querypath/src/QueryPath/CSS/SimpleSelector.php138
-rw-r--r--lib/querypath/src/QueryPath/CSS/Token.php60
-rw-r--r--lib/querypath/src/QueryPath/CSS/Traverser.php38
14 files changed, 4278 insertions, 0 deletions
diff --git a/lib/querypath/src/QueryPath/CSS/DOMTraverser.php b/lib/querypath/src/QueryPath/CSS/DOMTraverser.php
new file mode 100644
index 0000000..be8c2af
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/DOMTraverser.php
@@ -0,0 +1,775 @@
+<?php
+/** @file
+ * Traverse a DOM.
+ */
+
+namespace QueryPath\CSS;
+
+use \QueryPath\CSS\DOMTraverser\Util;
+use \QueryPath\CSS\DOMTraverser\PseudoClass;
+use \QueryPath\CSS\DOMTraverser\PseudoElement;
+
+/**
+ * Traverse a DOM, finding matches to the selector.
+ *
+ * This traverses a DOMDocument and attempts to find
+ * matches to the provided selector.
+ *
+ * \b How this works
+ *
+ * This performs a bottom-up search. On the first pass,
+ * it attempts to find all of the matching elements for the
+ * last simple selector in a selector.
+ *
+ * Subsequent passes attempt to eliminate matches from the
+ * initial matching set.
+ *
+ * Example:
+ *
+ * Say we begin with the selector `foo.bar baz`. This is processed
+ * as follows:
+ *
+ * - First, find all baz elements.
+ * - Next, for any baz element that does not have foo as an ancestor,
+ * eliminate it from the matches.
+ * - Finally, for those that have foo as an ancestor, does that foo
+ * also have a class baz? If not, it is removed from the matches.
+ *
+ * \b Extrapolation
+ *
+ * Partial simple selectors are almost always expanded to include an
+ * element.
+ *
+ * Examples:
+ *
+ * - `:first` is expanded to `*:first`
+ * - `.bar` is expanded to `*.bar`.
+ * - `.outer .inner` is expanded to `*.outer *.inner`
+ *
+ * The exception is that IDs are sometimes not expanded, e.g.:
+ *
+ * - `#myElement` does not get expanded
+ * - `#myElement .class` \i may be expanded to `*#myElement *.class`
+ * (which will obviously not perform well).
+ */
+class DOMTraverser implements Traverser {
+
+ protected $matches = array();
+ protected $selector;
+ protected $dom;
+ protected $initialized = TRUE;
+ protected $psHandler;
+ protected $scopeNode;
+
+ /**
+ * Build a new DOMTraverser.
+ *
+ * This requires a DOM-like object or collection of DOM nodes.
+ */
+ public function __construct(\SPLObjectStorage $splos, $initialized = FALSE, $scopeNode = NULL) {
+
+ $this->psHandler = new \QueryPath\CSS\DOMTraverser\PseudoClass();
+ $this->initialized = $initialized;
+
+ // Re-use the initial splos
+ $this->matches = $splos;
+
+ if (count($splos) != 0) {
+ $splos->rewind();
+ $first = $splos->current();
+ if ($first instanceof \DOMDocument) {
+ $this->dom = $first;//->documentElement;
+ }
+ else {
+ $this->dom = $first->ownerDocument;//->documentElement;
+ }
+ if (empty($scopeNode)) {
+ $this->scopeNode = $this->dom->documentElement;
+ }
+ else {
+ $this->scopeNode = $scopeNode;
+ }
+ }
+
+ // This assumes a DOM. Need to also accomodate the case
+ // where we get a set of elements.
+ /*
+ $this->dom = $dom;
+ $this->matches = new \SplObjectStorage();
+ $this->matches->attach($this->dom);
+ */
+ }
+
+ public function debug($msg) {
+ fwrite(STDOUT, PHP_EOL . $msg);
+ }
+
+ /**
+ * Given a selector, find the matches in the given DOM.
+ *
+ * This is the main function for querying the DOM using a CSS
+ * selector.
+ *
+ * @param string $selector
+ * The selector.
+ * @return \SPLObjectStorage
+ * An SPLObjectStorage containing a list of matched
+ * DOMNode objects.
+ */
+ public function find($selector) {
+ // Setup
+ $handler = new Selector();
+ $parser = new Parser($selector, $handler);
+ $parser->parse();
+ $this->selector = $handler;
+
+ //$selector = $handler->toArray();
+ $found = $this->newMatches();
+ foreach ($handler as $selectorGroup) {
+ // fprintf(STDOUT, "Selector group.\n");
+ // Initialize matches if necessary.
+ if ($this->initialized) {
+ $candidates = $this->matches;
+ }
+ else {
+ //if (empty($selectorGroup)) {
+ // fprintf(STDOUT, "%s", print_r($handler->toArray(), TRUE));
+ //}
+ $candidates = $this->initialMatch($selectorGroup[0], $this->matches);
+ //$this->initialized = TRUE;
+ }
+
+ foreach ($candidates as $candidate) {
+ // fprintf(STDOUT, "Testing %s against %s.\n", $candidate->tagName, $selectorGroup[0]);
+ if ($this->matchesSelector($candidate, $selectorGroup)) {
+ // $this->debug('Attaching ' . $candidate->nodeName);
+ $found->attach($candidate);
+ }
+ }
+ }
+ $this->setMatches($found);
+
+
+ return $this;
+ }
+
+ public function matches() {
+ return $this->matches;
+ }
+
+ /**
+ * Check whether the given node matches the given selector.
+ *
+ * A selector is a group of one or more simple selectors combined
+ * by combinators. This determines if a given selector
+ * matches the given node.
+ *
+ * @attention
+ * Evaluation of selectors is done recursively. Thus the length
+ * of the selector is limited to the recursion depth allowed by
+ * the PHP configuration. This should only cause problems for
+ * absolutely huge selectors or for versions of PHP tuned to
+ * strictly limit recursion depth.
+ *
+ * @param object DOMNode
+ * The DOMNode to check.
+ * @param array Selector->toArray()
+ * The Selector to check.
+ * @return boolean
+ * A boolean TRUE if the node matches, false otherwise.
+ */
+ public function matchesSelector($node, $selector) {
+ return $this->matchesSimpleSelector($node, $selector, 0);
+ }
+
+ /**
+ * Performs a match check on a SimpleSelector.
+ *
+ * Where matchesSelector() does a check on an entire selector,
+ * this checks only a simple selector (plus an optional
+ * combinator).
+ *
+ * @param object DOMNode
+ * The DOMNode to check.
+ * @param object SimpleSelector
+ * The Selector to check.
+ * @return boolean
+ * A boolean TRUE if the node matches, false otherwise.
+ */
+ public function matchesSimpleSelector($node, $selectors, $index) {
+ $selector = $selectors[$index];
+ // Note that this will short circuit as soon as one of these
+ // returns FALSE.
+ $result = $this->matchElement($node, $selector->element, $selector->ns)
+ && $this->matchAttributes($node, $selector->attributes)
+ && $this->matchId($node, $selector->id)
+ && $this->matchClasses($node, $selector->classes)
+ && $this->matchPseudoClasses($node, $selector->pseudoClasses)
+ && $this->matchPseudoElements($node, $selector->pseudoElements);
+
+ $isNextRule = isset($selectors[++$index]);
+ // If there is another selector, we process that if there a match
+ // hasn't been found.
+ /*
+ if ($isNextRule && $selectors[$index]->combinator == SimpleSelector::anotherSelector) {
+ // We may need to re-initialize the match set for the next selector.
+ if (!$this->initialized) {
+ $this->initialMatch($selectors[$index]);
+ }
+ if (!$result) fprintf(STDOUT, "Element: %s, Next selector: %s\n", $node->tagName, $selectors[$index]);
+ return $result || $this->matchesSimpleSelector($node, $selectors, $index);
+ }
+ // If we have a match and we have a combinator, we need to
+ // recurse up the tree.
+ else*/if ($isNextRule && $result) {
+ $result = $this->combine($node, $selectors, $index);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Combine the next selector with the given match
+ * using the next combinator.
+ *
+ * If the next selector is combined with another
+ * selector, that will be evaluated too, and so on.
+ * So if this function returns TRUE, it means that all
+ * child selectors are also matches.
+ *
+ * @param DOMNode $node
+ * The DOMNode to test.
+ * @param array $selectors
+ * The array of simple selectors.
+ * @param int $index
+ * The index of the current selector.
+ * @return boolean
+ * TRUE if the next selector(s) match.
+ */
+ public function combine($node, $selectors, $index) {
+ $selector = $selectors[$index];
+ //$this->debug(implode(' ', $selectors));
+ switch ($selector->combinator) {
+ case SimpleSelector::adjacent:
+ return $this->combineAdjacent($node, $selectors, $index);
+ case SimpleSelector::sibling:
+ return $this->combineSibling($node, $selectors, $index);
+ case SimpleSelector::directDescendant:
+ return $this->combineDirectDescendant($node, $selectors, $index);
+ case SimpleSelector::anyDescendant:
+ return $this->combineAnyDescendant($node, $selectors, $index);
+ case SimpleSelector::anotherSelector:
+ // fprintf(STDOUT, "Next selector: %s\n", $selectors[$index]);
+ return $this->matchesSimpleSelector($node, $selectors, $index);
+ ;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Process an Adjacent Sibling.
+ *
+ * The spec does not indicate whether Adjacent should ignore non-Element
+ * nodes, so we choose to ignore them.
+ *
+ * @param DOMNode $node
+ * A DOM Node.
+ * @param array $selectors
+ * The selectors array.
+ * @param int $index
+ * The current index to the operative simple selector in the selectors
+ * array.
+ * @return boolean
+ * TRUE if the combination matches, FALSE otherwise.
+ */
+ public function combineAdjacent($node, $selectors, $index) {
+ while (!empty($node->previousSibling)) {
+ $node = $node->previousSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE) {
+ //$this->debug(sprintf('Testing %s against "%s"', $node->tagName, $selectors[$index]));
+ return $this->matchesSimpleSelector($node, $selectors, $index);
+ }
+ }
+ return FALSE;
+ }
+
+ /**
+ * Check all siblings.
+ *
+ * According to the spec, this only tests elements LEFT of the provided
+ * node.
+ *
+ * @param DOMNode $node
+ * A DOM Node.
+ * @param array $selectors
+ * The selectors array.
+ * @param int $index
+ * The current index to the operative simple selector in the selectors
+ * array.
+ * @return boolean
+ * TRUE if the combination matches, FALSE otherwise.
+ */
+ public function combineSibling($node, $selectors, $index) {
+ while (!empty($node->previousSibling)) {
+ $node = $node->previousSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE && $this->matchesSimpleSelector($node, $selectors, $index)) {
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+
+ /**
+ * Handle a Direct Descendant combination.
+ *
+ * Check whether the given node is a rightly-related descendant
+ * of its parent node.
+ *
+ * @param DOMNode $node
+ * A DOM Node.
+ * @param array $selectors
+ * The selectors array.
+ * @param int $index
+ * The current index to the operative simple selector in the selectors
+ * array.
+ * @return boolean
+ * TRUE if the combination matches, FALSE otherwise.
+ */
+ public function combineDirectDescendant($node, $selectors, $index) {
+ $parent = $node->parentNode;
+ if (empty($parent)) {
+ return FALSE;
+ }
+ return $this->matchesSimpleSelector($parent, $selectors, $index);
+ }
+
+ /**
+ * Handle Any Descendant combinations.
+ *
+ * This checks to see if there are any matching routes from the
+ * selector beginning at the present node.
+ *
+ * @param DOMNode $node
+ * A DOM Node.
+ * @param array $selectors
+ * The selectors array.
+ * @param int $index
+ * The current index to the operative simple selector in the selectors
+ * array.
+ * @return boolean
+ * TRUE if the combination matches, FALSE otherwise.
+ */
+ public function combineAnyDescendant($node, $selectors, $index) {
+ while (!empty($node->parentNode)) {
+ $node = $node->parentNode;
+
+ // Catch case where element is child of something
+ // else. This should really only happen with a
+ // document element.
+ if ($node->nodeType != XML_ELEMENT_NODE) {
+ continue;
+ }
+
+ if ($this->matchesSimpleSelector($node, $selectors, $index)) {
+ return TRUE;
+ }
+ }
+ }
+
+ /**
+ * Get the intial match set.
+ *
+ * This should only be executed when not working with
+ * an existing match set.
+ */
+ protected function initialMatch($selector, $matches) {
+ $element = $selector->element;
+
+ // If no element is specified, we have to start with the
+ // entire document.
+ if ($element == NULL) {
+ $element = '*';
+ }
+
+ // fprintf(STDOUT, "Initial match using %s.\n", $selector);
+
+ // We try to do some optimization here to reduce the
+ // number of matches to the bare minimum. This will
+ // reduce the subsequent number of operations that
+ // must be performed in the query.
+
+ // Experimental: ID queries use XPath to match, since
+ // this should give us only a single matched element
+ // to work with.
+ if (/*$element == '*' &&*/ !empty($selector->id)) {
+ // fprintf(STDOUT, "ID Fastrack on %s\n", $selector);
+ $initialMatches = $this->initialMatchOnID($selector, $matches);
+ }
+ // If a namespace is set, find the namespace matches.
+ elseif (!empty($selector->ns)) {
+ $initialMatches = $this->initialMatchOnElementNS($selector, $matches);
+ }
+ // If the element is a wildcard, using class can
+ // substantially reduce the number of elements that
+ // we start with.
+ elseif ($element == '*' && !empty($selector->classes)) {
+ // fprintf(STDOUT, "Class Fastrack on %s\n", $selector);
+ $initialMatches = $this->initialMatchOnClasses($selector, $matches);
+ }
+ else {
+ $initialMatches = $this->initialMatchOnElement($selector, $matches);
+ }
+
+ //fprintf(STDOUT, "Found %d nodes.\n", count($this->matches));
+ return $initialMatches;
+ }
+
+ /**
+ * Shortcut for finding initial match by ID.
+ *
+ * If the element is set to '*' and an ID is
+ * set, then this should be used to find by ID,
+ * which will drastically reduce the amount of
+ * comparison operations done in PHP.
+ *
+ */
+ protected function initialMatchOnID($selector, $matches) {
+ $id = $selector->id;
+ $found = $this->newMatches();
+
+ // Issue #145: DOMXPath will through an exception if the DOM is
+ // not set.
+ if (!($this->dom instanceof \DOMDocument)) {
+ return $found;
+ }
+ $baseQuery = ".//*[@id='{$id}']";
+ $xpath = new \DOMXPath($this->dom);
+
+ // Now we try to find any matching IDs.
+ foreach ($matches as $node) {
+ if ($node->getAttribute('id') == $id) {
+ $found->attach($node);
+ }
+ $nl = $this->initialXpathQuery($xpath, $node, $baseQuery);
+ $this->attachNodeList($nl, $found);
+ }
+ // Unset the ID selector.
+ $selector->id = NULL;
+ return $found;
+ }
+
+ /**
+ * Shortcut for setting the intial match.
+ *
+ * This shortcut should only be used when the initial
+ * element is '*' and there are classes set.
+ *
+ * In any other case, the element finding algo is
+ * faster and should be used instead.
+ */
+ protected function initialMatchOnClasses($selector, $matches) {
+ $found = $this->newMatches();
+
+ // Issue #145: DOMXPath will through an exception if the DOM is
+ // not set.
+ if (!($this->dom instanceof \DOMDocument)) {
+ return $found;
+ }
+ $baseQuery = ".//*[@class]";
+ $xpath = new \DOMXPath($this->dom);
+
+ // Now we try to find any matching IDs.
+ foreach ($matches as $node) {
+ // Refactor me!
+ if ($node->hasAttribute('class')) {
+ $intersect = array_intersect($selector->classes, explode(' ', $node->getAttribute('class')));
+ if (count($intersect) == count($selector->classes)) {
+ $found->attach($node);
+ }
+ }
+
+ $nl = $this->initialXpathQuery($xpath, $node, $baseQuery);
+ foreach ($nl as $node) {
+ $classes = $node->getAttribute('class');
+ $classArray = explode(' ', $classes);
+
+ $intersect = array_intersect($selector->classes, $classArray);
+ if (count($intersect) == count($selector->classes)) {
+ $found->attach($node);
+ }
+ }
+ }
+
+ // Unset the classes selector.
+ $selector->classes = array();
+
+ return $found;
+ }
+
+ /**
+ * Internal xpath query.
+ *
+ * This is optimized for very specific use, and is not a general
+ * purpose function.
+ */
+ private function initialXpathQuery($xpath, $node, $query) {
+ // This works around a bug in which the document element
+ // does not correctly search with the $baseQuery.
+ if ($node->isSameNode($this->dom->documentElement)) {
+ $query = substr($query, 1);
+ }
+
+ return $xpath->query($query, $node);
+ }
+
+ /**
+ * Shortcut for setting the initial match.
+ */
+ protected function initialMatchOnElement($selector, $matches) {
+ $element = $selector->element;
+ if (is_null($element)) {
+ $element = '*';
+ }
+ $found = $this->newMatches();
+ foreach ($matches as $node) {
+ // Capture the case where the initial element is the root element.
+ if ($node->tagName == $element
+ || $element == '*' && $node->parentNode instanceof \DOMDocument) {
+ $found->attach($node);
+ }
+ $nl = $node->getElementsByTagName($element);
+ $this->attachNodeList($nl, $found);
+ }
+
+ $selector->element = NULL;
+ return $found;
+ }
+
+ /**
+ * Get elements and filter by namespace.
+ */
+ protected function initialMatchOnElementNS($selector, $matches) {
+ $ns = $selector->ns;
+
+ $elements = $this->initialMatchOnElement($selector, $matches);
+
+ // "any namespace" matches anything.
+ if ($ns == '*') {
+ return $elements;
+ }
+
+ // Loop through and make a list of items that need to be filtered
+ // out, then filter them. This is required b/c ObjectStorage iterates
+ // wrongly when an item is detached in an access loop.
+ $detach = array();
+ foreach ($elements as $node) {
+ // This lookup must be done PER NODE.
+ $nsuri = $node->lookupNamespaceURI($ns);
+ if (empty($nsuri) || $node->namespaceURI != $nsuri) {
+ $detach[] = $node;
+ }
+ }
+ foreach ($detach as $rem) {
+ $elements->detach($rem);
+ }
+ $selector->ns = NULL;
+ return $elements;
+ }
+
+ /**
+ * Checks to see if the DOMNode matches the given element selector.
+ *
+ * This handles the following cases:
+ *
+ * - element (foo)
+ * - namespaced element (ns|foo)
+ * - namespaced wildcard (ns|*)
+ * - wildcard (* or *|*)
+ */
+ protected function matchElement($node, $element, $ns = NULL) {
+ if (empty($element)) {
+ return TRUE;
+ }
+
+ // Handle namespace.
+ if (!empty($ns) && $ns != '*') {
+ // Check whether we have a matching NS URI.
+ $nsuri = $node->lookupNamespaceURI($ns);
+ if(empty($nsuri) || $node->namespaceURI !== $nsuri) {
+ return FALSE;
+ }
+ }
+
+ // Compare local name to given element name.
+ return $element == '*' || $node->localName == $element;
+ }
+
+ /**
+ * Checks to see if the given DOMNode matches an "any element" (*).
+ *
+ * This does not handle namespaced whildcards.
+ */
+ /*
+ protected function matchAnyElement($node) {
+ $ancestors = $this->ancestors($node);
+
+ return count($ancestors) > 0;
+ }
+ */
+
+ /**
+ * Get a list of ancestors to the present node.
+ */
+ protected function ancestors($node) {
+ $buffer = array();
+ $parent = $node;
+ while (($parent = $parent->parentNode) !== NULL) {
+ $buffer[] = $parent;
+ }
+ return $buffer;
+ }
+
+ /**
+ * Check to see if DOMNode has all of the given attributes.
+ *
+ * This can handle namespaced attributes, including namespace
+ * wildcards.
+ */
+ protected function matchAttributes($node, $attributes) {
+ if (empty($attributes)) {
+ return TRUE;
+ }
+
+ foreach($attributes as $attr) {
+ $val = isset($attr['value']) ? $attr['value'] : NULL;
+
+ // Namespaced attributes.
+ if (isset($attr['ns']) && $attr['ns'] != '*') {
+ $nsuri = $node->lookupNamespaceURI($attr['ns']);
+ if (empty($nsuri) || !$node->hasAttributeNS($nsuri, $attr['name'])) {
+ return FALSE;
+ }
+ $matches = Util::matchesAttributeNS($node, $attr['name'], $nsuri, $val, $attr['op']);
+ }
+ elseif (isset($attr['ns']) && $attr['ns'] == '*' && $node->hasAttributes()) {
+ // Cycle through all of the attributes in the node. Note that
+ // these are DOMAttr objects.
+ $matches = FALSE;
+ $name = $attr['name'];
+ foreach ($node->attributes as $attrNode) {
+ if ($attrNode->localName == $name) {
+ $nsuri = $attrNode->namespaceURI;
+ $matches = Util::matchesAttributeNS($node, $name, $nsuri, $val, $attr['op']);
+ }
+ }
+ }
+ // No namespace.
+ else {
+ $matches = Util::matchesAttribute($node, $attr['name'], $val, $attr['op']);
+ }
+
+ if (!$matches) {
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+ /**
+ * Check that the given DOMNode has the given ID.
+ */
+ protected function matchId($node, $id) {
+ if (empty($id)) {
+ return TRUE;
+ }
+ return $node->hasAttribute('id') && $node->getAttribute('id') == $id;
+ }
+ /**
+ * Check that the given DOMNode has all of the given classes.
+ */
+ protected function matchClasses($node, $classes) {
+ if (empty($classes)) {
+ return TRUE;
+ }
+
+ if (!$node->hasAttribute('class')) {
+ return FALSE;
+ }
+
+ $eleClasses = preg_split('/\s+/', $node->getAttribute('class'));
+ if (empty($eleClasses)) {
+ return FALSE;
+ }
+
+ // The intersection should match the given $classes.
+ $missing = array_diff($classes, array_intersect($classes, $eleClasses));
+
+ return count($missing) == 0;
+ }
+ protected function matchPseudoClasses($node, $pseudoClasses) {
+ $ret = TRUE;
+ foreach ($pseudoClasses as $pseudoClass) {
+ $name = $pseudoClass['name'];
+ // Avoid E_STRICT violation.
+ $value = isset($pseudoClass['value']) ? $pseudoClass['value'] : NULL;
+ $ret &= $this->psHandler->elementMatches($name, $node, $this->scopeNode, $value);
+ }
+ return $ret;
+ }
+ /**
+ * Test whether the given node matches the pseudoElements.
+ *
+ * If any pseudo-elements are passed, this will test to see
+ * <i>if conditions obtain that would allow the pseudo-element
+ * to be created</i>. This does not modify the match in any way.
+ */
+ protected function matchPseudoElements($node, $pseudoElements) {
+ if (empty($pseudoElements)) {
+ return TRUE;
+ }
+
+ foreach ($pseudoElements as $pse) {
+ switch ($pse) {
+ case 'first-line':
+ case 'first-letter':
+ case 'before':
+ case 'after':
+ return strlen($node->textContent) > 0;
+ case 'selection':
+ throw new \QueryPath\CSS\NotImplementedException("::$name is not implemented.");
+ }
+ }
+ }
+
+ protected function newMatches() {
+ return new \SplObjectStorage();
+ }
+
+ /**
+ * Get the internal match set.
+ * Internal utility function.
+ */
+ protected function getMatches() {
+ return $this->matches();
+ }
+
+ /**
+ * Set the internal match set.
+ *
+ * Internal utility function.
+ */
+ protected function setMatches($matches) {
+ $this->matches = $matches;
+ }
+
+ /**
+ * Attach all nodes in a node list to the given \SplObjectStorage.
+ */
+ public function attachNodeList(\DOMNodeList $nodeList, \SplObjectStorage $splos) {
+ foreach ($nodeList as $item) $splos->attach($item);
+ }
+
+ public function getDocument() {
+ return $this->dom;
+ }
+
+}
diff --git a/lib/querypath/src/QueryPath/CSS/DOMTraverser/PseudoClass.php b/lib/querypath/src/QueryPath/CSS/DOMTraverser/PseudoClass.php
new file mode 100644
index 0000000..0bcaf79
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/DOMTraverser/PseudoClass.php
@@ -0,0 +1,421 @@
+<?php
+/**
+ * @file
+ *
+ * PseudoClass class.
+ *
+ * This is the first pass in an experiment to break PseudoClass handling
+ * out of the normal traversal. Eventually, this should become a
+ * top-level pluggable registry that will allow custom pseudoclasses.
+ * For now, though, we just handle the core pseudoclasses.
+ */
+namespace QueryPath\CSS\DOMTraverser;
+
+use \QueryPath\CSS\NotImplementedException;
+use \QueryPath\CSS\EventHandler;
+/**
+ * The PseudoClass handler.
+ *
+ */
+class PseudoClass {
+
+ /**
+ * Tests whether the given element matches the given pseudoclass.
+ *
+ * @param string $pseudoclass
+ * The string name of the pseudoclass
+ * @param resource $node
+ * The DOMNode to be tested.
+ * @param resource $scope
+ * The DOMElement that is the active root for this node.
+ * @param mixed $value
+ * The optional value string provided with this class. This is
+ * used, for example, in an+b psuedoclasses.
+ * @retval boolean
+ * TRUE if the node matches, FALSE otherwise.
+ */
+ public function elementMatches($pseudoclass, $node, $scope, $value = NULL) {
+ $name = strtolower($pseudoclass);
+ // Need to handle known pseudoclasses.
+ switch($name) {
+ case 'current':
+ case 'past':
+ case 'future':
+ case 'visited':
+ case 'hover':
+ case 'active':
+ case 'focus':
+ case 'animated': // Last 3 are from jQuery
+ case 'visible':
+ case 'hidden':
+ // These require a UA, which we don't have.
+ case 'valid':
+ case 'invalid':
+ case 'required':
+ case 'optional':
+ case 'read-only':
+ case 'read-write':
+ // Since we don't know how to validate elements,
+ // we can't supply these.
+ case 'dir':
+ // FIXME: I don't know how to get directionality info.
+ case 'nth-column':
+ case 'nth-last-column':
+ // We don't know what a column is in most documents.
+ // FIXME: Can we do this for HTML?
+ case 'target':
+ // This requires a location URL, which we don't have.
+ return FALSE;
+ case 'indeterminate':
+ // Because sometimes screwing with people is fun.
+ return (boolean) mt_rand(0, 1);
+ case 'lang':
+ // No value = exception.
+ if (!isset($value)) {
+ throw new NotImplementedException(":lang() requires a value.");
+ }
+ return $this->lang($node, $value);
+ case 'any-link':
+ return Util::matchesAttribute($node, 'href')
+ || Util::matchesAttribute($node, 'src')
+ || Util::matchesAttribute($node, 'link');
+ case 'link':
+ return Util::matchesAttribute($node, 'href');
+ case 'local-link':
+ return $this->isLocalLink($node);
+ case 'root':
+ return $node->isSameNode($node->ownerDocument->documentElement);
+
+ // CSS 4 declares the :scope pseudo-class, which describes what was
+ // the :x-root QueryPath extension.
+ case 'x-root':
+ case 'x-reset':
+ case 'scope':
+ return $node->isSameNode($scope);
+ // NON-STANDARD extensions for simple support of even and odd. These
+ // are supported by jQuery, FF, and other user agents.
+ case 'even':
+ return $this->isNthChild($node, 'even');
+ case 'odd':
+ return $this->isNthChild($node, 'odd');
+ case 'nth-child':
+ return $this->isNthChild($node, $value);
+ case 'nth-last-child':
+ return $this->isNthChild($node, $value, TRUE);
+ case 'nth-of-type':
+ return $this->isNthChild($node, $value, FALSE, TRUE);
+ case 'nth-last-of-type':
+ return $this->isNthChild($node, $value, TRUE, TRUE);
+ case 'first-of-type':
+ return $this->isFirstOfType($node);
+ case 'last-of-type':
+ return $this->isLastOfType($node);
+ case 'only-of-type':
+ return $this->isFirstOfType($node) && $this->isLastOfType($node);
+
+ // Additional pseudo-classes defined in jQuery:
+ case 'lt':
+ // I'm treating this as "less than or equal to".
+ $rule = sprintf('-n + %d', (int) $value);
+ // $rule = '-n+15';
+ return $this->isNthChild($node, $rule);
+ case 'gt':
+ // I'm treating this as "greater than"
+ // return $this->nodePositionFromEnd($node) > (int) $value;
+ return $this->nodePositionFromStart($node) > (int) $value;
+ case 'nth':
+ case 'eq':
+ $rule = (int)$value;
+ return $this->isNthChild($node, $rule);
+ case 'first':
+ return $this->isNthChild($node, 1);
+ case 'first-child':
+ return $this->isFirst($node);
+ case 'last':
+ case 'last-child':
+ return $this->isLast($node);
+ case 'only-child':
+ return $this->isFirst($node) && $this->isLast($node);
+ case 'empty':
+ return $this->isEmpty($node);
+ case 'parent':
+ return !$this->isEmpty($node);
+
+ case 'enabled':
+ case 'disabled':
+ case 'checked':
+ return Util::matchesAttribute($node, $name);
+ case 'text':
+ case 'radio':
+ case 'checkbox':
+ case 'file':
+ case 'password':
+ case 'submit':
+ case 'image':
+ case 'reset':
+ case 'button':
+ return Util::matchesAttribute($node, 'type', $name);
+
+ case 'header':
+ return $this->header($node);
+ case 'has':
+ case 'matches':
+ return $this->has($node, $value);
+ break;
+ case 'not':
+ if (empty($value)) {
+ throw new ParseException(":not() requires a value.");
+ }
+ return $this->isNot($node, $value);
+ // Contains == text matches.
+ // In QP 2.1, this was changed.
+ case 'contains':
+ return $this->contains($node, $value);
+ // Since QP 2.1
+ case 'contains-exactly':
+ return $this->containsExactly($node, $value);
+ default:
+ throw new \QueryPath\CSS\ParseException("Unknown Pseudo-Class: " . $name);
+ }
+ $this->findAnyElement = FALSE;
+ }
+
+ /**
+ * Pseudo-class handler for :lang
+ *
+ * Note that this does not implement the spec in its entirety because we do
+ * not presume to "know the language" of the document. If anyone is interested
+ * in making this more intelligent, please do so.
+ */
+ protected function lang($node, $value) {
+ // TODO: This checks for cases where an explicit language is
+ // set. The spec seems to indicate that an element should inherit
+ // language from the parent... but this is unclear.
+ $operator = (strpos($value, '-') !== FALSE) ? EventHandler::isExactly : EventHandler::containsWithHyphen;
+
+ $match = TRUE;
+ foreach ($node->attributes as $attrNode) {
+ if ($attrNode->localName == 'lang') {
+
+ if ($attrNode->nodeName == $attrNode->localName) {
+ // fprintf(STDOUT, "%s in NS %s\n", $attrNode->name, $attrNode->nodeName);
+ return Util::matchesAttribute($node, 'lang', $value, $operator);
+ }
+ else {
+ $nsuri = $attrNode->namespaceURI;
+ // fprintf(STDOUT, "%s in NS %s\n", $attrNode->name, $nsuri);
+ return Util::matchesAttributeNS($node, 'lang', $nsuri, $value, $operator);
+ }
+
+ }
+ }
+ return FALSE;
+ }
+
+ /**
+ * Provides jQuery pseudoclass ':header'.
+ */
+ protected function header($node) {
+ return preg_match('/^h[1-9]$/i', $node->tagName) == 1;
+ }
+
+ /**
+ * Provides pseudoclass :empty.
+ */
+ protected function isEmpty($node) {
+ foreach ($node->childNodes as $kid) {
+ // We don't want to count PIs and comments. From the spec, it
+ // appears that CDATA is also not counted.
+ if ($kid->nodeType == XML_ELEMENT_NODE || $kid->nodeType == XML_TEXT_NODE) {
+ // As soon as we hit a FALSE, return.
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+
+ /**
+ * Provides jQuery pseudoclass :first.
+ *
+ * @todo
+ * This can be replaced by isNthChild().
+ */
+ protected function isFirst($node) {
+ while (isset($node->previousSibling)) {
+ $node = $node->previousSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE) {
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+ /**
+ * Fast version of first-of-type.
+ */
+ protected function isFirstOfType($node) {
+ $type = $node->tagName;
+ while (isset($node->previousSibling)) {
+ $node = $node->previousSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE && $node->tagName == $type) {
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+ /**
+ * Fast version of jQuery :last.
+ */
+ protected function isLast($node) {
+ while (isset($node->nextSibling)) {
+ $node = $node->nextSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE) {
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+ /**
+ * Provides last-of-type.
+ */
+ protected function isLastOfType($node) {
+ $type = $node->tagName;
+ while (isset($node->nextSibling)) {
+ $node = $node->nextSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE && $node->tagName == $type) {
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+ /**
+ * Provides :contains() as the original spec called for.
+ *
+ * This is an INEXACT match.
+ */
+ protected function contains($node, $value) {
+ $text = $node->textContent;
+ $value = Util::removeQuotes($value);
+ return isset($text) && (stripos($text, $value) !== FALSE);
+ }
+ /**
+ * Provides :contains-exactly QueryPath pseudoclass.
+ *
+ * This is an EXACT match.
+ */
+ protected function containsExactly($node, $value) {
+ $text = $node->textContent;
+ $value = Util::removeQuotes($value);
+ return isset($text) && $text == $value;
+ }
+
+ /**
+ * Provides :has pseudoclass.
+ */
+ protected function has($node, $selector) {
+ $splos = new \SPLObjectStorage();
+ $splos->attach($node);
+ $traverser = new \QueryPath\CSS\DOMTraverser($splos, TRUE);
+ $results = $traverser->find($selector)->matches();
+ return count($results) > 0;
+ }
+
+ /**
+ * Provides :not pseudoclass.
+ */
+ protected function isNot($node, $selector) {
+ return !$this->has($node, $selector);
+ }
+
+ /**
+ * Get the relative position of a node in its sibling set.
+ */
+ protected function nodePositionFromStart($node, $byType = FALSE) {
+ $i = 1;
+ $tag = $node->tagName;
+ while (isset($node->previousSibling)) {
+ $node = $node->previousSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE && (!$byType || $node->tagName == $tag)) {
+ ++$i;
+ }
+ }
+ return $i;
+ }
+ /**
+ * Get the relative position of a node in its sibling set.
+ */
+ protected function nodePositionFromEnd($node, $byType = FALSE) {
+ $i = 1;
+ $tag = $node->tagName;
+ while (isset($node->nextSibling)) {
+ $node = $node->nextSibling;
+ if ($node->nodeType == XML_ELEMENT_NODE && (!$byType || $node->tagName == $tag)) {
+ ++$i;
+ }
+ }
+ return $i;
+ }
+
+ /**
+ * Provides functionality for all "An+B" rules.
+ * Provides nth-child and also the functionality required for:
+ *
+ *- nth-last-child
+ *- even
+ *- odd
+ *- first
+ *- last
+ *- eq
+ *- nth
+ *- nth-of-type
+ *- first-of-type
+ *- last-of-type
+ *- nth-last-of-type
+ *
+ * See also QueryPath::CSS::DOMTraverser::Util::parseAnB().
+ */
+ protected function isNthChild($node, $value, $reverse = FALSE, $byType = FALSE) {
+ list($groupSize, $elementInGroup) = Util::parseAnB($value);
+ $parent = $node->parentNode;
+ if (empty($parent)
+ || ($groupSize == 0 && $elementInGroup == 0)
+ || ($groupSize > 0 && $elementInGroup > $groupSize)
+ ) {
+ return FALSE;
+ }
+
+ // First we need to find the position of $node in other elements.
+ if ($reverse) {
+ $pos = $this->nodePositionFromEnd($node, $byType);
+ }
+ else {
+ $pos = $this->nodePositionFromStart($node, $byType);
+ }
+
+ // If group size is 0, we just check to see if this
+ // is the nth element:
+ if ($groupSize == 0) {
+ return $pos == $elementInGroup;
+ }
+
+ // Next, we normalize $elementInGroup
+ if ($elementInGroup < 0) {
+ $elementInGroup = $groupSize + $elementInGroup;
+ }
+
+
+ $prod = ($pos - $elementInGroup) / $groupSize;
+ // fprintf(STDOUT, "%d n + %d on %d is %3.5f\n", $groupSize, $elementInGroup, $pos, $prod);
+
+ return is_int($prod) && $prod >= 0;
+ }
+
+ protected function isLocalLink($node) {
+ if (!$node->hasAttribute('href')) {
+ return FALSE;
+ }
+ $url = $node->getAttribute('href');
+ $scheme = parse_url($url, PHP_URL_SCHEME);
+ return empty($scheme) || $scheme == 'file';
+ }
+
+}
diff --git a/lib/querypath/src/QueryPath/CSS/DOMTraverser/Util.php b/lib/querypath/src/QueryPath/CSS/DOMTraverser/Util.php
new file mode 100644
index 0000000..ec01d8f
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/DOMTraverser/Util.php
@@ -0,0 +1,139 @@
+<?php
+/**
+ * @file
+ *
+ * Utilities for DOM traversal.
+ */
+namespace QueryPath\CSS\DOMTraverser;
+
+use \QueryPath\CSS\EventHandler;
+
+/**
+ * Utilities for DOM Traversal.
+ */
+class Util {
+
+ /**
+ * Check whether the given DOMElement has the given attribute.
+ */
+ public static function matchesAttribute($node, $name, $value = NULL, $operation = EventHandler::isExactly) {
+ if (!$node->hasAttribute($name)) {
+ return FALSE;
+ }
+
+ if (is_null($value)) {
+ return TRUE;
+ }
+
+ return self::matchesAttributeValue($value, $node->getAttribute($name), $operation);
+ }
+ /**
+ * Check whether the given DOMElement has the given namespaced attribute.
+ */
+ public static function matchesAttributeNS($node, $name, $nsuri, $value = NULL, $operation = EventHandler::isExactly) {
+ if (!$node->hasAttributeNS($nsuri, $name)) {
+ return FALSE;
+ }
+
+ if (is_null($value)) {
+ return TRUE;
+ }
+
+ return self::matchesAttributeValue($value, $node->getAttributeNS($nsuri, $name), $operation);
+ }
+
+ /**
+ * Check for attr value matches based on an operation.
+ */
+ public static function matchesAttributeValue($needle, $haystack, $operation) {
+
+ if (strlen($haystack) < strlen($needle)) return FALSE;
+
+ // According to the spec:
+ // "The case-sensitivity of attribute names in selectors depends on the document language."
+ // (6.3.2)
+ // To which I say, "huh?". We assume case sensitivity.
+ switch ($operation) {
+ case EventHandler::isExactly:
+ return $needle == $haystack;
+ case EventHandler::containsWithSpace:
+ // XXX: This needs testing!
+ return preg_match('/\b/', $haystack) == 1;
+ //return in_array($needle, explode(' ', $haystack));
+ case EventHandler::containsWithHyphen:
+ return in_array($needle, explode('-', $haystack));
+ case EventHandler::containsInString:
+ return strpos($haystack, $needle) !== FALSE;
+ case EventHandler::beginsWith:
+ return strpos($haystack, $needle) === 0;
+ case EventHandler::endsWith:
+ //return strrpos($haystack, $needle) === strlen($needle) - 1;
+ return preg_match('/' . $needle . '$/', $haystack) == 1;
+ }
+ return FALSE; // Shouldn't be able to get here.
+ }
+
+ /**
+ * Remove leading and trailing quotes.
+ */
+ public static function removeQuotes($str) {
+ $f = substr($str, 0, 1);
+ $l = substr($str, -1);
+ if ($f === $l && ($f == '"' || $f == "'")) {
+ $str = substr($str, 1, -1);
+ }
+ return $str;
+ }
+
+ /**
+ * Parse an an+b rule for CSS pseudo-classes.
+ *
+ * Invalid rules return `array(0, 0)`. This is per the spec.
+ *
+ * @param $rule
+ * Some rule in the an+b format.
+ * @retval array
+ * `array($aVal, $bVal)` of the two values.
+ */
+ public static function parseAnB($rule) {
+ if ($rule == 'even') {
+ return array(2, 0);
+ }
+ elseif ($rule == 'odd') {
+ return array(2, 1);
+ }
+ elseif ($rule == 'n') {
+ return array(1, 0);
+ }
+ elseif (is_numeric($rule)) {
+ return array(0, (int)$rule);
+ }
+
+ $regex = '/^\s*([+\-]?[0-9]*)n\s*([+\-]?)\s*([0-9]*)\s*$/';
+ $matches = array();
+ $res = preg_match($regex, $rule, $matches);
+
+ // If it doesn't parse, return 0, 0.
+ if (!$res) {
+ return array(0, 0);
+ }
+
+ $aVal = isset($matches[1]) ? $matches[1] : 1;
+ if ($aVal == '-') {
+ $aVal = -1;
+ }
+ else {
+ $aVal = (int) $aVal;
+ }
+
+ $bVal = 0;
+ if (isset($matches[3])) {
+ $bVal = (int) $matches[3];
+ if (isset($matches[2]) && $matches[2] == '-') {
+ $bVal *= -1;
+ }
+ }
+ return array($aVal, $bVal);
+ }
+
+}
diff --git a/lib/querypath/src/QueryPath/CSS/EventHandler.php b/lib/querypath/src/QueryPath/CSS/EventHandler.php
new file mode 100644
index 0000000..a003a0a
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/EventHandler.php
@@ -0,0 +1,171 @@
+<?php
+/** @file
+ * CSS selector parsing classes.
+ *
+ * This file contains the tools necessary for parsing CSS 3 selectors.
+ * In the future it may be expanded to handle all of CSS 3.
+ *
+ * The parser contained herein is has an event-based API. Implementors should
+ * begin by implementing the {@link EventHandler} interface. For an example
+ * of how this is done, see {@link EventHandler.php}.
+ *
+ * @author M Butcher <matt@aleph-null.tv>
+ * @license MIT
+ */
+namespace QueryPath\CSS;
+
+/** @addtogroup querypath_css CSS Parsing
+ * QueryPath includes a CSS 3 Selector parser.
+ *
+ *
+ * Typically the parser is not accessed directly. Most developers will use it indirectly from
+ * qp(), htmlqp(), or one of the methods on a QueryPath object.
+ *
+ * This parser is modular and is not tied to QueryPath, so you can use it in your
+ * own (non-QueryPath) projects if you wish. To dive in, start with EventHandler, the
+ * event interface that works like a SAX API for CSS selectors. If you want to check out
+ * the details, check out the parser (QueryPath::CSS::Parser), scanner
+ * (QueryPath::CSS::Scanner), and token list (QueryPath::CSS::Token).
+ */
+
+/**
+ * An event handler for handling CSS 3 Selector parsing.
+ *
+ * This provides a standard interface for CSS 3 Selector event handling. As the
+ * parser parses a selector, it will fire events. Implementations of EventHandler
+ * can then handle the events.
+ *
+ * This library is inspired by the SAX2 API for parsing XML. Each component of a
+ * selector fires an event, passing the necessary data on to the event handler.
+ *
+ * @ingroup querypath_css
+ */
+interface EventHandler {
+ /** The is-exactly (=) operator. */
+ const isExactly = 0; // =
+ /** The contains-with-space operator (~=). */
+ const containsWithSpace = 1; // ~=
+ /** The contains-with-hyphen operator (!=). */
+ const containsWithHyphen = 2; // |=
+ /** The contains-in-string operator (*=). */
+ const containsInString = 3; // *=
+ /** The begins-with operator (^=). */
+ const beginsWith = 4; // ^=
+ /** The ends-with operator ($=). */
+ const endsWith = 5; // $=
+ /** The any-element operator (*). */
+ const anyElement = '*';
+
+ /**
+ * This event is fired when a CSS ID is encountered.
+ * An ID begins with an octothorp: #name.
+ *
+ * @param string $id
+ * The ID passed in.
+ */
+ public function elementID($id); // #name
+ /**
+ * Handle an element name.
+ * Example: name
+ * @param string $name
+ * The name of the element.
+ */
+ public function element($name); // name
+ /**
+ * Handle a namespaced element name.
+ * example: namespace|name
+ * @param string $name
+ * The tag name.
+ * @param string $namespace
+ * The namespace identifier (Not the URI)
+ */
+ public function elementNS($name, $namespace = NULL);
+ /**
+ * Handle an any-element (*) operator.
+ * Example: *
+ */
+ public function anyElement(); // *
+ /**
+ * Handle an any-element operator that is constrained to a namespace.
+ * Example: ns|*
+ * @param string $ns
+ * The namespace identifier (not the URI).
+ */
+ public function anyElementInNS($ns); // ns|*
+ /**
+ * Handle a CSS class selector.
+ * Example: .name
+ * @param string $name
+ * The name of the class.
+ */
+ public function elementClass($name); // .name
+ /**
+ * Handle an attribute selector.
+ * Example: [name=attr]
+ * Example: [name~=attr]
+ * @param string $name
+ * The attribute name.
+ * @param string $value
+ * The value of the attribute, if given.
+ * @param int $operation
+ * The operation to be used for matching. See {@link EventHandler}
+ * constants for a list of supported operations.
+ */
+ public function attribute($name, $value = NULL, $operation = EventHandler::isExactly); // [name=attr]
+ /**
+ * Handle an attribute selector bound to a specific namespace.
+ * Example: [ns|name=attr]
+ * Example: [ns|name~=attr]
+ * @param string $name
+ * The attribute name.
+ * @param string $ns
+ * The namespace identifier (not the URI).
+ * @param string $value
+ * The value of the attribute, if given.
+ * @param int $operation
+ * The operation to be used for matching. See {@link EventHandler}
+ * constants for a list of supported operations.
+ */
+ public function attributeNS($name, $ns, $value = NULL, $operation = EventHandler::isExactly);
+ /**
+ * Handle a pseudo-class.
+ * Example: :name(value)
+ * @param string $name
+ * The pseudo-class name.
+ * @param string $value
+ * The value, if one is found.
+ */
+ public function pseudoClass($name, $value = NULL); //:name(value)
+ /**
+ * Handle a pseudo-element.
+ * Example: ::name
+ * @param string $name
+ * The pseudo-element name.
+ */
+ public function pseudoElement($name); // ::name
+ /**
+ * Handle a direct descendant combinator.
+ * Example: >
+ */
+ public function directDescendant(); // >
+ /**
+ * Handle a adjacent combinator.
+ * Example: +
+ */
+ public function adjacent(); // +
+ /**
+ * Handle an another-selector combinator.
+ * Example: ,
+ */
+ public function anotherSelector(); // ,
+ /**
+ * Handle a sibling combinator.
+ * Example: ~
+ */
+ public function sibling(); // ~ combinator
+ /**
+ * Handle an any-descendant combinator.
+ * Example: ' '
+ */
+ public function anyDescendant(); // ' ' (space) operator.
+}
diff --git a/lib/querypath/src/QueryPath/CSS/InputStream.php b/lib/querypath/src/QueryPath/CSS/InputStream.php
new file mode 100644
index 0000000..2967845
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/InputStream.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * @file
+ *
+ * The CSS Input Stream abstraction.
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * Simple wrapper to turn a string into an input stream.
+ * This provides a standard interface on top of an array of
+ * characters.
+ */
+class InputStream {
+ protected $stream = NULL;
+ public $position = 0;
+ /**
+ * Build a new CSS input stream from a string.
+ *
+ * @param string
+ * String to turn into an input stream.
+ */
+ function __construct($string) {
+ $this->stream = str_split($string);
+ }
+ /**
+ * Look ahead one character.
+ *
+ * @return char
+ * Returns the next character, but does not remove it from
+ * the stream.
+ */
+ function peek() {
+ return $this->stream[0];
+ }
+ /**
+ * Get the next unconsumed character in the stream.
+ * This will remove that character from the front of the
+ * stream and return it.
+ */
+ function consume() {
+ $ret = array_shift($this->stream);
+ if (!empty($ret)) {
+ $this->position++;
+ }
+ return $ret;
+ }
+ /**
+ * Check if the stream is empty.
+ * @return boolean
+ * Returns TRUE when the stream is empty, FALSE otherwise.
+ */
+ function isEmpty() {
+ return count($this->stream) == 0;
+ }
+}
diff --git a/lib/querypath/src/QueryPath/CSS/NotImplementedException.php b/lib/querypath/src/QueryPath/CSS/NotImplementedException.php
new file mode 100644
index 0000000..6705f30
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/NotImplementedException.php
@@ -0,0 +1,15 @@
+<?php
+/**
+ * @file
+ * An exception for CSS errors.
+ */
+namespace QueryPath\CSS;
+/**
+ * Exception thrown for unimplemented CSS.
+ *
+ * This is thrown in cases where some feature is expected, but the current
+ * implementation does not support that feature.
+ *
+ * @ingroup querypath_css
+ */
+class NotImplementedException extends \Exception {}
diff --git a/lib/querypath/src/QueryPath/CSS/ParseException.php b/lib/querypath/src/QueryPath/CSS/ParseException.php
new file mode 100644
index 0000000..957857a
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/ParseException.php
@@ -0,0 +1,15 @@
+<?php
+/**
+ * @file
+ *
+ * The CSS parsing exception class.
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * Exception indicating an error in CSS parsing.
+ *
+ * @ingroup querypath_css
+ */
+class ParseException extends \QueryPath\Exception {}
diff --git a/lib/querypath/src/QueryPath/CSS/Parser.php b/lib/querypath/src/QueryPath/CSS/Parser.php
new file mode 100644
index 0000000..f041612
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/Parser.php
@@ -0,0 +1,575 @@
+<?php
+/**
+ * @file
+ *
+ * The CSS parser
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * Parse a CSS selector.
+ *
+ * In CSS, a selector is used to identify which element or elements
+ * in a DOM are being selected for the application of a particular style.
+ * Effectively, selectors function as a query language for a structured
+ * document -- almost always HTML or XML.
+ *
+ * This class provides an event-based parser for CSS selectors. It can be
+ * used, for example, as a basis for writing a DOM query engine based on
+ * CSS.
+ *
+ * @ingroup querypath_css
+ */
+class Parser {
+ protected $scanner = NULL;
+ protected $buffer = '';
+ protected $handler = NULL;
+ protected $strict = FALSE;
+
+ protected $DEBUG = FALSE;
+
+ /**
+ * Construct a new CSS parser object. This will attempt to
+ * parse the string as a CSS selector. As it parses, it will
+ * send events to the EventHandler implementation.
+ */
+ public function __construct($string, EventHandler $handler) {
+ $this->originalString = $string;
+ $is = new InputStream($string);
+ $this->scanner = new Scanner($is);
+ $this->handler = $handler;
+ }
+
+ /**
+ * Parse the selector.
+ *
+ * This begins an event-based parsing process that will
+ * fire events as the selector is handled. A EventHandler
+ * implementation will be responsible for handling the events.
+ * @throws ParseException
+ */
+ public function parse() {
+
+ $this->scanner->nextToken();
+ while ($this->scanner->token !== FALSE) {
+ // Primitive recursion detection.
+ $position = $this->scanner->position();
+
+ if ($this->DEBUG) {
+ print "PARSE " . $this->scanner->token. "\n";
+ }
+ $this->selector();
+
+ $finalPosition = $this->scanner->position();
+
+ if ($this->scanner->token !== FALSE && $finalPosition == $position) {
+ // If we get here, then the scanner did not pop a single character
+ // off of the input stream during a full run of the parser, which
+ // means that the current input does not match any recognizable
+ // pattern.
+ throw new ParseException('CSS selector is not well formed.');
+ }
+
+ }
+
+ }
+
+ /**
+ * A restricted parser that can only parse simple selectors.
+ * The pseudoClass handler for this parser will throw an
+ * exception if it encounters a pseudo-element or the
+ * negation pseudo-class.
+ *
+ * @deprecated This is not used anywhere in QueryPath and
+ * may be removed.
+ *//*
+ public function parseSimpleSelector() {
+ while ($this->scanner->token !== FALSE) {
+ if ($this->DEBUG) print "SIMPLE SELECTOR\n";
+ $this->allElements();
+ $this->elementName();
+ $this->elementClass();
+ $this->elementID();
+ $this->pseudoClass(TRUE); // Operate in restricted mode.
+ $this->attribute();
+
+ // TODO: Need to add failure conditions here.
+ }
+ }*/
+
+ /**
+ * Handle an entire CSS selector.
+ */
+ private function selector() {
+ if ($this->DEBUG) print "SELECTOR{$this->scanner->position()}\n";
+ $this->consumeWhitespace(); // Remove leading whitespace
+ $this->simpleSelectors();
+ $this->combinator();
+ }
+
+ /**
+ * Consume whitespace and return a count of the number of whitespace consumed.
+ */
+ private function consumeWhitespace() {
+ if ($this->DEBUG) print "CONSUME WHITESPACE\n";
+ $white = 0;
+ while ($this->scanner->token == Token::white) {
+ $this->scanner->nextToken();
+ ++$white;
+ }
+ return $white;
+ }
+
+ /**
+ * Handle one of the five combinators: '>', '+', ' ', '~', and ','.
+ * This will call the appropriate event handlers.
+ * @see EventHandler::directDescendant(),
+ * @see EventHandler::adjacent(),
+ * @see EventHandler::anyDescendant(),
+ * @see EventHandler::anotherSelector().
+ */
+ private function combinator() {
+ if ($this->DEBUG) print "COMBINATOR\n";
+ /*
+ * Problem: ' ' and ' > ' are both valid combinators.
+ * So we have to track whitespace consumption to see
+ * if we are hitting the ' ' combinator or if the
+ * selector just has whitespace padding another combinator.
+ */
+
+ // Flag to indicate that post-checks need doing
+ $inCombinator = FALSE;
+ $white = $this->consumeWhitespace();
+ $t = $this->scanner->token;
+
+ if ($t == Token::rangle) {
+ $this->handler->directDescendant();
+ $this->scanner->nextToken();
+ $inCombinator = TRUE;
+ //$this->simpleSelectors();
+ }
+ elseif ($t == Token::plus) {
+ $this->handler->adjacent();
+ $this->scanner->nextToken();
+ $inCombinator = TRUE;
+ //$this->simpleSelectors();
+ }
+ elseif ($t == Token::comma) {
+ $this->handler->anotherSelector();
+ $this->scanner->nextToken();
+ $inCombinator = TRUE;
+ //$this->scanner->selectors();
+ }
+ elseif ($t == Token::tilde) {
+ $this->handler->sibling();
+ $this->scanner->nextToken();
+ $inCombinator = TRUE;
+ }
+
+ // Check that we don't get two combinators in a row.
+ if ($inCombinator) {
+ $white = 0;
+ if ($this->DEBUG) print "COMBINATOR: " . Token::name($t) . "\n";
+ $this->consumeWhitespace();
+ if ($this->isCombinator($this->scanner->token)) {
+ throw new ParseException("Illegal combinator: Cannot have two combinators in sequence.");
+ }
+ }
+ // Check to see if we have whitespace combinator:
+ elseif ($white > 0) {
+ if ($this->DEBUG) print "COMBINATOR: any descendant\n";
+ $inCombinator = TRUE;
+ $this->handler->anyDescendant();
+ }
+ else {
+ if ($this->DEBUG) print "COMBINATOR: no combinator found.\n";
+ }
+ }
+
+ /**
+ * Check if the token is a combinator.
+ */
+ private function isCombinator($tok) {
+ $combinators = array(Token::plus, Token::rangle, Token::comma, Token::tilde);
+ return in_array($tok, $combinators);
+ }
+
+ /**
+ * Handle a simple selector.
+ */
+ private function simpleSelectors() {
+ if ($this->DEBUG) print "SIMPLE SELECTOR\n";
+ $this->allElements();
+ $this->elementName();
+ $this->elementClass();
+ $this->elementID();
+ $this->pseudoClass();
+ $this->attribute();
+ }
+
+ /**
+ * Handles CSS ID selectors.
+ * This will call EventHandler::elementID().
+ */
+ private function elementID() {
+ if ($this->DEBUG) print "ELEMENT ID\n";
+ if ($this->scanner->token == Token::octo) {
+ $this->scanner->nextToken();
+ if ($this->scanner->token !== Token::char) {
+ throw new ParseException("Expected string after #");
+ }
+ $id = $this->scanner->getNameString();
+ $this->handler->elementID($id);
+ }
+ }
+
+ /**
+ * Handles CSS class selectors.
+ * This will call the EventHandler::elementClass() method.
+ */
+ private function elementClass() {
+ if ($this->DEBUG) print "ELEMENT CLASS\n";
+ if ($this->scanner->token == Token::dot) {
+ $this->scanner->nextToken();
+ $this->consumeWhitespace(); // We're very fault tolerent. This should prob through error.
+ $cssClass = $this->scanner->getNameString();
+ $this->handler->elementClass($cssClass);
+ }
+ }
+
+ /**
+ * Handle a pseudo-class and pseudo-element.
+ *
+ * CSS 3 selectors support separate pseudo-elements, using :: instead
+ * of : for separator. This is now supported, and calls the pseudoElement
+ * handler, EventHandler::pseudoElement().
+ *
+ * This will call EventHandler::pseudoClass() when a
+ * pseudo-class is parsed.
+ */
+ private function pseudoClass($restricted = FALSE) {
+ if ($this->DEBUG) print "PSEUDO-CLASS\n";
+ if ($this->scanner->token == Token::colon) {
+
+ // Check for CSS 3 pseudo element:
+ $isPseudoElement = FALSE;
+ if ($this->scanner->nextToken() === Token::colon) {
+ $isPseudoElement = TRUE;
+ $this->scanner->nextToken();
+ }
+
+ $name = $this->scanner->getNameString();
+ if ($restricted && $name == 'not') {
+ throw new ParseException("The 'not' pseudo-class is illegal in this context.");
+ }
+
+ $value = NULL;
+ if ($this->scanner->token == Token::lparen) {
+ if ($isPseudoElement) {
+ throw new ParseException("Illegal left paren. Pseudo-Element cannot have arguments.");
+ }
+ $value = $this->pseudoClassValue();
+ }
+
+ // FIXME: This should throw errors when pseudo element has values.
+ if ($isPseudoElement) {
+ if ($restricted) {
+ throw new ParseException("Pseudo-Elements are illegal in this context.");
+ }
+ $this->handler->pseudoElement($name);
+ $this->consumeWhitespace();
+
+ // Per the spec, pseudo-elements must be the last items in a selector, so we
+ // check to make sure that we are either at the end of the stream or that a
+ // new selector is starting. Only one pseudo-element is allowed per selector.
+ if ($this->scanner->token !== FALSE && $this->scanner->token !== Token::comma) {
+ throw new ParseException("A Pseudo-Element must be the last item in a selector.");
+ }
+ }
+ else {
+ $this->handler->pseudoClass($name, $value);
+ }
+ }
+ }
+
+ /**
+ * Get the value of a pseudo-classes.
+ *
+ * @return string
+ * Returns the value found from a pseudo-class.
+ *
+ * @todo Pseudoclasses can be passed pseudo-elements and
+ * other pseudo-classes as values, which means :pseudo(::pseudo)
+ * is legal.
+ */
+ private function pseudoClassValue() {
+ if ($this->scanner->token == Token::lparen) {
+ $buf = '';
+
+ // For now, just leave pseudoClass value vague.
+ /*
+ // We have to peek to see if next char is a colon because
+ // pseudo-classes and pseudo-elements are legal strings here.
+ print $this->scanner->peek();
+ if ($this->scanner->peek() == ':') {
+ print "Is pseudo\n";
+ $this->scanner->nextToken();
+
+ // Pseudo class
+ if ($this->scanner->token == Token::colon) {
+ $buf .= ':';
+ $this->scanner->nextToken();
+ // Pseudo element
+ if ($this->scanner->token == Token::colon) {
+ $buf .= ':';
+ $this->scanner->nextToken();
+ }
+ // Ident
+ $buf .= $this->scanner->getNameString();
+ }
+ }
+ else {
+ print "fetching string.\n";
+ $buf .= $this->scanner->getQuotedString();
+ if ($this->scanner->token != Token::rparen) {
+ $this->throwError(Token::rparen, $this->scanner->token);
+ }
+ $this->scanner->nextToken();
+ }
+ return $buf;
+ */
+ //$buf .= $this->scanner->getQuotedString();
+ $buf .= $this->scanner->getPseudoClassString();
+ return $buf;
+ }
+ }
+
+ /**
+ * Handle element names.
+ * This will call the EventHandler::elementName().
+ *
+ * This handles:
+ * <code>
+ * name (EventHandler::element())
+ * |name (EventHandler::element())
+ * ns|name (EventHandler::elementNS())
+ * ns|* (EventHandler::elementNS())
+ * </code>
+ */
+ private function elementName() {
+ if ($this->DEBUG) print "ELEMENT NAME\n";
+ if ($this->scanner->token === Token::pipe) {
+ // We have '|name', which is equiv to 'name'
+ $this->scanner->nextToken();
+ $this->consumeWhitespace();
+ $elementName = $this->scanner->getNameString();
+ $this->handler->element($elementName);
+ }
+ elseif ($this->scanner->token === Token::char) {
+ $elementName = $this->scanner->getNameString();
+ if ($this->scanner->token == Token::pipe) {
+ // Get ns|name
+ $elementNS = $elementName;
+ $this->scanner->nextToken();
+ $this->consumeWhitespace();
+ if ($this->scanner->token === Token::star) {
+ // We have ns|*
+ $this->handler->anyElementInNS($elementNS);
+ $this->scanner->nextToken();
+ }
+ elseif ($this->scanner->token !== Token::char) {
+ $this->throwError(Token::char, $this->scanner->token);
+ }
+ else {
+ $elementName = $this->scanner->getNameString();
+ // We have ns|name
+ $this->handler->elementNS($elementName, $elementNS);
+ }
+
+ }
+ else {
+ $this->handler->element($elementName);
+ }
+ }
+ }
+
+ /**
+ * Check for all elements designators. Due to the new CSS 3 namespace
+ * support, this is slightly more complicated, now, as it handles
+ * the *|name and *|* cases as well as *.
+ *
+ * Calls EventHandler::anyElement() or EventHandler::elementName().
+ */
+ private function allElements() {
+ if ($this->scanner->token === Token::star) {
+ $this->scanner->nextToken();
+ if ($this->scanner->token === Token::pipe) {
+ $this->scanner->nextToken();
+ if ($this->scanner->token === Token::star) {
+ // We got *|*. According to spec, this requires
+ // that the element has a namespace, so we pass it on
+ // to the handler:
+ $this->scanner->nextToken();
+ $this->handler->anyElementInNS('*');
+ }
+ else {
+ // We got *|name, which means the name MUST be in a namespce,
+ // so we pass this off to elementNameNS().
+ $name = $this->scanner->getNameString();
+ $this->handler->elementNS($name, '*');
+ }
+ }
+ else {
+ $this->handler->anyElement();
+ }
+ }
+ }
+
+ /**
+ * Handler an attribute.
+ * An attribute can be in one of two forms:
+ * <code>[attrName]</code>
+ * or
+ * <code>[attrName="AttrValue"]</code>
+ *
+ * This may call the following event handlers: EventHandler::attribute().
+ */
+ private function attribute() {
+ if($this->scanner->token == Token::lsquare) {
+ $attrVal = $op = $ns = NULL;
+
+ $this->scanner->nextToken();
+ $this->consumeWhitespace();
+
+ if ($this->scanner->token === Token::at) {
+ if ($this->strict) {
+ throw new ParseException('The @ is illegal in attributes.');
+ }
+ else {
+ $this->scanner->nextToken();
+ $this->consumeWhitespace();
+ }
+ }
+
+ if ($this->scanner->token === Token::star) {
+ // Global namespace... requires that attr be prefixed,
+ // so we pass this on to a namespace handler.
+ $ns = '*';
+ $this->scanner->nextToken();
+ }
+ if ($this->scanner->token === Token::pipe) {
+ // Skip this. It's a global namespace.
+ $this->scanner->nextToken();
+ $this->consumeWhitespace();
+ }
+
+ $attrName = $this->scanner->getNameString();
+ $this->consumeWhitespace();
+
+ // Check for namespace attribute: ns|attr. We have to peek() to make
+ // sure that we haven't hit the |= operator, which looks the same.
+ if ($this->scanner->token === Token::pipe && $this->scanner->peek() !== '=') {
+ // We have a namespaced attribute.
+ $ns = $attrName;
+ $this->scanner->nextToken();
+ $attrName = $this->scanner->getNameString();
+ $this->consumeWhitespace();
+ }
+
+ // Note: We require that operators do not have spaces
+ // between characters, e.g. ~= , not ~ =.
+
+ // Get the operator:
+ switch ($this->scanner->token) {
+ case Token::eq:
+ $this->consumeWhitespace();
+ $op = EventHandler::isExactly;
+ break;
+ case Token::tilde:
+ if ($this->scanner->nextToken() !== Token::eq) {
+ $this->throwError(Token::eq, $this->scanner->token);
+ }
+ $op = EventHandler::containsWithSpace;
+ break;
+ case Token::pipe:
+ if ($this->scanner->nextToken() !== Token::eq) {
+ $this->throwError(Token::eq, $this->scanner->token);
+ }
+ $op = EventHandler::containsWithHyphen;
+ break;
+ case Token::star:
+ if ($this->scanner->nextToken() !== Token::eq) {
+ $this->throwError(Token::eq, $this->scanner->token);
+ }
+ $op = EventHandler::containsInString;
+ break;
+ case Token::dollar;
+ if ($this->scanner->nextToken() !== Token::eq) {
+ $this->throwError(Token::eq, $this->scanner->token);
+ }
+ $op = EventHandler::endsWith;
+ break;
+ case Token::carat:
+ if ($this->scanner->nextToken() !== Token::eq) {
+ $this->throwError(Token::eq, $this->scanner->token);
+ }
+ $op = EventHandler::beginsWith;
+ break;
+ }
+
+ if (isset($op)) {
+ // Consume '=' and go on.
+ $this->scanner->nextToken();
+ $this->consumeWhitespace();
+
+ // So... here we have a problem. The grammer suggests that the
+ // value here is String1 or String2, both of which are enclosed
+ // in quotes of some sort, and both of which allow lots of special
+ // characters. But the spec itself includes examples like this:
+ // [lang=fr]
+ // So some bareword support is assumed. To get around this, we assume
+ // that bare words follow the NAME rules, while quoted strings follow
+ // the String1/String2 rules.
+
+ if ($this->scanner->token === Token::quote || $this->scanner->token === Token::squote) {
+ $attrVal = $this->scanner->getQuotedString();
+ }
+ else {
+ $attrVal = $this->scanner->getNameString();
+ }
+
+ if ($this->DEBUG) {
+ print "ATTR: $attrVal AND OP: $op\n";
+ }
+ }
+
+ $this->consumeWhitespace();
+
+ if ($this->scanner->token != Token::rsquare) {
+ $this->throwError(Token::rsquare, $this->scanner->token);
+ }
+
+ if (isset($ns)) {
+ $this->handler->attributeNS($attrName, $ns, $attrVal, $op);
+ }
+ elseif (isset($attrVal)) {
+ $this->handler->attribute($attrName, $attrVal, $op);
+ }
+ else {
+ $this->handler->attribute($attrName);
+ }
+ $this->scanner->nextToken();
+ }
+ }
+
+ /**
+ * Utility for throwing a consistantly-formatted parse error.
+ */
+ private function throwError($expected, $got) {
+ $filter = sprintf('Expected %s, got %s', Token::name($expected), Token::name($got));
+ throw new ParseException($filter);
+ }
+
+}
+
diff --git a/lib/querypath/src/QueryPath/CSS/QueryPathEventHandler.php b/lib/querypath/src/QueryPath/CSS/QueryPathEventHandler.php
new file mode 100644
index 0000000..2dcfd57
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/QueryPathEventHandler.php
@@ -0,0 +1,1424 @@
+<?php
+/** @file
+ * This file contains a full implementation of the EventHandler interface.
+ *
+ * The tools in this package initiate a CSS selector parsing routine and then
+ * handle all of the callbacks.
+ *
+ * The implementation provided herein adheres to the CSS 3 Selector specification
+ * with the following caveats:
+ *
+ * - The negation (:not()) and containment (:has()) pseudo-classes allow *full*
+ * selectors and not just simple selectors.
+ * - There are a variety of additional pseudo-classes supported by this
+ * implementation that are not part of the spec. Most of the jQuery
+ * pseudo-classes are supported. The :x-root pseudo-class is also supported.
+ * - Pseudo-classes that require a User Agent to function have been disabled.
+ * Thus there is no :hover pseudo-class.
+ * - All pseudo-elements require the double-colon (::) notation. This breaks
+ * backward compatibility with the 2.1 spec, but it makes visible the issue
+ * that pseudo-elements cannot be effectively used with most of the present
+ * library. They return <b>stdClass objects with a text property</b> (QP > 1.3)
+ * instead of elements.
+ * - The pseudo-classes first-of-type, nth-of-type and last-of-type may or may
+ * not conform to the specification. The spec is unclear.
+ * - pseudo-class filters of the form -an+b do not function as described in the
+ * specification. However, they do behave the same way here as they do in
+ * jQuery.
+ * - This library DOES provide XML namespace aware tools. Selectors can use
+ * namespaces to increase specificity.
+ * - This library does nothing with the CSS 3 Selector specificity rating. Of
+ * course specificity is preserved (to the best of our abilities), but there
+ * is no calculation done.
+ *
+ * For detailed examples of how the code works and what selectors are supported,
+ * see the CssEventTests file, which contains the unit tests used for
+ * testing this implementation.
+ *
+ * @author M Butcher <matt@aleph-null.tv>
+ * @license MIT
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * Handler that tracks progress of a query through a DOM.
+ *
+ * The main idea is that we keep a copy of the tree, and then use an
+ * array to keep track of matches. To handle a list of selectors (using
+ * the comma separator), we have to track both the currently progressing
+ * match and the previously matched elements.
+ *
+ * To use this handler:
+ * @code
+ * $filter = '#id'; // Some CSS selector
+ * $handler = new QueryPathEventHandler(DOMNode $dom);
+ * $parser = new Parser();
+ * $parser->parse($filter, $handler);
+ * $matches = $handler->getMatches();
+ * @endcode
+ *
+ * $matches will be an array of zero or more DOMElement objects.
+ *
+ * @ingroup querypath_css
+ */
+class QueryPathEventHandler implements EventHandler, Traverser {
+ protected $dom = NULL; // Always points to the top level.
+ protected $matches = NULL; // The matches
+ protected $alreadyMatched = NULL; // Matches found before current selector.
+ protected $findAnyElement = TRUE;
+
+
+ /**
+ * Create a new event handler.
+ */
+ public function __construct($dom) {
+ $this->alreadyMatched = new \SplObjectStorage();
+ $matches = new \SplObjectStorage();
+
+ // Array of DOMElements
+ if (is_array($dom) || $dom instanceof \SplObjectStorage) {
+ //$matches = array();
+ foreach($dom as $item) {
+ if ($item instanceof \DOMNode && $item->nodeType == XML_ELEMENT_NODE) {
+ //$matches[] = $item;
+ $matches->attach($item);
+ }
+ }
+ //$this->dom = count($matches) > 0 ? $matches[0] : NULL;
+ if ($matches->count() > 0) {
+ $matches->rewind();
+ $this->dom = $matches->current();
+ }
+ else {
+ //throw new Exception("Setting DOM to Null");
+ $this->dom = NULL;
+ }
+ $this->matches = $matches;
+ }
+ // DOM Document -- we get the root element.
+ elseif ($dom instanceof \DOMDocument) {
+ $this->dom = $dom->documentElement;
+ $matches->attach($dom->documentElement);
+ }
+ // DOM Element -- we use this directly
+ elseif ($dom instanceof \DOMElement) {
+ $this->dom = $dom;
+ $matches->attach($dom);
+ }
+ // NodeList -- We turn this into an array
+ elseif ($dom instanceof \DOMNodeList) {
+ $a = array(); // Not sure why we are doing this....
+ foreach ($dom as $item) {
+ if ($item->nodeType == XML_ELEMENT_NODE) {
+ $matches->attach($item);
+ $a[] = $item;
+ }
+ }
+ $this->dom = $a;
+ }
+ // FIXME: Handle SimpleXML!
+ // Uh-oh... we don't support anything else.
+ else {
+ throw new \QueryPath\Exception("Unhandled type: " . get_class($dom));
+ }
+ $this->matches = $matches;
+ }
+
+ /**
+ * Generic finding method.
+ *
+ * This is the primary searching method used throughout QueryPath.
+ *
+ * @param string $filter
+ * A valid CSS 3 filter.
+ * @return QueryPathEventHandler
+ * Returns itself.
+ */
+ public function find($filter) {
+ $parser = new Parser($filter, $this);
+ $parser->parse();
+ return $this;
+ }
+
+ /**
+ * Get the elements that match the evaluated selector.
+ *
+ * This should be called after the filter has been parsed.
+ *
+ * @return array
+ * The matched items. This is almost always an array of
+ * {@link DOMElement} objects. It is always an instance of
+ * {@link DOMNode} objects.
+ */
+ public function getMatches() {
+ //$result = array_merge($this->alreadyMatched, $this->matches);
+ $result = new \SplObjectStorage();
+ foreach($this->alreadyMatched as $m) $result->attach($m);
+ foreach($this->matches as $m) $result->attach($m);
+ return $result;
+ }
+
+ public function matches() {
+ return $this->getMatches();
+ }
+
+ /**
+ * Find any element with the ID that matches $id.
+ *
+ * If this finds an ID, it will immediately quit. Essentially, it doesn't
+ * enforce ID uniqueness, but it assumes it.
+ *
+ * @param $id
+ * String ID for an element.
+ */
+ public function elementID($id) {
+ $found = new \SplObjectStorage();
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ // Check if any of the current items has the desired ID.
+ if ($item->hasAttribute('id') && $item->getAttribute('id') === $id) {
+ $found->attach($item);
+ break;
+ }
+ }
+ $this->matches = $found;
+ $this->findAnyElement = FALSE;
+ }
+
+ // Inherited
+ public function element($name) {
+ $matches = $this->candidateList();
+ $this->findAnyElement = FALSE;
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ // Should the existing item be included?
+ // In some cases (e.g. element is root element)
+ // it definitely should. But what about other cases?
+ if ($item->tagName == $name) {
+ $found->attach($item);
+ }
+ // Search for matching kids.
+ //$nl = $item->getElementsByTagName($name);
+ //$found = array_merge($found, $this->nodeListToArray($nl));
+ }
+
+ $this->matches = $found;
+ }
+
+ // Inherited
+ public function elementNS($lname, $namespace = NULL) {
+ $this->findAnyElement = FALSE;
+ $found = new \SplObjectStorage();
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ // Looking up NS URI only works if the XMLNS attributes are declared
+ // at a level equal to or above the searching doc. Normalizing a doc
+ // should fix this, but it doesn't. So we have to use a fallback
+ // detection scheme which basically searches by lname and then
+ // does a post hoc check on the tagname.
+
+ //$nsuri = $item->lookupNamespaceURI($namespace);
+ $nsuri = $this->dom->lookupNamespaceURI($namespace);
+
+ // XXX: Presumably the base item needs to be checked. Spec isn't
+ // too clear, but there are three possibilities:
+ // - base should always be checked (what we do here)
+ // - base should never be checked (only children)
+ // - base should only be checked if it is the root node
+ if ($item instanceof \DOMNode
+ && $item->namespaceURI == $nsuri
+ && $lname == $item->localName) {
+ $found->attach($item);
+ }
+
+ if (!empty($nsuri)) {
+ $nl = $item->getElementsByTagNameNS($nsuri, $lname);
+ // If something is found, merge them:
+ //if (!empty($nl)) $found = array_merge($found, $this->nodeListToArray($nl));
+ if (!empty($nl)) $this->attachNodeList($nl, $found);
+ }
+ else {
+ //$nl = $item->getElementsByTagName($namespace . ':' . $lname);
+ $nl = $item->getElementsByTagName($lname);
+ $tagname = $namespace . ':' . $lname;
+ $nsmatches = array();
+ foreach ($nl as $node) {
+ if ($node->tagName == $tagname) {
+ //$nsmatches[] = $node;
+ $found->attach($node);
+ }
+ }
+ // If something is found, merge them:
+ //if (!empty($nsmatches)) $found = array_merge($found, $nsmatches);
+ }
+ }
+ $this->matches = $found;
+ }
+
+ public function anyElement() {
+ $found = new \SplObjectStorage();
+ //$this->findAnyElement = TRUE;
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ $found->attach($item); // Add self
+ // See issue #20 or section 6.2 of this:
+ // http://www.w3.org/TR/2009/PR-css3-selectors-20091215/#universal-selector
+ //$nl = $item->getElementsByTagName('*');
+ //$this->attachNodeList($nl, $found);
+ }
+
+ $this->matches = $found;
+ $this->findAnyElement = FALSE;
+ }
+ public function anyElementInNS($ns) {
+ //$this->findAnyElement = TRUE;
+ $nsuri = $this->dom->lookupNamespaceURI($ns);
+ $found = new \SplObjectStorage();
+ if (!empty($nsuri)) {
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ if ($item instanceOf \DOMNode && $nsuri == $item->namespaceURI) {
+ $found->attach($item);
+ }
+ }
+ }
+ $this->matches = $found;//UniqueElementList::get($found);
+ $this->findAnyElement = FALSE;
+ }
+ public function elementClass($name) {
+
+ $found = new \SplObjectStorage();
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ if ($item->hasAttribute('class')) {
+ $classes = explode(' ', $item->getAttribute('class'));
+ if (in_array($name, $classes)) $found->attach($item);
+ }
+ }
+
+ $this->matches = $found;//UniqueElementList::get($found);
+ $this->findAnyElement = FALSE;
+ }
+
+ public function attribute($name, $value = NULL, $operation = EventHandler::isExactly) {
+ $found = new \SplObjectStorage();
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ if ($item->hasAttribute($name)) {
+ if (isset($value)) {
+ // If a value exists, then we need a match.
+ if($this->attrValMatches($value, $item->getAttribute($name), $operation)) {
+ $found->attach($item);
+ }
+ }
+ else {
+ // If no value exists, then we consider it a match.
+ $found->attach($item);
+ }
+ }
+ }
+ $this->matches = $found; //UniqueElementList::get($found);
+ $this->findAnyElement = FALSE;
+ }
+
+ /**
+ * Helper function to find all elements with exact matches.
+ *
+ * @deprecated All use cases seem to be covered by attribute().
+ */
+ protected function searchForAttr($name, $value = NULL) {
+ $found = new \SplObjectStorage();
+ $matches = $this->candidateList();
+ foreach ($matches as $candidate) {
+ if ($candidate->hasAttribute($name)) {
+ // If value is required, match that, too.
+ if (isset($value) && $value == $candidate->getAttribute($name)) {
+ $found->attach($candidate);
+ }
+ // Otherwise, it's a match on name alone.
+ else {
+ $found->attach($candidate);
+ }
+ }
+ }
+
+ $this->matches = $found;
+ }
+
+ public function attributeNS($lname, $ns, $value = NULL, $operation = EventHandler::isExactly) {
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ if (count($matches) == 0) {
+ $this->matches = $found;
+ return;
+ }
+
+ // Get the namespace URI for the given label.
+ //$uri = $matches[0]->lookupNamespaceURI($ns);
+ $matches->rewind();
+ $e = $matches->current();
+ $uri = $e->lookupNamespaceURI($ns);
+
+ foreach ($matches as $item) {
+ //foreach ($item->attributes as $attr) {
+ // print "$attr->prefix:$attr->localName ($attr->namespaceURI), Value: $attr->nodeValue\n";
+ //}
+ if ($item->hasAttributeNS($uri, $lname)) {
+ if (isset($value)) {
+ if ($this->attrValMatches($value, $item->getAttributeNS($uri, $lname), $operation)) {
+ $found->attach($item);
+ }
+ }
+ else {
+ $found->attach($item);
+ }
+ }
+ }
+ $this->matches = $found;
+ $this->findAnyElement = FALSE;
+ }
+
+ /**
+ * This also supports the following nonstandard pseudo classes:
+ * - :x-reset/:x-root (reset to the main item passed into the constructor. Less drastic than :root)
+ * - :odd/:even (shorthand for :nth-child(odd)/:nth-child(even))
+ */
+ public function pseudoClass($name, $value = NULL) {
+ $name = strtolower($name);
+ // Need to handle known pseudoclasses.
+ switch($name) {
+ case 'visited':
+ case 'hover':
+ case 'active':
+ case 'focus':
+ case 'animated': // Last 3 are from jQuery
+ case 'visible':
+ case 'hidden':
+ // These require a UA, which we don't have.
+ case 'target':
+ // This requires a location URL, which we don't have.
+ $this->matches = new \SplObjectStorage();
+ break;
+ case 'indeterminate':
+ // The assumption is that there is a UA and the format is HTML.
+ // I don't know if this should is useful without a UA.
+ throw new NotImplementedException(":indeterminate is not implemented.");
+ break;
+ case 'lang':
+ // No value = exception.
+ if (!isset($value)) {
+ throw new NotImplementedException("No handler for lang pseudoclass without value.");
+ }
+ $this->lang($value);
+ break;
+ case 'link':
+ $this->searchForAttr('href');
+ break;
+ case 'root':
+ $found = new \SplObjectStorage();
+ if (empty($this->dom)) {
+ $this->matches = $found;
+ }
+ elseif (is_array($this->dom)) {
+ $found->attach($this->dom[0]->ownerDocument->documentElement);
+ $this->matches = $found;
+ }
+ elseif ($this->dom instanceof \DOMNode) {
+ $found->attach($this->dom->ownerDocument->documentElement);
+ $this->matches = $found;
+ }
+ elseif ($this->dom instanceof \DOMNodeList && $this->dom->length > 0) {
+ $found->attach($this->dom->item(0)->ownerDocument->documentElement);
+ $this->matches = $found;
+ }
+ else {
+ // Hopefully we never get here:
+ $found->attach($this->dom);
+ $this->matches = $found;
+ }
+ break;
+
+ // NON-STANDARD extensions for reseting to the "top" items set in
+ // the constructor.
+ case 'x-root':
+ case 'x-reset':
+ $this->matches = new \SplObjectStorage();
+ $this->matches->attach($this->dom);
+ break;
+
+ // NON-STANDARD extensions for simple support of even and odd. These
+ // are supported by jQuery, FF, and other user agents.
+ case 'even':
+ $this->nthChild(2, 0);
+ break;
+ case 'odd':
+ $this->nthChild(2, 1);
+ break;
+
+ // Standard child-checking items.
+ case 'nth-child':
+ list($aVal, $bVal) = $this->parseAnB($value);
+ $this->nthChild($aVal, $bVal);
+ break;
+ case 'nth-last-child':
+ list($aVal, $bVal) = $this->parseAnB($value);
+ $this->nthLastChild($aVal, $bVal);
+ break;
+ case 'nth-of-type':
+ list($aVal, $bVal) = $this->parseAnB($value);
+ $this->nthOfTypeChild($aVal, $bVal, FALSE);
+ break;
+ case 'nth-last-of-type':
+ list($aVal, $bVal) = $this->parseAnB($value);
+ $this->nthLastOfTypeChild($aVal, $bVal);
+ break;
+ case 'first-child':
+ $this->nthChild(0, 1);
+ break;
+ case 'last-child':
+ $this->nthLastChild(0, 1);
+ break;
+ case 'first-of-type':
+ $this->firstOfType();
+ break;
+ case 'last-of-type':
+ $this->lastOfType();
+ break;
+ case 'only-child':
+ $this->onlyChild();
+ break;
+ case 'only-of-type':
+ $this->onlyOfType();
+ break;
+ case 'empty':
+ $this->emptyElement();
+ break;
+ case 'not':
+ if (empty($value)) {
+ throw new ParseException(":not() requires a value.");
+ }
+ $this->not($value);
+ break;
+ // Additional pseudo-classes defined in jQuery:
+ case 'lt':
+ case 'gt':
+ case 'nth':
+ case 'eq':
+ case 'first':
+ case 'last':
+ //case 'even':
+ //case 'odd':
+ $this->getByPosition($name, $value);
+ break;
+ case 'parent':
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $match) {
+ if (!empty($match->firstChild)) {
+ $found->attach($match);
+ }
+ }
+ $this->matches = $found;
+ break;
+
+ case 'enabled':
+ case 'disabled':
+ case 'checked':
+ $this->attribute($name);
+ break;
+ case 'text':
+ case 'radio':
+ case 'checkbox':
+ case 'file':
+ case 'password':
+ case 'submit':
+ case 'image':
+ case 'reset':
+ case 'button':
+ $this->attribute('type', $name);
+ break;
+
+ case 'header':
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ $tag = $item->tagName;
+ $f = strtolower(substr($tag, 0, 1));
+ if ($f == 'h' && strlen($tag) == 2 && ctype_digit(substr($tag, 1, 1))) {
+ $found->attach($item);
+ }
+ }
+ $this->matches = $found;
+ break;
+ case 'has':
+ $this->has($value);
+ break;
+ // Contains == text matches.
+ // In QP 2.1, this was changed.
+ case 'contains':
+ $value = $this->removeQuotes($value);
+
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ if (strpos($item->textContent, $value) !== FALSE) {
+ $found->attach($item);
+ }
+ }
+ $this->matches = $found;
+ break;
+
+ // Since QP 2.1
+ case 'contains-exactly':
+ $value = $this->removeQuotes($value);
+
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ if ($item->textContent == $value) {
+ $found->attach($item);
+ }
+ }
+ $this->matches = $found;
+ break;
+ default:
+ throw new ParseException("Unknown Pseudo-Class: " . $name);
+ }
+ $this->findAnyElement = FALSE;
+ }
+
+ /**
+ * Remove leading and trailing quotes.
+ */
+ private function removeQuotes($str) {
+ $f = substr($str, 0, 1);
+ $l = substr($str, -1);
+ if ($f === $l && ($f == '"' || $f == "'")) {
+ $str = substr($str, 1, -1);
+ }
+ return $str;
+ }
+
+ /**
+ * Pseudo-class handler for a variety of jQuery pseudo-classes.
+ * Handles lt, gt, eq, nth, first, last pseudo-classes.
+ */
+ private function getByPosition($operator, $pos) {
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ if ($matches->count() == 0) {
+ return;
+ }
+
+ switch ($operator) {
+ case 'nth':
+ case 'eq':
+ if ($matches->count() >= $pos) {
+ //$found[] = $matches[$pos -1];
+ foreach ($matches as $match) {
+ // CSS is 1-based, so we pre-increment.
+ if ($matches->key() + 1 == $pos) {
+ $found->attach($match);
+ break;
+ }
+ }
+ }
+ break;
+ case 'first':
+ if ($matches->count() > 0) {
+ $matches->rewind(); // This is necessary to init.
+ $found->attach($matches->current());
+ }
+ break;
+ case 'last':
+ if ($matches->count() > 0) {
+
+ // Spin through iterator.
+ foreach ($matches as $item) {};
+
+ $found->attach($item);
+ }
+ break;
+ // case 'even':
+ // for ($i = 1; $i <= count($matches); ++$i) {
+ // if ($i % 2 == 0) {
+ // $found[] = $matches[$i];
+ // }
+ // }
+ // break;
+ // case 'odd':
+ // for ($i = 1; $i <= count($matches); ++$i) {
+ // if ($i % 2 == 0) {
+ // $found[] = $matches[$i];
+ // }
+ // }
+ // break;
+ case 'lt':
+ $i = 0;
+ foreach ($matches as $item) {
+ if (++$i < $pos) {
+ $found->attach($item);
+ }
+ }
+ break;
+ case 'gt':
+ $i = 0;
+ foreach ($matches as $item) {
+ if (++$i > $pos) {
+ $found->attach($item);
+ }
+ }
+ break;
+ }
+
+ $this->matches = $found;
+ }
+
+ /**
+ * Parse an an+b rule for CSS pseudo-classes.
+ * @param $rule
+ * Some rule in the an+b format.
+ * @return
+ * Array (list($aVal, $bVal)) of the two values.
+ * @throws ParseException
+ * If the rule does not follow conventions.
+ */
+ protected function parseAnB($rule) {
+ if ($rule == 'even') {
+ return array(2, 0);
+ }
+ elseif ($rule == 'odd') {
+ return array(2, 1);
+ }
+ elseif ($rule == 'n') {
+ return array(1, 0);
+ }
+ elseif (is_numeric($rule)) {
+ return array(0, (int)$rule);
+ }
+
+ $rule = explode('n', $rule);
+ if (count($rule) == 0) {
+ throw new ParseException("nth-child value is invalid.");
+ }
+
+ // Each of these is legal: 1, -1, and -. '-' is shorthand for -1.
+ $aVal = trim($rule[0]);
+ $aVal = ($aVal == '-') ? -1 : (int)$aVal;
+
+ $bVal = !empty($rule[1]) ? (int)trim($rule[1]) : 0;
+ return array($aVal, $bVal);
+ }
+
+ /**
+ * Pseudo-class handler for nth-child and all related pseudo-classes.
+ *
+ * @param int $groupSize
+ * The size of the group (in an+b, this is a).
+ * @param int $elementInGroup
+ * The offset in a group. (in an+b this is b).
+ * @param boolean $lastChild
+ * Whether counting should begin with the last child. By default, this is false.
+ * Pseudo-classes that start with the last-child can set this to true.
+ */
+ protected function nthChild($groupSize, $elementInGroup, $lastChild = FALSE) {
+ // EXPERIMENTAL: New in Quark. This should be substantially faster
+ // than the old (jQuery-ish) version. It still has E_STRICT violations
+ // though.
+ $parents = new \SplObjectStorage();
+ $matches = new \SplObjectStorage();
+
+ $i = 0;
+ foreach ($this->matches as $item) {
+ $parent = $item->parentNode;
+
+ // Build up an array of all of children of this parent, and store the
+ // index of each element for reference later. We only need to do this
+ // once per parent, though.
+ if (!$parents->contains($parent)) {
+
+ $c = 0;
+ foreach ($parent->childNodes as $child) {
+ // We only want nodes, and if this call is preceded by an element
+ // selector, we only want to match elements with the same tag name.
+ // !!! This last part is a grey area in the CSS 3 Selector spec. It seems
+ // necessary to make the implementation match the examples in the spec. However,
+ // jQuery 1.2 does not do this.
+ if ($child->nodeType == XML_ELEMENT_NODE && ($this->findAnyElement || $child->tagName == $item->tagName)) {
+ // This may break E_STRICT.
+ $child->nodeIndex = ++$c;
+ }
+ }
+ // This may break E_STRICT.
+ $parent->numElements = $c;
+ $parents->attach($parent);
+ }
+
+ // If we are looking for the last child, we count from the end of a list.
+ // Note that we add 1 because CSS indices begin at 1, not 0.
+ if ($lastChild) {
+ $indexToMatch = $item->parentNode->numElements - $item->nodeIndex + 1;
+ }
+ // Otherwise we count from the beginning of the list.
+ else {
+ $indexToMatch = $item->nodeIndex;
+ }
+
+ // If group size is 0, then we return element at the right index.
+ if ($groupSize == 0) {
+ if ($indexToMatch == $elementInGroup)
+ $matches->attach($item);
+ }
+ // If group size != 0, then we grab nth element from group offset by
+ // element in group.
+ else {
+ if (($indexToMatch - $elementInGroup) % $groupSize == 0
+ && ($indexToMatch - $elementInGroup) / $groupSize >= 0) {
+ $matches->attach($item);
+ }
+ }
+
+ // Iterate.
+ ++$i;
+ }
+ $this->matches = $matches;
+ }
+
+ /**
+ * Reverse a set of matches.
+ *
+ * This is now necessary because internal matches are no longer represented
+ * as arrays.
+ * @since QueryPath 2.0
+ *//*
+ private function reverseMatches() {
+ // Reverse the candidate list. There must be a better way of doing
+ // this.
+ $arr = array();
+ foreach ($this->matches as $m) array_unshift($arr, $m);
+
+ $this->found = new \SplObjectStorage();
+ foreach ($arr as $item) $this->found->attach($item);
+ }*/
+
+ /**
+ * Pseudo-class handler for :nth-last-child and related pseudo-classes.
+ */
+ protected function nthLastChild($groupSize, $elementInGroup) {
+ // New in Quark.
+ $this->nthChild($groupSize, $elementInGroup, TRUE);
+ }
+
+ /**
+ * Get a list of peer elements.
+ * If $requireSameTag is TRUE, then only peer elements with the same
+ * tagname as the given element will be returned.
+ *
+ * @param $element
+ * A DomElement.
+ * @param $requireSameTag
+ * Boolean flag indicating whether all matches should have the same
+ * element name (tagName) as $element.
+ * @return
+ * Array of peer elements.
+ *//*
+ protected function listPeerElements($element, $requireSameTag = FALSE) {
+ $peers = array();
+ $parent = $element->parentNode;
+ foreach ($parent->childNodes as $node) {
+ if ($node->nodeType == XML_ELEMENT_NODE) {
+ if ($requireSameTag) {
+ // Need to make sure that the tag matches:
+ if ($element->tagName == $node->tagName) {
+ $peers[] = $node;
+ }
+ }
+ else {
+ $peers[] = $node;
+ }
+ }
+ }
+ return $peers;
+ }
+ */
+ /**
+ * Get the nth child (by index) from matching candidates.
+ *
+ * This is used by pseudo-class handlers.
+ */
+ /*
+ protected function childAtIndex($index, $tagName = NULL) {
+ $restrictToElement = !$this->findAnyElement;
+ $matches = $this->candidateList();
+ $defaultTagName = $tagName;
+
+ // XXX: Added in Quark: I believe this should return an empty
+ // match set if no child was found tat the index.
+ $this->matches = new \SplObjectStorage();
+
+ foreach ($matches as $item) {
+ $parent = $item->parentNode;
+
+ // If a default tag name is supplied, we always use it.
+ if (!empty($defaultTagName)) {
+ $tagName = $defaultTagName;
+ }
+ // If we are inside of an element selector, we use the
+ // tag name of the given elements.
+ elseif ($restrictToElement) {
+ $tagName = $item->tagName;
+ }
+ // Otherwise, we skip the tag name match.
+ else {
+ $tagName = NULL;
+ }
+
+ // Loop through all children looking for matches.
+ $i = 0;
+ foreach ($parent->childNodes as $child) {
+ if ($child->nodeType !== XML_ELEMENT_NODE) {
+ break; // Skip non-elements
+ }
+
+ // If type is set, then we do type comparison
+ if (!empty($tagName)) {
+ // Check whether tag name matches the type.
+ if ($child->tagName == $tagName) {
+ // See if this is the index we are looking for.
+ if ($i == $index) {
+ //$this->matches = new \SplObjectStorage();
+ $this->matches->attach($child);
+ return;
+ }
+ // If it's not the one we are looking for, increment.
+ ++$i;
+ }
+ }
+ // We don't care about type. Any tagName will match.
+ else {
+ if ($i == $index) {
+ $this->matches->attach($child);
+ return;
+ }
+ ++$i;
+ }
+ } // End foreach
+ }
+
+ }*/
+
+ /**
+ * Pseudo-class handler for nth-of-type-child.
+ * Not implemented.
+ */
+ protected function nthOfTypeChild($groupSize, $elementInGroup, $lastChild) {
+ // EXPERIMENTAL: New in Quark. This should be substantially faster
+ // than the old (jQuery-ish) version. It still has E_STRICT violations
+ // though.
+ $parents = new \SplObjectStorage();
+ $matches = new \SplObjectStorage();
+
+ $i = 0;
+ foreach ($this->matches as $item) {
+ $parent = $item->parentNode;
+
+ // Build up an array of all of children of this parent, and store the
+ // index of each element for reference later. We only need to do this
+ // once per parent, though.
+ if (!$parents->contains($parent)) {
+
+ $c = 0;
+ foreach ($parent->childNodes as $child) {
+ // This doesn't totally make sense, since the CSS 3 spec does not require that
+ // this pseudo-class be adjoined to an element (e.g. ' :nth-of-type' is allowed).
+ if ($child->nodeType == XML_ELEMENT_NODE && $child->tagName == $item->tagName) {
+ // This may break E_STRICT.
+ $child->nodeIndex = ++$c;
+ }
+ }
+ // This may break E_STRICT.
+ $parent->numElements = $c;
+ $parents->attach($parent);
+ }
+
+ // If we are looking for the last child, we count from the end of a list.
+ // Note that we add 1 because CSS indices begin at 1, not 0.
+ if ($lastChild) {
+ $indexToMatch = $item->parentNode->numElements - $item->nodeIndex + 1;
+ }
+ // Otherwise we count from the beginning of the list.
+ else {
+ $indexToMatch = $item->nodeIndex;
+ }
+
+ // If group size is 0, then we return element at the right index.
+ if ($groupSize == 0) {
+ if ($indexToMatch == $elementInGroup)
+ $matches->attach($item);
+ }
+ // If group size != 0, then we grab nth element from group offset by
+ // element in group.
+ else {
+ if (($indexToMatch - $elementInGroup) % $groupSize == 0
+ && ($indexToMatch - $elementInGroup) / $groupSize >= 0) {
+ $matches->attach($item);
+ }
+ }
+
+ // Iterate.
+ ++$i;
+ }
+ $this->matches = $matches;
+ }
+
+ /**
+ * Pseudo-class handler for nth-last-of-type-child.
+ * Not implemented.
+ */
+ protected function nthLastOfTypeChild($groupSize, $elementInGroup) {
+ $this->nthOfTypeChild($groupSize, $elementInGroup, TRUE);
+ }
+
+ /**
+ * Pseudo-class handler for :lang
+ */
+ protected function lang($value) {
+ // TODO: This checks for cases where an explicit language is
+ // set. The spec seems to indicate that an element should inherit
+ // language from the parent... but this is unclear.
+ $operator = (strpos($value, '-') !== FALSE) ? self::isExactly : self::containsWithHyphen;
+
+ $orig = $this->matches;
+ $origDepth = $this->findAnyElement;
+
+ // Do first pass: attributes in default namespace
+ $this->attribute('lang', $value, $operator);
+ $lang = $this->matches; // Temp array for merging.
+
+ // Reset
+ $this->matches = $orig;
+ $this->findAnyElement = $origDepth;
+
+ // Do second pass: attributes in 'xml' namespace.
+ $this->attributeNS('lang', 'xml', $value, $operator);
+
+
+ // Merge results.
+ // FIXME: Note that we lose natural ordering in
+ // the document because we search for xml:lang separately
+ // from lang.
+ foreach ($this->matches as $added) $lang->attach($added);
+ $this->matches = $lang;
+ }
+
+ /**
+ * Pseudo-class handler for :not(filter).
+ *
+ * This does not follow the specification in the following way: The CSS 3
+ * selector spec says the value of not() must be a simple selector. This
+ * function allows complex selectors.
+ *
+ * @param string $filter
+ * A CSS selector.
+ */
+ protected function not($filter) {
+ $matches = $this->candidateList();
+ //$found = array();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ $handler = new QueryPathEventHandler($item);
+ $not_these = $handler->find($filter)->getMatches();
+ if ($not_these->count() == 0) {
+ $found->attach($item);
+ }
+ }
+ // No need to check for unique elements, since the list
+ // we began from already had no duplicates.
+ $this->matches = $found;
+ }
+
+ /**
+ * Pseudo-class handler for :has(filter).
+ * This can also be used as a general filtering routine.
+ */
+ public function has($filter) {
+ $matches = $this->candidateList();
+ //$found = array();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ $handler = new QueryPathEventHandler($item);
+ $these = $handler->find($filter)->getMatches();
+ if (count($these) > 0) {
+ $found->attach($item);
+ }
+ }
+ $this->matches = $found;
+ return $this;
+ }
+
+ /**
+ * Pseudo-class handler for :first-of-type.
+ */
+ protected function firstOfType() {
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ $type = $item->tagName;
+ $parent = $item->parentNode;
+ foreach ($parent->childNodes as $kid) {
+ if ($kid->nodeType == XML_ELEMENT_NODE && $kid->tagName == $type) {
+ if (!$found->contains($kid)) {
+ $found->attach($kid);
+ }
+ break;
+ }
+ }
+ }
+ $this->matches = $found;
+ }
+
+ /**
+ * Pseudo-class handler for :last-of-type.
+ */
+ protected function lastOfType() {
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ $type = $item->tagName;
+ $parent = $item->parentNode;
+ for ($i = $parent->childNodes->length - 1; $i >= 0; --$i) {
+ $kid = $parent->childNodes->item($i);
+ if ($kid->nodeType == XML_ELEMENT_NODE && $kid->tagName == $type) {
+ if (!$found->contains($kid)) {
+ $found->attach($kid);
+ }
+ break;
+ }
+ }
+ }
+ $this->matches = $found;
+ }
+
+ /**
+ * Pseudo-class handler for :only-child.
+ */
+ protected function onlyChild() {
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach($matches as $item) {
+ $parent = $item->parentNode;
+ $kids = array();
+ foreach($parent->childNodes as $kid) {
+ if ($kid->nodeType == XML_ELEMENT_NODE) {
+ $kids[] = $kid;
+ }
+ }
+ // There should be only one child element, and
+ // it should be the one being tested.
+ if (count($kids) == 1 && $kids[0] === $item) {
+ $found->attach($kids[0]);
+ }
+ }
+ $this->matches = $found;
+ }
+
+ /**
+ * Pseudo-class handler for :empty.
+ */
+ protected function emptyElement() {
+ $found = new \SplObjectStorage();
+ $matches = $this->candidateList();
+ foreach ($matches as $item) {
+ $empty = TRUE;
+ foreach($item->childNodes as $kid) {
+ // From the spec: Elements and Text nodes are the only ones to
+ // affect emptiness.
+ if ($kid->nodeType == XML_ELEMENT_NODE || $kid->nodeType == XML_TEXT_NODE) {
+ $empty = FALSE;
+ break;
+ }
+ }
+ if ($empty) {
+ $found->attach($item);
+ }
+ }
+ $this->matches = $found;
+ }
+
+ /**
+ * Pseudo-class handler for :only-of-type.
+ */
+ protected function onlyOfType() {
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ foreach ($matches as $item) {
+ if (!$item->parentNode) {
+ $this->matches = new \SplObjectStorage();
+ }
+ $parent = $item->parentNode;
+ $onlyOfType = TRUE;
+
+ // See if any peers are of the same type
+ foreach($parent->childNodes as $kid) {
+ if ($kid->nodeType == XML_ELEMENT_NODE
+ && $kid->tagName == $item->tagName
+ && $kid !== $item) {
+ //$this->matches = new \SplObjectStorage();
+ $onlyOfType = FALSE;
+ break;
+ }
+ }
+
+ // If no others were found, attach this one.
+ if ($onlyOfType) $found->attach($item);
+ }
+ $this->matches = $found;
+ }
+
+ /**
+ * Check for attr value matches based on an operation.
+ */
+ protected function attrValMatches($needle, $haystack, $operation) {
+
+ if (strlen($haystack) < strlen($needle)) return FALSE;
+
+ // According to the spec:
+ // "The case-sensitivity of attribute names in selectors depends on the document language."
+ // (6.3.2)
+ // To which I say, "huh?". We assume case sensitivity.
+ switch ($operation) {
+ case EventHandler::isExactly:
+ return $needle == $haystack;
+ case EventHandler::containsWithSpace:
+ return in_array($needle, explode(' ', $haystack));
+ case EventHandler::containsWithHyphen:
+ return in_array($needle, explode('-', $haystack));
+ case EventHandler::containsInString:
+ return strpos($haystack, $needle) !== FALSE;
+ case EventHandler::beginsWith:
+ return strpos($haystack, $needle) === 0;
+ case EventHandler::endsWith:
+ //return strrpos($haystack, $needle) === strlen($needle) - 1;
+ return preg_match('/' . $needle . '$/', $haystack) == 1;
+ }
+ return FALSE; // Shouldn't be able to get here.
+ }
+
+ /**
+ * As the spec mentions, these must be at the end of a selector or
+ * else they will cause errors. Most selectors return elements. Pseudo-elements
+ * do not.
+ */
+ public function pseudoElement($name) {
+ // process the pseudoElement
+ switch ($name) {
+ // XXX: Should this return an array -- first line of
+ // each of the matched elements?
+ case 'first-line':
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ $o = new \stdClass();
+ foreach ($matches as $item) {
+ $str = $item->textContent;
+ $lines = explode("\n", $str);
+ if (!empty($lines)) {
+ $line = trim($lines[0]);
+ if (!empty($line)) {
+ $o->textContent = $line;
+ $found->attach($o);//trim($lines[0]);
+ }
+ }
+ }
+ $this->matches = $found;
+ break;
+ // XXX: Should this return an array -- first letter of each
+ // of the matched elements?
+ case 'first-letter':
+ $matches = $this->candidateList();
+ $found = new \SplObjectStorage();
+ $o = new \stdClass();
+ foreach ($matches as $item) {
+ $str = $item->textContent;
+ if (!empty($str)) {
+ $str = substr($str,0, 1);
+ $o->textContent = $str;
+ $found->attach($o);
+ }
+ }
+ $this->matches = $found;
+ break;
+ case 'before':
+ case 'after':
+ // There is nothing in a DOM to return for the before and after
+ // selectors.
+ case 'selection':
+ // With no user agent, we don't have a concept of user selection.
+ throw new NotImplementedException("The $name pseudo-element is not implemented.");
+ break;
+ }
+ $this->findAnyElement = FALSE;
+ }
+ public function directDescendant() {
+ $this->findAnyElement = FALSE;
+
+ $kids = new \SplObjectStorage();
+ foreach ($this->matches as $item) {
+ $kidsNL = $item->childNodes;
+ foreach ($kidsNL as $kidNode) {
+ if ($kidNode->nodeType == XML_ELEMENT_NODE) {
+ $kids->attach($kidNode);
+ }
+ }
+ }
+ $this->matches = $kids;
+ }
+ /**
+ * For an element to be adjacent to another, it must be THE NEXT NODE
+ * in the node list. So if an element is surrounded by pcdata, there are
+ * no adjacent nodes. E.g. in <a/>FOO<b/>, the a and b elements are not
+ * adjacent.
+ *
+ * In a strict DOM parser, line breaks and empty spaces are nodes. That means
+ * nodes like this will not be adjacent: <test/> <test/>. The space between
+ * them makes them non-adjacent. If this is not the desired behavior, pass
+ * in the appropriate flags to your parser. Example:
+ * <code>
+ * $doc = new DomDocument();
+ * $doc->loadXML('<test/> <test/>', LIBXML_NOBLANKS);
+ * </code>
+ */
+ public function adjacent() {
+ $this->findAnyElement = FALSE;
+ // List of nodes that are immediately adjacent to the current one.
+ //$found = array();
+ $found = new \SplObjectStorage();
+ foreach ($this->matches as $item) {
+ while (isset($item->nextSibling)) {
+ if (isset($item->nextSibling) && $item->nextSibling->nodeType === XML_ELEMENT_NODE) {
+ $found->attach($item->nextSibling);
+ break;
+ }
+ $item = $item->nextSibling;
+ }
+ }
+ $this->matches = $found;
+ }
+
+ public function anotherSelector() {
+ $this->findAnyElement = FALSE;
+ // Copy old matches into buffer.
+ if ($this->matches->count() > 0) {
+ //$this->alreadyMatched = array_merge($this->alreadyMatched, $this->matches);
+ foreach ($this->matches as $item) $this->alreadyMatched->attach($item);
+ }
+
+ // Start over at the top of the tree.
+ $this->findAnyElement = TRUE; // Reset depth flag.
+ $this->matches = new \SplObjectStorage();
+ $this->matches->attach($this->dom);
+ }
+
+ /**
+ * Get all nodes that are siblings to currently selected nodes.
+ *
+ * If two passed in items are siblings of each other, neither will
+ * be included in the list of siblings. Their status as being candidates
+ * excludes them from being considered siblings.
+ */
+ public function sibling() {
+ $this->findAnyElement = FALSE;
+ // Get the nodes at the same level.
+
+ if ($this->matches->count() > 0) {
+ $sibs = new \SplObjectStorage();
+ foreach ($this->matches as $item) {
+ /*$candidates = $item->parentNode->childNodes;
+ foreach ($candidates as $candidate) {
+ if ($candidate->nodeType === XML_ELEMENT_NODE && $candidate !== $item) {
+ $sibs->attach($candidate);
+ }
+ }
+ */
+ while ($item->nextSibling != NULL) {
+ $item = $item->nextSibling;
+ if ($item->nodeType === XML_ELEMENT_NODE) $sibs->attach($item);
+ }
+ }
+ $this->matches = $sibs;
+ }
+ }
+
+ /**
+ * Get any descendant.
+ */
+ public function anyDescendant() {
+ // Get children:
+ $found = new \SplObjectStorage();
+ foreach ($this->matches as $item) {
+ $kids = $item->getElementsByTagName('*');
+ //$found = array_merge($found, $this->nodeListToArray($kids));
+ $this->attachNodeList($kids, $found);
+ }
+ $this->matches = $found;
+
+ // Set depth flag:
+ $this->findAnyElement = TRUE;
+ }
+
+ /**
+ * Determine what candidates are in the current scope.
+ *
+ * This is a utility method that gets the list of elements
+ * that should be evaluated in the context. If $this->findAnyElement
+ * is TRUE, this will return a list of every element that appears in
+ * the subtree of $this->matches. Otherwise, it will just return
+ * $this->matches.
+ */
+ private function candidateList() {
+ if ($this->findAnyElement) {
+ return $this->getAllCandidates($this->matches);
+ }
+ return $this->matches;
+ }
+
+ /**
+ * Get a list of all of the candidate elements.
+ *
+ * This is used when $this->findAnyElement is TRUE.
+ * @param $elements
+ * A list of current elements (usually $this->matches).
+ *
+ * @return
+ * A list of all candidate elements.
+ */
+ private function getAllCandidates($elements) {
+ $found = new \SplObjectStorage();
+ foreach ($elements as $item) {
+ $found->attach($item); // put self in
+ $nl = $item->getElementsByTagName('*');
+ //foreach ($nl as $node) $found[] = $node;
+ $this->attachNodeList($nl, $found);
+ }
+ return $found;
+ }
+ /*
+ public function nodeListToArray($nodeList) {
+ $array = array();
+ foreach ($nodeList as $node) {
+ if ($node->nodeType == XML_ELEMENT_NODE) {
+ $array[] = $node;
+ }
+ }
+ return $array;
+ }
+ */
+
+ /**
+ * Attach all nodes in a node list to the given \SplObjectStorage.
+ */
+ public function attachNodeList(\DOMNodeList $nodeList, \SplObjectStorage $splos) {
+ foreach ($nodeList as $item) $splos->attach($item);
+ }
+
+}
diff --git a/lib/querypath/src/QueryPath/CSS/Scanner.php b/lib/querypath/src/QueryPath/CSS/Scanner.php
new file mode 100644
index 0000000..3513a0b
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/Scanner.php
@@ -0,0 +1,306 @@
+<?php
+/** @file
+ * The scanner.
+ */
+namespace QueryPath\CSS;
+/**
+ * Scanner for CSS selector parsing.
+ *
+ * This provides a simple scanner for traversing an input stream.
+ *
+ * @ingroup querypath_css
+ */
+final class Scanner {
+ var $is = NULL;
+ public $value = NULL;
+ public $token = NULL;
+
+ var $recurse = FALSE;
+ var $it = 0;
+
+ /**
+ * Given a new input stream, tokenize the CSS selector string.
+ * @see InputStream
+ * @param InputStream $in
+ * An input stream to be scanned.
+ */
+ public function __construct(InputStream $in) {
+ $this->is = $in;
+ }
+
+ /**
+ * Return the position of the reader in the string.
+ */
+ public function position() {
+ return $this->is->position;
+ }
+
+ /**
+ * See the next char without removing it from the stack.
+ *
+ * @return char
+ * Returns the next character on the stack.
+ */
+ public function peek() {
+ return $this->is->peek();
+ }
+
+ /**
+ * Get the next token in the input stream.
+ *
+ * This sets the current token to the value of the next token in
+ * the stream.
+ *
+ * @return int
+ * Returns an int value corresponding to one of the Token constants,
+ * or FALSE if the end of the string is reached. (Remember to use
+ * strong equality checking on FALSE, since 0 is a valid token id.)
+ */
+ public function nextToken() {
+ $tok = -1;
+ ++$this->it;
+ if ($this->is->isEmpty()) {
+ if ($this->recurse) {
+ throw new \QueryPath\Exception("Recursion error detected at iteration " . $this->it . '.');
+ exit();
+ }
+ //print "{$this->it}: All done\n";
+ $this->recurse = TRUE;
+ $this->token = FALSE;
+ return FALSE;
+ }
+ $ch = $this->is->consume();
+ //print __FUNCTION__ . " Testing $ch.\n";
+ if (ctype_space($ch)) {
+ $this->value = ' '; // Collapse all WS to a space.
+ $this->token = $tok = Token::white;
+ //$ch = $this->is->consume();
+ return $tok;
+ }
+
+ if (ctype_alnum($ch) || $ch == '-' || $ch == '_') {
+ // It's a character
+ $this->value = $ch; //strtolower($ch);
+ $this->token = $tok = Token::char;
+ return $tok;
+ }
+
+ $this->value = $ch;
+
+ switch($ch) {
+ case '*':
+ $tok = Token::star;
+ break;
+ case chr(ord('>')):
+ $tok = Token::rangle;
+ break;
+ case '.':
+ $tok = Token::dot;
+ break;
+ case '#':
+ $tok = Token::octo;
+ break;
+ case '[':
+ $tok = Token::lsquare;
+ break;
+ case ']':
+ $tok = Token::rsquare;
+ break;
+ case ':':
+ $tok = Token::colon;
+ break;
+ case '(':
+ $tok = Token::lparen;
+ break;
+ case ')':
+ $tok = Token::rparen;
+ break;
+ case '+':
+ $tok = Token::plus;
+ break;
+ case '~':
+ $tok = Token::tilde;
+ break;
+ case '=':
+ $tok = Token::eq;
+ break;
+ case '|':
+ $tok = Token::pipe;
+ break;
+ case ',':
+ $tok = Token::comma;
+ break;
+ case chr(34):
+ $tok = Token::quote;
+ break;
+ case "'":
+ $tok = Token::squote;
+ break;
+ case '\\':
+ $tok = Token::bslash;
+ break;
+ case '^':
+ $tok = Token::carat;
+ break;
+ case '$':
+ $tok = Token::dollar;
+ break;
+ case '@':
+ $tok = Token::at;
+ break;
+ }
+
+
+ // Catch all characters that are legal within strings.
+ if ($tok == -1) {
+ // TODO: This should be UTF-8 compatible, but PHP doesn't
+ // have a native UTF-8 string. Should we use external
+ // mbstring library?
+
+ $ord = ord($ch);
+ // Characters in this pool are legal for use inside of
+ // certain strings. Extended ASCII is used here, though I
+ // Don't know if these are really legal.
+ if (($ord >= 32 && $ord <= 126) || ($ord >= 128 && $ord <= 255)) {
+ $tok = Token::stringLegal;
+ }
+ else {
+ throw new ParseException('Illegal character found in stream: ' . $ord);
+ }
+ }
+
+ $this->token = $tok;
+ return $tok;
+ }
+
+ /**
+ * Get a name string from the input stream.
+ * A name string must be composed of
+ * only characters defined in Token:char: -_a-zA-Z0-9
+ */
+ public function getNameString() {
+ $buf = '';
+ while ($this->token === Token::char) {
+ $buf .= $this->value;
+ $this->nextToken();
+ //print '_';
+ }
+ return $buf;
+ }
+
+ /**
+ * This gets a string with any legal 'string' characters.
+ * See CSS Selectors specification, section 11, for the
+ * definition of string.
+ *
+ * This will check for string1, string2, and the case where a
+ * string is unquoted (Oddly absent from the "official" grammar,
+ * though such strings are present as examples in the spec.)
+ *
+ * Note:
+ * Though the grammar supplied by CSS 3 Selectors section 11 does not
+ * address the contents of a pseudo-class value, the spec itself indicates
+ * that a pseudo-class value is a "value between parenthesis" [6.6]. The
+ * examples given use URLs among other things, making them closer to the
+ * definition of 'string' than to 'name'. So we handle them here as strings.
+ */
+ public function getQuotedString() {
+ if ($this->token == Token::quote || $this->token == Token::squote || $this->token == Token::lparen) {
+ $end = ($this->token == Token::lparen) ? Token::rparen : $this->token;
+ $buf = '';
+ $escape = FALSE;
+
+ $this->nextToken(); // Skip the opening quote/paren
+
+ // The second conjunct is probably not necessary.
+ while ($this->token !== FALSE && $this->token > -1) {
+ //print "Char: $this->value \n";
+ if ($this->token == Token::bslash && !$escape) {
+ // XXX: The backslash (\) is removed here.
+ // Turn on escaping.
+ //$buf .= $this->value;
+ $escape = TRUE;
+ }
+ elseif ($escape) {
+ // Turn off escaping
+ $buf .= $this->value;
+ $escape = FALSE;
+ }
+ elseif ($this->token === $end) {
+ // At end of string; skip token and break.
+ $this->nextToken();
+ break;
+ }
+ else {
+ // Append char.
+ $buf .= $this->value;
+ }
+ $this->nextToken();
+ }
+ return $buf;
+ }
+ }
+
+ // Get the contents inside of a pseudoClass().
+ public function getPseudoClassString() {
+ if ($this->token == Token::quote || $this->token == Token::squote || $this->token == Token::lparen) {
+ $end = ($this->token == Token::lparen) ? Token::rparen : $this->token;
+ $buf = '';
+ $escape = FALSE;
+
+ $this->nextToken(); // Skip the opening quote/paren
+
+ // The second conjunct is probably not necessary.
+ while ($this->token !== FALSE && $this->token > -1) {
+ //print "Char: $this->value \n";
+ if ($this->token == Token::bslash && !$escape) {
+ // XXX: The backslash (\) is removed here.
+ // Turn on escaping.
+ //$buf .= $this->value;
+ $escape = TRUE;
+ }
+ elseif ($escape) {
+ // Turn off escaping
+ $buf .= $this->value;
+ $escape = FALSE;
+ }
+ // Allow nested pseudoclasses.
+ elseif ($this->token == Token::lparen) {
+ $buf .= "(";
+ $buf .= $this->getPseudoClassString();
+ $buf .= ")";
+ }
+ elseif ($this->token === $end) {
+ // At end of string; skip token and break.
+ $this->nextToken();
+ break;
+ }
+ else {
+ // Append char.
+ $buf .= $this->value;
+ }
+ $this->nextToken();
+ }
+ return $buf;
+ }
+ }
+
+ /**
+ * Get a string from the input stream.
+ * This is a convenience function for getting a string of
+ * characters that are either alphanumber or whitespace. See
+ * the Token::white and Token::char definitions.
+ *
+ * @deprecated This is not used anywhere in QueryPath.
+ *//*
+ public function getStringPlusWhitespace() {
+ $buf = '';
+ if($this->token === FALSE) {return '';}
+ while ($this->token === Token::char || $this->token == Token::white) {
+ $buf .= $this->value;
+ $this->nextToken();
+ }
+ return $buf;
+ }*/
+
+}
diff --git a/lib/querypath/src/QueryPath/CSS/Selector.php b/lib/querypath/src/QueryPath/CSS/Selector.php
new file mode 100644
index 0000000..4b538bd
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/Selector.php
@@ -0,0 +1,144 @@
+<?php
+/** @file
+ * A selector.
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * A CSS Selector.
+ *
+ * A CSS selector is made up of one or more Simple Selectors
+ * (SimpleSelector).
+ *
+ * @attention
+ * The Selector data structure is a LIFO (Last in, First out). This is
+ * because CSS selectors are best processed "bottom up". Thus, when
+ * iterating over 'a>b>c', the iterator will produce:
+ * - c
+ * - b
+ * - a
+ * It is assumed, therefore, that any suitable querying engine will
+ * traverse from the bottom (`c`) back up.
+ *
+ * @b Usage
+ *
+ * This class is an event handler. It can be plugged into an Parser and
+ * receive the events the Parser generates.
+ *
+ * This class is also an iterator. Once the parser has completed, the
+ * captured selectors can be iterated over.
+ *
+ * @code
+ * <?php
+ * $selectorList = new \QueryPath\CSS\Selector();
+ * $parser = new \QueryPath\CSS\Parser($selector, $selectorList);
+ *
+ * $parser->parse();
+ *
+ * foreach ($selectorList as $simpleSelector) {
+ * // Do something with the SimpleSelector.
+ * print_r($simpleSelector);
+ * }
+ * ?>
+ * @endode
+ *
+ *
+ * @since QueryPath 3.0.0
+ */
+class Selector implements EventHandler, \IteratorAggregate, \Countable {
+ protected $selectors = array();
+ protected $currSelector;
+ protected $selectorGroups = array();
+ protected $groupIndex = 0;
+
+ public function __construct() {
+ $this->currSelector = new SimpleSelector();
+
+ $this->selectors[$this->groupIndex][] = $this->currSelector;
+ }
+
+ public function getIterator() {
+ return new \ArrayIterator($this->selectors);
+ }
+
+ /**
+ * Get the array of SimpleSelector objects.
+ *
+ * Normally, one iterates over a Selector. However, if it is
+ * necessary to get the selector array and manipulate it, this
+ * method can be used.
+ */
+ public function toArray() {
+ return $this->selectors;
+ }
+
+ public function count() {
+ return count($this->selectors);
+ }
+
+ public function elementID($id) {
+ $this->currSelector->id = $id;
+ }
+ public function element($name) {
+ $this->currSelector->element = $name;
+ }
+ public function elementNS($name, $namespace = NULL) {
+ $this->currSelector->ns = $namespace;
+ $this->currSelector->element = $name;
+ }
+ public function anyElement() {
+ $this->currSelector->element = '*';
+ }
+ public function anyElementInNS($ns) {
+ $this->currSelector->ns = $ns;
+ $this->currSelector->element = '*';
+ }
+ public function elementClass($name) {
+ $this->currSelector->classes[] = $name;
+ }
+ public function attribute($name, $value = NULL, $operation = EventHandler::isExactly) {
+ $this->currSelector->attributes[] = array(
+ 'name' => $name,
+ 'value' => $value,
+ 'op' => $operation,
+ );
+ }
+ public function attributeNS($name, $ns, $value = NULL, $operation = EventHandler::isExactly) {
+ $this->currSelector->attributes[] = array(
+ 'name' => $name,
+ 'value' => $value,
+ 'op' => $operation,
+ 'ns' => $ns,
+ );
+ }
+ public function pseudoClass($name, $value = NULL) {
+ $this->currSelector->pseudoClasses[] = array('name' => $name, 'value' => $value);
+ }
+ public function pseudoElement($name) {
+ $this->currSelector->pseudoElements[] = $name;
+ }
+ public function combinator($combinatorName) {
+ $this->currSelector->combinator = $combinatorName;
+ $this->currSelector = new SimpleSelector();
+ array_unshift($this->selectors[$this->groupIndex], $this->currSelector);
+ //$this->selectors[]= $this->currSelector;
+ }
+ public function directDescendant() {
+ $this->combinator(SimpleSelector::directDescendant);
+ }
+ public function adjacent() {
+ $this->combinator(SimpleSelector::adjacent);
+ }
+ public function anotherSelector() {
+ $this->groupIndex++;
+ $this->currSelector = new SimpleSelector();
+ $this->selectors[$this->groupIndex] = array($this->currSelector);
+ }
+ public function sibling() {
+ $this->combinator(SimpleSelector::sibling);
+ }
+ public function anyDescendant() {
+ $this->combinator(SimpleSelector::anyDescendant);
+ }
+}
diff --git a/lib/querypath/src/QueryPath/CSS/SimpleSelector.php b/lib/querypath/src/QueryPath/CSS/SimpleSelector.php
new file mode 100644
index 0000000..3fcc796
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/SimpleSelector.php
@@ -0,0 +1,138 @@
+<?php
+/** @file
+ *
+ * A simple selector.
+ *
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * Models a simple selector.
+ *
+ * CSS Selectors are composed of one or more simple selectors, where
+ * each simple selector may have any of the following components:
+ *
+ * - An element name (or wildcard *)
+ * - An ID (#foo)
+ * - One or more classes (.foo.bar)
+ * - One or more attribute matchers ([foo=bar])
+ * - One or more pseudo-classes (:foo)
+ * - One or more pseudo-elements (::first)
+ *
+ * For performance reasons, this object has been kept as sparse as
+ * possible.
+ *
+ * @since QueryPath 3.x
+ * @author M Butcher
+ *
+ */
+class SimpleSelector {
+
+ const adjacent = 1;
+ const directDescendant = 2;
+ const anotherSelector = 4;
+ const sibling = 8;
+ const anyDescendant = 16;
+
+ public $element;
+ public $ns;
+ public $id;
+ public $classes = array();
+ public $attributes = array();
+ public $pseudoClasses = array();
+ public $pseudoElements = array();
+ public $combinator;
+
+ public static function attributeOperator($code) {
+ switch($code) {
+ case EventHandler::containsWithSpace:
+ return '~=';
+ case EventHandler::containsWithHyphen:
+ return '|=';
+ case EventHandler::containsInString:
+ return '*=';
+ case EventHandler::beginsWith:
+ return '^=';
+ case EventHandler::endsWith:
+ return '$=';
+ default:
+ return '=';
+ }
+ }
+
+ public static function combinatorOperator($code) {
+ switch ($code) {
+ case self::adjacent:
+ return '+';
+ case self::directDescendant:
+ return '>';
+ case self::sibling:
+ return '~';
+ case self::anotherSelector:
+ return ', ';
+ case self::anyDescendant:
+ return ' ';
+ }
+ }
+
+ public function __construct() {
+ }
+
+ public function notEmpty() {
+ return !empty($element)
+ && !empty($id)
+ && !empty($classes)
+ && !empty($combinator)
+ && !empty($attributes)
+ && !empty($pseudoClasses)
+ && !empty($pseudoElements)
+ ;
+ }
+
+ public function __tostring() {
+ $buffer = array();
+ try {
+
+ if (!empty($this->ns)) {
+ $buffer[] = $this->ns; $buffer[] = '|';
+ }
+ if (!empty($this->element)) $buffer[] = $this->element;
+ if (!empty($this->id)) $buffer[] = '#' . $this->id;
+ if (!empty($this->attributes)) {
+ foreach ($this->attributes as $attr) {
+ $buffer[] = '[';
+ if(!empty($attr['ns'])) $buffer[] = $attr['ns'] . '|';
+ $buffer[] = $attr['name'];
+ if (!empty($attr['value'])) {
+ $buffer[] = self::attributeOperator($attr['op']);
+ $buffer[] = $attr['value'];
+ }
+ $buffer[] = ']';
+ }
+ }
+ if (!empty($this->pseudoClasses)) {
+ foreach ($this->pseudoClasses as $ps) {
+ $buffer[] = ':' . $ps['name'];
+ if (isset($ps['value'])) {
+ $buffer[] = '(' . $ps['value'] . ')';
+ }
+ }
+ }
+ foreach ($this->pseudoElements as $pe) {
+ $buffer[] = '::' . $pe;
+ }
+
+ if (!empty($this->combinator)) {
+ $buffer[] = self::combinatorOperator($this->combinator);
+ }
+
+ }
+ catch (\Exception $e) {
+ return $e->getMessage();
+ }
+
+ return implode('', $buffer);
+ }
+
+}
diff --git a/lib/querypath/src/QueryPath/CSS/Token.php b/lib/querypath/src/QueryPath/CSS/Token.php
new file mode 100644
index 0000000..3c31ef4
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/Token.php
@@ -0,0 +1,60 @@
+<?php
+/** @file
+ * Parser tokens.
+ */
+namespace QueryPath\CSS;
+/**
+ * Tokens for CSS.
+ * This class defines the recognized tokens for the parser, and also
+ * provides utility functions for error reporting.
+ *
+ * @ingroup querypath_css
+ */
+final class Token {
+ const char = 0;
+ const star = 1;
+ const rangle = 2;
+ const dot = 3;
+ const octo = 4;
+ const rsquare = 5;
+ const lsquare = 6;
+ const colon = 7;
+ const rparen = 8;
+ const lparen = 9;
+ const plus = 10;
+ const tilde = 11;
+ const eq = 12;
+ const pipe = 13;
+ const comma = 14;
+ const white = 15;
+ const quote = 16;
+ const squote = 17;
+ const bslash = 18;
+ const carat = 19;
+ const dollar = 20;
+ const at = 21; // This is not in the spec. Apparently, old broken CSS uses it.
+
+ // In legal range for string.
+ const stringLegal = 99;
+
+ /**
+ * Get a name for a given constant. Used for error handling.
+ */
+ static function name($const_int) {
+ $a = array('character', 'star', 'right angle bracket',
+ 'dot', 'octothorp', 'right square bracket', 'left square bracket',
+ 'colon', 'right parenthesis', 'left parenthesis', 'plus', 'tilde',
+ 'equals', 'vertical bar', 'comma', 'space', 'quote', 'single quote',
+ 'backslash', 'carat', 'dollar', 'at');
+ if (isset($a[$const_int]) && is_numeric($const_int)) {
+ return $a[$const_int];
+ }
+ elseif ($const_int == 99) {
+ return 'a legal non-alphanumeric character';
+ }
+ elseif ($const_int == FALSE) {
+ return 'end of file';
+ }
+ return sprintf('illegal character (%s)', $const_int);
+ }
+}
diff --git a/lib/querypath/src/QueryPath/CSS/Traverser.php b/lib/querypath/src/QueryPath/CSS/Traverser.php
new file mode 100644
index 0000000..6d16d63
--- /dev/null
+++ b/lib/querypath/src/QueryPath/CSS/Traverser.php
@@ -0,0 +1,38 @@
+<?php
+/**
+ * @file
+ * The main Traverser interface.
+ */
+
+namespace QueryPath\CSS;
+
+/**
+ * An object capable of walking (and searching) a datastructure.
+ */
+interface Traverser {
+ /**
+ * Process a CSS selector and find matches.
+ *
+ * This specifies a query to be run by the Traverser. A given
+ * Traverser may, in practice, delay the finding until some later time
+ * but must return the found results when getMatches() is called.
+ *
+ * @param string $selector
+ * A selector. Typically this is a CSS 3 Selector.
+ * @return \Traverser
+ * The Traverser that can return matches.
+ */
+ public function find($selector);
+ /**
+ * Get the results of a find() operation.
+ *
+ * Return an array of matching items.
+ *
+ * @return array
+ * An array of matched values. The specific data type in the matches
+ * will differ depending on the data type searched, but in the core
+ * QueryPath implementation, this will be an array of DOMNode
+ * objects.
+ */
+ public function matches();
+}