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 $this->parser
->limitationWarn( 'node-count-exceeded',
962 $this->parser
->mPPNodeCount
,
963 $this->parser
->mOptions
->getMaxPPNodeCount()
965 return '<span class="error">Node-count limit exceeded</span>';
968 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
969 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
971 $this->parser
->mOptions
->getMaxPPExpandDepth()
973 return '<span class="error">Expansion depth limit exceeded</span>';
975 wfProfileIn( __METHOD__
);
978 if ( $root instanceof PPNode_DOM
) {
981 if ( $root instanceof DOMDocument
) {
982 $root = $root->documentElement
;
985 $outStack = array( '', '' );
986 $iteratorStack = array( false, $root );
987 $indexStack = array( 0, 0 );
989 while ( count( $iteratorStack ) > 1 ) {
990 $level = count( $outStack ) - 1;
991 $iteratorNode =& $iteratorStack[ $level ];
992 $out =& $outStack[$level];
993 $index =& $indexStack[$level];
995 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
997 if ( is_array( $iteratorNode ) ) {
998 if ( $index >= count( $iteratorNode ) ) {
999 // All done with this iterator
1000 $iteratorStack[$level] = false;
1001 $contextNode = false;
1003 $contextNode = $iteratorNode[$index];
1006 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1007 if ( $index >= $iteratorNode->length
) {
1008 // All done with this iterator
1009 $iteratorStack[$level] = false;
1010 $contextNode = false;
1012 $contextNode = $iteratorNode->item( $index );
1016 // Copy to $contextNode and then delete from iterator stack,
1017 // because this is not an iterator but we do have to execute it once
1018 $contextNode = $iteratorStack[$level];
1019 $iteratorStack[$level] = false;
1022 if ( $contextNode instanceof PPNode_DOM
) {
1023 $contextNode = $contextNode->node
;
1026 $newIterator = false;
1028 if ( $contextNode === false ) {
1030 } elseif ( is_string( $contextNode ) ) {
1031 $out .= $contextNode;
1032 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1033 $newIterator = $contextNode;
1034 } elseif ( $contextNode instanceof DOMNode
) {
1035 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1036 $out .= $contextNode->nodeValue
;
1037 } elseif ( $contextNode->nodeName
== 'template' ) {
1038 # Double-brace expansion
1039 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1040 $titles = $xpath->query( 'title', $contextNode );
1041 $title = $titles->item( 0 );
1042 $parts = $xpath->query( 'part', $contextNode );
1043 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1044 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1046 $lineStart = $contextNode->getAttribute( 'lineStart' );
1048 'title' => new PPNode_DOM( $title ),
1049 'parts' => new PPNode_DOM( $parts ),
1050 'lineStart' => $lineStart );
1051 $ret = $this->parser
->braceSubstitution( $params, $this );
1052 if ( isset( $ret['object'] ) ) {
1053 $newIterator = $ret['object'];
1055 $out .= $ret['text'];
1058 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1059 # Triple-brace expansion
1060 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1061 $titles = $xpath->query( 'title', $contextNode );
1062 $title = $titles->item( 0 );
1063 $parts = $xpath->query( 'part', $contextNode );
1064 if ( $flags & PPFrame
::NO_ARGS
) {
1065 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1068 'title' => new PPNode_DOM( $title ),
1069 'parts' => new PPNode_DOM( $parts ) );
1070 $ret = $this->parser
->argSubstitution( $params, $this );
1071 if ( isset( $ret['object'] ) ) {
1072 $newIterator = $ret['object'];
1074 $out .= $ret['text'];
1077 } elseif ( $contextNode->nodeName
== 'comment' ) {
1078 # HTML-style comment
1079 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1080 if ( $this->parser
->ot
['html']
1081 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1082 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1086 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1087 # Not in RECOVER_COMMENTS mode (extractSections) though
1088 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1089 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1091 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1093 $out .= $contextNode->textContent
;
1095 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1096 # Output suppression used by <includeonly> etc.
1097 # OT_WIKI will only respect <ignore> in substed templates.
1098 # The other output types respect it unless NO_IGNORE is set.
1099 # extractSections() sets NO_IGNORE and so never respects it.
1100 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1101 $out .= $contextNode->textContent
;
1105 } elseif ( $contextNode->nodeName
== 'ext' ) {
1107 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1108 $names = $xpath->query( 'name', $contextNode );
1109 $attrs = $xpath->query( 'attr', $contextNode );
1110 $inners = $xpath->query( 'inner', $contextNode );
1111 $closes = $xpath->query( 'close', $contextNode );
1113 'name' => new PPNode_DOM( $names->item( 0 ) ),
1114 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1115 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1116 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1118 $out .= $this->parser
->extensionSubstitution( $params, $this );
1119 } elseif ( $contextNode->nodeName
== 'h' ) {
1121 $s = $this->expand( $contextNode->childNodes
, $flags );
1123 # Insert a heading marker only for <h> children of <root>
1124 # This is to stop extractSections from going over multiple tree levels
1125 if ( $contextNode->parentNode
->nodeName
== 'root'
1126 && $this->parser
->ot
['html'] )
1128 # Insert heading index marker
1129 $headingIndex = $contextNode->getAttribute( 'i' );
1130 $titleText = $this->title
->getPrefixedDBkey();
1131 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1132 $serial = count( $this->parser
->mHeadings
) - 1;
1133 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1134 $count = $contextNode->getAttribute( 'level' );
1135 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1136 $this->parser
->mStripState
->addGeneral( $marker, '' );
1140 # Generic recursive expansion
1141 $newIterator = $contextNode->childNodes
;
1144 wfProfileOut( __METHOD__
);
1145 throw new MWException( __METHOD__
.': Invalid parameter type' );
1148 if ( $newIterator !== false ) {
1149 if ( $newIterator instanceof PPNode_DOM
) {
1150 $newIterator = $newIterator->node
;
1153 $iteratorStack[] = $newIterator;
1155 } elseif ( $iteratorStack[$level] === false ) {
1156 // Return accumulated value to parent
1157 // With tail recursion
1158 while ( $iteratorStack[$level] === false && $level > 0 ) {
1159 $outStack[$level - 1] .= $out;
1160 array_pop( $outStack );
1161 array_pop( $iteratorStack );
1162 array_pop( $indexStack );
1168 wfProfileOut( __METHOD__
);
1169 return $outStack[0];
1177 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1178 $args = array_slice( func_get_args(), 2 );
1182 foreach ( $args as $root ) {
1183 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1184 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1185 $root = array( $root );
1187 foreach ( $root as $node ) {
1193 $s .= $this->expand( $node, $flags );
1200 * Implode with no flags specified
1201 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1205 function implode( $sep /*, ... */ ) {
1206 $args = array_slice( func_get_args(), 1 );
1210 foreach ( $args as $root ) {
1211 if ( $root instanceof PPNode_DOM
) {
1212 $root = $root->node
;
1214 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1215 $root = array( $root );
1217 foreach ( $root as $node ) {
1223 $s .= $this->expand( $node );
1230 * Makes an object that, when expand()ed, will be the same as one obtained
1235 function virtualImplode( $sep /*, ... */ ) {
1236 $args = array_slice( func_get_args(), 1 );
1240 foreach ( $args as $root ) {
1241 if ( $root instanceof PPNode_DOM
) {
1242 $root = $root->node
;
1244 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1245 $root = array( $root );
1247 foreach ( $root as $node ) {
1260 * Virtual implode with brackets
1263 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1264 $args = array_slice( func_get_args(), 3 );
1265 $out = array( $start );
1268 foreach ( $args as $root ) {
1269 if ( $root instanceof PPNode_DOM
) {
1270 $root = $root->node
;
1272 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1273 $root = array( $root );
1275 foreach ( $root as $node ) {
1288 function __toString() {
1292 function getPDBK( $level = false ) {
1293 if ( $level === false ) {
1294 return $this->title
->getPrefixedDBkey();
1296 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1303 function getArguments() {
1310 function getNumberedArguments() {
1317 function getNamedArguments() {
1322 * Returns true if there are no arguments in this frame
1326 function isEmpty() {
1330 function getArgument( $name ) {
1335 * Returns true if the infinite loop check is OK, false if a loop is detected
1339 function loopCheck( $title ) {
1340 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1344 * Return true if the frame is a template frame
1348 function isTemplate() {
1353 * Get a title of frame
1357 function getTitle() {
1358 return $this->title
;
1363 * Expansion frame with template arguments
1366 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1367 var $numberedArgs, $namedArgs;
1373 var $numberedExpansionCache, $namedExpansionCache;
1376 * @param $preprocessor
1377 * @param $parent PPFrame_DOM
1378 * @param $numberedArgs array
1379 * @param $namedArgs array
1380 * @param $title Title
1382 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1383 parent
::__construct( $preprocessor );
1385 $this->parent
= $parent;
1386 $this->numberedArgs
= $numberedArgs;
1387 $this->namedArgs
= $namedArgs;
1388 $this->title
= $title;
1389 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1390 $this->titleCache
= $parent->titleCache
;
1391 $this->titleCache
[] = $pdbk;
1392 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1393 if ( $pdbk !== false ) {
1394 $this->loopCheckHash
[$pdbk] = true;
1396 $this->depth
= $parent->depth +
1;
1397 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1400 function __toString() {
1403 $args = $this->numberedArgs +
$this->namedArgs
;
1404 foreach ( $args as $name => $value ) {
1410 $s .= "\"$name\":\"" .
1411 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1418 * Returns true if there are no arguments in this frame
1422 function isEmpty() {
1423 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1426 function getArguments() {
1427 $arguments = array();
1428 foreach ( array_merge(
1429 array_keys($this->numberedArgs
),
1430 array_keys($this->namedArgs
)) as $key ) {
1431 $arguments[$key] = $this->getArgument($key);
1436 function getNumberedArguments() {
1437 $arguments = array();
1438 foreach ( array_keys($this->numberedArgs
) as $key ) {
1439 $arguments[$key] = $this->getArgument($key);
1444 function getNamedArguments() {
1445 $arguments = array();
1446 foreach ( array_keys($this->namedArgs
) as $key ) {
1447 $arguments[$key] = $this->getArgument($key);
1452 function getNumberedArgument( $index ) {
1453 if ( !isset( $this->numberedArgs
[$index] ) ) {
1456 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1457 # No trimming for unnamed arguments
1458 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1460 return $this->numberedExpansionCache
[$index];
1463 function getNamedArgument( $name ) {
1464 if ( !isset( $this->namedArgs
[$name] ) ) {
1467 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1468 # Trim named arguments post-expand, for backwards compatibility
1469 $this->namedExpansionCache
[$name] = trim(
1470 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1472 return $this->namedExpansionCache
[$name];
1475 function getArgument( $name ) {
1476 $text = $this->getNumberedArgument( $name );
1477 if ( $text === false ) {
1478 $text = $this->getNamedArgument( $name );
1484 * Return true if the frame is a template frame
1488 function isTemplate() {
1494 * Expansion frame with custom arguments
1497 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1500 function __construct( $preprocessor, $args ) {
1501 parent
::__construct( $preprocessor );
1502 $this->args
= $args;
1505 function __toString() {
1508 foreach ( $this->args
as $name => $value ) {
1514 $s .= "\"$name\":\"" .
1515 str_replace( '"', '\\"', $value->__toString() ) . '"';
1524 function isEmpty() {
1525 return !count( $this->args
);
1528 function getArgument( $index ) {
1529 if ( !isset( $this->args
[$index] ) ) {
1532 return $this->args
[$index];
1539 class PPNode_DOM
implements PPNode
{
1547 function __construct( $node, $xpath = false ) {
1548 $this->node
= $node;
1554 function getXPath() {
1555 if ( $this->xpath
=== null ) {
1556 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1558 return $this->xpath
;
1561 function __toString() {
1562 if ( $this->node
instanceof DOMNodeList
) {
1564 foreach ( $this->node
as $node ) {
1565 $s .= $node->ownerDocument
->saveXML( $node );
1568 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1574 * @return bool|PPNode_DOM
1576 function getChildren() {
1577 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1581 * @return bool|PPNode_DOM
1583 function getFirstChild() {
1584 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1588 * @return bool|PPNode_DOM
1590 function getNextSibling() {
1591 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1597 * @return bool|PPNode_DOM
1599 function getChildrenOfType( $type ) {
1600 return new self( $this->getXPath()->query( $type, $this->node
) );
1606 function getLength() {
1607 if ( $this->node
instanceof DOMNodeList
) {
1608 return $this->node
->length
;
1616 * @return bool|PPNode_DOM
1618 function item( $i ) {
1619 $item = $this->node
->item( $i );
1620 return $item ?
new self( $item ) : false;
1626 function getName() {
1627 if ( $this->node
instanceof DOMNodeList
) {
1630 return $this->node
->nodeName
;
1635 * Split a <part> node into an associative array containing:
1637 * index String index
1638 * value PPNode value
1642 function splitArg() {
1643 $xpath = $this->getXPath();
1644 $names = $xpath->query( 'name', $this->node
);
1645 $values = $xpath->query( 'value', $this->node
);
1646 if ( !$names->length ||
!$values->length
) {
1647 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1649 $name = $names->item( 0 );
1650 $index = $name->getAttribute( 'index' );
1652 'name' => new self( $name ),
1654 'value' => new self( $values->item( 0 ) ) );
1658 * Split an <ext> node into an associative array containing name, attr, inner and close
1659 * All values in the resulting array are PPNodes. Inner and close are optional.
1663 function splitExt() {
1664 $xpath = $this->getXPath();
1665 $names = $xpath->query( 'name', $this->node
);
1666 $attrs = $xpath->query( 'attr', $this->node
);
1667 $inners = $xpath->query( 'inner', $this->node
);
1668 $closes = $xpath->query( 'close', $this->node
);
1669 if ( !$names->length ||
!$attrs->length
) {
1670 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1673 'name' => new self( $names->item( 0 ) ),
1674 'attr' => new self( $attrs->item( 0 ) ) );
1675 if ( $inners->length
) {
1676 $parts['inner'] = new self( $inners->item( 0 ) );
1678 if ( $closes->length
) {
1679 $parts['close'] = new self( $closes->item( 0 ) );
1688 function splitHeading() {
1689 if ( $this->getName() !== 'h' ) {
1690 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1693 'i' => $this->node
->getAttribute( 'i' ),
1694 'level' => $this->node
->getAttribute( 'level' ),
1695 'contents' => $this->getChildren()