3 * Preprocessor using PHP's dom extension
12 class Preprocessor_DOM
implements Preprocessor
{
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;
40 return new PPFrame_DOM( $this );
45 * @return PPCustomFrame_DOM
47 function newCustomFrame( $args ) {
48 return new PPCustomFrame_DOM( $this, $args );
55 function newPartNodeArray( $values ) {
56 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
59 foreach ( $values as $k => $val ) {
62 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
64 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
70 $dom = new DOMDocument();
71 $dom->loadXML( $xml );
72 $root = $dom->documentElement
;
74 $node = new PPNode_DOM( $root->childNodes
);
83 if ( $this->memoryLimit
=== false ) {
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;
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.
116 function preprocessToObj( $text, $flags = 0 ) {
117 wfProfileIn( __METHOD__
);
118 global $wgMemc, $wgPreprocessorCacheThreshold;
121 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
123 wfProfileIn( __METHOD__
.'-cacheable' );
125 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
126 $cacheValue = $wgMemc->get( $cacheKey );
128 $version = substr( $cacheValue, 0, 8 );
129 if ( intval( $version ) == self
::CACHE_VERSION
) {
130 $xml = substr( $cacheValue, 8 );
132 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
136 if ( $xml === false ) {
138 wfProfileIn( __METHOD__
.'-cache-miss' );
139 $xml = $this->preprocessToXml( $text, $flags );
140 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
141 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
142 wfProfileOut( __METHOD__
.'-cache-miss' );
143 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
145 $xml = $this->preprocessToXml( $text, $flags );
149 wfProfileIn( __METHOD__
.'-loadXML' );
150 $dom = new DOMDocument
;
151 wfSuppressWarnings();
152 $result = $dom->loadXML( $xml );
155 // Try running the XML through UtfNormal to get rid of invalid characters
156 $xml = UtfNormal
::cleanUp( $xml );
157 $result = $dom->loadXML( $xml );
159 throw new MWException( __METHOD__
.' generated invalid XML' );
162 $obj = new PPNode_DOM( $dom->documentElement
);
163 wfProfileOut( __METHOD__
.'-loadXML' );
165 wfProfileOut( __METHOD__
.'-cacheable' );
167 wfProfileOut( __METHOD__
);
172 * @param $text string
176 function preprocessToXml( $text, $flags = 0 ) {
177 wfProfileIn( __METHOD__
);
190 'names' => array( 2 => null ),
196 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
198 $xmlishElements = $this->parser
->getStripList();
199 $enableOnlyinclude = false;
200 if ( $forInclusion ) {
201 $ignoredTags = array( 'includeonly', '/includeonly' );
202 $ignoredElements = array( 'noinclude' );
203 $xmlishElements[] = 'noinclude';
204 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
205 $enableOnlyinclude = true;
207 } else if ( isset( $this->parser
->ot
) && $this->parser
->ot
['wiki'] ) {
208 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude', 'includeonly', '/includeonly' );
209 $ignoredElements = array();
211 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
212 $ignoredElements = array( 'includeonly' );
213 $xmlishElements[] = 'includeonly';
215 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
217 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
218 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
220 $stack = new PPDStack
;
222 $searchBase = "[{<\n"; #}
223 $revText = strrev( $text ); // For fast reverse searches
225 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
226 $accum =& $stack->getAccum(); # Current accumulator
228 $findEquals = false; # True to find equals signs in arguments
229 $findPipe = false; # True to take notice of pipe characters
231 $inHeading = false; # True if $i is inside a possible heading
232 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
233 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
234 $fakeLineStart = true; # Do a line-start run without outputting an LF character
239 if ( $findOnlyinclude ) {
240 // Ignore all input up to the next <onlyinclude>
241 $startPos = strpos( $text, '<onlyinclude>', $i );
242 if ( $startPos === false ) {
243 // Ignored section runs to the end
244 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
247 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
248 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
250 $findOnlyinclude = false;
253 if ( $fakeLineStart ) {
254 $found = 'line-start';
257 # Find next opening brace, closing brace or pipe
258 $search = $searchBase;
259 if ( $stack->top
=== false ) {
260 $currentClosing = '';
262 $currentClosing = $stack->top
->close
;
263 $search .= $currentClosing;
269 // First equals will be for the template
273 # Output literal section, advance input counter
274 $literalLength = strcspn( $text, $search, $i );
275 if ( $literalLength > 0 ) {
276 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
277 $i +
= $literalLength;
279 if ( $i >= strlen( $text ) ) {
280 if ( $currentClosing == "\n" ) {
281 // Do a past-the-end run to finish off the heading
289 $curChar = $text[$i];
290 if ( $curChar == '|' ) {
292 } elseif ( $curChar == '=' ) {
294 } elseif ( $curChar == '<' ) {
296 } elseif ( $curChar == "\n" ) {
300 $found = 'line-start';
302 } elseif ( $curChar == $currentClosing ) {
304 } elseif ( isset( $rules[$curChar] ) ) {
306 $rule = $rules[$curChar];
308 # Some versions of PHP have a strcspn which stops on null characters
309 # Ignore and continue
316 if ( $found == 'angle' ) {
318 // Handle </onlyinclude>
319 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
320 $findOnlyinclude = true;
324 // Determine element name
325 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
326 // Element name missing or not listed
332 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
333 // To avoid leaving blank lines, when a comment is both preceded
334 // and followed by a newline (ignoring spaces), trim leading and
335 // trailing spaces and one of the newlines.
338 $endPos = strpos( $text, '-->', $i +
4 );
339 if ( $endPos === false ) {
340 // Unclosed comment in input, runs to end
341 $inner = substr( $text, $i );
342 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
343 $i = strlen( $text );
345 // Search backwards for leading whitespace
346 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
347 // Search forwards for trailing whitespace
348 // $wsEnd will be the position of the last space (or the '>' if there's none)
349 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
350 // Eat the line if possible
351 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
352 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
353 // it's a possible beneficial b/c break.
354 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
355 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
357 $startPos = $wsStart;
358 $endPos = $wsEnd +
1;
359 // Remove leading whitespace from the end of the accumulator
360 // Sanity check first though
361 $wsLength = $i - $wsStart;
362 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
363 $accum = substr( $accum, 0, -$wsLength );
365 // Do a line-start run next time to look for headings after the comment
366 $fakeLineStart = true;
368 // No line to eat, just take the comment itself
374 $part = $stack->top
->getCurrentPart();
375 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
376 $part->visualEnd
= $wsStart;
378 // Else comments abutting, no change in visual end
379 $part->commentEnd
= $endPos;
382 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
383 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
388 $lowerName = strtolower( $name );
389 $attrStart = $i +
strlen( $name ) +
1;
392 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
393 if ( $tagEndPos === false ) {
394 // Infinite backtrack
395 // Disable tag search to prevent worst-case O(N^2) performance
402 // Handle ignored tags
403 if ( in_array( $lowerName, $ignoredTags ) ) {
404 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
410 if ( $text[$tagEndPos-1] == '/' ) {
411 $attrEnd = $tagEndPos - 1;
416 $attrEnd = $tagEndPos;
418 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
419 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
421 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
422 $i = $matches[0][1] +
strlen( $matches[0][0] );
423 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
425 // No end tag -- let it run out to the end of the text.
426 $inner = substr( $text, $tagEndPos +
1 );
427 $i = strlen( $text );
431 // <includeonly> and <noinclude> just become <ignore> tags
432 if ( in_array( $lowerName, $ignoredElements ) ) {
433 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
439 if ( $attrEnd <= $attrStart ) {
442 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
444 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
445 // Note that the attr element contains the whitespace between name and attribute,
446 // this is necessary for precise reconstruction during pre-save transform.
447 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
448 if ( $inner !== null ) {
449 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
451 $accum .= $close . '</ext>';
452 } elseif ( $found == 'line-start' ) {
453 // Is this the start of a heading?
454 // Line break belongs before the heading element in any case
455 if ( $fakeLineStart ) {
456 $fakeLineStart = false;
462 $count = strspn( $text, '=', $i, 6 );
463 if ( $count == 1 && $findEquals ) {
464 // DWIM: This looks kind of like a name/value separator
465 // Let's let the equals handler have it and break the potential heading
466 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
467 } elseif ( $count > 0 ) {
471 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
474 $stack->push( $piece );
475 $accum =& $stack->getAccum();
476 $flags = $stack->getFlags();
480 } elseif ( $found == 'line-end' ) {
481 $piece = $stack->top
;
482 // A heading must be open, otherwise \n wouldn't have been in the search list
483 assert( $piece->open
== "\n" );
484 $part = $piece->getCurrentPart();
485 // Search back through the input to see if it has a proper close
486 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
487 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
488 $searchStart = $i - $wsLength;
489 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
490 // Comment found at line end
491 // Search for equals signs before the comment
492 $searchStart = $part->visualEnd
;
493 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
495 $count = $piece->count
;
496 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
497 if ( $equalsLength > 0 ) {
498 if ( $searchStart - $equalsLength == $piece->startPos
) {
499 // This is just a single string of equals signs on its own line
500 // Replicate the doHeadings behaviour /={count}(.+)={count}/
501 // First find out how many equals signs there really are (don't stop at 6)
502 $count = $equalsLength;
506 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
509 $count = min( $equalsLength, $count );
512 // Normal match, output <h>
513 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
516 // Single equals sign on its own line, count=0
520 // No match, no <h>, just pass down the inner text
525 $accum =& $stack->getAccum();
526 $flags = $stack->getFlags();
529 // Append the result to the enclosing accumulator
531 // Note that we do NOT increment the input pointer.
532 // This is because the closing linebreak could be the opening linebreak of
533 // another heading. Infinite loops are avoided because the next iteration MUST
534 // hit the heading open case above, which unconditionally increments the
536 } elseif ( $found == 'open' ) {
537 # count opening brace characters
538 $count = strspn( $text, $curChar, $i );
540 # we need to add to stack only if opening brace count is enough for one of the rules
541 if ( $count >= $rule['min'] ) {
542 # Add it to the stack
545 'close' => $rule['end'],
547 'lineStart' => ($i == 0 ||
$text[$i-1] == "\n"),
550 $stack->push( $piece );
551 $accum =& $stack->getAccum();
552 $flags = $stack->getFlags();
555 # Add literal brace(s)
556 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
559 } elseif ( $found == 'close' ) {
560 $piece = $stack->top
;
561 # lets check if there are enough characters for closing brace
562 $maxCount = $piece->count
;
563 $count = strspn( $text, $curChar, $i, $maxCount );
565 # check for maximum matching characters (if there are 5 closing
566 # characters, we will probably need only 3 - depending on the rules)
567 $rule = $rules[$piece->open
];
568 if ( $count > $rule['max'] ) {
569 # The specified maximum exists in the callback array, unless the caller
571 $matchingCount = $rule['max'];
573 # Count is less than the maximum
574 # Skip any gaps in the callback array to find the true largest match
575 # Need to use array_key_exists not isset because the callback can be null
576 $matchingCount = $count;
577 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
582 if ( $matchingCount <= 0 ) {
583 # No matching element found in callback array
584 # Output a literal closing brace and continue
585 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
589 $name = $rule['names'][$matchingCount];
590 if ( $name === null ) {
591 // No element, just literal text
592 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
595 # Note: $parts is already XML, does not need to be encoded further
596 $parts = $piece->parts
;
597 $title = $parts[0]->out
;
600 # The invocation is at the start of the line if lineStart is set in
601 # the stack, and all opening brackets are used up.
602 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
603 $attr = ' lineStart="1"';
608 $element = "<$name$attr>";
609 $element .= "<title>$title</title>";
611 foreach ( $parts as $part ) {
612 if ( isset( $part->eqpos
) ) {
613 $argName = substr( $part->out
, 0, $part->eqpos
);
614 $argValue = substr( $part->out
, $part->eqpos +
1 );
615 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
617 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
621 $element .= "</$name>";
624 # Advance input pointer
625 $i +
= $matchingCount;
629 $accum =& $stack->getAccum();
631 # Re-add the old stack element if it still has unmatched opening characters remaining
632 if ( $matchingCount < $piece->count
) {
633 $piece->parts
= array( new PPDPart
);
634 $piece->count
-= $matchingCount;
635 # do we still qualify for any callback with remaining count?
636 $names = $rules[$piece->open
]['names'];
638 $enclosingAccum =& $accum;
639 while ( $piece->count
) {
640 if ( array_key_exists( $piece->count
, $names ) ) {
641 $stack->push( $piece );
642 $accum =& $stack->getAccum();
648 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
650 $flags = $stack->getFlags();
653 # Add XML element to the enclosing accumulator
655 } elseif ( $found == 'pipe' ) {
656 $findEquals = true; // shortcut for getFlags()
658 $accum =& $stack->getAccum();
660 } elseif ( $found == 'equals' ) {
661 $findEquals = false; // shortcut for getFlags()
662 $stack->getCurrentPart()->eqpos
= strlen( $accum );
668 # Output any remaining unclosed brackets
669 foreach ( $stack->stack
as $piece ) {
670 $stack->rootAccum
.= $piece->breakSyntax();
672 $stack->rootAccum
.= '</root>';
673 $xml = $stack->rootAccum
;
675 wfProfileOut( __METHOD__
);
682 * Stack class to help Preprocessor::preprocessToObj()
686 var $stack, $rootAccum;
693 var $elementClass = 'PPDStackElement';
695 static $false = false;
697 function __construct() {
698 $this->stack
= array();
700 $this->rootAccum
= '';
701 $this->accum
=& $this->rootAccum
;
708 return count( $this->stack
);
711 function &getAccum() {
715 function getCurrentPart() {
716 if ( $this->top
=== false ) {
719 return $this->top
->getCurrentPart();
723 function push( $data ) {
724 if ( $data instanceof $this->elementClass
) {
725 $this->stack
[] = $data;
727 $class = $this->elementClass
;
728 $this->stack
[] = new $class( $data );
730 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
731 $this->accum
=& $this->top
->getAccum();
735 if ( !count( $this->stack
) ) {
736 throw new MWException( __METHOD__
.': no elements remaining' );
738 $temp = array_pop( $this->stack
);
740 if ( count( $this->stack
) ) {
741 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
742 $this->accum
=& $this->top
->getAccum();
744 $this->top
= self
::$false;
745 $this->accum
=& $this->rootAccum
;
750 function addPart( $s = '' ) {
751 $this->top
->addPart( $s );
752 $this->accum
=& $this->top
->getAccum();
758 function getFlags() {
759 if ( !count( $this->stack
) ) {
761 'findEquals' => false,
763 'inHeading' => false,
766 return $this->top
->getFlags();
774 class PPDStackElement
{
775 var $open, // Opening character (\n for heading)
776 $close, // Matching closing character
777 $count, // Number of opening characters found (number of "=" for heading)
778 $parts, // Array of PPDPart objects describing pipe-separated parts.
779 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
781 var $partClass = 'PPDPart';
783 function __construct( $data = array() ) {
784 $class = $this->partClass
;
785 $this->parts
= array( new $class );
787 foreach ( $data as $name => $value ) {
788 $this->$name = $value;
792 function &getAccum() {
793 return $this->parts
[count($this->parts
) - 1]->out
;
796 function addPart( $s = '' ) {
797 $class = $this->partClass
;
798 $this->parts
[] = new $class( $s );
801 function getCurrentPart() {
802 return $this->parts
[count($this->parts
) - 1];
808 function getFlags() {
809 $partCount = count( $this->parts
);
810 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
812 'findPipe' => $findPipe,
813 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
814 'inHeading' => $this->open
== "\n",
819 * Get the output string that would result if the close is not found.
823 function breakSyntax( $openingCount = false ) {
824 if ( $this->open
== "\n" ) {
825 $s = $this->parts
[0]->out
;
827 if ( $openingCount === false ) {
828 $openingCount = $this->count
;
830 $s = str_repeat( $this->open
, $openingCount );
832 foreach ( $this->parts
as $part ) {
849 var $out; // Output accumulator string
851 // Optional member variables:
852 // eqpos Position of equals sign in output accumulator
853 // commentEnd Past-the-end input pointer for the last comment encountered
854 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
856 function __construct( $out = '' ) {
862 * An expansion frame, used as a context to expand the result of preprocessToObj()
865 class PPFrame_DOM
implements PPFrame
{
884 * Hashtable listing templates which are disallowed for expansion in this frame,
885 * having been encountered previously in parent frames.
890 * Recursion depth of this frame, top = 0
891 * Note that this is NOT the same as expansion depth in expand()
897 * Construct a new preprocessor frame.
898 * @param $preprocessor Preprocessor The parent preprocessor
900 function __construct( $preprocessor ) {
901 $this->preprocessor
= $preprocessor;
902 $this->parser
= $preprocessor->parser
;
903 $this->title
= $this->parser
->mTitle
;
904 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
905 $this->loopCheckHash
= array();
910 * Create a new child frame
911 * $args is optionally a multi-root PPNode or array containing the template arguments
913 * @return PPTemplateFrame_DOM
915 function newChild( $args = false, $title = false ) {
916 $namedArgs = array();
917 $numberedArgs = array();
918 if ( $title === false ) {
919 $title = $this->title
;
921 if ( $args !== false ) {
923 if ( $args instanceof PPNode
) {
926 foreach ( $args as $arg ) {
928 $xpath = new DOMXPath( $arg->ownerDocument
);
931 $nameNodes = $xpath->query( 'name', $arg );
932 $value = $xpath->query( 'value', $arg );
933 if ( $nameNodes->item( 0 )->hasAttributes() ) {
934 // Numbered parameter
935 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
936 $numberedArgs[$index] = $value->item( 0 );
937 unset( $namedArgs[$index] );
940 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
941 $namedArgs[$name] = $value->item( 0 );
942 unset( $numberedArgs[$name] );
946 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
950 * @throws MWException
955 function expand( $root, $flags = 0 ) {
956 static $expansionDepth = 0;
957 if ( is_string( $root ) ) {
961 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
963 return '<span class="error">Node-count limit exceeded</span>';
966 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
967 return '<span class="error">Expansion depth limit exceeded</span>';
969 wfProfileIn( __METHOD__
);
972 if ( $root instanceof PPNode_DOM
) {
975 if ( $root instanceof DOMDocument
) {
976 $root = $root->documentElement
;
979 $outStack = array( '', '' );
980 $iteratorStack = array( false, $root );
981 $indexStack = array( 0, 0 );
983 while ( count( $iteratorStack ) > 1 ) {
984 $level = count( $outStack ) - 1;
985 $iteratorNode =& $iteratorStack[ $level ];
986 $out =& $outStack[$level];
987 $index =& $indexStack[$level];
989 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
991 if ( is_array( $iteratorNode ) ) {
992 if ( $index >= count( $iteratorNode ) ) {
993 // All done with this iterator
994 $iteratorStack[$level] = false;
995 $contextNode = false;
997 $contextNode = $iteratorNode[$index];
1000 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1001 if ( $index >= $iteratorNode->length
) {
1002 // All done with this iterator
1003 $iteratorStack[$level] = false;
1004 $contextNode = false;
1006 $contextNode = $iteratorNode->item( $index );
1010 // Copy to $contextNode and then delete from iterator stack,
1011 // because this is not an iterator but we do have to execute it once
1012 $contextNode = $iteratorStack[$level];
1013 $iteratorStack[$level] = false;
1016 if ( $contextNode instanceof PPNode_DOM
) {
1017 $contextNode = $contextNode->node
;
1020 $newIterator = false;
1022 if ( $contextNode === false ) {
1024 } elseif ( is_string( $contextNode ) ) {
1025 $out .= $contextNode;
1026 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1027 $newIterator = $contextNode;
1028 } elseif ( $contextNode instanceof DOMNode
) {
1029 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1030 $out .= $contextNode->nodeValue
;
1031 } elseif ( $contextNode->nodeName
== 'template' ) {
1032 # Double-brace expansion
1033 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1034 $titles = $xpath->query( 'title', $contextNode );
1035 $title = $titles->item( 0 );
1036 $parts = $xpath->query( 'part', $contextNode );
1037 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1038 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1040 $lineStart = $contextNode->getAttribute( 'lineStart' );
1042 'title' => new PPNode_DOM( $title ),
1043 'parts' => new PPNode_DOM( $parts ),
1044 'lineStart' => $lineStart );
1045 $ret = $this->parser
->braceSubstitution( $params, $this );
1046 if ( isset( $ret['object'] ) ) {
1047 $newIterator = $ret['object'];
1049 $out .= $ret['text'];
1052 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1053 # Triple-brace expansion
1054 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1055 $titles = $xpath->query( 'title', $contextNode );
1056 $title = $titles->item( 0 );
1057 $parts = $xpath->query( 'part', $contextNode );
1058 if ( $flags & PPFrame
::NO_ARGS
) {
1059 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1062 'title' => new PPNode_DOM( $title ),
1063 'parts' => new PPNode_DOM( $parts ) );
1064 $ret = $this->parser
->argSubstitution( $params, $this );
1065 if ( isset( $ret['object'] ) ) {
1066 $newIterator = $ret['object'];
1068 $out .= $ret['text'];
1071 } elseif ( $contextNode->nodeName
== 'comment' ) {
1072 # HTML-style comment
1073 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1074 if ( $this->parser
->ot
['html']
1075 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1076 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1080 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1081 # Not in RECOVER_COMMENTS mode (extractSections) though
1082 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1083 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1085 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1087 $out .= $contextNode->textContent
;
1089 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1090 # Output suppression used by <includeonly> etc.
1091 # OT_WIKI will only respect <ignore> in substed templates.
1092 # The other output types respect it unless NO_IGNORE is set.
1093 # extractSections() sets NO_IGNORE and so never respects it.
1094 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1095 $out .= $contextNode->textContent
;
1099 } elseif ( $contextNode->nodeName
== 'ext' ) {
1101 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1102 $names = $xpath->query( 'name', $contextNode );
1103 $attrs = $xpath->query( 'attr', $contextNode );
1104 $inners = $xpath->query( 'inner', $contextNode );
1105 $closes = $xpath->query( 'close', $contextNode );
1107 'name' => new PPNode_DOM( $names->item( 0 ) ),
1108 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1109 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1110 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1112 $out .= $this->parser
->extensionSubstitution( $params, $this );
1113 } elseif ( $contextNode->nodeName
== 'h' ) {
1115 $s = $this->expand( $contextNode->childNodes
, $flags );
1117 # Insert a heading marker only for <h> children of <root>
1118 # This is to stop extractSections from going over multiple tree levels
1119 if ( $contextNode->parentNode
->nodeName
== 'root'
1120 && $this->parser
->ot
['html'] )
1122 # Insert heading index marker
1123 $headingIndex = $contextNode->getAttribute( 'i' );
1124 $titleText = $this->title
->getPrefixedDBkey();
1125 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1126 $serial = count( $this->parser
->mHeadings
) - 1;
1127 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1128 $count = $contextNode->getAttribute( 'level' );
1129 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1130 $this->parser
->mStripState
->addGeneral( $marker, '' );
1134 # Generic recursive expansion
1135 $newIterator = $contextNode->childNodes
;
1138 wfProfileOut( __METHOD__
);
1139 throw new MWException( __METHOD__
.': Invalid parameter type' );
1142 if ( $newIterator !== false ) {
1143 if ( $newIterator instanceof PPNode_DOM
) {
1144 $newIterator = $newIterator->node
;
1147 $iteratorStack[] = $newIterator;
1149 } elseif ( $iteratorStack[$level] === false ) {
1150 // Return accumulated value to parent
1151 // With tail recursion
1152 while ( $iteratorStack[$level] === false && $level > 0 ) {
1153 $outStack[$level - 1] .= $out;
1154 array_pop( $outStack );
1155 array_pop( $iteratorStack );
1156 array_pop( $indexStack );
1162 wfProfileOut( __METHOD__
);
1163 return $outStack[0];
1171 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1172 $args = array_slice( func_get_args(), 2 );
1176 foreach ( $args as $root ) {
1177 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1178 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1179 $root = array( $root );
1181 foreach ( $root as $node ) {
1187 $s .= $this->expand( $node, $flags );
1194 * Implode with no flags specified
1195 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1199 function implode( $sep /*, ... */ ) {
1200 $args = array_slice( func_get_args(), 1 );
1204 foreach ( $args as $root ) {
1205 if ( $root instanceof PPNode_DOM
) {
1206 $root = $root->node
;
1208 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1209 $root = array( $root );
1211 foreach ( $root as $node ) {
1217 $s .= $this->expand( $node );
1224 * Makes an object that, when expand()ed, will be the same as one obtained
1229 function virtualImplode( $sep /*, ... */ ) {
1230 $args = array_slice( func_get_args(), 1 );
1234 foreach ( $args as $root ) {
1235 if ( $root instanceof PPNode_DOM
) {
1236 $root = $root->node
;
1238 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1239 $root = array( $root );
1241 foreach ( $root as $node ) {
1254 * Virtual implode with brackets
1256 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1257 $args = array_slice( func_get_args(), 3 );
1258 $out = array( $start );
1261 foreach ( $args as $root ) {
1262 if ( $root instanceof PPNode_DOM
) {
1263 $root = $root->node
;
1265 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1266 $root = array( $root );
1268 foreach ( $root as $node ) {
1281 function __toString() {
1285 function getPDBK( $level = false ) {
1286 if ( $level === false ) {
1287 return $this->title
->getPrefixedDBkey();
1289 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1296 function getArguments() {
1303 function getNumberedArguments() {
1310 function getNamedArguments() {
1315 * Returns true if there are no arguments in this frame
1319 function isEmpty() {
1323 function getArgument( $name ) {
1328 * Returns true if the infinite loop check is OK, false if a loop is detected
1332 function loopCheck( $title ) {
1333 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1337 * Return true if the frame is a template frame
1341 function isTemplate() {
1347 * Expansion frame with template arguments
1350 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1351 var $numberedArgs, $namedArgs;
1357 var $numberedExpansionCache, $namedExpansionCache;
1360 * @param $preprocessor
1361 * @param $parent PPFrame_DOM
1362 * @param $numberedArgs array
1363 * @param $namedArgs array
1364 * @param $title Title
1366 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1367 parent
::__construct( $preprocessor );
1369 $this->parent
= $parent;
1370 $this->numberedArgs
= $numberedArgs;
1371 $this->namedArgs
= $namedArgs;
1372 $this->title
= $title;
1373 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1374 $this->titleCache
= $parent->titleCache
;
1375 $this->titleCache
[] = $pdbk;
1376 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1377 if ( $pdbk !== false ) {
1378 $this->loopCheckHash
[$pdbk] = true;
1380 $this->depth
= $parent->depth +
1;
1381 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1384 function __toString() {
1387 $args = $this->numberedArgs +
$this->namedArgs
;
1388 foreach ( $args as $name => $value ) {
1394 $s .= "\"$name\":\"" .
1395 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1402 * Returns true if there are no arguments in this frame
1406 function isEmpty() {
1407 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1410 function getArguments() {
1411 $arguments = array();
1412 foreach ( array_merge(
1413 array_keys($this->numberedArgs
),
1414 array_keys($this->namedArgs
)) as $key ) {
1415 $arguments[$key] = $this->getArgument($key);
1420 function getNumberedArguments() {
1421 $arguments = array();
1422 foreach ( array_keys($this->numberedArgs
) as $key ) {
1423 $arguments[$key] = $this->getArgument($key);
1428 function getNamedArguments() {
1429 $arguments = array();
1430 foreach ( array_keys($this->namedArgs
) as $key ) {
1431 $arguments[$key] = $this->getArgument($key);
1436 function getNumberedArgument( $index ) {
1437 if ( !isset( $this->numberedArgs
[$index] ) ) {
1440 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1441 # No trimming for unnamed arguments
1442 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1444 return $this->numberedExpansionCache
[$index];
1447 function getNamedArgument( $name ) {
1448 if ( !isset( $this->namedArgs
[$name] ) ) {
1451 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1452 # Trim named arguments post-expand, for backwards compatibility
1453 $this->namedExpansionCache
[$name] = trim(
1454 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1456 return $this->namedExpansionCache
[$name];
1459 function getArgument( $name ) {
1460 $text = $this->getNumberedArgument( $name );
1461 if ( $text === false ) {
1462 $text = $this->getNamedArgument( $name );
1468 * Return true if the frame is a template frame
1472 function isTemplate() {
1478 * Expansion frame with custom arguments
1481 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1484 function __construct( $preprocessor, $args ) {
1485 parent
::__construct( $preprocessor );
1486 $this->args
= $args;
1489 function __toString() {
1492 foreach ( $this->args
as $name => $value ) {
1498 $s .= "\"$name\":\"" .
1499 str_replace( '"', '\\"', $value->__toString() ) . '"';
1508 function isEmpty() {
1509 return !count( $this->args
);
1512 function getArgument( $index ) {
1513 if ( !isset( $this->args
[$index] ) ) {
1516 return $this->args
[$index];
1523 class PPNode_DOM
implements PPNode
{
1531 function __construct( $node, $xpath = false ) {
1532 $this->node
= $node;
1538 function getXPath() {
1539 if ( $this->xpath
=== null ) {
1540 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1542 return $this->xpath
;
1545 function __toString() {
1546 if ( $this->node
instanceof DOMNodeList
) {
1548 foreach ( $this->node
as $node ) {
1549 $s .= $node->ownerDocument
->saveXML( $node );
1552 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1558 * @return bool|PPNode_DOM
1560 function getChildren() {
1561 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1565 * @return bool|PPNode_DOM
1567 function getFirstChild() {
1568 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1572 * @return bool|PPNode_DOM
1574 function getNextSibling() {
1575 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1581 * @return bool|PPNode_DOM
1583 function getChildrenOfType( $type ) {
1584 return new self( $this->getXPath()->query( $type, $this->node
) );
1590 function getLength() {
1591 if ( $this->node
instanceof DOMNodeList
) {
1592 return $this->node
->length
;
1600 * @return bool|PPNode_DOM
1602 function item( $i ) {
1603 $item = $this->node
->item( $i );
1604 return $item ?
new self( $item ) : false;
1610 function getName() {
1611 if ( $this->node
instanceof DOMNodeList
) {
1614 return $this->node
->nodeName
;
1619 * Split a <part> node into an associative array containing:
1621 * index String index
1622 * value PPNode value
1626 function splitArg() {
1627 $xpath = $this->getXPath();
1628 $names = $xpath->query( 'name', $this->node
);
1629 $values = $xpath->query( 'value', $this->node
);
1630 if ( !$names->length ||
!$values->length
) {
1631 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1633 $name = $names->item( 0 );
1634 $index = $name->getAttribute( 'index' );
1636 'name' => new self( $name ),
1638 'value' => new self( $values->item( 0 ) ) );
1642 * Split an <ext> node into an associative array containing name, attr, inner and close
1643 * All values in the resulting array are PPNodes. Inner and close are optional.
1647 function splitExt() {
1648 $xpath = $this->getXPath();
1649 $names = $xpath->query( 'name', $this->node
);
1650 $attrs = $xpath->query( 'attr', $this->node
);
1651 $inners = $xpath->query( 'inner', $this->node
);
1652 $closes = $xpath->query( 'close', $this->node
);
1653 if ( !$names->length ||
!$attrs->length
) {
1654 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1657 'name' => new self( $names->item( 0 ) ),
1658 'attr' => new self( $attrs->item( 0 ) ) );
1659 if ( $inners->length
) {
1660 $parts['inner'] = new self( $inners->item( 0 ) );
1662 if ( $closes->length
) {
1663 $parts['close'] = new self( $closes->item( 0 ) );
1671 function splitHeading() {
1672 if ( $this->getName() !== 'h' ) {
1673 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1676 'i' => $this->node
->getAttribute( 'i' ),
1677 'level' => $this->node
->getAttribute( 'level' ),
1678 'contents' => $this->getChildren()