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 $flags = $stack->getFlags();
428 elseif ( $found == 'line-end' ) {
429 $piece = $stack->top
;
430 // A heading must be open, otherwise \n wouldn't have been in the search list
431 assert( $piece->open
== "\n" );
432 $part = $piece->getCurrentPart();
433 // Search back through the input to see if it has a proper close
434 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
435 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
436 $searchStart = $i - $wsLength;
437 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
438 // Comment found at line end
439 // Search for equals signs before the comment
440 $searchStart = $part->visualEnd
;
441 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
443 $count = $piece->count
;
444 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
445 if ( $equalsLength > 0 ) {
446 if ( $i - $equalsLength == $piece->startPos
) {
447 // This is just a single string of equals signs on its own line
448 // Replicate the doHeadings behaviour /={count}(.+)={count}/
449 // First find out how many equals signs there really are (don't stop at 6)
450 $count = $equalsLength;
454 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
457 $count = min( $equalsLength, $count );
460 // Normal match, output <h>
461 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
464 // Single equals sign on its own line, count=0
468 // No match, no <h>, just pass down the inner text
473 $accum =& $stack->getAccum();
474 $flags = $stack->getFlags();
477 // Append the result to the enclosing accumulator
479 // Note that we do NOT increment the input pointer.
480 // This is because the closing linebreak could be the opening linebreak of
481 // another heading. Infinite loops are avoided because the next iteration MUST
482 // hit the heading open case above, which unconditionally increments the
486 elseif ( $found == 'open' ) {
487 # count opening brace characters
488 $count = strspn( $text, $curChar, $i );
490 # we need to add to stack only if opening brace count is enough for one of the rules
491 if ( $count >= $rule['min'] ) {
492 # Add it to the stack
495 'close' => $rule['end'],
497 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
500 $stack->push( $piece );
501 $accum =& $stack->getAccum();
502 $flags = $stack->getFlags();
505 # Add literal brace(s)
506 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
511 elseif ( $found == 'close' ) {
512 $piece = $stack->top
;
513 # lets check if there are enough characters for closing brace
514 $maxCount = $piece->count
;
515 $count = strspn( $text, $curChar, $i, $maxCount );
517 # check for maximum matching characters (if there are 5 closing
518 # characters, we will probably need only 3 - depending on the rules)
520 $rule = $rules[$piece->open
];
521 if ( $count > $rule['max'] ) {
522 # The specified maximum exists in the callback array, unless the caller
524 $matchingCount = $rule['max'];
526 # Count is less than the maximum
527 # Skip any gaps in the callback array to find the true largest match
528 # Need to use array_key_exists not isset because the callback can be null
529 $matchingCount = $count;
530 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
535 if ($matchingCount <= 0) {
536 # No matching element found in callback array
537 # Output a literal closing brace and continue
538 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
542 $name = $rule['names'][$matchingCount];
543 if ( $name === null ) {
544 // No element, just literal text
545 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
548 # Note: $parts is already XML, does not need to be encoded further
549 $parts = $piece->parts
;
550 $title = $parts[0]->out
;
553 # The invocation is at the start of the line if lineStart is set in
554 # the stack, and all opening brackets are used up.
555 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
556 $attr = ' lineStart="1"';
561 $element = "<$name$attr>";
562 $element .= "<title>$title</title>";
564 foreach ( $parts as $partIndex => $part ) {
565 if ( isset( $part->eqpos
) ) {
566 $argName = substr( $part->out
, 0, $part->eqpos
);
567 $argValue = substr( $part->out
, $part->eqpos +
1 );
568 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
570 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
574 $element .= "</$name>";
577 # Advance input pointer
578 $i +
= $matchingCount;
582 $accum =& $stack->getAccum();
584 # Re-add the old stack element if it still has unmatched opening characters remaining
585 if ($matchingCount < $piece->count
) {
586 $piece->parts
= array( new PPDPart
);
587 $piece->count
-= $matchingCount;
588 # do we still qualify for any callback with remaining count?
589 $names = $rules[$piece->open
]['names'];
591 $enclosingAccum =& $accum;
592 while ( $piece->count
) {
593 if ( array_key_exists( $piece->count
, $names ) ) {
594 $stack->push( $piece );
595 $accum =& $stack->getAccum();
601 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
603 $flags = $stack->getFlags();
606 # Add XML element to the enclosing accumulator
610 elseif ( $found == 'pipe' ) {
611 $findEquals = true; // shortcut for getFlags()
613 $accum =& $stack->getAccum();
617 elseif ( $found == 'equals' ) {
618 $findEquals = false; // shortcut for getFlags()
619 $stack->getCurrentPart()->eqpos
= strlen( $accum );
625 # Output any remaining unclosed brackets
626 foreach ( $stack->stack
as $piece ) {
627 $stack->rootAccum
.= $piece->breakSyntax();
629 $stack->rootAccum
.= '</root>';
630 $xml = $stack->rootAccum
;
632 wfProfileOut( __METHOD__
);
639 * Stack class to help Preprocessor::preprocessToObj()
643 var $stack, $rootAccum, $top;
645 var $elementClass = 'PPDStackElement';
647 static $false = false;
649 function __construct() {
650 $this->stack
= array();
652 $this->rootAccum
= '';
653 $this->accum
=& $this->rootAccum
;
657 return count( $this->stack
);
660 function &getAccum() {
664 function getCurrentPart() {
665 if ( $this->top
=== false ) {
668 return $this->top
->getCurrentPart();
672 function push( $data ) {
673 if ( $data instanceof $this->elementClass
) {
674 $this->stack
[] = $data;
676 $class = $this->elementClass
;
677 $this->stack
[] = new $class( $data );
679 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
680 $this->accum
=& $this->top
->getAccum();
684 if ( !count( $this->stack
) ) {
685 throw new MWException( __METHOD__
.': no elements remaining' );
687 $temp = array_pop( $this->stack
);
689 if ( count( $this->stack
) ) {
690 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
691 $this->accum
=& $this->top
->getAccum();
693 $this->top
= self
::$false;
694 $this->accum
=& $this->rootAccum
;
699 function addPart( $s = '' ) {
700 $this->top
->addPart( $s );
701 $this->accum
=& $this->top
->getAccum();
704 function getFlags() {
705 if ( !count( $this->stack
) ) {
707 'findEquals' => false,
709 'inHeading' => false,
712 return $this->top
->getFlags();
720 class PPDStackElement
{
721 var $open, // Opening character (\n for heading)
722 $close, // Matching closing character
723 $count, // Number of opening characters found (number of "=" for heading)
724 $parts, // Array of PPDPart objects describing pipe-separated parts.
725 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
727 var $partClass = 'PPDPart';
729 function __construct( $data = array() ) {
730 $class = $this->partClass
;
731 $this->parts
= array( new $class );
733 foreach ( $data as $name => $value ) {
734 $this->$name = $value;
738 function &getAccum() {
739 return $this->parts
[count($this->parts
) - 1]->out
;
742 function addPart( $s = '' ) {
743 $class = $this->partClass
;
744 $this->parts
[] = new $class( $s );
747 function getCurrentPart() {
748 return $this->parts
[count($this->parts
) - 1];
751 function getFlags() {
752 $partCount = count( $this->parts
);
753 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
755 'findPipe' => $findPipe,
756 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
757 'inHeading' => $this->open
== "\n",
762 * Get the output string that would result if the close is not found.
764 function breakSyntax( $openingCount = false ) {
765 if ( $this->open
== "\n" ) {
766 $s = $this->parts
[0]->out
;
768 if ( $openingCount === false ) {
769 $openingCount = $this->count
;
771 $s = str_repeat( $this->open
, $openingCount );
773 foreach ( $this->parts
as $part ) {
790 var $out; // Output accumulator string
792 // Optional member variables:
793 // eqpos Position of equals sign in output accumulator
794 // commentEnd Past-the-end input pointer for the last comment encountered
795 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
797 function __construct( $out = '' ) {
803 * An expansion frame, used as a context to expand the result of preprocessToObj()
806 class PPFrame_DOM
implements PPFrame
{
807 var $preprocessor, $parser, $title;
811 * Hashtable listing templates which are disallowed for expansion in this frame,
812 * having been encountered previously in parent frames.
817 * Recursion depth of this frame, top = 0
818 * Note that this is NOT the same as expansion depth in expand()
824 * Construct a new preprocessor frame.
825 * @param Preprocessor $preprocessor The parent preprocessor
827 function __construct( $preprocessor ) {
828 $this->preprocessor
= $preprocessor;
829 $this->parser
= $preprocessor->parser
;
830 $this->title
= $this->parser
->mTitle
;
831 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
832 $this->loopCheckHash
= array();
837 * Create a new child frame
838 * $args is optionally a multi-root PPNode or array containing the template arguments
840 function newChild( $args = false, $title = false ) {
841 $namedArgs = array();
842 $numberedArgs = array();
843 if ( $title === false ) {
844 $title = $this->title
;
846 if ( $args !== false ) {
848 if ( $args instanceof PPNode
) {
851 foreach ( $args as $arg ) {
853 $xpath = new DOMXPath( $arg->ownerDocument
);
856 $nameNodes = $xpath->query( 'name', $arg );
857 $value = $xpath->query( 'value', $arg );
858 if ( $nameNodes->item( 0 )->hasAttributes() ) {
859 // Numbered parameter
860 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
861 $numberedArgs[$index] = $value->item( 0 );
862 unset( $namedArgs[$index] );
865 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
866 $namedArgs[$name] = $value->item( 0 );
867 unset( $numberedArgs[$name] );
871 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
874 function expand( $root, $flags = 0 ) {
875 static $expansionDepth = 0;
876 if ( is_string( $root ) ) {
880 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
882 return '<span class="error">Node-count limit exceeded</span>';
885 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
886 return '<span class="error">Expansion depth limit exceeded</span>';
888 wfProfileIn( __METHOD__
);
891 if ( $root instanceof PPNode_DOM
) {
894 if ( $root instanceof DOMDocument
) {
895 $root = $root->documentElement
;
898 $outStack = array( '', '' );
899 $iteratorStack = array( false, $root );
900 $indexStack = array( 0, 0 );
902 while ( count( $iteratorStack ) > 1 ) {
903 $level = count( $outStack ) - 1;
904 $iteratorNode =& $iteratorStack[ $level ];
905 $out =& $outStack[$level];
906 $index =& $indexStack[$level];
908 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
910 if ( is_array( $iteratorNode ) ) {
911 if ( $index >= count( $iteratorNode ) ) {
912 // All done with this iterator
913 $iteratorStack[$level] = false;
914 $contextNode = false;
916 $contextNode = $iteratorNode[$index];
919 } elseif ( $iteratorNode instanceof DOMNodeList
) {
920 if ( $index >= $iteratorNode->length
) {
921 // All done with this iterator
922 $iteratorStack[$level] = false;
923 $contextNode = false;
925 $contextNode = $iteratorNode->item( $index );
929 // Copy to $contextNode and then delete from iterator stack,
930 // because this is not an iterator but we do have to execute it once
931 $contextNode = $iteratorStack[$level];
932 $iteratorStack[$level] = false;
935 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
937 $newIterator = false;
939 if ( $contextNode === false ) {
941 } elseif ( is_string( $contextNode ) ) {
942 $out .= $contextNode;
943 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
944 $newIterator = $contextNode;
945 } elseif ( $contextNode instanceof DOMNode
) {
946 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
947 $out .= $contextNode->nodeValue
;
948 } elseif ( $contextNode->nodeName
== 'template' ) {
949 # Double-brace expansion
950 $xpath = new DOMXPath( $contextNode->ownerDocument
);
951 $titles = $xpath->query( 'title', $contextNode );
952 $title = $titles->item( 0 );
953 $parts = $xpath->query( 'part', $contextNode );
954 if ( $flags & self
::NO_TEMPLATES
) {
955 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
957 $lineStart = $contextNode->getAttribute( 'lineStart' );
959 'title' => new PPNode_DOM( $title ),
960 'parts' => new PPNode_DOM( $parts ),
961 'lineStart' => $lineStart );
962 $ret = $this->parser
->braceSubstitution( $params, $this );
963 if ( isset( $ret['object'] ) ) {
964 $newIterator = $ret['object'];
966 $out .= $ret['text'];
969 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
970 # Triple-brace expansion
971 $xpath = new DOMXPath( $contextNode->ownerDocument
);
972 $titles = $xpath->query( 'title', $contextNode );
973 $title = $titles->item( 0 );
974 $parts = $xpath->query( 'part', $contextNode );
975 if ( $flags & self
::NO_ARGS
) {
976 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
979 'title' => new PPNode_DOM( $title ),
980 'parts' => new PPNode_DOM( $parts ) );
981 $ret = $this->parser
->argSubstitution( $params, $this );
982 if ( isset( $ret['object'] ) ) {
983 $newIterator = $ret['object'];
985 $out .= $ret['text'];
988 } elseif ( $contextNode->nodeName
== 'comment' ) {
990 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
991 if ( $this->parser
->ot
['html']
992 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
993 ||
( $flags & self
::STRIP_COMMENTS
) )
997 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
998 # Not in RECOVER_COMMENTS mode (extractSections) though
999 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
1000 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1002 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1004 $out .= $contextNode->textContent
;
1006 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1007 # Output suppression used by <includeonly> etc.
1008 # OT_WIKI will only respect <ignore> in substed templates.
1009 # The other output types respect it unless NO_IGNORE is set.
1010 # extractSections() sets NO_IGNORE and so never respects it.
1011 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
1012 $out .= $contextNode->textContent
;
1016 } elseif ( $contextNode->nodeName
== 'ext' ) {
1018 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1019 $names = $xpath->query( 'name', $contextNode );
1020 $attrs = $xpath->query( 'attr', $contextNode );
1021 $inners = $xpath->query( 'inner', $contextNode );
1022 $closes = $xpath->query( 'close', $contextNode );
1024 'name' => new PPNode_DOM( $names->item( 0 ) ),
1025 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1026 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1027 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1029 $out .= $this->parser
->extensionSubstitution( $params, $this );
1030 } elseif ( $contextNode->nodeName
== 'h' ) {
1032 $s = $this->expand( $contextNode->childNodes
, $flags );
1034 # Insert a heading marker only for <h> children of <root>
1035 # This is to stop extractSections from going over multiple tree levels
1036 if ( $contextNode->parentNode
->nodeName
== 'root'
1037 && $this->parser
->ot
['html'] )
1039 # Insert heading index marker
1040 $headingIndex = $contextNode->getAttribute( 'i' );
1041 $titleText = $this->title
->getPrefixedDBkey();
1042 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1043 $serial = count( $this->parser
->mHeadings
) - 1;
1044 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1045 $count = $contextNode->getAttribute( 'level' );
1046 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1047 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1051 # Generic recursive expansion
1052 $newIterator = $contextNode->childNodes
;
1055 wfProfileOut( __METHOD__
);
1056 throw new MWException( __METHOD__
.': Invalid parameter type' );
1059 if ( $newIterator !== false ) {
1060 if ( $newIterator instanceof PPNode_DOM
) {
1061 $newIterator = $newIterator->node
;
1064 $iteratorStack[] = $newIterator;
1066 } elseif ( $iteratorStack[$level] === false ) {
1067 // Return accumulated value to parent
1068 // With tail recursion
1069 while ( $iteratorStack[$level] === false && $level > 0 ) {
1070 $outStack[$level - 1] .= $out;
1071 array_pop( $outStack );
1072 array_pop( $iteratorStack );
1073 array_pop( $indexStack );
1079 wfProfileOut( __METHOD__
);
1080 return $outStack[0];
1083 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1084 $args = array_slice( func_get_args(), 2 );
1088 foreach ( $args as $root ) {
1089 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1090 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1091 $root = array( $root );
1093 foreach ( $root as $node ) {
1099 $s .= $this->expand( $node, $flags );
1106 * Implode with no flags specified
1107 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1109 function implode( $sep /*, ... */ ) {
1110 $args = array_slice( func_get_args(), 1 );
1114 foreach ( $args as $root ) {
1115 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1116 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1117 $root = array( $root );
1119 foreach ( $root as $node ) {
1125 $s .= $this->expand( $node );
1132 * Makes an object that, when expand()ed, will be the same as one obtained
1135 function virtualImplode( $sep /*, ... */ ) {
1136 $args = array_slice( func_get_args(), 1 );
1139 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1141 foreach ( $args as $root ) {
1142 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1143 $root = array( $root );
1145 foreach ( $root as $node ) {
1158 * Virtual implode with brackets
1160 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1161 $args = array_slice( func_get_args(), 3 );
1162 $out = array( $start );
1165 foreach ( $args as $root ) {
1166 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1167 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1168 $root = array( $root );
1170 foreach ( $root as $node ) {
1183 function __toString() {
1187 function getPDBK( $level = false ) {
1188 if ( $level === false ) {
1189 return $this->title
->getPrefixedDBkey();
1191 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1195 function getArguments() {
1199 function getNumberedArguments() {
1203 function getNamedArguments() {
1208 * Returns true if there are no arguments in this frame
1210 function isEmpty() {
1214 function getArgument( $name ) {
1219 * Returns true if the infinite loop check is OK, false if a loop is detected
1221 function loopCheck( $title ) {
1222 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1226 * Return true if the frame is a template frame
1228 function isTemplate() {
1234 * Expansion frame with template arguments
1237 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1238 var $numberedArgs, $namedArgs, $parent;
1239 var $numberedExpansionCache, $namedExpansionCache;
1241 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1242 PPFrame_DOM
::__construct( $preprocessor );
1243 $this->parent
= $parent;
1244 $this->numberedArgs
= $numberedArgs;
1245 $this->namedArgs
= $namedArgs;
1246 $this->title
= $title;
1247 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1248 $this->titleCache
= $parent->titleCache
;
1249 $this->titleCache
[] = $pdbk;
1250 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1251 if ( $pdbk !== false ) {
1252 $this->loopCheckHash
[$pdbk] = true;
1254 $this->depth
= $parent->depth +
1;
1255 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1258 function __toString() {
1261 $args = $this->numberedArgs +
$this->namedArgs
;
1262 foreach ( $args as $name => $value ) {
1268 $s .= "\"$name\":\"" .
1269 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1275 * Returns true if there are no arguments in this frame
1277 function isEmpty() {
1278 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1281 function getArguments() {
1282 $arguments = array();
1283 foreach ( array_merge(
1284 array_keys($this->numberedArgs
),
1285 array_keys($this->namedArgs
)) as $key ) {
1286 $arguments[$key] = $this->getArgument($key);
1291 function getNumberedArguments() {
1292 $arguments = array();
1293 foreach ( array_keys($this->numberedArgs
) as $key ) {
1294 $arguments[$key] = $this->getArgument($key);
1299 function getNamedArguments() {
1300 $arguments = array();
1301 foreach ( array_keys($this->namedArgs
) as $key ) {
1302 $arguments[$key] = $this->getArgument($key);
1307 function getNumberedArgument( $index ) {
1308 if ( !isset( $this->numberedArgs
[$index] ) ) {
1311 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1312 # No trimming for unnamed arguments
1313 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1315 return $this->numberedExpansionCache
[$index];
1318 function getNamedArgument( $name ) {
1319 if ( !isset( $this->namedArgs
[$name] ) ) {
1322 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1323 # Trim named arguments post-expand, for backwards compatibility
1324 $this->namedExpansionCache
[$name] = trim(
1325 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1327 return $this->namedExpansionCache
[$name];
1330 function getArgument( $name ) {
1331 $text = $this->getNumberedArgument( $name );
1332 if ( $text === false ) {
1333 $text = $this->getNamedArgument( $name );
1339 * Return true if the frame is a template frame
1341 function isTemplate() {
1347 * Expansion frame with custom arguments
1350 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1353 function __construct( $preprocessor, $args ) {
1354 PPFrame_DOM
::__construct( $preprocessor );
1355 $this->args
= $args;
1358 function __toString() {
1361 foreach ( $this->args
as $name => $value ) {
1367 $s .= "\"$name\":\"" .
1368 str_replace( '"', '\\"', $value->__toString() ) . '"';
1374 function isEmpty() {
1375 return !count( $this->args
);
1378 function getArgument( $index ) {
1379 if ( !isset( $this->args
[$index] ) ) {
1382 return $this->args
[$index];
1389 class PPNode_DOM
implements PPNode
{
1392 function __construct( $node, $xpath = false ) {
1393 $this->node
= $node;
1396 function __get( $name ) {
1397 if ( $name == 'xpath' ) {
1398 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1400 return $this->xpath
;
1403 function __toString() {
1404 if ( $this->node
instanceof DOMNodeList
) {
1406 foreach ( $this->node
as $node ) {
1407 $s .= $node->ownerDocument
->saveXML( $node );
1410 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1415 function getChildren() {
1416 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1419 function getFirstChild() {
1420 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1423 function getNextSibling() {
1424 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1427 function getChildrenOfType( $type ) {
1428 return new self( $this->xpath
->query( $type, $this->node
) );
1431 function getLength() {
1432 if ( $this->node
instanceof DOMNodeList
) {
1433 return $this->node
->length
;
1439 function item( $i ) {
1440 $item = $this->node
->item( $i );
1441 return $item ?
new self( $item ) : false;
1444 function getName() {
1445 if ( $this->node
instanceof DOMNodeList
) {
1448 return $this->node
->nodeName
;
1453 * Split a <part> node into an associative array containing:
1455 * index String index
1456 * value PPNode value
1458 function splitArg() {
1459 $names = $this->xpath
->query( 'name', $this->node
);
1460 $values = $this->xpath
->query( 'value', $this->node
);
1461 if ( !$names->length ||
!$values->length
) {
1462 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1464 $name = $names->item( 0 );
1465 $index = $name->getAttribute( 'index' );
1467 'name' => new self( $name ),
1469 'value' => new self( $values->item( 0 ) ) );
1473 * Split an <ext> node into an associative array containing name, attr, inner and close
1474 * All values in the resulting array are PPNodes. Inner and close are optional.
1476 function splitExt() {
1477 $names = $this->xpath
->query( 'name', $this->node
);
1478 $attrs = $this->xpath
->query( 'attr', $this->node
);
1479 $inners = $this->xpath
->query( 'inner', $this->node
);
1480 $closes = $this->xpath
->query( 'close', $this->node
);
1481 if ( !$names->length ||
!$attrs->length
) {
1482 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1485 'name' => new self( $names->item( 0 ) ),
1486 'attr' => new self( $attrs->item( 0 ) ) );
1487 if ( $inners->length
) {
1488 $parts['inner'] = new self( $inners->item( 0 ) );
1490 if ( $closes->length
) {
1491 $parts['close'] = new self( $closes->item( 0 ) );
1499 function splitHeading() {
1500 if ( !$this->nodeName
== 'h' ) {
1501 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1504 'i' => $this->node
->getAttribute( 'i' ),
1505 'level' => $this->node
->getAttribute( 'level' ),
1506 'contents' => $this->getChildren()