Some misc fixes to tests:
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob5b79876bea040293e8b56b91fe451d49bf58d1fe
1 <?php
2 /**
3 * Preprocessor using PHP's dom extension
5 * @file
6 * @ingroup Parser
7 */
9 /**
10 * @ingroup Parser
12 class Preprocessor_DOM implements Preprocessor {
14 /**
15 * @var Parser
17 var $parser;
19 var $memoryLimit;
21 const CACHE_VERSION = 1;
23 function __construct( $parser ) {
24 $this->parser = $parser;
25 $mem = ini_get( 'memory_limit' );
26 $this->memoryLimit = false;
27 if ( strval( $mem ) !== '' && $mem != -1 ) {
28 if ( preg_match( '/^\d+$/', $mem ) ) {
29 $this->memoryLimit = $mem;
30 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
31 $this->memoryLimit = $m[1] * 1048576;
36 /**
37 * @return PPFrame_DOM
39 function newFrame() {
40 return new PPFrame_DOM( $this );
43 /**
44 * @param $args
45 * @return PPCustomFrame_DOM
47 function newCustomFrame( $args ) {
48 return new PPCustomFrame_DOM( $this, $args );
51 /**
52 * @param $values
53 * @return PPNode_DOM
55 function newPartNodeArray( $values ) {
56 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
57 $xml = "<list>";
59 foreach ( $values as $k => $val ) {
61 if ( is_int( $k ) ) {
62 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
63 } else {
64 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
68 $xml .= "</list>";
70 $dom = new DOMDocument();
71 $dom->loadXML( $xml );
72 $root = $dom->documentElement;
74 $node = new PPNode_DOM( $root->childNodes );
75 return $node;
78 /**
79 * @throws MWException
80 * @return bool
82 function memCheck() {
83 if ( $this->memoryLimit === false ) {
84 return;
86 $usage = memory_get_usage();
87 if ( $usage > $this->memoryLimit * 0.9 ) {
88 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
89 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
91 return $usage <= $this->memoryLimit * 0.8;
94 /**
95 * Preprocess some wikitext and return the document tree.
96 * This is the ghost of Parser::replace_variables().
98 * @param $text String: the text to parse
99 * @param $flags Integer: bitwise combination of:
100 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
101 * included. Default is to assume a direct page view.
103 * The generated DOM tree must depend only on the input text and the flags.
104 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
106 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
107 * change in the DOM tree for a given text, must be passed through the section identifier
108 * in the section edit link and thus back to extractSections().
110 * The output of this function is currently only cached in process memory, but a persistent
111 * cache may be implemented at a later date which takes further advantage of these strict
112 * dependency requirements.
114 * @return PPNode_DOM
116 function preprocessToObj( $text, $flags = 0 ) {
117 wfProfileIn( __METHOD__ );
118 global $wgMemc, $wgPreprocessorCacheThreshold;
120 $xml = false;
121 $cacheable = ( $wgPreprocessorCacheThreshold !== false
122 && strlen( $text ) > $wgPreprocessorCacheThreshold );
123 if ( $cacheable ) {
124 wfProfileIn( __METHOD__.'-cacheable' );
126 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
127 $cacheValue = $wgMemc->get( $cacheKey );
128 if ( $cacheValue ) {
129 $version = substr( $cacheValue, 0, 8 );
130 if ( intval( $version ) == self::CACHE_VERSION ) {
131 $xml = substr( $cacheValue, 8 );
132 // From the cache
133 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
137 if ( $xml === false ) {
138 if ( $cacheable ) {
139 wfProfileIn( __METHOD__.'-cache-miss' );
140 $xml = $this->preprocessToXml( $text, $flags );
141 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
142 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
143 wfProfileOut( __METHOD__.'-cache-miss' );
144 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
145 } else {
146 $xml = $this->preprocessToXml( $text, $flags );
150 wfProfileIn( __METHOD__.'-loadXML' );
151 $dom = new DOMDocument;
152 wfSuppressWarnings();
153 $result = $dom->loadXML( $xml );
154 wfRestoreWarnings();
155 if ( !$result ) {
156 // Try running the XML through UtfNormal to get rid of invalid characters
157 $xml = UtfNormal::cleanUp( $xml );
158 $result = $dom->loadXML( $xml );
159 if ( !$result ) {
160 throw new MWException( __METHOD__.' generated invalid XML' );
163 $obj = new PPNode_DOM( $dom->documentElement );
164 wfProfileOut( __METHOD__.'-loadXML' );
165 if ( $cacheable ) {
166 wfProfileOut( __METHOD__.'-cacheable' );
168 wfProfileOut( __METHOD__ );
169 return $obj;
173 * @param $text string
174 * @param $flags int
175 * @return string
177 function preprocessToXml( $text, $flags = 0 ) {
178 wfProfileIn( __METHOD__ );
179 $rules = array(
180 '{' => array(
181 'end' => '}',
182 'names' => array(
183 2 => 'template',
184 3 => 'tplarg',
186 'min' => 2,
187 'max' => 3,
189 '[' => array(
190 'end' => ']',
191 'names' => array( 2 => null ),
192 'min' => 2,
193 'max' => 2,
197 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
199 $xmlishElements = $this->parser->getStripList();
200 $enableOnlyinclude = false;
201 if ( $forInclusion ) {
202 $ignoredTags = array( 'includeonly', '/includeonly' );
203 $ignoredElements = array( 'noinclude' );
204 $xmlishElements[] = 'noinclude';
205 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
206 $enableOnlyinclude = true;
208 } else {
209 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
210 $ignoredElements = array( 'includeonly' );
211 $xmlishElements[] = 'includeonly';
213 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
215 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
216 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
218 $stack = new PPDStack;
220 $searchBase = "[{<\n"; #}
221 $revText = strrev( $text ); // For fast reverse searches
223 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
224 $accum =& $stack->getAccum(); # Current accumulator
225 $accum = '<root>';
226 $findEquals = false; # True to find equals signs in arguments
227 $findPipe = false; # True to take notice of pipe characters
228 $headingIndex = 1;
229 $inHeading = false; # True if $i is inside a possible heading
230 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
231 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
232 $fakeLineStart = true; # Do a line-start run without outputting an LF character
234 while ( true ) {
235 //$this->memCheck();
237 if ( $findOnlyinclude ) {
238 // Ignore all input up to the next <onlyinclude>
239 $startPos = strpos( $text, '<onlyinclude>', $i );
240 if ( $startPos === false ) {
241 // Ignored section runs to the end
242 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
243 break;
245 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
246 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
247 $i = $tagEndPos;
248 $findOnlyinclude = false;
251 if ( $fakeLineStart ) {
252 $found = 'line-start';
253 $curChar = '';
254 } else {
255 # Find next opening brace, closing brace or pipe
256 $search = $searchBase;
257 if ( $stack->top === false ) {
258 $currentClosing = '';
259 } else {
260 $currentClosing = $stack->top->close;
261 $search .= $currentClosing;
263 if ( $findPipe ) {
264 $search .= '|';
266 if ( $findEquals ) {
267 // First equals will be for the template
268 $search .= '=';
270 $rule = null;
271 # Output literal section, advance input counter
272 $literalLength = strcspn( $text, $search, $i );
273 if ( $literalLength > 0 ) {
274 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
275 $i += $literalLength;
277 if ( $i >= strlen( $text ) ) {
278 if ( $currentClosing == "\n" ) {
279 // Do a past-the-end run to finish off the heading
280 $curChar = '';
281 $found = 'line-end';
282 } else {
283 # All done
284 break;
286 } else {
287 $curChar = $text[$i];
288 if ( $curChar == '|' ) {
289 $found = 'pipe';
290 } elseif ( $curChar == '=' ) {
291 $found = 'equals';
292 } elseif ( $curChar == '<' ) {
293 $found = 'angle';
294 } elseif ( $curChar == "\n" ) {
295 if ( $inHeading ) {
296 $found = 'line-end';
297 } else {
298 $found = 'line-start';
300 } elseif ( $curChar == $currentClosing ) {
301 $found = 'close';
302 } elseif ( isset( $rules[$curChar] ) ) {
303 $found = 'open';
304 $rule = $rules[$curChar];
305 } else {
306 # Some versions of PHP have a strcspn which stops on null characters
307 # Ignore and continue
308 ++$i;
309 continue;
314 if ( $found == 'angle' ) {
315 $matches = false;
316 // Handle </onlyinclude>
317 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
318 $findOnlyinclude = true;
319 continue;
322 // Determine element name
323 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
324 // Element name missing or not listed
325 $accum .= '&lt;';
326 ++$i;
327 continue;
329 // Handle comments
330 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
331 // To avoid leaving blank lines, when a comment is both preceded
332 // and followed by a newline (ignoring spaces), trim leading and
333 // trailing spaces and one of the newlines.
335 // Find the end
336 $endPos = strpos( $text, '-->', $i + 4 );
337 if ( $endPos === false ) {
338 // Unclosed comment in input, runs to end
339 $inner = substr( $text, $i );
340 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
341 $i = strlen( $text );
342 } else {
343 // Search backwards for leading whitespace
344 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
345 // Search forwards for trailing whitespace
346 // $wsEnd will be the position of the last space (or the '>' if there's none)
347 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
348 // Eat the line if possible
349 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
350 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
351 // it's a possible beneficial b/c break.
352 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
353 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
355 $startPos = $wsStart;
356 $endPos = $wsEnd + 1;
357 // Remove leading whitespace from the end of the accumulator
358 // Sanity check first though
359 $wsLength = $i - $wsStart;
360 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
361 $accum = substr( $accum, 0, -$wsLength );
363 // Do a line-start run next time to look for headings after the comment
364 $fakeLineStart = true;
365 } else {
366 // No line to eat, just take the comment itself
367 $startPos = $i;
368 $endPos += 2;
371 if ( $stack->top ) {
372 $part = $stack->top->getCurrentPart();
373 if ( ! (isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 )) {
374 $part->visualEnd = $wsStart;
376 // Else comments abutting, no change in visual end
377 $part->commentEnd = $endPos;
379 $i = $endPos + 1;
380 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
381 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
383 continue;
385 $name = $matches[1];
386 $lowerName = strtolower( $name );
387 $attrStart = $i + strlen( $name ) + 1;
389 // Find end of tag
390 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
391 if ( $tagEndPos === false ) {
392 // Infinite backtrack
393 // Disable tag search to prevent worst-case O(N^2) performance
394 $noMoreGT = true;
395 $accum .= '&lt;';
396 ++$i;
397 continue;
400 // Handle ignored tags
401 if ( in_array( $lowerName, $ignoredTags ) ) {
402 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
403 $i = $tagEndPos + 1;
404 continue;
407 $tagStartPos = $i;
408 if ( $text[$tagEndPos-1] == '/' ) {
409 $attrEnd = $tagEndPos - 1;
410 $inner = null;
411 $i = $tagEndPos + 1;
412 $close = '';
413 } else {
414 $attrEnd = $tagEndPos;
415 // Find closing tag
416 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
417 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
419 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
420 $i = $matches[0][1] + strlen( $matches[0][0] );
421 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
422 } else {
423 // No end tag -- let it run out to the end of the text.
424 $inner = substr( $text, $tagEndPos + 1 );
425 $i = strlen( $text );
426 $close = '';
429 // <includeonly> and <noinclude> just become <ignore> tags
430 if ( in_array( $lowerName, $ignoredElements ) ) {
431 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
432 . '</ignore>';
433 continue;
436 $accum .= '<ext>';
437 if ( $attrEnd <= $attrStart ) {
438 $attr = '';
439 } else {
440 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
442 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
443 // Note that the attr element contains the whitespace between name and attribute,
444 // this is necessary for precise reconstruction during pre-save transform.
445 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
446 if ( $inner !== null ) {
447 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
449 $accum .= $close . '</ext>';
450 } elseif ( $found == 'line-start' ) {
451 // Is this the start of a heading?
452 // Line break belongs before the heading element in any case
453 if ( $fakeLineStart ) {
454 $fakeLineStart = false;
455 } else {
456 $accum .= $curChar;
457 $i++;
460 $count = strspn( $text, '=', $i, 6 );
461 if ( $count == 1 && $findEquals ) {
462 // DWIM: This looks kind of like a name/value separator
463 // Let's let the equals handler have it and break the potential heading
464 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
465 } elseif ( $count > 0 ) {
466 $piece = array(
467 'open' => "\n",
468 'close' => "\n",
469 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
470 'startPos' => $i,
471 'count' => $count );
472 $stack->push( $piece );
473 $accum =& $stack->getAccum();
474 $flags = $stack->getFlags();
475 extract( $flags );
476 $i += $count;
478 } elseif ( $found == 'line-end' ) {
479 $piece = $stack->top;
480 // A heading must be open, otherwise \n wouldn't have been in the search list
481 assert( $piece->open == "\n" );
482 $part = $piece->getCurrentPart();
483 // Search back through the input to see if it has a proper close
484 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
485 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
486 $searchStart = $i - $wsLength;
487 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
488 // Comment found at line end
489 // Search for equals signs before the comment
490 $searchStart = $part->visualEnd;
491 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
493 $count = $piece->count;
494 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
495 if ( $equalsLength > 0 ) {
496 if ( $searchStart - $equalsLength == $piece->startPos ) {
497 // This is just a single string of equals signs on its own line
498 // Replicate the doHeadings behaviour /={count}(.+)={count}/
499 // First find out how many equals signs there really are (don't stop at 6)
500 $count = $equalsLength;
501 if ( $count < 3 ) {
502 $count = 0;
503 } else {
504 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
506 } else {
507 $count = min( $equalsLength, $count );
509 if ( $count > 0 ) {
510 // Normal match, output <h>
511 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
512 $headingIndex++;
513 } else {
514 // Single equals sign on its own line, count=0
515 $element = $accum;
517 } else {
518 // No match, no <h>, just pass down the inner text
519 $element = $accum;
521 // Unwind the stack
522 $stack->pop();
523 $accum =& $stack->getAccum();
524 $flags = $stack->getFlags();
525 extract( $flags );
527 // Append the result to the enclosing accumulator
528 $accum .= $element;
529 // Note that we do NOT increment the input pointer.
530 // This is because the closing linebreak could be the opening linebreak of
531 // another heading. Infinite loops are avoided because the next iteration MUST
532 // hit the heading open case above, which unconditionally increments the
533 // input pointer.
534 } elseif ( $found == 'open' ) {
535 # count opening brace characters
536 $count = strspn( $text, $curChar, $i );
538 # we need to add to stack only if opening brace count is enough for one of the rules
539 if ( $count >= $rule['min'] ) {
540 # Add it to the stack
541 $piece = array(
542 'open' => $curChar,
543 'close' => $rule['end'],
544 'count' => $count,
545 'lineStart' => ($i == 0 || $text[$i-1] == "\n"),
548 $stack->push( $piece );
549 $accum =& $stack->getAccum();
550 $flags = $stack->getFlags();
551 extract( $flags );
552 } else {
553 # Add literal brace(s)
554 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
556 $i += $count;
557 } elseif ( $found == 'close' ) {
558 $piece = $stack->top;
559 # lets check if there are enough characters for closing brace
560 $maxCount = $piece->count;
561 $count = strspn( $text, $curChar, $i, $maxCount );
563 # check for maximum matching characters (if there are 5 closing
564 # characters, we will probably need only 3 - depending on the rules)
565 $rule = $rules[$piece->open];
566 if ( $count > $rule['max'] ) {
567 # The specified maximum exists in the callback array, unless the caller
568 # has made an error
569 $matchingCount = $rule['max'];
570 } else {
571 # Count is less than the maximum
572 # Skip any gaps in the callback array to find the true largest match
573 # Need to use array_key_exists not isset because the callback can be null
574 $matchingCount = $count;
575 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
576 --$matchingCount;
580 if ( $matchingCount <= 0 ) {
581 # No matching element found in callback array
582 # Output a literal closing brace and continue
583 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
584 $i += $count;
585 continue;
587 $name = $rule['names'][$matchingCount];
588 if ( $name === null ) {
589 // No element, just literal text
590 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
591 } else {
592 # Create XML element
593 # Note: $parts is already XML, does not need to be encoded further
594 $parts = $piece->parts;
595 $title = $parts[0]->out;
596 unset( $parts[0] );
598 # The invocation is at the start of the line if lineStart is set in
599 # the stack, and all opening brackets are used up.
600 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
601 $attr = ' lineStart="1"';
602 } else {
603 $attr = '';
606 $element = "<$name$attr>";
607 $element .= "<title>$title</title>";
608 $argIndex = 1;
609 foreach ( $parts as $part ) {
610 if ( isset( $part->eqpos ) ) {
611 $argName = substr( $part->out, 0, $part->eqpos );
612 $argValue = substr( $part->out, $part->eqpos + 1 );
613 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
614 } else {
615 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
616 $argIndex++;
619 $element .= "</$name>";
622 # Advance input pointer
623 $i += $matchingCount;
625 # Unwind the stack
626 $stack->pop();
627 $accum =& $stack->getAccum();
629 # Re-add the old stack element if it still has unmatched opening characters remaining
630 if ( $matchingCount < $piece->count ) {
631 $piece->parts = array( new PPDPart );
632 $piece->count -= $matchingCount;
633 # do we still qualify for any callback with remaining count?
634 $names = $rules[$piece->open]['names'];
635 $skippedBraces = 0;
636 $enclosingAccum =& $accum;
637 while ( $piece->count ) {
638 if ( array_key_exists( $piece->count, $names ) ) {
639 $stack->push( $piece );
640 $accum =& $stack->getAccum();
641 break;
643 --$piece->count;
644 $skippedBraces ++;
646 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
648 $flags = $stack->getFlags();
649 extract( $flags );
651 # Add XML element to the enclosing accumulator
652 $accum .= $element;
653 } elseif ( $found == 'pipe' ) {
654 $findEquals = true; // shortcut for getFlags()
655 $stack->addPart();
656 $accum =& $stack->getAccum();
657 ++$i;
658 } elseif ( $found == 'equals' ) {
659 $findEquals = false; // shortcut for getFlags()
660 $stack->getCurrentPart()->eqpos = strlen( $accum );
661 $accum .= '=';
662 ++$i;
666 # Output any remaining unclosed brackets
667 foreach ( $stack->stack as $piece ) {
668 $stack->rootAccum .= $piece->breakSyntax();
670 $stack->rootAccum .= '</root>';
671 $xml = $stack->rootAccum;
673 wfProfileOut( __METHOD__ );
675 return $xml;
680 * Stack class to help Preprocessor::preprocessToObj()
681 * @ingroup Parser
683 class PPDStack {
684 var $stack, $rootAccum;
687 * @var PPDStack
689 var $top;
690 var $out;
691 var $elementClass = 'PPDStackElement';
693 static $false = false;
695 function __construct() {
696 $this->stack = array();
697 $this->top = false;
698 $this->rootAccum = '';
699 $this->accum =& $this->rootAccum;
703 * @return int
705 function count() {
706 return count( $this->stack );
709 function &getAccum() {
710 return $this->accum;
713 function getCurrentPart() {
714 if ( $this->top === false ) {
715 return false;
716 } else {
717 return $this->top->getCurrentPart();
721 function push( $data ) {
722 if ( $data instanceof $this->elementClass ) {
723 $this->stack[] = $data;
724 } else {
725 $class = $this->elementClass;
726 $this->stack[] = new $class( $data );
728 $this->top = $this->stack[ count( $this->stack ) - 1 ];
729 $this->accum =& $this->top->getAccum();
732 function pop() {
733 if ( !count( $this->stack ) ) {
734 throw new MWException( __METHOD__.': no elements remaining' );
736 $temp = array_pop( $this->stack );
738 if ( count( $this->stack ) ) {
739 $this->top = $this->stack[ count( $this->stack ) - 1 ];
740 $this->accum =& $this->top->getAccum();
741 } else {
742 $this->top = self::$false;
743 $this->accum =& $this->rootAccum;
745 return $temp;
748 function addPart( $s = '' ) {
749 $this->top->addPart( $s );
750 $this->accum =& $this->top->getAccum();
754 * @return array
756 function getFlags() {
757 if ( !count( $this->stack ) ) {
758 return array(
759 'findEquals' => false,
760 'findPipe' => false,
761 'inHeading' => false,
763 } else {
764 return $this->top->getFlags();
770 * @ingroup Parser
772 class PPDStackElement {
773 var $open, // Opening character (\n for heading)
774 $close, // Matching closing character
775 $count, // Number of opening characters found (number of "=" for heading)
776 $parts, // Array of PPDPart objects describing pipe-separated parts.
777 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
779 var $partClass = 'PPDPart';
781 function __construct( $data = array() ) {
782 $class = $this->partClass;
783 $this->parts = array( new $class );
785 foreach ( $data as $name => $value ) {
786 $this->$name = $value;
790 function &getAccum() {
791 return $this->parts[count($this->parts) - 1]->out;
794 function addPart( $s = '' ) {
795 $class = $this->partClass;
796 $this->parts[] = new $class( $s );
799 function getCurrentPart() {
800 return $this->parts[count($this->parts) - 1];
804 * @return array
806 function getFlags() {
807 $partCount = count( $this->parts );
808 $findPipe = $this->open != "\n" && $this->open != '[';
809 return array(
810 'findPipe' => $findPipe,
811 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
812 'inHeading' => $this->open == "\n",
817 * Get the output string that would result if the close is not found.
819 * @return string
821 function breakSyntax( $openingCount = false ) {
822 if ( $this->open == "\n" ) {
823 $s = $this->parts[0]->out;
824 } else {
825 if ( $openingCount === false ) {
826 $openingCount = $this->count;
828 $s = str_repeat( $this->open, $openingCount );
829 $first = true;
830 foreach ( $this->parts as $part ) {
831 if ( $first ) {
832 $first = false;
833 } else {
834 $s .= '|';
836 $s .= $part->out;
839 return $s;
844 * @ingroup Parser
846 class PPDPart {
847 var $out; // Output accumulator string
849 // Optional member variables:
850 // eqpos Position of equals sign in output accumulator
851 // commentEnd Past-the-end input pointer for the last comment encountered
852 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
854 function __construct( $out = '' ) {
855 $this->out = $out;
860 * An expansion frame, used as a context to expand the result of preprocessToObj()
861 * @ingroup Parser
863 class PPFrame_DOM implements PPFrame {
866 * @var Preprocessor
868 var $preprocessor;
871 * @var Parser
873 var $parser;
876 * @var Title
878 var $title;
879 var $titleCache;
882 * Hashtable listing templates which are disallowed for expansion in this frame,
883 * having been encountered previously in parent frames.
885 var $loopCheckHash;
888 * Recursion depth of this frame, top = 0
889 * Note that this is NOT the same as expansion depth in expand()
891 var $depth;
895 * Construct a new preprocessor frame.
896 * @param $preprocessor Preprocessor The parent preprocessor
898 function __construct( $preprocessor ) {
899 $this->preprocessor = $preprocessor;
900 $this->parser = $preprocessor->parser;
901 $this->title = $this->parser->mTitle;
902 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
903 $this->loopCheckHash = array();
904 $this->depth = 0;
908 * Create a new child frame
909 * $args is optionally a multi-root PPNode or array containing the template arguments
911 * @return PPTemplateFrame_DOM
913 function newChild( $args = false, $title = false ) {
914 $namedArgs = array();
915 $numberedArgs = array();
916 if ( $title === false ) {
917 $title = $this->title;
919 if ( $args !== false ) {
920 $xpath = false;
921 if ( $args instanceof PPNode ) {
922 $args = $args->node;
924 foreach ( $args as $arg ) {
925 if ( !$xpath ) {
926 $xpath = new DOMXPath( $arg->ownerDocument );
929 $nameNodes = $xpath->query( 'name', $arg );
930 $value = $xpath->query( 'value', $arg );
931 if ( $nameNodes->item( 0 )->hasAttributes() ) {
932 // Numbered parameter
933 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
934 $numberedArgs[$index] = $value->item( 0 );
935 unset( $namedArgs[$index] );
936 } else {
937 // Named parameter
938 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
939 $namedArgs[$name] = $value->item( 0 );
940 unset( $numberedArgs[$name] );
944 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
948 * @throws MWException
949 * @param $root
950 * @param $flags int
951 * @return string
953 function expand( $root, $flags = 0 ) {
954 static $expansionDepth = 0;
955 if ( is_string( $root ) ) {
956 return $root;
959 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
960 return '<span class="error">Node-count limit exceeded</span>';
963 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
964 return '<span class="error">Expansion depth limit exceeded</span>';
966 wfProfileIn( __METHOD__ );
967 ++$expansionDepth;
969 if ( $root instanceof PPNode_DOM ) {
970 $root = $root->node;
972 if ( $root instanceof DOMDocument ) {
973 $root = $root->documentElement;
976 $outStack = array( '', '' );
977 $iteratorStack = array( false, $root );
978 $indexStack = array( 0, 0 );
980 while ( count( $iteratorStack ) > 1 ) {
981 $level = count( $outStack ) - 1;
982 $iteratorNode =& $iteratorStack[ $level ];
983 $out =& $outStack[$level];
984 $index =& $indexStack[$level];
986 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
988 if ( is_array( $iteratorNode ) ) {
989 if ( $index >= count( $iteratorNode ) ) {
990 // All done with this iterator
991 $iteratorStack[$level] = false;
992 $contextNode = false;
993 } else {
994 $contextNode = $iteratorNode[$index];
995 $index++;
997 } elseif ( $iteratorNode instanceof DOMNodeList ) {
998 if ( $index >= $iteratorNode->length ) {
999 // All done with this iterator
1000 $iteratorStack[$level] = false;
1001 $contextNode = false;
1002 } else {
1003 $contextNode = $iteratorNode->item( $index );
1004 $index++;
1006 } else {
1007 // Copy to $contextNode and then delete from iterator stack,
1008 // because this is not an iterator but we do have to execute it once
1009 $contextNode = $iteratorStack[$level];
1010 $iteratorStack[$level] = false;
1013 if ( $contextNode instanceof PPNode_DOM ) {
1014 $contextNode = $contextNode->node;
1017 $newIterator = false;
1019 if ( $contextNode === false ) {
1020 // nothing to do
1021 } elseif ( is_string( $contextNode ) ) {
1022 $out .= $contextNode;
1023 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1024 $newIterator = $contextNode;
1025 } elseif ( $contextNode instanceof DOMNode ) {
1026 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1027 $out .= $contextNode->nodeValue;
1028 } elseif ( $contextNode->nodeName == 'template' ) {
1029 # Double-brace expansion
1030 $xpath = new DOMXPath( $contextNode->ownerDocument );
1031 $titles = $xpath->query( 'title', $contextNode );
1032 $title = $titles->item( 0 );
1033 $parts = $xpath->query( 'part', $contextNode );
1034 if ( $flags & PPFrame::NO_TEMPLATES ) {
1035 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1036 } else {
1037 $lineStart = $contextNode->getAttribute( 'lineStart' );
1038 $params = array(
1039 'title' => new PPNode_DOM( $title ),
1040 'parts' => new PPNode_DOM( $parts ),
1041 'lineStart' => $lineStart );
1042 $ret = $this->parser->braceSubstitution( $params, $this );
1043 if ( isset( $ret['object'] ) ) {
1044 $newIterator = $ret['object'];
1045 } else {
1046 $out .= $ret['text'];
1049 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1050 # Triple-brace expansion
1051 $xpath = new DOMXPath( $contextNode->ownerDocument );
1052 $titles = $xpath->query( 'title', $contextNode );
1053 $title = $titles->item( 0 );
1054 $parts = $xpath->query( 'part', $contextNode );
1055 if ( $flags & PPFrame::NO_ARGS ) {
1056 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1057 } else {
1058 $params = array(
1059 'title' => new PPNode_DOM( $title ),
1060 'parts' => new PPNode_DOM( $parts ) );
1061 $ret = $this->parser->argSubstitution( $params, $this );
1062 if ( isset( $ret['object'] ) ) {
1063 $newIterator = $ret['object'];
1064 } else {
1065 $out .= $ret['text'];
1068 } elseif ( $contextNode->nodeName == 'comment' ) {
1069 # HTML-style comment
1070 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1071 if ( $this->parser->ot['html']
1072 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1073 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1075 $out .= '';
1077 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1078 # Not in RECOVER_COMMENTS mode (extractSections) though
1079 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1080 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1082 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1083 else {
1084 $out .= $contextNode->textContent;
1086 } elseif ( $contextNode->nodeName == 'ignore' ) {
1087 # Output suppression used by <includeonly> etc.
1088 # OT_WIKI will only respect <ignore> in substed templates.
1089 # The other output types respect it unless NO_IGNORE is set.
1090 # extractSections() sets NO_IGNORE and so never respects it.
1091 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1092 $out .= $contextNode->textContent;
1093 } else {
1094 $out .= '';
1096 } elseif ( $contextNode->nodeName == 'ext' ) {
1097 # Extension tag
1098 $xpath = new DOMXPath( $contextNode->ownerDocument );
1099 $names = $xpath->query( 'name', $contextNode );
1100 $attrs = $xpath->query( 'attr', $contextNode );
1101 $inners = $xpath->query( 'inner', $contextNode );
1102 $closes = $xpath->query( 'close', $contextNode );
1103 $params = array(
1104 'name' => new PPNode_DOM( $names->item( 0 ) ),
1105 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1106 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1107 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1109 $out .= $this->parser->extensionSubstitution( $params, $this );
1110 } elseif ( $contextNode->nodeName == 'h' ) {
1111 # Heading
1112 $s = $this->expand( $contextNode->childNodes, $flags );
1114 # Insert a heading marker only for <h> children of <root>
1115 # This is to stop extractSections from going over multiple tree levels
1116 if ( $contextNode->parentNode->nodeName == 'root'
1117 && $this->parser->ot['html'] )
1119 # Insert heading index marker
1120 $headingIndex = $contextNode->getAttribute( 'i' );
1121 $titleText = $this->title->getPrefixedDBkey();
1122 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1123 $serial = count( $this->parser->mHeadings ) - 1;
1124 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1125 $count = $contextNode->getAttribute( 'level' );
1126 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1127 $this->parser->mStripState->addGeneral( $marker, '' );
1129 $out .= $s;
1130 } else {
1131 # Generic recursive expansion
1132 $newIterator = $contextNode->childNodes;
1134 } else {
1135 wfProfileOut( __METHOD__ );
1136 throw new MWException( __METHOD__.': Invalid parameter type' );
1139 if ( $newIterator !== false ) {
1140 if ( $newIterator instanceof PPNode_DOM ) {
1141 $newIterator = $newIterator->node;
1143 $outStack[] = '';
1144 $iteratorStack[] = $newIterator;
1145 $indexStack[] = 0;
1146 } elseif ( $iteratorStack[$level] === false ) {
1147 // Return accumulated value to parent
1148 // With tail recursion
1149 while ( $iteratorStack[$level] === false && $level > 0 ) {
1150 $outStack[$level - 1] .= $out;
1151 array_pop( $outStack );
1152 array_pop( $iteratorStack );
1153 array_pop( $indexStack );
1154 $level--;
1158 --$expansionDepth;
1159 wfProfileOut( __METHOD__ );
1160 return $outStack[0];
1164 * @param $sep
1165 * @param $flags
1166 * @return string
1168 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1169 $args = array_slice( func_get_args(), 2 );
1171 $first = true;
1172 $s = '';
1173 foreach ( $args as $root ) {
1174 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1175 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1176 $root = array( $root );
1178 foreach ( $root as $node ) {
1179 if ( $first ) {
1180 $first = false;
1181 } else {
1182 $s .= $sep;
1184 $s .= $this->expand( $node, $flags );
1187 return $s;
1191 * Implode with no flags specified
1192 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1194 * @return string
1196 function implode( $sep /*, ... */ ) {
1197 $args = array_slice( func_get_args(), 1 );
1199 $first = true;
1200 $s = '';
1201 foreach ( $args as $root ) {
1202 if ( $root instanceof PPNode_DOM ) {
1203 $root = $root->node;
1205 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1206 $root = array( $root );
1208 foreach ( $root as $node ) {
1209 if ( $first ) {
1210 $first = false;
1211 } else {
1212 $s .= $sep;
1214 $s .= $this->expand( $node );
1217 return $s;
1221 * Makes an object that, when expand()ed, will be the same as one obtained
1222 * with implode()
1224 * @return array
1226 function virtualImplode( $sep /*, ... */ ) {
1227 $args = array_slice( func_get_args(), 1 );
1228 $out = array();
1229 $first = true;
1231 foreach ( $args as $root ) {
1232 if ( $root instanceof PPNode_DOM ) {
1233 $root = $root->node;
1235 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1236 $root = array( $root );
1238 foreach ( $root as $node ) {
1239 if ( $first ) {
1240 $first = false;
1241 } else {
1242 $out[] = $sep;
1244 $out[] = $node;
1247 return $out;
1251 * Virtual implode with brackets
1253 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1254 $args = array_slice( func_get_args(), 3 );
1255 $out = array( $start );
1256 $first = true;
1258 foreach ( $args as $root ) {
1259 if ( $root instanceof PPNode_DOM ) {
1260 $root = $root->node;
1262 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1263 $root = array( $root );
1265 foreach ( $root as $node ) {
1266 if ( $first ) {
1267 $first = false;
1268 } else {
1269 $out[] = $sep;
1271 $out[] = $node;
1274 $out[] = $end;
1275 return $out;
1278 function __toString() {
1279 return 'frame{}';
1282 function getPDBK( $level = false ) {
1283 if ( $level === false ) {
1284 return $this->title->getPrefixedDBkey();
1285 } else {
1286 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1291 * @return array
1293 function getArguments() {
1294 return array();
1298 * @return array
1300 function getNumberedArguments() {
1301 return array();
1305 * @return array
1307 function getNamedArguments() {
1308 return array();
1312 * Returns true if there are no arguments in this frame
1314 * @return bool
1316 function isEmpty() {
1317 return true;
1320 function getArgument( $name ) {
1321 return false;
1325 * Returns true if the infinite loop check is OK, false if a loop is detected
1327 * @return bool
1329 function loopCheck( $title ) {
1330 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1334 * Return true if the frame is a template frame
1336 * @return bool
1338 function isTemplate() {
1339 return false;
1344 * Expansion frame with template arguments
1345 * @ingroup Parser
1347 class PPTemplateFrame_DOM extends PPFrame_DOM {
1348 var $numberedArgs, $namedArgs;
1351 * @var PPFrame_DOM
1353 var $parent;
1354 var $numberedExpansionCache, $namedExpansionCache;
1357 * @param $preprocessor
1358 * @param $parent PPFrame_DOM
1359 * @param $numberedArgs array
1360 * @param $namedArgs array
1361 * @param $title Title
1363 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1364 parent::__construct( $preprocessor );
1366 $this->parent = $parent;
1367 $this->numberedArgs = $numberedArgs;
1368 $this->namedArgs = $namedArgs;
1369 $this->title = $title;
1370 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1371 $this->titleCache = $parent->titleCache;
1372 $this->titleCache[] = $pdbk;
1373 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1374 if ( $pdbk !== false ) {
1375 $this->loopCheckHash[$pdbk] = true;
1377 $this->depth = $parent->depth + 1;
1378 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1381 function __toString() {
1382 $s = 'tplframe{';
1383 $first = true;
1384 $args = $this->numberedArgs + $this->namedArgs;
1385 foreach ( $args as $name => $value ) {
1386 if ( $first ) {
1387 $first = false;
1388 } else {
1389 $s .= ', ';
1391 $s .= "\"$name\":\"" .
1392 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1394 $s .= '}';
1395 return $s;
1399 * Returns true if there are no arguments in this frame
1401 * @return bool
1403 function isEmpty() {
1404 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1407 function getArguments() {
1408 $arguments = array();
1409 foreach ( array_merge(
1410 array_keys($this->numberedArgs),
1411 array_keys($this->namedArgs)) as $key ) {
1412 $arguments[$key] = $this->getArgument($key);
1414 return $arguments;
1417 function getNumberedArguments() {
1418 $arguments = array();
1419 foreach ( array_keys($this->numberedArgs) as $key ) {
1420 $arguments[$key] = $this->getArgument($key);
1422 return $arguments;
1425 function getNamedArguments() {
1426 $arguments = array();
1427 foreach ( array_keys($this->namedArgs) as $key ) {
1428 $arguments[$key] = $this->getArgument($key);
1430 return $arguments;
1433 function getNumberedArgument( $index ) {
1434 if ( !isset( $this->numberedArgs[$index] ) ) {
1435 return false;
1437 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1438 # No trimming for unnamed arguments
1439 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1441 return $this->numberedExpansionCache[$index];
1444 function getNamedArgument( $name ) {
1445 if ( !isset( $this->namedArgs[$name] ) ) {
1446 return false;
1448 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1449 # Trim named arguments post-expand, for backwards compatibility
1450 $this->namedExpansionCache[$name] = trim(
1451 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1453 return $this->namedExpansionCache[$name];
1456 function getArgument( $name ) {
1457 $text = $this->getNumberedArgument( $name );
1458 if ( $text === false ) {
1459 $text = $this->getNamedArgument( $name );
1461 return $text;
1465 * Return true if the frame is a template frame
1467 * @return bool
1469 function isTemplate() {
1470 return true;
1475 * Expansion frame with custom arguments
1476 * @ingroup Parser
1478 class PPCustomFrame_DOM extends PPFrame_DOM {
1479 var $args;
1481 function __construct( $preprocessor, $args ) {
1482 parent::__construct( $preprocessor );
1483 $this->args = $args;
1486 function __toString() {
1487 $s = 'cstmframe{';
1488 $first = true;
1489 foreach ( $this->args as $name => $value ) {
1490 if ( $first ) {
1491 $first = false;
1492 } else {
1493 $s .= ', ';
1495 $s .= "\"$name\":\"" .
1496 str_replace( '"', '\\"', $value->__toString() ) . '"';
1498 $s .= '}';
1499 return $s;
1503 * @return bool
1505 function isEmpty() {
1506 return !count( $this->args );
1509 function getArgument( $index ) {
1510 if ( !isset( $this->args[$index] ) ) {
1511 return false;
1513 return $this->args[$index];
1518 * @ingroup Parser
1520 class PPNode_DOM implements PPNode {
1523 * @var DOMElement
1525 var $node;
1526 var $xpath;
1528 function __construct( $node, $xpath = false ) {
1529 $this->node = $node;
1533 * @return DOMXPath
1535 function getXPath() {
1536 if ( $this->xpath === null ) {
1537 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1539 return $this->xpath;
1542 function __toString() {
1543 if ( $this->node instanceof DOMNodeList ) {
1544 $s = '';
1545 foreach ( $this->node as $node ) {
1546 $s .= $node->ownerDocument->saveXML( $node );
1548 } else {
1549 $s = $this->node->ownerDocument->saveXML( $this->node );
1551 return $s;
1555 * @return bool|PPNode_DOM
1557 function getChildren() {
1558 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1562 * @return bool|PPNode_DOM
1564 function getFirstChild() {
1565 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1569 * @return bool|PPNode_DOM
1571 function getNextSibling() {
1572 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1576 * @param $type
1578 * @return bool|PPNode_DOM
1580 function getChildrenOfType( $type ) {
1581 return new self( $this->getXPath()->query( $type, $this->node ) );
1585 * @return int
1587 function getLength() {
1588 if ( $this->node instanceof DOMNodeList ) {
1589 return $this->node->length;
1590 } else {
1591 return false;
1596 * @param $i
1597 * @return bool|PPNode_DOM
1599 function item( $i ) {
1600 $item = $this->node->item( $i );
1601 return $item ? new self( $item ) : false;
1605 * @return string
1607 function getName() {
1608 if ( $this->node instanceof DOMNodeList ) {
1609 return '#nodelist';
1610 } else {
1611 return $this->node->nodeName;
1616 * Split a <part> node into an associative array containing:
1617 * name PPNode name
1618 * index String index
1619 * value PPNode value
1621 * @return array
1623 function splitArg() {
1624 $xpath = $this->getXPath();
1625 $names = $xpath->query( 'name', $this->node );
1626 $values = $xpath->query( 'value', $this->node );
1627 if ( !$names->length || !$values->length ) {
1628 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1630 $name = $names->item( 0 );
1631 $index = $name->getAttribute( 'index' );
1632 return array(
1633 'name' => new self( $name ),
1634 'index' => $index,
1635 'value' => new self( $values->item( 0 ) ) );
1639 * Split an <ext> node into an associative array containing name, attr, inner and close
1640 * All values in the resulting array are PPNodes. Inner and close are optional.
1642 * @return array
1644 function splitExt() {
1645 $xpath = $this->getXPath();
1646 $names = $xpath->query( 'name', $this->node );
1647 $attrs = $xpath->query( 'attr', $this->node );
1648 $inners = $xpath->query( 'inner', $this->node );
1649 $closes = $xpath->query( 'close', $this->node );
1650 if ( !$names->length || !$attrs->length ) {
1651 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1653 $parts = array(
1654 'name' => new self( $names->item( 0 ) ),
1655 'attr' => new self( $attrs->item( 0 ) ) );
1656 if ( $inners->length ) {
1657 $parts['inner'] = new self( $inners->item( 0 ) );
1659 if ( $closes->length ) {
1660 $parts['close'] = new self( $closes->item( 0 ) );
1662 return $parts;
1666 * Split a <h> node
1668 function splitHeading() {
1669 if ( $this->getName() !== 'h' ) {
1670 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1672 return array(
1673 'i' => $this->node->getAttribute( 'i' ),
1674 'level' => $this->node->getAttribute( 'level' ),
1675 'contents' => $this->getChildren()