6 class Preprocessor_DOM
implements Preprocessor
{
7 var $parser, $memoryLimit;
9 const CACHE_VERSION
= 1;
11 function __construct( $parser ) {
12 $this->parser
= $parser;
13 $mem = ini_get( 'memory_limit' );
14 $this->memoryLimit
= false;
15 if ( strval( $mem ) !== '' && $mem != -1 ) {
16 if ( preg_match( '/^\d+$/', $mem ) ) {
17 $this->memoryLimit
= $mem;
18 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
19 $this->memoryLimit
= $m[1] * 1048576;
25 return new PPFrame_DOM( $this );
28 function newCustomFrame( $args ) {
29 return new PPCustomFrame_DOM( $this, $args );
33 if ( $this->memoryLimit
=== false ) {
36 $usage = memory_get_usage();
37 if ( $usage > $this->memoryLimit
* 0.9 ) {
38 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
39 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
41 return $usage <= $this->memoryLimit
* 0.8;
45 * Preprocess some wikitext and return the document tree.
46 * This is the ghost of Parser::replace_variables().
48 * @param string $text The text to parse
49 * @param integer flags Bitwise combination of:
50 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
51 * included. Default is to assume a direct page view.
53 * The generated DOM tree must depend only on the input text and the flags.
54 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
56 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
57 * change in the DOM tree for a given text, must be passed through the section identifier
58 * in the section edit link and thus back to extractSections().
60 * The output of this function is currently only cached in process memory, but a persistent
61 * cache may be implemented at a later date which takes further advantage of these strict
62 * dependency requirements.
66 function preprocessToObj( $text, $flags = 0 ) {
67 wfProfileIn( __METHOD__
);
68 global $wgMemc, $wgPreprocessorCacheThreshold;
71 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
73 wfProfileIn( __METHOD__
.'-cacheable' );
75 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
76 $cacheValue = $wgMemc->get( $cacheKey );
78 $version = substr( $cacheValue, 0, 8 );
79 if ( intval( $version ) == self
::CACHE_VERSION
) {
80 $xml = substr( $cacheValue, 8 );
82 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
86 if ( $xml === false ) {
88 wfProfileIn( __METHOD__
.'-cache-miss' );
89 $xml = $this->preprocessToXml( $text, $flags );
90 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
91 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
92 wfProfileOut( __METHOD__
.'-cache-miss' );
93 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
95 $xml = $this->preprocessToXml( $text, $flags );
99 wfProfileIn( __METHOD__
.'-loadXML' );
100 $dom = new DOMDocument
;
101 wfSuppressWarnings();
102 $result = $dom->loadXML( $xml );
105 // Try running the XML through UtfNormal to get rid of invalid characters
106 $xml = UtfNormal
::cleanUp( $xml );
107 $result = $dom->loadXML( $xml );
109 throw new MWException( __METHOD__
.' generated invalid XML' );
112 $obj = new PPNode_DOM( $dom->documentElement
);
113 wfProfileOut( __METHOD__
.'-loadXML' );
115 wfProfileOut( __METHOD__
.'-cacheable' );
117 wfProfileOut( __METHOD__
);
121 function preprocessToXml( $text, $flags = 0 ) {
122 wfProfileIn( __METHOD__
);
135 'names' => array( 2 => null ),
141 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
143 $xmlishElements = $this->parser
->getStripList();
144 $enableOnlyinclude = false;
145 if ( $forInclusion ) {
146 $ignoredTags = array( 'includeonly', '/includeonly' );
147 $ignoredElements = array( 'noinclude' );
148 $xmlishElements[] = 'noinclude';
149 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
150 $enableOnlyinclude = true;
153 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
154 $ignoredElements = array( 'includeonly' );
155 $xmlishElements[] = 'includeonly';
157 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
159 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
160 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
162 $stack = new PPDStack
;
164 $searchBase = "[{<\n"; #}
165 $revText = strrev( $text ); // For fast reverse searches
167 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
168 $accum =& $stack->getAccum(); # Current accumulator
170 $findEquals = false; # True to find equals signs in arguments
171 $findPipe = false; # True to take notice of pipe characters
173 $inHeading = false; # True if $i is inside a possible heading
174 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
175 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
176 $fakeLineStart = true; # Do a line-start run without outputting an LF character
181 if ( $findOnlyinclude ) {
182 // Ignore all input up to the next <onlyinclude>
183 $startPos = strpos( $text, '<onlyinclude>', $i );
184 if ( $startPos === false ) {
185 // Ignored section runs to the end
186 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
189 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
190 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
192 $findOnlyinclude = false;
195 if ( $fakeLineStart ) {
196 $found = 'line-start';
199 # Find next opening brace, closing brace or pipe
200 $search = $searchBase;
201 if ( $stack->top
=== false ) {
202 $currentClosing = '';
204 $currentClosing = $stack->top
->close
;
205 $search .= $currentClosing;
211 // First equals will be for the template
215 # Output literal section, advance input counter
216 $literalLength = strcspn( $text, $search, $i );
217 if ( $literalLength > 0 ) {
218 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
219 $i +
= $literalLength;
221 if ( $i >= strlen( $text ) ) {
222 if ( $currentClosing == "\n" ) {
223 // Do a past-the-end run to finish off the heading
231 $curChar = $text[$i];
232 if ( $curChar == '|' ) {
234 } elseif ( $curChar == '=' ) {
236 } elseif ( $curChar == '<' ) {
238 } elseif ( $curChar == "\n" ) {
242 $found = 'line-start';
244 } elseif ( $curChar == $currentClosing ) {
246 } elseif ( isset( $rules[$curChar] ) ) {
248 $rule = $rules[$curChar];
250 # Some versions of PHP have a strcspn which stops on null characters
251 # Ignore and continue
258 if ( $found == 'angle' ) {
260 // Handle </onlyinclude>
261 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
262 $findOnlyinclude = true;
266 // Determine element name
267 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
268 // Element name missing or not listed
274 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
275 // To avoid leaving blank lines, when a comment is both preceded
276 // and followed by a newline (ignoring spaces), trim leading and
277 // trailing spaces and one of the newlines.
280 $endPos = strpos( $text, '-->', $i +
4 );
281 if ( $endPos === false ) {
282 // Unclosed comment in input, runs to end
283 $inner = substr( $text, $i );
284 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
285 $i = strlen( $text );
287 // Search backwards for leading whitespace
288 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
289 // Search forwards for trailing whitespace
290 // $wsEnd will be the position of the last space
291 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
292 // Eat the line if possible
293 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
294 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
295 // it's a possible beneficial b/c break.
296 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
297 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
299 $startPos = $wsStart;
300 $endPos = $wsEnd +
1;
301 // Remove leading whitespace from the end of the accumulator
302 // Sanity check first though
303 $wsLength = $i - $wsStart;
304 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
305 $accum = substr( $accum, 0, -$wsLength );
307 // Do a line-start run next time to look for headings after the comment
308 $fakeLineStart = true;
310 // No line to eat, just take the comment itself
316 $part = $stack->top
->getCurrentPart();
317 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
318 // Comments abutting, no change in visual end
319 $part->commentEnd
= $wsEnd;
321 $part->visualEnd
= $wsStart;
322 $part->commentEnd
= $endPos;
326 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
327 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
332 $lowerName = strtolower( $name );
333 $attrStart = $i +
strlen( $name ) +
1;
336 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
337 if ( $tagEndPos === false ) {
338 // Infinite backtrack
339 // Disable tag search to prevent worst-case O(N^2) performance
346 // Handle ignored tags
347 if ( in_array( $lowerName, $ignoredTags ) ) {
348 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
354 if ( $text[$tagEndPos-1] == '/' ) {
355 $attrEnd = $tagEndPos - 1;
360 $attrEnd = $tagEndPos;
362 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
363 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
365 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
366 $i = $matches[0][1] +
strlen( $matches[0][0] );
367 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
369 // No end tag -- let it run out to the end of the text.
370 $inner = substr( $text, $tagEndPos +
1 );
371 $i = strlen( $text );
375 // <includeonly> and <noinclude> just become <ignore> tags
376 if ( in_array( $lowerName, $ignoredElements ) ) {
377 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
383 if ( $attrEnd <= $attrStart ) {
386 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
388 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
389 // Note that the attr element contains the whitespace between name and attribute,
390 // this is necessary for precise reconstruction during pre-save transform.
391 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
392 if ( $inner !== null ) {
393 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
395 $accum .= $close . '</ext>';
398 elseif ( $found == 'line-start' ) {
399 // Is this the start of a heading?
400 // Line break belongs before the heading element in any case
401 if ( $fakeLineStart ) {
402 $fakeLineStart = false;
408 $count = strspn( $text, '=', $i, 6 );
409 if ( $count == 1 && $findEquals ) {
410 // DWIM: This looks kind of like a name/value separator
411 // Let's let the equals handler have it and break the potential heading
412 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
413 } elseif ( $count > 0 ) {
417 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
420 $stack->push( $piece );
421 $accum =& $stack->getAccum();
422 extract( $stack->getFlags() );
427 elseif ( $found == 'line-end' ) {
428 $piece = $stack->top
;
429 // A heading must be open, otherwise \n wouldn't have been in the search list
430 assert( $piece->open
== "\n" );
431 $part = $piece->getCurrentPart();
432 // Search back through the input to see if it has a proper close
433 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
434 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
435 $searchStart = $i - $wsLength;
436 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
437 // Comment found at line end
438 // Search for equals signs before the comment
439 $searchStart = $part->visualEnd
;
440 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
442 $count = $piece->count
;
443 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
444 if ( $equalsLength > 0 ) {
445 if ( $i - $equalsLength == $piece->startPos
) {
446 // This is just a single string of equals signs on its own line
447 // Replicate the doHeadings behaviour /={count}(.+)={count}/
448 // First find out how many equals signs there really are (don't stop at 6)
449 $count = $equalsLength;
453 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
456 $count = min( $equalsLength, $count );
459 // Normal match, output <h>
460 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
463 // Single equals sign on its own line, count=0
467 // No match, no <h>, just pass down the inner text
472 $accum =& $stack->getAccum();
473 extract( $stack->getFlags() );
475 // Append the result to the enclosing accumulator
477 // Note that we do NOT increment the input pointer.
478 // This is because the closing linebreak could be the opening linebreak of
479 // another heading. Infinite loops are avoided because the next iteration MUST
480 // hit the heading open case above, which unconditionally increments the
484 elseif ( $found == 'open' ) {
485 # count opening brace characters
486 $count = strspn( $text, $curChar, $i );
488 # we need to add to stack only if opening brace count is enough for one of the rules
489 if ( $count >= $rule['min'] ) {
490 # Add it to the stack
493 'close' => $rule['end'],
495 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
498 $stack->push( $piece );
499 $accum =& $stack->getAccum();
500 extract( $stack->getFlags() );
502 # Add literal brace(s)
503 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
508 elseif ( $found == 'close' ) {
509 $piece = $stack->top
;
510 # lets check if there are enough characters for closing brace
511 $maxCount = $piece->count
;
512 $count = strspn( $text, $curChar, $i, $maxCount );
514 # check for maximum matching characters (if there are 5 closing
515 # characters, we will probably need only 3 - depending on the rules)
517 $rule = $rules[$piece->open
];
518 if ( $count > $rule['max'] ) {
519 # The specified maximum exists in the callback array, unless the caller
521 $matchingCount = $rule['max'];
523 # Count is less than the maximum
524 # Skip any gaps in the callback array to find the true largest match
525 # Need to use array_key_exists not isset because the callback can be null
526 $matchingCount = $count;
527 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
532 if ($matchingCount <= 0) {
533 # No matching element found in callback array
534 # Output a literal closing brace and continue
535 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
539 $name = $rule['names'][$matchingCount];
540 if ( $name === null ) {
541 // No element, just literal text
542 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
545 # Note: $parts is already XML, does not need to be encoded further
546 $parts = $piece->parts
;
547 $title = $parts[0]->out
;
550 # The invocation is at the start of the line if lineStart is set in
551 # the stack, and all opening brackets are used up.
552 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
553 $attr = ' lineStart="1"';
558 $element = "<$name$attr>";
559 $element .= "<title>$title</title>";
561 foreach ( $parts as $partIndex => $part ) {
562 if ( isset( $part->eqpos
) ) {
563 $argName = substr( $part->out
, 0, $part->eqpos
);
564 $argValue = substr( $part->out
, $part->eqpos +
1 );
565 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
567 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
571 $element .= "</$name>";
574 # Advance input pointer
575 $i +
= $matchingCount;
579 $accum =& $stack->getAccum();
581 # Re-add the old stack element if it still has unmatched opening characters remaining
582 if ($matchingCount < $piece->count
) {
583 $piece->parts
= array( new PPDPart
);
584 $piece->count
-= $matchingCount;
585 # do we still qualify for any callback with remaining count?
586 $names = $rules[$piece->open
]['names'];
588 $enclosingAccum =& $accum;
589 while ( $piece->count
) {
590 if ( array_key_exists( $piece->count
, $names ) ) {
591 $stack->push( $piece );
592 $accum =& $stack->getAccum();
598 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
601 extract( $stack->getFlags() );
603 # Add XML element to the enclosing accumulator
607 elseif ( $found == 'pipe' ) {
608 $findEquals = true; // shortcut for getFlags()
610 $accum =& $stack->getAccum();
614 elseif ( $found == 'equals' ) {
615 $findEquals = false; // shortcut for getFlags()
616 $stack->getCurrentPart()->eqpos
= strlen( $accum );
622 # Output any remaining unclosed brackets
623 foreach ( $stack->stack
as $piece ) {
624 $stack->rootAccum
.= $piece->breakSyntax();
626 $stack->rootAccum
.= '</root>';
627 $xml = $stack->rootAccum
;
629 wfProfileOut( __METHOD__
);
636 * Stack class to help Preprocessor::preprocessToObj()
640 var $stack, $rootAccum, $top;
642 var $elementClass = 'PPDStackElement';
644 static $false = false;
646 function __construct() {
647 $this->stack
= array();
649 $this->rootAccum
= '';
650 $this->accum
=& $this->rootAccum
;
654 return count( $this->stack
);
657 function &getAccum() {
661 function getCurrentPart() {
662 if ( $this->top
=== false ) {
665 return $this->top
->getCurrentPart();
669 function push( $data ) {
670 if ( $data instanceof $this->elementClass
) {
671 $this->stack
[] = $data;
673 $class = $this->elementClass
;
674 $this->stack
[] = new $class( $data );
676 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
677 $this->accum
=& $this->top
->getAccum();
681 if ( !count( $this->stack
) ) {
682 throw new MWException( __METHOD__
.': no elements remaining' );
684 $temp = array_pop( $this->stack
);
686 if ( count( $this->stack
) ) {
687 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
688 $this->accum
=& $this->top
->getAccum();
690 $this->top
= self
::$false;
691 $this->accum
=& $this->rootAccum
;
696 function addPart( $s = '' ) {
697 $this->top
->addPart( $s );
698 $this->accum
=& $this->top
->getAccum();
701 function getFlags() {
702 if ( !count( $this->stack
) ) {
704 'findEquals' => false,
706 'inHeading' => false,
709 return $this->top
->getFlags();
717 class PPDStackElement
{
718 var $open, // Opening character (\n for heading)
719 $close, // Matching closing character
720 $count, // Number of opening characters found (number of "=" for heading)
721 $parts, // Array of PPDPart objects describing pipe-separated parts.
722 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
724 var $partClass = 'PPDPart';
726 function __construct( $data = array() ) {
727 $class = $this->partClass
;
728 $this->parts
= array( new $class );
730 foreach ( $data as $name => $value ) {
731 $this->$name = $value;
735 function &getAccum() {
736 return $this->parts
[count($this->parts
) - 1]->out
;
739 function addPart( $s = '' ) {
740 $class = $this->partClass
;
741 $this->parts
[] = new $class( $s );
744 function getCurrentPart() {
745 return $this->parts
[count($this->parts
) - 1];
748 function getFlags() {
749 $partCount = count( $this->parts
);
750 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
752 'findPipe' => $findPipe,
753 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
754 'inHeading' => $this->open
== "\n",
759 * Get the output string that would result if the close is not found.
761 function breakSyntax( $openingCount = false ) {
762 if ( $this->open
== "\n" ) {
763 $s = $this->parts
[0]->out
;
765 if ( $openingCount === false ) {
766 $openingCount = $this->count
;
768 $s = str_repeat( $this->open
, $openingCount );
770 foreach ( $this->parts
as $part ) {
787 var $out; // Output accumulator string
789 // Optional member variables:
790 // eqpos Position of equals sign in output accumulator
791 // commentEnd Past-the-end input pointer for the last comment encountered
792 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
794 function __construct( $out = '' ) {
800 * An expansion frame, used as a context to expand the result of preprocessToObj()
803 class PPFrame_DOM
implements PPFrame
{
804 var $preprocessor, $parser, $title;
808 * Hashtable listing templates which are disallowed for expansion in this frame,
809 * having been encountered previously in parent frames.
814 * Recursion depth of this frame, top = 0
815 * Note that this is NOT the same as expansion depth in expand()
821 * Construct a new preprocessor frame.
822 * @param Preprocessor $preprocessor The parent preprocessor
824 function __construct( $preprocessor ) {
825 $this->preprocessor
= $preprocessor;
826 $this->parser
= $preprocessor->parser
;
827 $this->title
= $this->parser
->mTitle
;
828 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
829 $this->loopCheckHash
= array();
834 * Create a new child frame
835 * $args is optionally a multi-root PPNode or array containing the template arguments
837 function newChild( $args = false, $title = false ) {
838 $namedArgs = array();
839 $numberedArgs = array();
840 if ( $title === false ) {
841 $title = $this->title
;
843 if ( $args !== false ) {
845 if ( $args instanceof PPNode
) {
848 foreach ( $args as $arg ) {
850 $xpath = new DOMXPath( $arg->ownerDocument
);
853 $nameNodes = $xpath->query( 'name', $arg );
854 $value = $xpath->query( 'value', $arg );
855 if ( $nameNodes->item( 0 )->hasAttributes() ) {
856 // Numbered parameter
857 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
858 $numberedArgs[$index] = $value->item( 0 );
859 unset( $namedArgs[$index] );
862 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
863 $namedArgs[$name] = $value->item( 0 );
864 unset( $numberedArgs[$name] );
868 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
871 function expand( $root, $flags = 0 ) {
872 static $expansionDepth = 0;
873 if ( is_string( $root ) ) {
877 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
879 return '<span class="error">Node-count limit exceeded</span>';
882 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
883 return '<span class="error">Expansion depth limit exceeded</span>';
885 wfProfileIn( __METHOD__
);
888 if ( $root instanceof PPNode_DOM
) {
891 if ( $root instanceof DOMDocument
) {
892 $root = $root->documentElement
;
895 $outStack = array( '', '' );
896 $iteratorStack = array( false, $root );
897 $indexStack = array( 0, 0 );
899 while ( count( $iteratorStack ) > 1 ) {
900 $level = count( $outStack ) - 1;
901 $iteratorNode =& $iteratorStack[ $level ];
902 $out =& $outStack[$level];
903 $index =& $indexStack[$level];
905 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
907 if ( is_array( $iteratorNode ) ) {
908 if ( $index >= count( $iteratorNode ) ) {
909 // All done with this iterator
910 $iteratorStack[$level] = false;
911 $contextNode = false;
913 $contextNode = $iteratorNode[$index];
916 } elseif ( $iteratorNode instanceof DOMNodeList
) {
917 if ( $index >= $iteratorNode->length
) {
918 // All done with this iterator
919 $iteratorStack[$level] = false;
920 $contextNode = false;
922 $contextNode = $iteratorNode->item( $index );
926 // Copy to $contextNode and then delete from iterator stack,
927 // because this is not an iterator but we do have to execute it once
928 $contextNode = $iteratorStack[$level];
929 $iteratorStack[$level] = false;
932 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
934 $newIterator = false;
936 if ( $contextNode === false ) {
938 } elseif ( is_string( $contextNode ) ) {
939 $out .= $contextNode;
940 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
941 $newIterator = $contextNode;
942 } elseif ( $contextNode instanceof DOMNode
) {
943 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
944 $out .= $contextNode->nodeValue
;
945 } elseif ( $contextNode->nodeName
== 'template' ) {
946 # Double-brace expansion
947 $xpath = new DOMXPath( $contextNode->ownerDocument
);
948 $titles = $xpath->query( 'title', $contextNode );
949 $title = $titles->item( 0 );
950 $parts = $xpath->query( 'part', $contextNode );
951 if ( $flags & self
::NO_TEMPLATES
) {
952 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
954 $lineStart = $contextNode->getAttribute( 'lineStart' );
956 'title' => new PPNode_DOM( $title ),
957 'parts' => new PPNode_DOM( $parts ),
958 'lineStart' => $lineStart );
959 $ret = $this->parser
->braceSubstitution( $params, $this );
960 if ( isset( $ret['object'] ) ) {
961 $newIterator = $ret['object'];
963 $out .= $ret['text'];
966 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
967 # Triple-brace expansion
968 $xpath = new DOMXPath( $contextNode->ownerDocument
);
969 $titles = $xpath->query( 'title', $contextNode );
970 $title = $titles->item( 0 );
971 $parts = $xpath->query( 'part', $contextNode );
972 if ( $flags & self
::NO_ARGS
) {
973 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
976 'title' => new PPNode_DOM( $title ),
977 'parts' => new PPNode_DOM( $parts ) );
978 $ret = $this->parser
->argSubstitution( $params, $this );
979 if ( isset( $ret['object'] ) ) {
980 $newIterator = $ret['object'];
982 $out .= $ret['text'];
985 } elseif ( $contextNode->nodeName
== 'comment' ) {
987 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
988 if ( $this->parser
->ot
['html']
989 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
990 ||
( $flags & self
::STRIP_COMMENTS
) )
994 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
995 # Not in RECOVER_COMMENTS mode (extractSections) though
996 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
997 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
999 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1001 $out .= $contextNode->textContent
;
1003 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1004 # Output suppression used by <includeonly> etc.
1005 # OT_WIKI will only respect <ignore> in substed templates.
1006 # The other output types respect it unless NO_IGNORE is set.
1007 # extractSections() sets NO_IGNORE and so never respects it.
1008 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
1009 $out .= $contextNode->textContent
;
1013 } elseif ( $contextNode->nodeName
== 'ext' ) {
1015 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1016 $names = $xpath->query( 'name', $contextNode );
1017 $attrs = $xpath->query( 'attr', $contextNode );
1018 $inners = $xpath->query( 'inner', $contextNode );
1019 $closes = $xpath->query( 'close', $contextNode );
1021 'name' => new PPNode_DOM( $names->item( 0 ) ),
1022 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1023 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1024 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1026 $out .= $this->parser
->extensionSubstitution( $params, $this );
1027 } elseif ( $contextNode->nodeName
== 'h' ) {
1029 $s = $this->expand( $contextNode->childNodes
, $flags );
1031 # Insert a heading marker only for <h> children of <root>
1032 # This is to stop extractSections from going over multiple tree levels
1033 if ( $contextNode->parentNode
->nodeName
== 'root'
1034 && $this->parser
->ot
['html'] )
1036 # Insert heading index marker
1037 $headingIndex = $contextNode->getAttribute( 'i' );
1038 $titleText = $this->title
->getPrefixedDBkey();
1039 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1040 $serial = count( $this->parser
->mHeadings
) - 1;
1041 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1042 $count = $contextNode->getAttribute( 'level' );
1043 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1044 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1048 # Generic recursive expansion
1049 $newIterator = $contextNode->childNodes
;
1052 wfProfileOut( __METHOD__
);
1053 throw new MWException( __METHOD__
.': Invalid parameter type' );
1056 if ( $newIterator !== false ) {
1057 if ( $newIterator instanceof PPNode_DOM
) {
1058 $newIterator = $newIterator->node
;
1061 $iteratorStack[] = $newIterator;
1063 } elseif ( $iteratorStack[$level] === false ) {
1064 // Return accumulated value to parent
1065 // With tail recursion
1066 while ( $iteratorStack[$level] === false && $level > 0 ) {
1067 $outStack[$level - 1] .= $out;
1068 array_pop( $outStack );
1069 array_pop( $iteratorStack );
1070 array_pop( $indexStack );
1076 wfProfileOut( __METHOD__
);
1077 return $outStack[0];
1080 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1081 $args = array_slice( func_get_args(), 2 );
1085 foreach ( $args as $root ) {
1086 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1087 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1088 $root = array( $root );
1090 foreach ( $root as $node ) {
1096 $s .= $this->expand( $node, $flags );
1103 * Implode with no flags specified
1104 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1106 function implode( $sep /*, ... */ ) {
1107 $args = array_slice( func_get_args(), 1 );
1111 foreach ( $args as $root ) {
1112 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1113 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1114 $root = array( $root );
1116 foreach ( $root as $node ) {
1122 $s .= $this->expand( $node );
1129 * Makes an object that, when expand()ed, will be the same as one obtained
1132 function virtualImplode( $sep /*, ... */ ) {
1133 $args = array_slice( func_get_args(), 1 );
1136 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1138 foreach ( $args as $root ) {
1139 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1140 $root = array( $root );
1142 foreach ( $root as $node ) {
1155 * Virtual implode with brackets
1157 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1158 $args = array_slice( func_get_args(), 3 );
1159 $out = array( $start );
1162 foreach ( $args as $root ) {
1163 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1164 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1165 $root = array( $root );
1167 foreach ( $root as $node ) {
1180 function __toString() {
1184 function getPDBK( $level = false ) {
1185 if ( $level === false ) {
1186 return $this->title
->getPrefixedDBkey();
1188 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1193 * Returns true if there are no arguments in this frame
1195 function isEmpty() {
1199 function getArgument( $name ) {
1204 * Returns true if the infinite loop check is OK, false if a loop is detected
1206 function loopCheck( $title ) {
1207 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1211 * Return true if the frame is a template frame
1213 function isTemplate() {
1219 * Expansion frame with template arguments
1222 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1223 var $numberedArgs, $namedArgs, $parent;
1224 var $numberedExpansionCache, $namedExpansionCache;
1226 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1227 $this->preprocessor
= $preprocessor;
1228 $this->parser
= $preprocessor->parser
;
1229 $this->parent
= $parent;
1230 $this->numberedArgs
= $numberedArgs;
1231 $this->namedArgs
= $namedArgs;
1232 $this->title
= $title;
1233 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1234 $this->titleCache
= $parent->titleCache
;
1235 $this->titleCache
[] = $pdbk;
1236 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1237 if ( $pdbk !== false ) {
1238 $this->loopCheckHash
[$pdbk] = true;
1240 $this->depth
= $parent->depth +
1;
1241 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1244 function __toString() {
1247 $args = $this->numberedArgs +
$this->namedArgs
;
1248 foreach ( $args as $name => $value ) {
1254 $s .= "\"$name\":\"" .
1255 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1261 * Returns true if there are no arguments in this frame
1263 function isEmpty() {
1264 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1267 function getArguments() {
1268 $arguments = array();
1269 foreach ( array_merge(
1270 array_keys($this->numberedArgs
),
1271 array_keys($this->namedArgs
)) as $key ) {
1272 $arguments[$key] = $this->getArgument($key);
1277 function getNumberedArguments() {
1278 $arguments = array();
1279 foreach ( array_keys($this->numberedArgs
) as $key ) {
1280 $arguments[$key] = $this->getArgument($key);
1285 function getNamedArguments() {
1286 $arguments = array();
1287 foreach ( array_keys($this->namedArgs
) as $key ) {
1288 $arguments[$key] = $this->getArgument($key);
1293 function getNumberedArgument( $index ) {
1294 if ( !isset( $this->numberedArgs
[$index] ) ) {
1297 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1298 # No trimming for unnamed arguments
1299 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1301 return $this->numberedExpansionCache
[$index];
1304 function getNamedArgument( $name ) {
1305 if ( !isset( $this->namedArgs
[$name] ) ) {
1308 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1309 # Trim named arguments post-expand, for backwards compatibility
1310 $this->namedExpansionCache
[$name] = trim(
1311 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1313 return $this->namedExpansionCache
[$name];
1316 function getArgument( $name ) {
1317 $text = $this->getNumberedArgument( $name );
1318 if ( $text === false ) {
1319 $text = $this->getNamedArgument( $name );
1325 * Return true if the frame is a template frame
1327 function isTemplate() {
1333 * Expansion frame with custom arguments
1336 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1339 function __construct( $preprocessor, $args ) {
1340 $this->preprocessor
= $preprocessor;
1341 $this->parser
= $preprocessor->parser
;
1342 $this->args
= $args;
1345 function __toString() {
1348 foreach ( $this->args
as $name => $value ) {
1354 $s .= "\"$name\":\"" .
1355 str_replace( '"', '\\"', $value->__toString() ) . '"';
1361 function isEmpty() {
1362 return !count( $this->args
);
1365 function getArgument( $index ) {
1366 if ( !isset( $this->args
[$index] ) ) {
1369 return $this->args
[$index];
1376 class PPNode_DOM
implements PPNode
{
1379 function __construct( $node, $xpath = false ) {
1380 $this->node
= $node;
1383 function __get( $name ) {
1384 if ( $name == 'xpath' ) {
1385 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1387 return $this->xpath
;
1390 function __toString() {
1391 if ( $this->node
instanceof DOMNodeList
) {
1393 foreach ( $this->node
as $node ) {
1394 $s .= $node->ownerDocument
->saveXML( $node );
1397 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1402 function getChildren() {
1403 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1406 function getFirstChild() {
1407 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1410 function getNextSibling() {
1411 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1414 function getChildrenOfType( $type ) {
1415 return new self( $this->xpath
->query( $type, $this->node
) );
1418 function getLength() {
1419 if ( $this->node
instanceof DOMNodeList
) {
1420 return $this->node
->length
;
1426 function item( $i ) {
1427 $item = $this->node
->item( $i );
1428 return $item ?
new self( $item ) : false;
1431 function getName() {
1432 if ( $this->node
instanceof DOMNodeList
) {
1435 return $this->node
->nodeName
;
1440 * Split a <part> node into an associative array containing:
1442 * index String index
1443 * value PPNode value
1445 function splitArg() {
1446 $names = $this->xpath
->query( 'name', $this->node
);
1447 $values = $this->xpath
->query( 'value', $this->node
);
1448 if ( !$names->length ||
!$values->length
) {
1449 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1451 $name = $names->item( 0 );
1452 $index = $name->getAttribute( 'index' );
1454 'name' => new self( $name ),
1456 'value' => new self( $values->item( 0 ) ) );
1460 * Split an <ext> node into an associative array containing name, attr, inner and close
1461 * All values in the resulting array are PPNodes. Inner and close are optional.
1463 function splitExt() {
1464 $names = $this->xpath
->query( 'name', $this->node
);
1465 $attrs = $this->xpath
->query( 'attr', $this->node
);
1466 $inners = $this->xpath
->query( 'inner', $this->node
);
1467 $closes = $this->xpath
->query( 'close', $this->node
);
1468 if ( !$names->length ||
!$attrs->length
) {
1469 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1472 'name' => new self( $names->item( 0 ) ),
1473 'attr' => new self( $attrs->item( 0 ) ) );
1474 if ( $inners->length
) {
1475 $parts['inner'] = new self( $inners->item( 0 ) );
1477 if ( $closes->length
) {
1478 $parts['close'] = new self( $closes->item( 0 ) );
1486 function splitHeading() {
1487 if ( !$this->nodeName
== 'h' ) {
1488 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1491 'i' => $this->node
->getAttribute( 'i' ),
1492 'level' => $this->node
->getAttribute( 'level' ),
1493 'contents' => $this->getChildren()