3 * Preprocessor using PHP's dom extension
12 class Preprocessor_DOM
implements Preprocessor
{
13 var $parser, $memoryLimit;
15 const CACHE_VERSION
= 1;
17 function __construct( $parser ) {
18 $this->parser
= $parser;
19 $mem = ini_get( 'memory_limit' );
20 $this->memoryLimit
= false;
21 if ( strval( $mem ) !== '' && $mem != -1 ) {
22 if ( preg_match( '/^\d+$/', $mem ) ) {
23 $this->memoryLimit
= $mem;
24 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
25 $this->memoryLimit
= $m[1] * 1048576;
31 return new PPFrame_DOM( $this );
34 function newCustomFrame( $args ) {
35 return new PPCustomFrame_DOM( $this, $args );
38 function newPartNodeArray( $values ) {
39 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
42 foreach ( $values as $k => $val ) {
45 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
47 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name><value>" . htmlspecialchars( $val ) . "</value></part>";
53 $dom = new DOMDocument();
54 $dom->loadXML( $xml );
55 $root = $dom->documentElement
;
57 $node = new PPNode_DOM( $root->childNodes
);
62 if ( $this->memoryLimit
=== false ) {
65 $usage = memory_get_usage();
66 if ( $usage > $this->memoryLimit
* 0.9 ) {
67 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
68 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
70 return $usage <= $this->memoryLimit
* 0.8;
74 * Preprocess some wikitext and return the document tree.
75 * This is the ghost of Parser::replace_variables().
77 * @param $text String: the text to parse
78 * @param $flags Integer: bitwise combination of:
79 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
80 * included. Default is to assume a direct page view.
82 * The generated DOM tree must depend only on the input text and the flags.
83 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
85 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
86 * change in the DOM tree for a given text, must be passed through the section identifier
87 * in the section edit link and thus back to extractSections().
89 * The output of this function is currently only cached in process memory, but a persistent
90 * cache may be implemented at a later date which takes further advantage of these strict
91 * dependency requirements.
95 function preprocessToObj( $text, $flags = 0 ) {
96 wfProfileIn( __METHOD__
);
97 global $wgMemc, $wgPreprocessorCacheThreshold;
100 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
102 wfProfileIn( __METHOD__
.'-cacheable' );
104 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
105 $cacheValue = $wgMemc->get( $cacheKey );
107 $version = substr( $cacheValue, 0, 8 );
108 if ( intval( $version ) == self
::CACHE_VERSION
) {
109 $xml = substr( $cacheValue, 8 );
111 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
115 if ( $xml === false ) {
117 wfProfileIn( __METHOD__
.'-cache-miss' );
118 $xml = $this->preprocessToXml( $text, $flags );
119 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
120 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
121 wfProfileOut( __METHOD__
.'-cache-miss' );
122 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
124 $xml = $this->preprocessToXml( $text, $flags );
128 wfProfileIn( __METHOD__
.'-loadXML' );
129 $dom = new DOMDocument
;
130 wfSuppressWarnings();
131 $result = $dom->loadXML( $xml );
134 // Try running the XML through UtfNormal to get rid of invalid characters
135 $xml = UtfNormal
::cleanUp( $xml );
136 $result = $dom->loadXML( $xml );
138 throw new MWException( __METHOD__
.' generated invalid XML' );
141 $obj = new PPNode_DOM( $dom->documentElement
);
142 wfProfileOut( __METHOD__
.'-loadXML' );
144 wfProfileOut( __METHOD__
.'-cacheable' );
146 wfProfileOut( __METHOD__
);
150 function preprocessToXml( $text, $flags = 0 ) {
151 wfProfileIn( __METHOD__
);
164 'names' => array( 2 => null ),
170 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
172 $xmlishElements = $this->parser
->getStripList();
173 $enableOnlyinclude = false;
174 if ( $forInclusion ) {
175 $ignoredTags = array( 'includeonly', '/includeonly' );
176 $ignoredElements = array( 'noinclude' );
177 $xmlishElements[] = 'noinclude';
178 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
179 $enableOnlyinclude = true;
182 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
183 $ignoredElements = array( 'includeonly' );
184 $xmlishElements[] = 'includeonly';
186 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
188 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
189 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
191 $stack = new PPDStack
;
193 $searchBase = "[{<\n"; #}
194 $revText = strrev( $text ); // For fast reverse searches
196 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
197 $accum =& $stack->getAccum(); # Current accumulator
199 $findEquals = false; # True to find equals signs in arguments
200 $findPipe = false; # True to take notice of pipe characters
202 $inHeading = false; # True if $i is inside a possible heading
203 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
204 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
205 $fakeLineStart = true; # Do a line-start run without outputting an LF character
210 if ( $findOnlyinclude ) {
211 // Ignore all input up to the next <onlyinclude>
212 $startPos = strpos( $text, '<onlyinclude>', $i );
213 if ( $startPos === false ) {
214 // Ignored section runs to the end
215 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
218 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
219 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
221 $findOnlyinclude = false;
224 if ( $fakeLineStart ) {
225 $found = 'line-start';
228 # Find next opening brace, closing brace or pipe
229 $search = $searchBase;
230 if ( $stack->top
=== false ) {
231 $currentClosing = '';
233 $currentClosing = $stack->top
->close
;
234 $search .= $currentClosing;
240 // First equals will be for the template
244 # Output literal section, advance input counter
245 $literalLength = strcspn( $text, $search, $i );
246 if ( $literalLength > 0 ) {
247 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
248 $i +
= $literalLength;
250 if ( $i >= strlen( $text ) ) {
251 if ( $currentClosing == "\n" ) {
252 // Do a past-the-end run to finish off the heading
260 $curChar = $text[$i];
261 if ( $curChar == '|' ) {
263 } elseif ( $curChar == '=' ) {
265 } elseif ( $curChar == '<' ) {
267 } elseif ( $curChar == "\n" ) {
271 $found = 'line-start';
273 } elseif ( $curChar == $currentClosing ) {
275 } elseif ( isset( $rules[$curChar] ) ) {
277 $rule = $rules[$curChar];
279 # Some versions of PHP have a strcspn which stops on null characters
280 # Ignore and continue
287 if ( $found == 'angle' ) {
289 // Handle </onlyinclude>
290 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
291 $findOnlyinclude = true;
295 // Determine element name
296 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
297 // Element name missing or not listed
303 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
304 // To avoid leaving blank lines, when a comment is both preceded
305 // and followed by a newline (ignoring spaces), trim leading and
306 // trailing spaces and one of the newlines.
309 $endPos = strpos( $text, '-->', $i +
4 );
310 if ( $endPos === false ) {
311 // Unclosed comment in input, runs to end
312 $inner = substr( $text, $i );
313 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
314 $i = strlen( $text );
316 // Search backwards for leading whitespace
317 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
318 // Search forwards for trailing whitespace
319 // $wsEnd will be the position of the last space
320 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
321 // Eat the line if possible
322 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
323 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
324 // it's a possible beneficial b/c break.
325 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
326 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
328 $startPos = $wsStart;
329 $endPos = $wsEnd +
1;
330 // Remove leading whitespace from the end of the accumulator
331 // Sanity check first though
332 $wsLength = $i - $wsStart;
333 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
334 $accum = substr( $accum, 0, -$wsLength );
336 // Do a line-start run next time to look for headings after the comment
337 $fakeLineStart = true;
339 // No line to eat, just take the comment itself
345 $part = $stack->top
->getCurrentPart();
346 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
347 // Comments abutting, no change in visual end
348 $part->commentEnd
= $wsEnd;
350 $part->visualEnd
= $wsStart;
351 $part->commentEnd
= $endPos;
355 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
356 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
361 $lowerName = strtolower( $name );
362 $attrStart = $i +
strlen( $name ) +
1;
365 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
366 if ( $tagEndPos === false ) {
367 // Infinite backtrack
368 // Disable tag search to prevent worst-case O(N^2) performance
375 // Handle ignored tags
376 if ( in_array( $lowerName, $ignoredTags ) ) {
377 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
383 if ( $text[$tagEndPos-1] == '/' ) {
384 $attrEnd = $tagEndPos - 1;
389 $attrEnd = $tagEndPos;
391 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
392 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
394 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
395 $i = $matches[0][1] +
strlen( $matches[0][0] );
396 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
398 // No end tag -- let it run out to the end of the text.
399 $inner = substr( $text, $tagEndPos +
1 );
400 $i = strlen( $text );
404 // <includeonly> and <noinclude> just become <ignore> tags
405 if ( in_array( $lowerName, $ignoredElements ) ) {
406 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
412 if ( $attrEnd <= $attrStart ) {
415 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
417 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
418 // Note that the attr element contains the whitespace between name and attribute,
419 // this is necessary for precise reconstruction during pre-save transform.
420 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
421 if ( $inner !== null ) {
422 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
424 $accum .= $close . '</ext>';
427 elseif ( $found == 'line-start' ) {
428 // Is this the start of a heading?
429 // Line break belongs before the heading element in any case
430 if ( $fakeLineStart ) {
431 $fakeLineStart = false;
437 $count = strspn( $text, '=', $i, 6 );
438 if ( $count == 1 && $findEquals ) {
439 // DWIM: This looks kind of like a name/value separator
440 // Let's let the equals handler have it and break the potential heading
441 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
442 } elseif ( $count > 0 ) {
446 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
449 $stack->push( $piece );
450 $accum =& $stack->getAccum();
451 $flags = $stack->getFlags();
457 elseif ( $found == 'line-end' ) {
458 $piece = $stack->top
;
459 // A heading must be open, otherwise \n wouldn't have been in the search list
460 assert( $piece->open
== "\n" );
461 $part = $piece->getCurrentPart();
462 // Search back through the input to see if it has a proper close
463 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
464 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
465 $searchStart = $i - $wsLength;
466 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
467 // Comment found at line end
468 // Search for equals signs before the comment
469 $searchStart = $part->visualEnd
;
470 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
472 $count = $piece->count
;
473 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
474 if ( $equalsLength > 0 ) {
475 if ( $searchStart - $equalsLength == $piece->startPos
) {
476 // This is just a single string of equals signs on its own line
477 // Replicate the doHeadings behaviour /={count}(.+)={count}/
478 // First find out how many equals signs there really are (don't stop at 6)
479 $count = $equalsLength;
483 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
486 $count = min( $equalsLength, $count );
489 // Normal match, output <h>
490 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
493 // Single equals sign on its own line, count=0
497 // No match, no <h>, just pass down the inner text
502 $accum =& $stack->getAccum();
503 $flags = $stack->getFlags();
506 // Append the result to the enclosing accumulator
508 // Note that we do NOT increment the input pointer.
509 // This is because the closing linebreak could be the opening linebreak of
510 // another heading. Infinite loops are avoided because the next iteration MUST
511 // hit the heading open case above, which unconditionally increments the
513 } elseif ( $found == 'open' ) {
514 # count opening brace characters
515 $count = strspn( $text, $curChar, $i );
517 # we need to add to stack only if opening brace count is enough for one of the rules
518 if ( $count >= $rule['min'] ) {
519 # Add it to the stack
522 'close' => $rule['end'],
524 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
527 $stack->push( $piece );
528 $accum =& $stack->getAccum();
529 $flags = $stack->getFlags();
532 # Add literal brace(s)
533 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
536 } elseif ( $found == 'close' ) {
537 $piece = $stack->top
;
538 # lets check if there are enough characters for closing brace
539 $maxCount = $piece->count
;
540 $count = strspn( $text, $curChar, $i, $maxCount );
542 # check for maximum matching characters (if there are 5 closing
543 # characters, we will probably need only 3 - depending on the rules)
544 $rule = $rules[$piece->open
];
545 if ( $count > $rule['max'] ) {
546 # The specified maximum exists in the callback array, unless the caller
548 $matchingCount = $rule['max'];
550 # Count is less than the maximum
551 # Skip any gaps in the callback array to find the true largest match
552 # Need to use array_key_exists not isset because the callback can be null
553 $matchingCount = $count;
554 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
559 if ($matchingCount <= 0) {
560 # No matching element found in callback array
561 # Output a literal closing brace and continue
562 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
566 $name = $rule['names'][$matchingCount];
567 if ( $name === null ) {
568 // No element, just literal text
569 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
572 # Note: $parts is already XML, does not need to be encoded further
573 $parts = $piece->parts
;
574 $title = $parts[0]->out
;
577 # The invocation is at the start of the line if lineStart is set in
578 # the stack, and all opening brackets are used up.
579 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
580 $attr = ' lineStart="1"';
585 $element = "<$name$attr>";
586 $element .= "<title>$title</title>";
588 foreach ( $parts as $part ) {
589 if ( isset( $part->eqpos
) ) {
590 $argName = substr( $part->out
, 0, $part->eqpos
);
591 $argValue = substr( $part->out
, $part->eqpos +
1 );
592 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
594 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
598 $element .= "</$name>";
601 # Advance input pointer
602 $i +
= $matchingCount;
606 $accum =& $stack->getAccum();
608 # Re-add the old stack element if it still has unmatched opening characters remaining
609 if ($matchingCount < $piece->count
) {
610 $piece->parts
= array( new PPDPart
);
611 $piece->count
-= $matchingCount;
612 # do we still qualify for any callback with remaining count?
613 $names = $rules[$piece->open
]['names'];
615 $enclosingAccum =& $accum;
616 while ( $piece->count
) {
617 if ( array_key_exists( $piece->count
, $names ) ) {
618 $stack->push( $piece );
619 $accum =& $stack->getAccum();
625 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
627 $flags = $stack->getFlags();
630 # Add XML element to the enclosing accumulator
634 elseif ( $found == 'pipe' ) {
635 $findEquals = true; // shortcut for getFlags()
637 $accum =& $stack->getAccum();
641 elseif ( $found == 'equals' ) {
642 $findEquals = false; // shortcut for getFlags()
643 $stack->getCurrentPart()->eqpos
= strlen( $accum );
649 # Output any remaining unclosed brackets
650 foreach ( $stack->stack
as $piece ) {
651 $stack->rootAccum
.= $piece->breakSyntax();
653 $stack->rootAccum
.= '</root>';
654 $xml = $stack->rootAccum
;
656 wfProfileOut( __METHOD__
);
663 * Stack class to help Preprocessor::preprocessToObj()
667 var $stack, $rootAccum, $top;
669 var $elementClass = 'PPDStackElement';
671 static $false = false;
673 function __construct() {
674 $this->stack
= array();
676 $this->rootAccum
= '';
677 $this->accum
=& $this->rootAccum
;
681 return count( $this->stack
);
684 function &getAccum() {
688 function getCurrentPart() {
689 if ( $this->top
=== false ) {
692 return $this->top
->getCurrentPart();
696 function push( $data ) {
697 if ( $data instanceof $this->elementClass
) {
698 $this->stack
[] = $data;
700 $class = $this->elementClass
;
701 $this->stack
[] = new $class( $data );
703 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
704 $this->accum
=& $this->top
->getAccum();
708 if ( !count( $this->stack
) ) {
709 throw new MWException( __METHOD__
.': no elements remaining' );
711 $temp = array_pop( $this->stack
);
713 if ( count( $this->stack
) ) {
714 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
715 $this->accum
=& $this->top
->getAccum();
717 $this->top
= self
::$false;
718 $this->accum
=& $this->rootAccum
;
723 function addPart( $s = '' ) {
724 $this->top
->addPart( $s );
725 $this->accum
=& $this->top
->getAccum();
728 function getFlags() {
729 if ( !count( $this->stack
) ) {
731 'findEquals' => false,
733 'inHeading' => false,
736 return $this->top
->getFlags();
744 class PPDStackElement
{
745 var $open, // Opening character (\n for heading)
746 $close, // Matching closing character
747 $count, // Number of opening characters found (number of "=" for heading)
748 $parts, // Array of PPDPart objects describing pipe-separated parts.
749 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
751 var $partClass = 'PPDPart';
753 function __construct( $data = array() ) {
754 $class = $this->partClass
;
755 $this->parts
= array( new $class );
757 foreach ( $data as $name => $value ) {
758 $this->$name = $value;
762 function &getAccum() {
763 return $this->parts
[count($this->parts
) - 1]->out
;
766 function addPart( $s = '' ) {
767 $class = $this->partClass
;
768 $this->parts
[] = new $class( $s );
771 function getCurrentPart() {
772 return $this->parts
[count($this->parts
) - 1];
775 function getFlags() {
776 $partCount = count( $this->parts
);
777 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
779 'findPipe' => $findPipe,
780 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
781 'inHeading' => $this->open
== "\n",
786 * Get the output string that would result if the close is not found.
788 function breakSyntax( $openingCount = false ) {
789 if ( $this->open
== "\n" ) {
790 $s = $this->parts
[0]->out
;
792 if ( $openingCount === false ) {
793 $openingCount = $this->count
;
795 $s = str_repeat( $this->open
, $openingCount );
797 foreach ( $this->parts
as $part ) {
814 var $out; // Output accumulator string
816 // Optional member variables:
817 // eqpos Position of equals sign in output accumulator
818 // commentEnd Past-the-end input pointer for the last comment encountered
819 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
821 function __construct( $out = '' ) {
827 * An expansion frame, used as a context to expand the result of preprocessToObj()
830 class PPFrame_DOM
implements PPFrame
{
831 var $preprocessor, $parser, $title;
835 * Hashtable listing templates which are disallowed for expansion in this frame,
836 * having been encountered previously in parent frames.
841 * Recursion depth of this frame, top = 0
842 * Note that this is NOT the same as expansion depth in expand()
848 * Construct a new preprocessor frame.
849 * @param $preprocessor Preprocessor: The parent preprocessor
851 function __construct( $preprocessor ) {
852 $this->preprocessor
= $preprocessor;
853 $this->parser
= $preprocessor->parser
;
854 $this->title
= $this->parser
->mTitle
;
855 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
856 $this->loopCheckHash
= array();
861 * Create a new child frame
862 * $args is optionally a multi-root PPNode or array containing the template arguments
864 function newChild( $args = false, $title = false ) {
865 $namedArgs = array();
866 $numberedArgs = array();
867 if ( $title === false ) {
868 $title = $this->title
;
870 if ( $args !== false ) {
872 if ( $args instanceof PPNode
) {
875 foreach ( $args as $arg ) {
877 $xpath = new DOMXPath( $arg->ownerDocument
);
880 $nameNodes = $xpath->query( 'name', $arg );
881 $value = $xpath->query( 'value', $arg );
882 if ( $nameNodes->item( 0 )->hasAttributes() ) {
883 // Numbered parameter
884 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
885 $numberedArgs[$index] = $value->item( 0 );
886 unset( $namedArgs[$index] );
889 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
890 $namedArgs[$name] = $value->item( 0 );
891 unset( $numberedArgs[$name] );
895 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
898 function expand( $root, $flags = 0 ) {
899 static $expansionDepth = 0;
900 if ( is_string( $root ) ) {
904 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
906 return '<span class="error">Node-count limit exceeded</span>';
909 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
910 return '<span class="error">Expansion depth limit exceeded</span>';
912 wfProfileIn( __METHOD__
);
915 if ( $root instanceof PPNode_DOM
) {
918 if ( $root instanceof DOMDocument
) {
919 $root = $root->documentElement
;
922 $outStack = array( '', '' );
923 $iteratorStack = array( false, $root );
924 $indexStack = array( 0, 0 );
926 while ( count( $iteratorStack ) > 1 ) {
927 $level = count( $outStack ) - 1;
928 $iteratorNode =& $iteratorStack[ $level ];
929 $out =& $outStack[$level];
930 $index =& $indexStack[$level];
932 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
934 if ( is_array( $iteratorNode ) ) {
935 if ( $index >= count( $iteratorNode ) ) {
936 // All done with this iterator
937 $iteratorStack[$level] = false;
938 $contextNode = false;
940 $contextNode = $iteratorNode[$index];
943 } elseif ( $iteratorNode instanceof DOMNodeList
) {
944 if ( $index >= $iteratorNode->length
) {
945 // All done with this iterator
946 $iteratorStack[$level] = false;
947 $contextNode = false;
949 $contextNode = $iteratorNode->item( $index );
953 // Copy to $contextNode and then delete from iterator stack,
954 // because this is not an iterator but we do have to execute it once
955 $contextNode = $iteratorStack[$level];
956 $iteratorStack[$level] = false;
959 if ( $contextNode instanceof PPNode_DOM
) {
960 $contextNode = $contextNode->node
;
963 $newIterator = false;
965 if ( $contextNode === false ) {
967 } elseif ( is_string( $contextNode ) ) {
968 $out .= $contextNode;
969 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
970 $newIterator = $contextNode;
971 } elseif ( $contextNode instanceof DOMNode
) {
972 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
973 $out .= $contextNode->nodeValue
;
974 } elseif ( $contextNode->nodeName
== 'template' ) {
975 # Double-brace expansion
976 $xpath = new DOMXPath( $contextNode->ownerDocument
);
977 $titles = $xpath->query( 'title', $contextNode );
978 $title = $titles->item( 0 );
979 $parts = $xpath->query( 'part', $contextNode );
980 if ( $flags & PPFrame
::NO_TEMPLATES
) {
981 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
983 $lineStart = $contextNode->getAttribute( 'lineStart' );
985 'title' => new PPNode_DOM( $title ),
986 'parts' => new PPNode_DOM( $parts ),
987 'lineStart' => $lineStart );
988 $ret = $this->parser
->braceSubstitution( $params, $this );
989 if ( isset( $ret['object'] ) ) {
990 $newIterator = $ret['object'];
992 $out .= $ret['text'];
995 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
996 # Triple-brace expansion
997 $xpath = new DOMXPath( $contextNode->ownerDocument
);
998 $titles = $xpath->query( 'title', $contextNode );
999 $title = $titles->item( 0 );
1000 $parts = $xpath->query( 'part', $contextNode );
1001 if ( $flags & PPFrame
::NO_ARGS
) {
1002 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1005 'title' => new PPNode_DOM( $title ),
1006 'parts' => new PPNode_DOM( $parts ) );
1007 $ret = $this->parser
->argSubstitution( $params, $this );
1008 if ( isset( $ret['object'] ) ) {
1009 $newIterator = $ret['object'];
1011 $out .= $ret['text'];
1014 } elseif ( $contextNode->nodeName
== 'comment' ) {
1015 # HTML-style comment
1016 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1017 if ( $this->parser
->ot
['html']
1018 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1019 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1023 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1024 # Not in RECOVER_COMMENTS mode (extractSections) though
1025 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1026 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1028 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1030 $out .= $contextNode->textContent
;
1032 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1033 # Output suppression used by <includeonly> etc.
1034 # OT_WIKI will only respect <ignore> in substed templates.
1035 # The other output types respect it unless NO_IGNORE is set.
1036 # extractSections() sets NO_IGNORE and so never respects it.
1037 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1038 $out .= $contextNode->textContent
;
1042 } elseif ( $contextNode->nodeName
== 'ext' ) {
1044 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1045 $names = $xpath->query( 'name', $contextNode );
1046 $attrs = $xpath->query( 'attr', $contextNode );
1047 $inners = $xpath->query( 'inner', $contextNode );
1048 $closes = $xpath->query( 'close', $contextNode );
1050 'name' => new PPNode_DOM( $names->item( 0 ) ),
1051 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1052 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1053 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1055 $out .= $this->parser
->extensionSubstitution( $params, $this );
1056 } elseif ( $contextNode->nodeName
== 'h' ) {
1058 $s = $this->expand( $contextNode->childNodes
, $flags );
1060 # Insert a heading marker only for <h> children of <root>
1061 # This is to stop extractSections from going over multiple tree levels
1062 if ( $contextNode->parentNode
->nodeName
== 'root'
1063 && $this->parser
->ot
['html'] )
1065 # Insert heading index marker
1066 $headingIndex = $contextNode->getAttribute( 'i' );
1067 $titleText = $this->title
->getPrefixedDBkey();
1068 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1069 $serial = count( $this->parser
->mHeadings
) - 1;
1070 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1071 $count = $contextNode->getAttribute( 'level' );
1072 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1073 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1077 # Generic recursive expansion
1078 $newIterator = $contextNode->childNodes
;
1081 wfProfileOut( __METHOD__
);
1082 throw new MWException( __METHOD__
.': Invalid parameter type' );
1085 if ( $newIterator !== false ) {
1086 if ( $newIterator instanceof PPNode_DOM
) {
1087 $newIterator = $newIterator->node
;
1090 $iteratorStack[] = $newIterator;
1092 } elseif ( $iteratorStack[$level] === false ) {
1093 // Return accumulated value to parent
1094 // With tail recursion
1095 while ( $iteratorStack[$level] === false && $level > 0 ) {
1096 $outStack[$level - 1] .= $out;
1097 array_pop( $outStack );
1098 array_pop( $iteratorStack );
1099 array_pop( $indexStack );
1105 wfProfileOut( __METHOD__
);
1106 return $outStack[0];
1109 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1110 $args = array_slice( func_get_args(), 2 );
1114 foreach ( $args as $root ) {
1115 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1116 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1117 $root = array( $root );
1119 foreach ( $root as $node ) {
1125 $s .= $this->expand( $node, $flags );
1132 * Implode with no flags specified
1133 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1135 function implode( $sep /*, ... */ ) {
1136 $args = array_slice( func_get_args(), 1 );
1140 foreach ( $args as $root ) {
1141 if ( $root instanceof PPNode_DOM
) {
1142 $root = $root->node
;
1144 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1145 $root = array( $root );
1147 foreach ( $root as $node ) {
1153 $s .= $this->expand( $node );
1160 * Makes an object that, when expand()ed, will be the same as one obtained
1163 function virtualImplode( $sep /*, ... */ ) {
1164 $args = array_slice( func_get_args(), 1 );
1168 foreach ( $args as $root ) {
1169 if ( $root instanceof PPNode_DOM
) {
1170 $root = $root->node
;
1172 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1173 $root = array( $root );
1175 foreach ( $root as $node ) {
1188 * Virtual implode with brackets
1190 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1191 $args = array_slice( func_get_args(), 3 );
1192 $out = array( $start );
1195 foreach ( $args as $root ) {
1196 if ( $root instanceof PPNode_DOM
) {
1197 $root = $root->node
;
1199 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1200 $root = array( $root );
1202 foreach ( $root as $node ) {
1215 function __toString() {
1219 function getPDBK( $level = false ) {
1220 if ( $level === false ) {
1221 return $this->title
->getPrefixedDBkey();
1223 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1227 function getArguments() {
1231 function getNumberedArguments() {
1235 function getNamedArguments() {
1240 * Returns true if there are no arguments in this frame
1242 function isEmpty() {
1246 function getArgument( $name ) {
1251 * Returns true if the infinite loop check is OK, false if a loop is detected
1253 function loopCheck( $title ) {
1254 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1258 * Return true if the frame is a template frame
1260 function isTemplate() {
1266 * Expansion frame with template arguments
1269 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1270 var $numberedArgs, $namedArgs, $parent;
1271 var $numberedExpansionCache, $namedExpansionCache;
1273 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1274 parent
::__construct( $preprocessor );
1276 $this->parent
= $parent;
1277 $this->numberedArgs
= $numberedArgs;
1278 $this->namedArgs
= $namedArgs;
1279 $this->title
= $title;
1280 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1281 $this->titleCache
= $parent->titleCache
;
1282 $this->titleCache
[] = $pdbk;
1283 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1284 if ( $pdbk !== false ) {
1285 $this->loopCheckHash
[$pdbk] = true;
1287 $this->depth
= $parent->depth +
1;
1288 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1291 function __toString() {
1294 $args = $this->numberedArgs +
$this->namedArgs
;
1295 foreach ( $args as $name => $value ) {
1301 $s .= "\"$name\":\"" .
1302 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1308 * Returns true if there are no arguments in this frame
1310 function isEmpty() {
1311 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1314 function getArguments() {
1315 $arguments = array();
1316 foreach ( array_merge(
1317 array_keys($this->numberedArgs
),
1318 array_keys($this->namedArgs
)) as $key ) {
1319 $arguments[$key] = $this->getArgument($key);
1324 function getNumberedArguments() {
1325 $arguments = array();
1326 foreach ( array_keys($this->numberedArgs
) as $key ) {
1327 $arguments[$key] = $this->getArgument($key);
1332 function getNamedArguments() {
1333 $arguments = array();
1334 foreach ( array_keys($this->namedArgs
) as $key ) {
1335 $arguments[$key] = $this->getArgument($key);
1340 function getNumberedArgument( $index ) {
1341 if ( !isset( $this->numberedArgs
[$index] ) ) {
1344 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1345 # No trimming for unnamed arguments
1346 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1348 return $this->numberedExpansionCache
[$index];
1351 function getNamedArgument( $name ) {
1352 if ( !isset( $this->namedArgs
[$name] ) ) {
1355 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1356 # Trim named arguments post-expand, for backwards compatibility
1357 $this->namedExpansionCache
[$name] = trim(
1358 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1360 return $this->namedExpansionCache
[$name];
1363 function getArgument( $name ) {
1364 $text = $this->getNumberedArgument( $name );
1365 if ( $text === false ) {
1366 $text = $this->getNamedArgument( $name );
1372 * Return true if the frame is a template frame
1374 function isTemplate() {
1380 * Expansion frame with custom arguments
1383 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1386 function __construct( $preprocessor, $args ) {
1387 parent
::__construct( $preprocessor );
1388 $this->args
= $args;
1391 function __toString() {
1394 foreach ( $this->args
as $name => $value ) {
1400 $s .= "\"$name\":\"" .
1401 str_replace( '"', '\\"', $value->__toString() ) . '"';
1407 function isEmpty() {
1408 return !count( $this->args
);
1411 function getArgument( $index ) {
1412 if ( !isset( $this->args
[$index] ) ) {
1415 return $this->args
[$index];
1422 class PPNode_DOM
implements PPNode
{
1425 function __construct( $node, $xpath = false ) {
1426 $this->node
= $node;
1429 function __get( $name ) {
1430 if ( $name == 'xpath' ) {
1431 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1433 return $this->xpath
;
1436 function __toString() {
1437 if ( $this->node
instanceof DOMNodeList
) {
1439 foreach ( $this->node
as $node ) {
1440 $s .= $node->ownerDocument
->saveXML( $node );
1443 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1448 function getChildren() {
1449 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1452 function getFirstChild() {
1453 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1456 function getNextSibling() {
1457 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1460 function getChildrenOfType( $type ) {
1461 return new self( $this->xpath
->query( $type, $this->node
) );
1464 function getLength() {
1465 if ( $this->node
instanceof DOMNodeList
) {
1466 return $this->node
->length
;
1472 function item( $i ) {
1473 $item = $this->node
->item( $i );
1474 return $item ?
new self( $item ) : false;
1477 function getName() {
1478 if ( $this->node
instanceof DOMNodeList
) {
1481 return $this->node
->nodeName
;
1486 * Split a <part> node into an associative array containing:
1488 * index String index
1489 * value PPNode value
1491 function splitArg() {
1492 $names = $this->xpath
->query( 'name', $this->node
);
1493 $values = $this->xpath
->query( 'value', $this->node
);
1494 if ( !$names->length ||
!$values->length
) {
1495 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1497 $name = $names->item( 0 );
1498 $index = $name->getAttribute( 'index' );
1500 'name' => new self( $name ),
1502 'value' => new self( $values->item( 0 ) ) );
1506 * Split an <ext> node into an associative array containing name, attr, inner and close
1507 * All values in the resulting array are PPNodes. Inner and close are optional.
1509 function splitExt() {
1510 $names = $this->xpath
->query( 'name', $this->node
);
1511 $attrs = $this->xpath
->query( 'attr', $this->node
);
1512 $inners = $this->xpath
->query( 'inner', $this->node
);
1513 $closes = $this->xpath
->query( 'close', $this->node
);
1514 if ( !$names->length ||
!$attrs->length
) {
1515 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1518 'name' => new self( $names->item( 0 ) ),
1519 'attr' => new self( $attrs->item( 0 ) ) );
1520 if ( $inners->length
) {
1521 $parts['inner'] = new self( $inners->item( 0 ) );
1523 if ( $closes->length
) {
1524 $parts['close'] = new self( $closes->item( 0 ) );
1532 function splitHeading() {
1533 if ( !$this->nodeName
== 'h' ) {
1534 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1537 'i' => $this->node
->getAttribute( 'i' ),
1538 'level' => $this->node
->getAttribute( 'level' ),
1539 'contents' => $this->getChildren()