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
122 && strlen( $text ) > $wgPreprocessorCacheThreshold );
124 wfProfileIn( __METHOD__
.'-cacheable' );
126 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
127 $cacheValue = $wgMemc->get( $cacheKey );
129 $version = substr( $cacheValue, 0, 8 );
130 if ( intval( $version ) == self
::CACHE_VERSION
) {
131 $xml = substr( $cacheValue, 8 );
133 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
137 if ( $xml === false ) {
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)" );
146 $xml = $this->preprocessToXml( $text, $flags );
150 wfProfileIn( __METHOD__
.'-loadXML' );
151 $dom = new DOMDocument
;
152 wfSuppressWarnings();
153 $result = $dom->loadXML( $xml );
156 // Try running the XML through UtfNormal to get rid of invalid characters
157 $xml = UtfNormal
::cleanUp( $xml );
158 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
159 $result = $dom->loadXML( $xml, 1 << 19 );
161 throw new MWException( __METHOD__
.' generated invalid XML' );
164 $obj = new PPNode_DOM( $dom->documentElement
);
165 wfProfileOut( __METHOD__
.'-loadXML' );
167 wfProfileOut( __METHOD__
.'-cacheable' );
169 wfProfileOut( __METHOD__
);
174 * @param $text string
178 function preprocessToXml( $text, $flags = 0 ) {
179 wfProfileIn( __METHOD__
);
192 'names' => array( 2 => null ),
198 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
200 $xmlishElements = $this->parser
->getStripList();
201 $enableOnlyinclude = false;
202 if ( $forInclusion ) {
203 $ignoredTags = array( 'includeonly', '/includeonly' );
204 $ignoredElements = array( 'noinclude' );
205 $xmlishElements[] = 'noinclude';
206 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
207 $enableOnlyinclude = true;
210 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
211 $ignoredElements = array( 'includeonly' );
212 $xmlishElements[] = 'includeonly';
214 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
216 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
217 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
219 $stack = new PPDStack
;
221 $searchBase = "[{<\n"; #}
222 $revText = strrev( $text ); // For fast reverse searches
224 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
225 $accum =& $stack->getAccum(); # Current accumulator
227 $findEquals = false; # True to find equals signs in arguments
228 $findPipe = false; # True to take notice of pipe characters
230 $inHeading = false; # True if $i is inside a possible heading
231 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
232 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
233 $fakeLineStart = true; # Do a line-start run without outputting an LF character
238 if ( $findOnlyinclude ) {
239 // Ignore all input up to the next <onlyinclude>
240 $startPos = strpos( $text, '<onlyinclude>', $i );
241 if ( $startPos === false ) {
242 // Ignored section runs to the end
243 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
246 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
247 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
249 $findOnlyinclude = false;
252 if ( $fakeLineStart ) {
253 $found = 'line-start';
256 # Find next opening brace, closing brace or pipe
257 $search = $searchBase;
258 if ( $stack->top
=== false ) {
259 $currentClosing = '';
261 $currentClosing = $stack->top
->close
;
262 $search .= $currentClosing;
268 // First equals will be for the template
272 # Output literal section, advance input counter
273 $literalLength = strcspn( $text, $search, $i );
274 if ( $literalLength > 0 ) {
275 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
276 $i +
= $literalLength;
278 if ( $i >= strlen( $text ) ) {
279 if ( $currentClosing == "\n" ) {
280 // Do a past-the-end run to finish off the heading
288 $curChar = $text[$i];
289 if ( $curChar == '|' ) {
291 } elseif ( $curChar == '=' ) {
293 } elseif ( $curChar == '<' ) {
295 } elseif ( $curChar == "\n" ) {
299 $found = 'line-start';
301 } elseif ( $curChar == $currentClosing ) {
303 } elseif ( isset( $rules[$curChar] ) ) {
305 $rule = $rules[$curChar];
307 # Some versions of PHP have a strcspn which stops on null characters
308 # Ignore and continue
315 if ( $found == 'angle' ) {
317 // Handle </onlyinclude>
318 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
319 $findOnlyinclude = true;
323 // Determine element name
324 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
325 // Element name missing or not listed
331 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
332 // To avoid leaving blank lines, when a comment is both preceded
333 // and followed by a newline (ignoring spaces), trim leading and
334 // trailing spaces and one of the newlines.
337 $endPos = strpos( $text, '-->', $i +
4 );
338 if ( $endPos === false ) {
339 // Unclosed comment in input, runs to end
340 $inner = substr( $text, $i );
341 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
342 $i = strlen( $text );
344 // Search backwards for leading whitespace
345 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
346 // Search forwards for trailing whitespace
347 // $wsEnd will be the position of the last space (or the '>' if there's none)
348 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
349 // Eat the line if possible
350 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
351 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
352 // it's a possible beneficial b/c break.
353 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
354 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
356 $startPos = $wsStart;
357 $endPos = $wsEnd +
1;
358 // Remove leading whitespace from the end of the accumulator
359 // Sanity check first though
360 $wsLength = $i - $wsStart;
361 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
362 $accum = substr( $accum, 0, -$wsLength );
364 // Do a line-start run next time to look for headings after the comment
365 $fakeLineStart = true;
367 // No line to eat, just take the comment itself
373 $part = $stack->top
->getCurrentPart();
374 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
375 $part->visualEnd
= $wsStart;
377 // Else comments abutting, no change in visual end
378 $part->commentEnd
= $endPos;
381 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
382 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
387 $lowerName = strtolower( $name );
388 $attrStart = $i +
strlen( $name ) +
1;
391 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
392 if ( $tagEndPos === false ) {
393 // Infinite backtrack
394 // Disable tag search to prevent worst-case O(N^2) performance
401 // Handle ignored tags
402 if ( in_array( $lowerName, $ignoredTags ) ) {
403 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
409 if ( $text[$tagEndPos-1] == '/' ) {
410 $attrEnd = $tagEndPos - 1;
415 $attrEnd = $tagEndPos;
417 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
418 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
420 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
421 $i = $matches[0][1] +
strlen( $matches[0][0] );
422 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
424 // No end tag -- let it run out to the end of the text.
425 $inner = substr( $text, $tagEndPos +
1 );
426 $i = strlen( $text );
430 // <includeonly> and <noinclude> just become <ignore> tags
431 if ( in_array( $lowerName, $ignoredElements ) ) {
432 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
438 if ( $attrEnd <= $attrStart ) {
441 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
443 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
444 // Note that the attr element contains the whitespace between name and attribute,
445 // this is necessary for precise reconstruction during pre-save transform.
446 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
447 if ( $inner !== null ) {
448 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
450 $accum .= $close . '</ext>';
451 } elseif ( $found == 'line-start' ) {
452 // Is this the start of a heading?
453 // Line break belongs before the heading element in any case
454 if ( $fakeLineStart ) {
455 $fakeLineStart = false;
461 $count = strspn( $text, '=', $i, 6 );
462 if ( $count == 1 && $findEquals ) {
463 // DWIM: This looks kind of like a name/value separator
464 // Let's let the equals handler have it and break the potential heading
465 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
466 } elseif ( $count > 0 ) {
470 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
473 $stack->push( $piece );
474 $accum =& $stack->getAccum();
475 $flags = $stack->getFlags();
479 } elseif ( $found == 'line-end' ) {
480 $piece = $stack->top
;
481 // A heading must be open, otherwise \n wouldn't have been in the search list
482 assert( '$piece->open == "\n"' );
483 $part = $piece->getCurrentPart();
484 // Search back through the input to see if it has a proper close
485 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
486 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
487 $searchStart = $i - $wsLength;
488 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
489 // Comment found at line end
490 // Search for equals signs before the comment
491 $searchStart = $part->visualEnd
;
492 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
494 $count = $piece->count
;
495 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
496 if ( $equalsLength > 0 ) {
497 if ( $searchStart - $equalsLength == $piece->startPos
) {
498 // This is just a single string of equals signs on its own line
499 // Replicate the doHeadings behaviour /={count}(.+)={count}/
500 // First find out how many equals signs there really are (don't stop at 6)
501 $count = $equalsLength;
505 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
508 $count = min( $equalsLength, $count );
511 // Normal match, output <h>
512 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
515 // Single equals sign on its own line, count=0
519 // No match, no <h>, just pass down the inner text
524 $accum =& $stack->getAccum();
525 $flags = $stack->getFlags();
528 // Append the result to the enclosing accumulator
530 // Note that we do NOT increment the input pointer.
531 // This is because the closing linebreak could be the opening linebreak of
532 // another heading. Infinite loops are avoided because the next iteration MUST
533 // hit the heading open case above, which unconditionally increments the
535 } elseif ( $found == 'open' ) {
536 # count opening brace characters
537 $count = strspn( $text, $curChar, $i );
539 # we need to add to stack only if opening brace count is enough for one of the rules
540 if ( $count >= $rule['min'] ) {
541 # Add it to the stack
544 'close' => $rule['end'],
546 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
549 $stack->push( $piece );
550 $accum =& $stack->getAccum();
551 $flags = $stack->getFlags();
554 # Add literal brace(s)
555 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
558 } elseif ( $found == 'close' ) {
559 $piece = $stack->top
;
560 # lets check if there are enough characters for closing brace
561 $maxCount = $piece->count
;
562 $count = strspn( $text, $curChar, $i, $maxCount );
564 # check for maximum matching characters (if there are 5 closing
565 # characters, we will probably need only 3 - depending on the rules)
566 $rule = $rules[$piece->open
];
567 if ( $count > $rule['max'] ) {
568 # The specified maximum exists in the callback array, unless the caller
570 $matchingCount = $rule['max'];
572 # Count is less than the maximum
573 # Skip any gaps in the callback array to find the true largest match
574 # Need to use array_key_exists not isset because the callback can be null
575 $matchingCount = $count;
576 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
581 if ( $matchingCount <= 0 ) {
582 # No matching element found in callback array
583 # Output a literal closing brace and continue
584 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
588 $name = $rule['names'][$matchingCount];
589 if ( $name === null ) {
590 // No element, just literal text
591 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
594 # Note: $parts is already XML, does not need to be encoded further
595 $parts = $piece->parts
;
596 $title = $parts[0]->out
;
599 # The invocation is at the start of the line if lineStart is set in
600 # the stack, and all opening brackets are used up.
601 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
602 $attr = ' lineStart="1"';
607 $element = "<$name$attr>";
608 $element .= "<title>$title</title>";
610 foreach ( $parts as $part ) {
611 if ( isset( $part->eqpos
) ) {
612 $argName = substr( $part->out
, 0, $part->eqpos
);
613 $argValue = substr( $part->out
, $part->eqpos +
1 );
614 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
616 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
620 $element .= "</$name>";
623 # Advance input pointer
624 $i +
= $matchingCount;
628 $accum =& $stack->getAccum();
630 # Re-add the old stack element if it still has unmatched opening characters remaining
631 if ( $matchingCount < $piece->count
) {
632 $piece->parts
= array( new PPDPart
);
633 $piece->count
-= $matchingCount;
634 # do we still qualify for any callback with remaining count?
635 $names = $rules[$piece->open
]['names'];
637 $enclosingAccum =& $accum;
638 while ( $piece->count
) {
639 if ( array_key_exists( $piece->count
, $names ) ) {
640 $stack->push( $piece );
641 $accum =& $stack->getAccum();
647 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
649 $flags = $stack->getFlags();
652 # Add XML element to the enclosing accumulator
654 } elseif ( $found == 'pipe' ) {
655 $findEquals = true; // shortcut for getFlags()
657 $accum =& $stack->getAccum();
659 } elseif ( $found == 'equals' ) {
660 $findEquals = false; // shortcut for getFlags()
661 $stack->getCurrentPart()->eqpos
= strlen( $accum );
667 # Output any remaining unclosed brackets
668 foreach ( $stack->stack
as $piece ) {
669 $stack->rootAccum
.= $piece->breakSyntax();
671 $stack->rootAccum
.= '</root>';
672 $xml = $stack->rootAccum
;
674 wfProfileOut( __METHOD__
);
681 * Stack class to help Preprocessor::preprocessToObj()
685 var $stack, $rootAccum;
692 var $elementClass = 'PPDStackElement';
694 static $false = false;
696 function __construct() {
697 $this->stack
= array();
699 $this->rootAccum
= '';
700 $this->accum
=& $this->rootAccum
;
707 return count( $this->stack
);
710 function &getAccum() {
714 function getCurrentPart() {
715 if ( $this->top
=== false ) {
718 return $this->top
->getCurrentPart();
722 function push( $data ) {
723 if ( $data instanceof $this->elementClass
) {
724 $this->stack
[] = $data;
726 $class = $this->elementClass
;
727 $this->stack
[] = new $class( $data );
729 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
730 $this->accum
=& $this->top
->getAccum();
734 if ( !count( $this->stack
) ) {
735 throw new MWException( __METHOD__
.': no elements remaining' );
737 $temp = array_pop( $this->stack
);
739 if ( count( $this->stack
) ) {
740 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
741 $this->accum
=& $this->top
->getAccum();
743 $this->top
= self
::$false;
744 $this->accum
=& $this->rootAccum
;
749 function addPart( $s = '' ) {
750 $this->top
->addPart( $s );
751 $this->accum
=& $this->top
->getAccum();
757 function getFlags() {
758 if ( !count( $this->stack
) ) {
760 'findEquals' => false,
762 'inHeading' => false,
765 return $this->top
->getFlags();
773 class PPDStackElement
{
774 var $open, // Opening character (\n for heading)
775 $close, // Matching closing character
776 $count, // Number of opening characters found (number of "=" for heading)
777 $parts, // Array of PPDPart objects describing pipe-separated parts.
778 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
780 var $partClass = 'PPDPart';
782 function __construct( $data = array() ) {
783 $class = $this->partClass
;
784 $this->parts
= array( new $class );
786 foreach ( $data as $name => $value ) {
787 $this->$name = $value;
791 function &getAccum() {
792 return $this->parts
[count($this->parts
) - 1]->out
;
795 function addPart( $s = '' ) {
796 $class = $this->partClass
;
797 $this->parts
[] = new $class( $s );
800 function getCurrentPart() {
801 return $this->parts
[count($this->parts
) - 1];
807 function getFlags() {
808 $partCount = count( $this->parts
);
809 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
811 'findPipe' => $findPipe,
812 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
813 'inHeading' => $this->open
== "\n",
818 * Get the output string that would result if the close is not found.
822 function breakSyntax( $openingCount = false ) {
823 if ( $this->open
== "\n" ) {
824 $s = $this->parts
[0]->out
;
826 if ( $openingCount === false ) {
827 $openingCount = $this->count
;
829 $s = str_repeat( $this->open
, $openingCount );
831 foreach ( $this->parts
as $part ) {
848 var $out; // Output accumulator string
850 // Optional member variables:
851 // eqpos Position of equals sign in output accumulator
852 // commentEnd Past-the-end input pointer for the last comment encountered
853 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
855 function __construct( $out = '' ) {
861 * An expansion frame, used as a context to expand the result of preprocessToObj()
864 class PPFrame_DOM
implements PPFrame
{
883 * Hashtable listing templates which are disallowed for expansion in this frame,
884 * having been encountered previously in parent frames.
889 * Recursion depth of this frame, top = 0
890 * Note that this is NOT the same as expansion depth in expand()
896 * Construct a new preprocessor frame.
897 * @param $preprocessor Preprocessor The parent preprocessor
899 function __construct( $preprocessor ) {
900 $this->preprocessor
= $preprocessor;
901 $this->parser
= $preprocessor->parser
;
902 $this->title
= $this->parser
->mTitle
;
903 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
904 $this->loopCheckHash
= array();
909 * Create a new child frame
910 * $args is optionally a multi-root PPNode or array containing the template arguments
912 * @return PPTemplateFrame_DOM
914 function newChild( $args = false, $title = false ) {
915 $namedArgs = array();
916 $numberedArgs = array();
917 if ( $title === false ) {
918 $title = $this->title
;
920 if ( $args !== false ) {
922 if ( $args instanceof PPNode
) {
925 foreach ( $args as $arg ) {
927 $xpath = new DOMXPath( $arg->ownerDocument
);
930 $nameNodes = $xpath->query( 'name', $arg );
931 $value = $xpath->query( 'value', $arg );
932 if ( $nameNodes->item( 0 )->hasAttributes() ) {
933 // Numbered parameter
934 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
935 $numberedArgs[$index] = $value->item( 0 );
936 unset( $namedArgs[$index] );
939 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
940 $namedArgs[$name] = $value->item( 0 );
941 unset( $numberedArgs[$name] );
945 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
949 * @throws MWException
954 function expand( $root, $flags = 0 ) {
955 static $expansionDepth = 0;
956 if ( is_string( $root ) ) {
960 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
961 return '<span class="error">Node-count limit exceeded</span>';
964 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
965 return '<span class="error">Expansion depth limit exceeded</span>';
967 wfProfileIn( __METHOD__
);
970 if ( $root instanceof PPNode_DOM
) {
973 if ( $root instanceof DOMDocument
) {
974 $root = $root->documentElement
;
977 $outStack = array( '', '' );
978 $iteratorStack = array( false, $root );
979 $indexStack = array( 0, 0 );
981 while ( count( $iteratorStack ) > 1 ) {
982 $level = count( $outStack ) - 1;
983 $iteratorNode =& $iteratorStack[ $level ];
984 $out =& $outStack[$level];
985 $index =& $indexStack[$level];
987 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
989 if ( is_array( $iteratorNode ) ) {
990 if ( $index >= count( $iteratorNode ) ) {
991 // All done with this iterator
992 $iteratorStack[$level] = false;
993 $contextNode = false;
995 $contextNode = $iteratorNode[$index];
998 } elseif ( $iteratorNode instanceof DOMNodeList
) {
999 if ( $index >= $iteratorNode->length
) {
1000 // All done with this iterator
1001 $iteratorStack[$level] = false;
1002 $contextNode = false;
1004 $contextNode = $iteratorNode->item( $index );
1008 // Copy to $contextNode and then delete from iterator stack,
1009 // because this is not an iterator but we do have to execute it once
1010 $contextNode = $iteratorStack[$level];
1011 $iteratorStack[$level] = false;
1014 if ( $contextNode instanceof PPNode_DOM
) {
1015 $contextNode = $contextNode->node
;
1018 $newIterator = false;
1020 if ( $contextNode === false ) {
1022 } elseif ( is_string( $contextNode ) ) {
1023 $out .= $contextNode;
1024 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1025 $newIterator = $contextNode;
1026 } elseif ( $contextNode instanceof DOMNode
) {
1027 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1028 $out .= $contextNode->nodeValue
;
1029 } elseif ( $contextNode->nodeName
== 'template' ) {
1030 # Double-brace expansion
1031 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1032 $titles = $xpath->query( 'title', $contextNode );
1033 $title = $titles->item( 0 );
1034 $parts = $xpath->query( 'part', $contextNode );
1035 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1036 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1038 $lineStart = $contextNode->getAttribute( 'lineStart' );
1040 'title' => new PPNode_DOM( $title ),
1041 'parts' => new PPNode_DOM( $parts ),
1042 'lineStart' => $lineStart );
1043 $ret = $this->parser
->braceSubstitution( $params, $this );
1044 if ( isset( $ret['object'] ) ) {
1045 $newIterator = $ret['object'];
1047 $out .= $ret['text'];
1050 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1051 # Triple-brace expansion
1052 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1053 $titles = $xpath->query( 'title', $contextNode );
1054 $title = $titles->item( 0 );
1055 $parts = $xpath->query( 'part', $contextNode );
1056 if ( $flags & PPFrame
::NO_ARGS
) {
1057 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1060 'title' => new PPNode_DOM( $title ),
1061 'parts' => new PPNode_DOM( $parts ) );
1062 $ret = $this->parser
->argSubstitution( $params, $this );
1063 if ( isset( $ret['object'] ) ) {
1064 $newIterator = $ret['object'];
1066 $out .= $ret['text'];
1069 } elseif ( $contextNode->nodeName
== 'comment' ) {
1070 # HTML-style comment
1071 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1072 if ( $this->parser
->ot
['html']
1073 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1074 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1078 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1079 # Not in RECOVER_COMMENTS mode (extractSections) though
1080 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1081 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1083 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1085 $out .= $contextNode->textContent
;
1087 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1088 # Output suppression used by <includeonly> etc.
1089 # OT_WIKI will only respect <ignore> in substed templates.
1090 # The other output types respect it unless NO_IGNORE is set.
1091 # extractSections() sets NO_IGNORE and so never respects it.
1092 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1093 $out .= $contextNode->textContent
;
1097 } elseif ( $contextNode->nodeName
== 'ext' ) {
1099 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1100 $names = $xpath->query( 'name', $contextNode );
1101 $attrs = $xpath->query( 'attr', $contextNode );
1102 $inners = $xpath->query( 'inner', $contextNode );
1103 $closes = $xpath->query( 'close', $contextNode );
1105 'name' => new PPNode_DOM( $names->item( 0 ) ),
1106 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1107 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1108 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1110 $out .= $this->parser
->extensionSubstitution( $params, $this );
1111 } elseif ( $contextNode->nodeName
== 'h' ) {
1113 $s = $this->expand( $contextNode->childNodes
, $flags );
1115 # Insert a heading marker only for <h> children of <root>
1116 # This is to stop extractSections from going over multiple tree levels
1117 if ( $contextNode->parentNode
->nodeName
== 'root'
1118 && $this->parser
->ot
['html'] )
1120 # Insert heading index marker
1121 $headingIndex = $contextNode->getAttribute( 'i' );
1122 $titleText = $this->title
->getPrefixedDBkey();
1123 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1124 $serial = count( $this->parser
->mHeadings
) - 1;
1125 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1126 $count = $contextNode->getAttribute( 'level' );
1127 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1128 $this->parser
->mStripState
->addGeneral( $marker, '' );
1132 # Generic recursive expansion
1133 $newIterator = $contextNode->childNodes
;
1136 wfProfileOut( __METHOD__
);
1137 throw new MWException( __METHOD__
.': Invalid parameter type' );
1140 if ( $newIterator !== false ) {
1141 if ( $newIterator instanceof PPNode_DOM
) {
1142 $newIterator = $newIterator->node
;
1145 $iteratorStack[] = $newIterator;
1147 } elseif ( $iteratorStack[$level] === false ) {
1148 // Return accumulated value to parent
1149 // With tail recursion
1150 while ( $iteratorStack[$level] === false && $level > 0 ) {
1151 $outStack[$level - 1] .= $out;
1152 array_pop( $outStack );
1153 array_pop( $iteratorStack );
1154 array_pop( $indexStack );
1160 wfProfileOut( __METHOD__
);
1161 return $outStack[0];
1169 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1170 $args = array_slice( func_get_args(), 2 );
1174 foreach ( $args as $root ) {
1175 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1176 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1177 $root = array( $root );
1179 foreach ( $root as $node ) {
1185 $s .= $this->expand( $node, $flags );
1192 * Implode with no flags specified
1193 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1197 function implode( $sep /*, ... */ ) {
1198 $args = array_slice( func_get_args(), 1 );
1202 foreach ( $args as $root ) {
1203 if ( $root instanceof PPNode_DOM
) {
1204 $root = $root->node
;
1206 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1207 $root = array( $root );
1209 foreach ( $root as $node ) {
1215 $s .= $this->expand( $node );
1222 * Makes an object that, when expand()ed, will be the same as one obtained
1227 function virtualImplode( $sep /*, ... */ ) {
1228 $args = array_slice( func_get_args(), 1 );
1232 foreach ( $args as $root ) {
1233 if ( $root instanceof PPNode_DOM
) {
1234 $root = $root->node
;
1236 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1237 $root = array( $root );
1239 foreach ( $root as $node ) {
1252 * Virtual implode with brackets
1255 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1256 $args = array_slice( func_get_args(), 3 );
1257 $out = array( $start );
1260 foreach ( $args as $root ) {
1261 if ( $root instanceof PPNode_DOM
) {
1262 $root = $root->node
;
1264 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1265 $root = array( $root );
1267 foreach ( $root as $node ) {
1280 function __toString() {
1284 function getPDBK( $level = false ) {
1285 if ( $level === false ) {
1286 return $this->title
->getPrefixedDBkey();
1288 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1295 function getArguments() {
1302 function getNumberedArguments() {
1309 function getNamedArguments() {
1314 * Returns true if there are no arguments in this frame
1318 function isEmpty() {
1322 function getArgument( $name ) {
1327 * Returns true if the infinite loop check is OK, false if a loop is detected
1331 function loopCheck( $title ) {
1332 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1336 * Return true if the frame is a template frame
1340 function isTemplate() {
1345 * Get a title of frame
1349 function getTitle() {
1350 return $this->title
;
1355 * Expansion frame with template arguments
1358 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1359 var $numberedArgs, $namedArgs;
1365 var $numberedExpansionCache, $namedExpansionCache;
1368 * @param $preprocessor
1369 * @param $parent PPFrame_DOM
1370 * @param $numberedArgs array
1371 * @param $namedArgs array
1372 * @param $title Title
1374 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1375 parent
::__construct( $preprocessor );
1377 $this->parent
= $parent;
1378 $this->numberedArgs
= $numberedArgs;
1379 $this->namedArgs
= $namedArgs;
1380 $this->title
= $title;
1381 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1382 $this->titleCache
= $parent->titleCache
;
1383 $this->titleCache
[] = $pdbk;
1384 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1385 if ( $pdbk !== false ) {
1386 $this->loopCheckHash
[$pdbk] = true;
1388 $this->depth
= $parent->depth +
1;
1389 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1392 function __toString() {
1395 $args = $this->numberedArgs +
$this->namedArgs
;
1396 foreach ( $args as $name => $value ) {
1402 $s .= "\"$name\":\"" .
1403 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1410 * Returns true if there are no arguments in this frame
1414 function isEmpty() {
1415 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1418 function getArguments() {
1419 $arguments = array();
1420 foreach ( array_merge(
1421 array_keys($this->numberedArgs
),
1422 array_keys($this->namedArgs
)) as $key ) {
1423 $arguments[$key] = $this->getArgument($key);
1428 function getNumberedArguments() {
1429 $arguments = array();
1430 foreach ( array_keys($this->numberedArgs
) as $key ) {
1431 $arguments[$key] = $this->getArgument($key);
1436 function getNamedArguments() {
1437 $arguments = array();
1438 foreach ( array_keys($this->namedArgs
) as $key ) {
1439 $arguments[$key] = $this->getArgument($key);
1444 function getNumberedArgument( $index ) {
1445 if ( !isset( $this->numberedArgs
[$index] ) ) {
1448 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1449 # No trimming for unnamed arguments
1450 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1452 return $this->numberedExpansionCache
[$index];
1455 function getNamedArgument( $name ) {
1456 if ( !isset( $this->namedArgs
[$name] ) ) {
1459 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1460 # Trim named arguments post-expand, for backwards compatibility
1461 $this->namedExpansionCache
[$name] = trim(
1462 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1464 return $this->namedExpansionCache
[$name];
1467 function getArgument( $name ) {
1468 $text = $this->getNumberedArgument( $name );
1469 if ( $text === false ) {
1470 $text = $this->getNamedArgument( $name );
1476 * Return true if the frame is a template frame
1480 function isTemplate() {
1486 * Expansion frame with custom arguments
1489 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1492 function __construct( $preprocessor, $args ) {
1493 parent
::__construct( $preprocessor );
1494 $this->args
= $args;
1497 function __toString() {
1500 foreach ( $this->args
as $name => $value ) {
1506 $s .= "\"$name\":\"" .
1507 str_replace( '"', '\\"', $value->__toString() ) . '"';
1516 function isEmpty() {
1517 return !count( $this->args
);
1520 function getArgument( $index ) {
1521 if ( !isset( $this->args
[$index] ) ) {
1524 return $this->args
[$index];
1531 class PPNode_DOM
implements PPNode
{
1539 function __construct( $node, $xpath = false ) {
1540 $this->node
= $node;
1546 function getXPath() {
1547 if ( $this->xpath
=== null ) {
1548 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1550 return $this->xpath
;
1553 function __toString() {
1554 if ( $this->node
instanceof DOMNodeList
) {
1556 foreach ( $this->node
as $node ) {
1557 $s .= $node->ownerDocument
->saveXML( $node );
1560 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1566 * @return bool|PPNode_DOM
1568 function getChildren() {
1569 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1573 * @return bool|PPNode_DOM
1575 function getFirstChild() {
1576 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1580 * @return bool|PPNode_DOM
1582 function getNextSibling() {
1583 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1589 * @return bool|PPNode_DOM
1591 function getChildrenOfType( $type ) {
1592 return new self( $this->getXPath()->query( $type, $this->node
) );
1598 function getLength() {
1599 if ( $this->node
instanceof DOMNodeList
) {
1600 return $this->node
->length
;
1608 * @return bool|PPNode_DOM
1610 function item( $i ) {
1611 $item = $this->node
->item( $i );
1612 return $item ?
new self( $item ) : false;
1618 function getName() {
1619 if ( $this->node
instanceof DOMNodeList
) {
1622 return $this->node
->nodeName
;
1627 * Split a <part> node into an associative array containing:
1629 * index String index
1630 * value PPNode value
1634 function splitArg() {
1635 $xpath = $this->getXPath();
1636 $names = $xpath->query( 'name', $this->node
);
1637 $values = $xpath->query( 'value', $this->node
);
1638 if ( !$names->length ||
!$values->length
) {
1639 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1641 $name = $names->item( 0 );
1642 $index = $name->getAttribute( 'index' );
1644 'name' => new self( $name ),
1646 'value' => new self( $values->item( 0 ) ) );
1650 * Split an <ext> node into an associative array containing name, attr, inner and close
1651 * All values in the resulting array are PPNodes. Inner and close are optional.
1655 function splitExt() {
1656 $xpath = $this->getXPath();
1657 $names = $xpath->query( 'name', $this->node
);
1658 $attrs = $xpath->query( 'attr', $this->node
);
1659 $inners = $xpath->query( 'inner', $this->node
);
1660 $closes = $xpath->query( 'close', $this->node
);
1661 if ( !$names->length ||
!$attrs->length
) {
1662 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1665 'name' => new self( $names->item( 0 ) ),
1666 'attr' => new self( $attrs->item( 0 ) ) );
1667 if ( $inners->length
) {
1668 $parts['inner'] = new self( $inners->item( 0 ) );
1670 if ( $closes->length
) {
1671 $parts['close'] = new self( $closes->item( 0 ) );
1680 function splitHeading() {
1681 if ( $this->getName() !== 'h' ) {
1682 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1685 'i' => $this->node
->getAttribute( 'i' ),
1686 'level' => $this->node
->getAttribute( 'level' ),
1687 'contents' => $this->getChildren()