6 class Preprocessor_DOM
implements Preprocessor
{
7 var $parser, $memoryLimit;
9 function __construct( $parser ) {
10 $this->parser
= $parser;
11 $mem = ini_get( 'memory_limit' );
12 $this->memoryLimit
= false;
13 if ( strval( $mem ) !== '' && $mem != -1 ) {
14 if ( preg_match( '/^\d+$/', $mem ) ) {
15 $this->memoryLimit
= $mem;
16 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
17 $this->memoryLimit
= $m[1] * 1048576;
23 return new PPFrame_DOM( $this );
26 function newCustomFrame( $args ) {
27 return new PPCustomFrame_DOM( $this, $args );
31 if ( $this->memoryLimit
=== false ) {
34 $usage = memory_get_usage();
35 if ( $usage > $this->memoryLimit
* 0.9 ) {
36 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
37 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
39 return $usage <= $this->memoryLimit
* 0.8;
43 * Preprocess some wikitext and return the document tree.
44 * This is the ghost of Parser::replace_variables().
46 * @param string $text The text to parse
47 * @param integer flags Bitwise combination of:
48 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
49 * included. Default is to assume a direct page view.
51 * The generated DOM tree must depend only on the input text and the flags.
52 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
54 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
55 * change in the DOM tree for a given text, must be passed through the section identifier
56 * in the section edit link and thus back to extractSections().
58 * The output of this function is currently only cached in process memory, but a persistent
59 * cache may be implemented at a later date which takes further advantage of these strict
60 * dependency requirements.
64 function preprocessToObj( $text, $flags = 0 ) {
65 wfProfileIn( __METHOD__
);
68 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
70 if ( $xml = $wgMemc->get( $cacheKey ) ) {
72 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
74 $xml = $this->preprocessToXml( $text, $flags );
75 $wgMemc->set( $cacheKey, $xml, 86400 );
76 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
79 wfProfileIn( __METHOD__
.'-loadXML' );
80 $dom = new DOMDocument
;
82 $result = $dom->loadXML( $xml );
85 // Try running the XML through UtfNormal to get rid of invalid characters
86 $xml = UtfNormal
::cleanUp( $xml );
87 $result = $dom->loadXML( $xml );
89 throw new MWException( __METHOD__
.' generated invalid XML' );
92 $obj = new PPNode_DOM( $dom->documentElement
);
93 wfProfileOut( __METHOD__
.'-loadXML' );
94 wfProfileOut( __METHOD__
);
98 function preprocessToXml( $text, $flags = 0 ) {
99 wfProfileIn( __METHOD__
);
112 'names' => array( 2 => null ),
118 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
120 $xmlishElements = $this->parser
->getStripList();
121 $enableOnlyinclude = false;
122 if ( $forInclusion ) {
123 $ignoredTags = array( 'includeonly', '/includeonly' );
124 $ignoredElements = array( 'noinclude' );
125 $xmlishElements[] = 'noinclude';
126 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
127 $enableOnlyinclude = true;
130 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
131 $ignoredElements = array( 'includeonly' );
132 $xmlishElements[] = 'includeonly';
134 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
136 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
137 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
139 $stack = new PPDStack
;
141 $searchBase = "[{<\n"; #}
142 $revText = strrev( $text ); // For fast reverse searches
144 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
145 $accum =& $stack->getAccum(); # Current accumulator
147 $findEquals = false; # True to find equals signs in arguments
148 $findPipe = false; # True to take notice of pipe characters
150 $inHeading = false; # True if $i is inside a possible heading
151 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
152 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
153 $fakeLineStart = true; # Do a line-start run without outputting an LF character
158 if ( $findOnlyinclude ) {
159 // Ignore all input up to the next <onlyinclude>
160 $startPos = strpos( $text, '<onlyinclude>', $i );
161 if ( $startPos === false ) {
162 // Ignored section runs to the end
163 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
166 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
167 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
169 $findOnlyinclude = false;
172 if ( $fakeLineStart ) {
173 $found = 'line-start';
176 # Find next opening brace, closing brace or pipe
177 $search = $searchBase;
178 if ( $stack->top
=== false ) {
179 $currentClosing = '';
181 $currentClosing = $stack->top
->close
;
182 $search .= $currentClosing;
188 // First equals will be for the template
192 # Output literal section, advance input counter
193 $literalLength = strcspn( $text, $search, $i );
194 if ( $literalLength > 0 ) {
195 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
196 $i +
= $literalLength;
198 if ( $i >= strlen( $text ) ) {
199 if ( $currentClosing == "\n" ) {
200 // Do a past-the-end run to finish off the heading
208 $curChar = $text[$i];
209 if ( $curChar == '|' ) {
211 } elseif ( $curChar == '=' ) {
213 } elseif ( $curChar == '<' ) {
215 } elseif ( $curChar == "\n" ) {
219 $found = 'line-start';
221 } elseif ( $curChar == $currentClosing ) {
223 } elseif ( isset( $rules[$curChar] ) ) {
225 $rule = $rules[$curChar];
227 # Some versions of PHP have a strcspn which stops on null characters
228 # Ignore and continue
235 if ( $found == 'angle' ) {
237 // Handle </onlyinclude>
238 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
239 $findOnlyinclude = true;
243 // Determine element name
244 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
245 // Element name missing or not listed
251 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
252 // To avoid leaving blank lines, when a comment is both preceded
253 // and followed by a newline (ignoring spaces), trim leading and
254 // trailing spaces and one of the newlines.
257 $endPos = strpos( $text, '-->', $i +
4 );
258 if ( $endPos === false ) {
259 // Unclosed comment in input, runs to end
260 $inner = substr( $text, $i );
261 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
262 $i = strlen( $text );
264 // Search backwards for leading whitespace
265 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
266 // Search forwards for trailing whitespace
267 // $wsEnd will be the position of the last space
268 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
269 // Eat the line if possible
270 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
271 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
272 // it's a possible beneficial b/c break.
273 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
274 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
276 $startPos = $wsStart;
277 $endPos = $wsEnd +
1;
278 // Remove leading whitespace from the end of the accumulator
279 // Sanity check first though
280 $wsLength = $i - $wsStart;
281 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
282 $accum = substr( $accum, 0, -$wsLength );
284 // Do a line-start run next time to look for headings after the comment
285 $fakeLineStart = true;
287 // No line to eat, just take the comment itself
293 $part = $stack->top
->getCurrentPart();
294 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
295 // Comments abutting, no change in visual end
296 $part->commentEnd
= $wsEnd;
298 $part->visualEnd
= $wsStart;
299 $part->commentEnd
= $endPos;
303 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
304 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
309 $lowerName = strtolower( $name );
310 $attrStart = $i +
strlen( $name ) +
1;
313 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
314 if ( $tagEndPos === false ) {
315 // Infinite backtrack
316 // Disable tag search to prevent worst-case O(N^2) performance
323 // Handle ignored tags
324 if ( in_array( $lowerName, $ignoredTags ) ) {
325 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
331 if ( $text[$tagEndPos-1] == '/' ) {
332 $attrEnd = $tagEndPos - 1;
337 $attrEnd = $tagEndPos;
339 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
340 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
342 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
343 $i = $matches[0][1] +
strlen( $matches[0][0] );
344 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
346 // No end tag -- let it run out to the end of the text.
347 $inner = substr( $text, $tagEndPos +
1 );
348 $i = strlen( $text );
352 // <includeonly> and <noinclude> just become <ignore> tags
353 if ( in_array( $lowerName, $ignoredElements ) ) {
354 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
360 if ( $attrEnd <= $attrStart ) {
363 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
365 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
366 // Note that the attr element contains the whitespace between name and attribute,
367 // this is necessary for precise reconstruction during pre-save transform.
368 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
369 if ( $inner !== null ) {
370 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
372 $accum .= $close . '</ext>';
375 elseif ( $found == 'line-start' ) {
376 // Is this the start of a heading?
377 // Line break belongs before the heading element in any case
378 if ( $fakeLineStart ) {
379 $fakeLineStart = false;
385 $count = strspn( $text, '=', $i, 6 );
386 if ( $count == 1 && $findEquals ) {
387 // DWIM: This looks kind of like a name/value separator
388 // Let's let the equals handler have it and break the potential heading
389 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
390 } elseif ( $count > 0 ) {
394 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
397 $stack->push( $piece );
398 $accum =& $stack->getAccum();
399 extract( $stack->getFlags() );
404 elseif ( $found == 'line-end' ) {
405 $piece = $stack->top
;
406 // A heading must be open, otherwise \n wouldn't have been in the search list
407 assert( $piece->open
== "\n" );
408 $part = $piece->getCurrentPart();
409 // Search back through the input to see if it has a proper close
410 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
411 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
412 $searchStart = $i - $wsLength;
413 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
414 // Comment found at line end
415 // Search for equals signs before the comment
416 $searchStart = $part->visualEnd
;
417 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
419 $count = $piece->count
;
420 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
421 if ( $equalsLength > 0 ) {
422 if ( $i - $equalsLength == $piece->startPos
) {
423 // This is just a single string of equals signs on its own line
424 // Replicate the doHeadings behaviour /={count}(.+)={count}/
425 // First find out how many equals signs there really are (don't stop at 6)
426 $count = $equalsLength;
430 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
433 $count = min( $equalsLength, $count );
436 // Normal match, output <h>
437 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
440 // Single equals sign on its own line, count=0
444 // No match, no <h>, just pass down the inner text
449 $accum =& $stack->getAccum();
450 extract( $stack->getFlags() );
452 // Append the result to the enclosing accumulator
454 // Note that we do NOT increment the input pointer.
455 // This is because the closing linebreak could be the opening linebreak of
456 // another heading. Infinite loops are avoided because the next iteration MUST
457 // hit the heading open case above, which unconditionally increments the
461 elseif ( $found == 'open' ) {
462 # count opening brace characters
463 $count = strspn( $text, $curChar, $i );
465 # we need to add to stack only if opening brace count is enough for one of the rules
466 if ( $count >= $rule['min'] ) {
467 # Add it to the stack
470 'close' => $rule['end'],
472 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
475 $stack->push( $piece );
476 $accum =& $stack->getAccum();
477 extract( $stack->getFlags() );
479 # Add literal brace(s)
480 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
485 elseif ( $found == 'close' ) {
486 $piece = $stack->top
;
487 # lets check if there are enough characters for closing brace
488 $maxCount = $piece->count
;
489 $count = strspn( $text, $curChar, $i, $maxCount );
491 # check for maximum matching characters (if there are 5 closing
492 # characters, we will probably need only 3 - depending on the rules)
494 $rule = $rules[$piece->open
];
495 if ( $count > $rule['max'] ) {
496 # The specified maximum exists in the callback array, unless the caller
498 $matchingCount = $rule['max'];
500 # Count is less than the maximum
501 # Skip any gaps in the callback array to find the true largest match
502 # Need to use array_key_exists not isset because the callback can be null
503 $matchingCount = $count;
504 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
509 if ($matchingCount <= 0) {
510 # No matching element found in callback array
511 # Output a literal closing brace and continue
512 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
516 $name = $rule['names'][$matchingCount];
517 if ( $name === null ) {
518 // No element, just literal text
519 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
522 # Note: $parts is already XML, does not need to be encoded further
523 $parts = $piece->parts
;
524 $title = $parts[0]->out
;
527 # The invocation is at the start of the line if lineStart is set in
528 # the stack, and all opening brackets are used up.
529 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
530 $attr = ' lineStart="1"';
535 $element = "<$name$attr>";
536 $element .= "<title>$title</title>";
538 foreach ( $parts as $partIndex => $part ) {
539 if ( isset( $part->eqpos
) ) {
540 $argName = substr( $part->out
, 0, $part->eqpos
);
541 $argValue = substr( $part->out
, $part->eqpos +
1 );
542 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
544 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
548 $element .= "</$name>";
551 # Advance input pointer
552 $i +
= $matchingCount;
556 $accum =& $stack->getAccum();
558 # Re-add the old stack element if it still has unmatched opening characters remaining
559 if ($matchingCount < $piece->count
) {
560 $piece->parts
= array( new PPDPart
);
561 $piece->count
-= $matchingCount;
562 # do we still qualify for any callback with remaining count?
563 $names = $rules[$piece->open
]['names'];
565 $enclosingAccum =& $accum;
566 while ( $piece->count
) {
567 if ( array_key_exists( $piece->count
, $names ) ) {
568 $stack->push( $piece );
569 $accum =& $stack->getAccum();
575 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
578 extract( $stack->getFlags() );
580 # Add XML element to the enclosing accumulator
584 elseif ( $found == 'pipe' ) {
585 $findEquals = true; // shortcut for getFlags()
587 $accum =& $stack->getAccum();
591 elseif ( $found == 'equals' ) {
592 $findEquals = false; // shortcut for getFlags()
593 $stack->getCurrentPart()->eqpos
= strlen( $accum );
599 # Output any remaining unclosed brackets
600 foreach ( $stack->stack
as $piece ) {
601 $stack->rootAccum
.= $piece->breakSyntax();
603 $stack->rootAccum
.= '</root>';
604 $xml = $stack->rootAccum
;
606 wfProfileOut( __METHOD__
);
613 * Stack class to help Preprocessor::preprocessToObj()
617 var $stack, $rootAccum, $top;
619 var $elementClass = 'PPDStackElement';
621 static $false = false;
623 function __construct() {
624 $this->stack
= array();
626 $this->rootAccum
= '';
627 $this->accum
=& $this->rootAccum
;
631 return count( $this->stack
);
634 function &getAccum() {
638 function getCurrentPart() {
639 if ( $this->top
=== false ) {
642 return $this->top
->getCurrentPart();
646 function push( $data ) {
647 if ( $data instanceof $this->elementClass
) {
648 $this->stack
[] = $data;
650 $class = $this->elementClass
;
651 $this->stack
[] = new $class( $data );
653 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
654 $this->accum
=& $this->top
->getAccum();
658 if ( !count( $this->stack
) ) {
659 throw new MWException( __METHOD__
.': no elements remaining' );
661 $temp = array_pop( $this->stack
);
663 if ( count( $this->stack
) ) {
664 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
665 $this->accum
=& $this->top
->getAccum();
667 $this->top
= self
::$false;
668 $this->accum
=& $this->rootAccum
;
673 function addPart( $s = '' ) {
674 $this->top
->addPart( $s );
675 $this->accum
=& $this->top
->getAccum();
678 function getFlags() {
679 if ( !count( $this->stack
) ) {
681 'findEquals' => false,
683 'inHeading' => false,
686 return $this->top
->getFlags();
694 class PPDStackElement
{
695 var $open, // Opening character (\n for heading)
696 $close, // Matching closing character
697 $count, // Number of opening characters found (number of "=" for heading)
698 $parts, // Array of PPDPart objects describing pipe-separated parts.
699 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
701 var $partClass = 'PPDPart';
703 function __construct( $data = array() ) {
704 $class = $this->partClass
;
705 $this->parts
= array( new $class );
707 foreach ( $data as $name => $value ) {
708 $this->$name = $value;
712 function &getAccum() {
713 return $this->parts
[count($this->parts
) - 1]->out
;
716 function addPart( $s = '' ) {
717 $class = $this->partClass
;
718 $this->parts
[] = new $class( $s );
721 function getCurrentPart() {
722 return $this->parts
[count($this->parts
) - 1];
725 function getFlags() {
726 $partCount = count( $this->parts
);
727 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
729 'findPipe' => $findPipe,
730 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
731 'inHeading' => $this->open
== "\n",
736 * Get the output string that would result if the close is not found.
738 function breakSyntax( $openingCount = false ) {
739 if ( $this->open
== "\n" ) {
740 $s = $this->parts
[0]->out
;
742 if ( $openingCount === false ) {
743 $openingCount = $this->count
;
745 $s = str_repeat( $this->open
, $openingCount );
747 foreach ( $this->parts
as $part ) {
764 var $out; // Output accumulator string
766 // Optional member variables:
767 // eqpos Position of equals sign in output accumulator
768 // commentEnd Past-the-end input pointer for the last comment encountered
769 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
771 function __construct( $out = '' ) {
777 * An expansion frame, used as a context to expand the result of preprocessToObj()
780 class PPFrame_DOM
implements PPFrame
{
781 var $preprocessor, $parser, $title;
785 * Hashtable listing templates which are disallowed for expansion in this frame,
786 * having been encountered previously in parent frames.
791 * Recursion depth of this frame, top = 0
792 * Note that this is NOT the same as expansion depth in expand()
798 * Construct a new preprocessor frame.
799 * @param Preprocessor $preprocessor The parent preprocessor
801 function __construct( $preprocessor ) {
802 $this->preprocessor
= $preprocessor;
803 $this->parser
= $preprocessor->parser
;
804 $this->title
= $this->parser
->mTitle
;
805 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
806 $this->loopCheckHash
= array();
811 * Create a new child frame
812 * $args is optionally a multi-root PPNode or array containing the template arguments
814 function newChild( $args = false, $title = false ) {
815 $namedArgs = array();
816 $numberedArgs = array();
817 if ( $title === false ) {
818 $title = $this->title
;
820 if ( $args !== false ) {
822 if ( $args instanceof PPNode
) {
825 foreach ( $args as $arg ) {
827 $xpath = new DOMXPath( $arg->ownerDocument
);
830 $nameNodes = $xpath->query( 'name', $arg );
831 $value = $xpath->query( 'value', $arg );
832 if ( $nameNodes->item( 0 )->hasAttributes() ) {
833 // Numbered parameter
834 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
835 $numberedArgs[$index] = $value->item( 0 );
836 unset( $namedArgs[$index] );
839 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
840 $namedArgs[$name] = $value->item( 0 );
841 unset( $numberedArgs[$name] );
845 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
848 function expand( $root, $flags = 0 ) {
849 static $expansionDepth = 0;
850 if ( is_string( $root ) ) {
853 wfProfileIn( __METHOD__
);
855 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
857 return '<span class="error">Node-count limit exceeded</span>';
860 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
861 return '<span class="error">Expansion depth limit exceeded</span>';
865 if ( $root instanceof PPNode_DOM
) {
868 if ( $root instanceof DOMDocument
) {
869 $root = $root->documentElement
;
872 $outStack = array( '', '' );
873 $iteratorStack = array( false, $root );
874 $indexStack = array( 0, 0 );
876 while ( count( $iteratorStack ) > 1 ) {
877 $level = count( $outStack ) - 1;
878 $iteratorNode =& $iteratorStack[ $level ];
879 $out =& $outStack[$level];
880 $index =& $indexStack[$level];
882 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
884 if ( is_array( $iteratorNode ) ) {
885 if ( $index >= count( $iteratorNode ) ) {
886 // All done with this iterator
887 $iteratorStack[$level] = false;
888 $contextNode = false;
890 $contextNode = $iteratorNode[$index];
893 } elseif ( $iteratorNode instanceof DOMNodeList
) {
894 if ( $index >= $iteratorNode->length
) {
895 // All done with this iterator
896 $iteratorStack[$level] = false;
897 $contextNode = false;
899 $contextNode = $iteratorNode->item( $index );
903 // Copy to $contextNode and then delete from iterator stack,
904 // because this is not an iterator but we do have to execute it once
905 $contextNode = $iteratorStack[$level];
906 $iteratorStack[$level] = false;
909 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
911 $newIterator = false;
913 if ( $contextNode === false ) {
915 } elseif ( is_string( $contextNode ) ) {
916 $out .= $contextNode;
917 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
918 $newIterator = $contextNode;
919 } elseif ( $contextNode instanceof DOMNode
) {
920 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
921 $out .= $contextNode->nodeValue
;
922 } elseif ( $contextNode->nodeName
== 'template' ) {
923 # Double-brace expansion
924 $xpath = new DOMXPath( $contextNode->ownerDocument
);
925 $titles = $xpath->query( 'title', $contextNode );
926 $title = $titles->item( 0 );
927 $parts = $xpath->query( 'part', $contextNode );
928 if ( $flags & self
::NO_TEMPLATES
) {
929 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
931 $lineStart = $contextNode->getAttribute( 'lineStart' );
933 'title' => new PPNode_DOM( $title ),
934 'parts' => new PPNode_DOM( $parts ),
935 'lineStart' => $lineStart );
936 $ret = $this->parser
->braceSubstitution( $params, $this );
937 if ( isset( $ret['object'] ) ) {
938 $newIterator = $ret['object'];
940 $out .= $ret['text'];
943 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
944 # Triple-brace expansion
945 $xpath = new DOMXPath( $contextNode->ownerDocument
);
946 $titles = $xpath->query( 'title', $contextNode );
947 $title = $titles->item( 0 );
948 $parts = $xpath->query( 'part', $contextNode );
949 if ( $flags & self
::NO_ARGS
) {
950 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
953 'title' => new PPNode_DOM( $title ),
954 'parts' => new PPNode_DOM( $parts ) );
955 $ret = $this->parser
->argSubstitution( $params, $this );
956 if ( isset( $ret['object'] ) ) {
957 $newIterator = $ret['object'];
959 $out .= $ret['text'];
962 } elseif ( $contextNode->nodeName
== 'comment' ) {
964 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
965 if ( $this->parser
->ot
['html']
966 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
967 ||
( $flags & self
::STRIP_COMMENTS
) )
971 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
972 # Not in RECOVER_COMMENTS mode (extractSections) though
973 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
974 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
976 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
978 $out .= $contextNode->textContent
;
980 } elseif ( $contextNode->nodeName
== 'ignore' ) {
981 # Output suppression used by <includeonly> etc.
982 # OT_WIKI will only respect <ignore> in substed templates.
983 # The other output types respect it unless NO_IGNORE is set.
984 # extractSections() sets NO_IGNORE and so never respects it.
985 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
986 $out .= $contextNode->textContent
;
990 } elseif ( $contextNode->nodeName
== 'ext' ) {
992 $xpath = new DOMXPath( $contextNode->ownerDocument
);
993 $names = $xpath->query( 'name', $contextNode );
994 $attrs = $xpath->query( 'attr', $contextNode );
995 $inners = $xpath->query( 'inner', $contextNode );
996 $closes = $xpath->query( 'close', $contextNode );
998 'name' => new PPNode_DOM( $names->item( 0 ) ),
999 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1000 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1001 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1003 $out .= $this->parser
->extensionSubstitution( $params, $this );
1004 } elseif ( $contextNode->nodeName
== 'h' ) {
1006 $s = $this->expand( $contextNode->childNodes
, $flags );
1008 # Insert a heading marker only for <h> children of <root>
1009 # This is to stop extractSections from going over multiple tree levels
1010 if ( $contextNode->parentNode
->nodeName
== 'root'
1011 && $this->parser
->ot
['html'] )
1013 # Insert heading index marker
1014 $headingIndex = $contextNode->getAttribute( 'i' );
1015 $titleText = $this->title
->getPrefixedDBkey();
1016 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1017 $serial = count( $this->parser
->mHeadings
) - 1;
1018 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1019 $count = $contextNode->getAttribute( 'level' );
1020 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1021 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1025 # Generic recursive expansion
1026 $newIterator = $contextNode->childNodes
;
1029 wfProfileOut( __METHOD__
);
1030 throw new MWException( __METHOD__
.': Invalid parameter type' );
1033 if ( $newIterator !== false ) {
1034 if ( $newIterator instanceof PPNode_DOM
) {
1035 $newIterator = $newIterator->node
;
1038 $iteratorStack[] = $newIterator;
1040 } elseif ( $iteratorStack[$level] === false ) {
1041 // Return accumulated value to parent
1042 // With tail recursion
1043 while ( $iteratorStack[$level] === false && $level > 0 ) {
1044 $outStack[$level - 1] .= $out;
1045 array_pop( $outStack );
1046 array_pop( $iteratorStack );
1047 array_pop( $indexStack );
1053 wfProfileOut( __METHOD__
);
1054 return $outStack[0];
1057 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1058 $args = array_slice( func_get_args(), 2 );
1062 foreach ( $args as $root ) {
1063 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1064 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1065 $root = array( $root );
1067 foreach ( $root as $node ) {
1073 $s .= $this->expand( $node, $flags );
1080 * Implode with no flags specified
1081 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1083 function implode( $sep /*, ... */ ) {
1084 $args = array_slice( func_get_args(), 1 );
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 );
1106 * Makes an object that, when expand()ed, will be the same as one obtained
1109 function virtualImplode( $sep /*, ... */ ) {
1110 $args = array_slice( func_get_args(), 1 );
1113 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1115 foreach ( $args as $root ) {
1116 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1117 $root = array( $root );
1119 foreach ( $root as $node ) {
1132 * Virtual implode with brackets
1134 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1135 $args = array_slice( func_get_args(), 3 );
1136 $out = array( $start );
1139 foreach ( $args as $root ) {
1140 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1141 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1142 $root = array( $root );
1144 foreach ( $root as $node ) {
1157 function __toString() {
1161 function getPDBK( $level = false ) {
1162 if ( $level === false ) {
1163 return $this->title
->getPrefixedDBkey();
1165 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1170 * Returns true if there are no arguments in this frame
1172 function isEmpty() {
1176 function getArgument( $name ) {
1181 * Returns true if the infinite loop check is OK, false if a loop is detected
1183 function loopCheck( $title ) {
1184 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1188 * Return true if the frame is a template frame
1190 function isTemplate() {
1196 * Expansion frame with template arguments
1199 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1200 var $numberedArgs, $namedArgs, $parent;
1201 var $numberedExpansionCache, $namedExpansionCache;
1203 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1204 $this->preprocessor
= $preprocessor;
1205 $this->parser
= $preprocessor->parser
;
1206 $this->parent
= $parent;
1207 $this->numberedArgs
= $numberedArgs;
1208 $this->namedArgs
= $namedArgs;
1209 $this->title
= $title;
1210 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1211 $this->titleCache
= $parent->titleCache
;
1212 $this->titleCache
[] = $pdbk;
1213 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1214 if ( $pdbk !== false ) {
1215 $this->loopCheckHash
[$pdbk] = true;
1217 $this->depth
= $parent->depth +
1;
1218 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1221 function __toString() {
1224 $args = $this->numberedArgs +
$this->namedArgs
;
1225 foreach ( $args as $name => $value ) {
1231 $s .= "\"$name\":\"" .
1232 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1238 * Returns true if there are no arguments in this frame
1240 function isEmpty() {
1241 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1244 function getArguments() {
1245 $arguments = array();
1246 foreach ( array_merge(
1247 array_keys($this->numberedArgs
),
1248 array_keys($this->namedArgs
)) as $key ) {
1249 $arguments[$key] = $this->getArgument($key);
1254 function getNumberedArguments() {
1255 $arguments = array();
1256 foreach ( array_keys($this->numberedArgs
) as $key ) {
1257 $arguments[$key] = $this->getArgument($key);
1262 function getNamedArguments() {
1263 $arguments = array();
1264 foreach ( array_keys($this->namedArgs
) as $key ) {
1265 $arguments[$key] = $this->getArgument($key);
1270 function getNumberedArgument( $index ) {
1271 if ( !isset( $this->numberedArgs
[$index] ) ) {
1274 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1275 # No trimming for unnamed arguments
1276 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1278 return $this->numberedExpansionCache
[$index];
1281 function getNamedArgument( $name ) {
1282 if ( !isset( $this->namedArgs
[$name] ) ) {
1285 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1286 # Trim named arguments post-expand, for backwards compatibility
1287 $this->namedExpansionCache
[$name] = trim(
1288 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1290 return $this->namedExpansionCache
[$name];
1293 function getArgument( $name ) {
1294 $text = $this->getNumberedArgument( $name );
1295 if ( $text === false ) {
1296 $text = $this->getNamedArgument( $name );
1302 * Return true if the frame is a template frame
1304 function isTemplate() {
1310 * Expansion frame with custom arguments
1313 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1316 function __construct( $preprocessor, $args ) {
1317 $this->preprocessor
= $preprocessor;
1318 $this->parser
= $preprocessor->parser
;
1319 $this->args
= $args;
1322 function __toString() {
1325 foreach ( $this->args
as $name => $value ) {
1331 $s .= "\"$name\":\"" .
1332 str_replace( '"', '\\"', $value->__toString() ) . '"';
1338 function isEmpty() {
1339 return !count( $this->args
);
1342 function getArgument( $index ) {
1343 if ( !isset( $this->args
[$index] ) ) {
1346 return $this->args
[$index];
1353 class PPNode_DOM
implements PPNode
{
1356 function __construct( $node, $xpath = false ) {
1357 $this->node
= $node;
1360 function __get( $name ) {
1361 if ( $name == 'xpath' ) {
1362 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1364 return $this->xpath
;
1367 function __toString() {
1368 if ( $this->node
instanceof DOMNodeList
) {
1370 foreach ( $this->node
as $node ) {
1371 $s .= $node->ownerDocument
->saveXML( $node );
1374 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1379 function getChildren() {
1380 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1383 function getFirstChild() {
1384 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1387 function getNextSibling() {
1388 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1391 function getChildrenOfType( $type ) {
1392 return new self( $this->xpath
->query( $type, $this->node
) );
1395 function getLength() {
1396 if ( $this->node
instanceof DOMNodeList
) {
1397 return $this->node
->length
;
1403 function item( $i ) {
1404 $item = $this->node
->item( $i );
1405 return $item ?
new self( $item ) : false;
1408 function getName() {
1409 if ( $this->node
instanceof DOMNodeList
) {
1412 return $this->node
->nodeName
;
1417 * Split a <part> node into an associative array containing:
1419 * index String index
1420 * value PPNode value
1422 function splitArg() {
1423 $names = $this->xpath
->query( 'name', $this->node
);
1424 $values = $this->xpath
->query( 'value', $this->node
);
1425 if ( !$names->length ||
!$values->length
) {
1426 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1428 $name = $names->item( 0 );
1429 $index = $name->getAttribute( 'index' );
1431 'name' => new self( $name ),
1433 'value' => new self( $values->item( 0 ) ) );
1437 * Split an <ext> node into an associative array containing name, attr, inner and close
1438 * All values in the resulting array are PPNodes. Inner and close are optional.
1440 function splitExt() {
1441 $names = $this->xpath
->query( 'name', $this->node
);
1442 $attrs = $this->xpath
->query( 'attr', $this->node
);
1443 $inners = $this->xpath
->query( 'inner', $this->node
);
1444 $closes = $this->xpath
->query( 'close', $this->node
);
1445 if ( !$names->length ||
!$attrs->length
) {
1446 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1449 'name' => new self( $names->item( 0 ) ),
1450 'attr' => new self( $attrs->item( 0 ) ) );
1451 if ( $inners->length
) {
1452 $parts['inner'] = new self( $inners->item( 0 ) );
1454 if ( $closes->length
) {
1455 $parts['close'] = new self( $closes->item( 0 ) );
1463 function splitHeading() {
1464 if ( !$this->nodeName
== 'h' ) {
1465 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1468 'i' => $this->node
->getAttribute( 'i' ),
1469 'level' => $this->node
->getAttribute( 'level' ),
1470 'contents' => $this->getChildren()