summaryrefslogtreecommitdiff
path: root/lib/querypath/src/QueryPath/CSS/DOMTraverser/PseudoClass.php
blob: 0bcaf79c258b99d19055609210fb759f8a35771d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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';
  }

}