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 );
27 if ( $this->memoryLimit
=== false ) {
30 $usage = memory_get_usage();
31 if ( $usage > $this->memoryLimit
* 0.9 ) {
32 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
33 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
35 return $usage <= $this->memoryLimit
* 0.8;
39 * Preprocess some wikitext and return the document tree.
40 * This is the ghost of Parser::replace_variables().
42 * @param string $text The text to parse
43 * @param integer flags Bitwise combination of:
44 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
45 * included. Default is to assume a direct page view.
47 * The generated DOM tree must depend only on the input text and the flags.
48 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
50 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
51 * change in the DOM tree for a given text, must be passed through the section identifier
52 * in the section edit link and thus back to extractSections().
54 * The output of this function is currently only cached in process memory, but a persistent
55 * cache may be implemented at a later date which takes further advantage of these strict
56 * dependency requirements.
60 function preprocessToObj( $text, $flags = 0 ) {
61 wfProfileIn( __METHOD__
);
62 wfProfileIn( __METHOD__
.'-makexml' );
76 'names' => array( 2 => null ),
82 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
84 $xmlishElements = $this->parser
->getStripList();
85 $enableOnlyinclude = false;
86 if ( $forInclusion ) {
87 $ignoredTags = array( 'includeonly', '/includeonly' );
88 $ignoredElements = array( 'noinclude' );
89 $xmlishElements[] = 'noinclude';
90 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
91 $enableOnlyinclude = true;
94 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
95 $ignoredElements = array( 'includeonly' );
96 $xmlishElements[] = 'includeonly';
98 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
100 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
101 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
103 $stack = new PPDStack
;
105 $searchBase = "[{<\n"; #}
106 $revText = strrev( $text ); // For fast reverse searches
108 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
109 $accum =& $stack->getAccum(); # Current accumulator
111 $findEquals = false; # True to find equals signs in arguments
112 $findPipe = false; # True to take notice of pipe characters
114 $inHeading = false; # True if $i is inside a possible heading
115 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
116 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
117 $fakeLineStart = true; # Do a line-start run without outputting an LF character
122 if ( $findOnlyinclude ) {
123 // Ignore all input up to the next <onlyinclude>
124 $startPos = strpos( $text, '<onlyinclude>', $i );
125 if ( $startPos === false ) {
126 // Ignored section runs to the end
127 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
130 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
131 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
133 $findOnlyinclude = false;
136 if ( $fakeLineStart ) {
137 $found = 'line-start';
140 # Find next opening brace, closing brace or pipe
141 $search = $searchBase;
142 if ( $stack->top
=== false ) {
143 $currentClosing = '';
145 $currentClosing = $stack->top
->close
;
146 $search .= $currentClosing;
152 // First equals will be for the template
156 # Output literal section, advance input counter
157 $literalLength = strcspn( $text, $search, $i );
158 if ( $literalLength > 0 ) {
159 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
160 $i +
= $literalLength;
162 if ( $i >= strlen( $text ) ) {
163 if ( $currentClosing == "\n" ) {
164 // Do a past-the-end run to finish off the heading
172 $curChar = $text[$i];
173 if ( $curChar == '|' ) {
175 } elseif ( $curChar == '=' ) {
177 } elseif ( $curChar == '<' ) {
179 } elseif ( $curChar == "\n" ) {
183 $found = 'line-start';
185 } elseif ( $curChar == $currentClosing ) {
187 } elseif ( isset( $rules[$curChar] ) ) {
189 $rule = $rules[$curChar];
191 # Some versions of PHP have a strcspn which stops on null characters
192 # Ignore and continue
199 if ( $found == 'angle' ) {
201 // Handle </onlyinclude>
202 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
203 $findOnlyinclude = true;
207 // Determine element name
208 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
209 // Element name missing or not listed
215 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
216 // To avoid leaving blank lines, when a comment is both preceded
217 // and followed by a newline (ignoring spaces), trim leading and
218 // trailing spaces and one of the newlines.
221 $endPos = strpos( $text, '-->', $i +
4 );
222 if ( $endPos === false ) {
223 // Unclosed comment in input, runs to end
224 $inner = substr( $text, $i );
225 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
226 $i = strlen( $text );
228 // Search backwards for leading whitespace
229 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
230 // Search forwards for trailing whitespace
231 // $wsEnd will be the position of the last space
232 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
233 // Eat the line if possible
234 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
235 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
236 // it's a possible beneficial b/c break.
237 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
238 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
240 $startPos = $wsStart;
241 $endPos = $wsEnd +
1;
242 // Remove leading whitespace from the end of the accumulator
243 // Sanity check first though
244 $wsLength = $i - $wsStart;
245 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
246 $accum = substr( $accum, 0, -$wsLength );
248 // Do a line-start run next time to look for headings after the comment
249 $fakeLineStart = true;
251 // No line to eat, just take the comment itself
257 $part = $stack->top
->getCurrentPart();
258 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
259 // Comments abutting, no change in visual end
260 $part->commentEnd
= $wsEnd;
262 $part->visualEnd
= $wsStart;
263 $part->commentEnd
= $endPos;
267 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
268 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
273 $lowerName = strtolower( $name );
274 $attrStart = $i +
strlen( $name ) +
1;
277 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
278 if ( $tagEndPos === false ) {
279 // Infinite backtrack
280 // Disable tag search to prevent worst-case O(N^2) performance
287 // Handle ignored tags
288 if ( in_array( $lowerName, $ignoredTags ) ) {
289 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
295 if ( $text[$tagEndPos-1] == '/' ) {
296 $attrEnd = $tagEndPos - 1;
301 $attrEnd = $tagEndPos;
303 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
304 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
305 $i = $matches[0][1] +
strlen( $matches[0][0] );
306 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
308 // No end tag -- let it run out to the end of the text.
309 $inner = substr( $text, $tagEndPos +
1 );
310 $i = strlen( $text );
314 // <includeonly> and <noinclude> just become <ignore> tags
315 if ( in_array( $lowerName, $ignoredElements ) ) {
316 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
322 if ( $attrEnd <= $attrStart ) {
325 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
327 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
328 // Note that the attr element contains the whitespace between name and attribute,
329 // this is necessary for precise reconstruction during pre-save transform.
330 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
331 if ( $inner !== null ) {
332 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
334 $accum .= $close . '</ext>';
337 elseif ( $found == 'line-start' ) {
338 // Is this the start of a heading?
339 // Line break belongs before the heading element in any case
340 if ( $fakeLineStart ) {
341 $fakeLineStart = false;
347 $count = strspn( $text, '=', $i, 6 );
348 if ( $count == 1 && $findEquals ) {
349 // DWIM: This looks kind of like a name/value separator
350 // Let's let the equals handler have it and break the potential heading
351 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
352 } elseif ( $count > 0 ) {
356 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
359 $stack->push( $piece );
360 $accum =& $stack->getAccum();
361 extract( $stack->getFlags() );
366 elseif ( $found == 'line-end' ) {
367 $piece = $stack->top
;
368 // A heading must be open, otherwise \n wouldn't have been in the search list
369 assert( $piece->open
== "\n" );
370 $part = $piece->getCurrentPart();
371 // Search back through the input to see if it has a proper close
372 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
373 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
374 $searchStart = $i - $wsLength;
375 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
376 // Comment found at line end
377 // Search for equals signs before the comment
378 $searchStart = $part->visualEnd
;
379 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
381 $count = $piece->count
;
382 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
383 if ( $equalsLength > 0 ) {
384 if ( $i - $equalsLength == $piece->startPos
) {
385 // This is just a single string of equals signs on its own line
386 // Replicate the doHeadings behaviour /={count}(.+)={count}/
387 // First find out how many equals signs there really are (don't stop at 6)
388 $count = $equalsLength;
392 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
395 $count = min( $equalsLength, $count );
398 // Normal match, output <h>
399 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
402 // Single equals sign on its own line, count=0
406 // No match, no <h>, just pass down the inner text
411 $accum =& $stack->getAccum();
412 extract( $stack->getFlags() );
414 // Append the result to the enclosing accumulator
416 // Note that we do NOT increment the input pointer.
417 // This is because the closing linebreak could be the opening linebreak of
418 // another heading. Infinite loops are avoided because the next iteration MUST
419 // hit the heading open case above, which unconditionally increments the
423 elseif ( $found == 'open' ) {
424 # count opening brace characters
425 $count = strspn( $text, $curChar, $i );
427 # we need to add to stack only if opening brace count is enough for one of the rules
428 if ( $count >= $rule['min'] ) {
429 # Add it to the stack
432 'close' => $rule['end'],
434 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
437 $stack->push( $piece );
438 $accum =& $stack->getAccum();
439 extract( $stack->getFlags() );
441 # Add literal brace(s)
442 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
447 elseif ( $found == 'close' ) {
448 $piece = $stack->top
;
449 # lets check if there are enough characters for closing brace
450 $maxCount = $piece->count
;
451 $count = strspn( $text, $curChar, $i, $maxCount );
453 # check for maximum matching characters (if there are 5 closing
454 # characters, we will probably need only 3 - depending on the rules)
456 $rule = $rules[$piece->open
];
457 if ( $count > $rule['max'] ) {
458 # The specified maximum exists in the callback array, unless the caller
460 $matchingCount = $rule['max'];
462 # Count is less than the maximum
463 # Skip any gaps in the callback array to find the true largest match
464 # Need to use array_key_exists not isset because the callback can be null
465 $matchingCount = $count;
466 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
471 if ($matchingCount <= 0) {
472 # No matching element found in callback array
473 # Output a literal closing brace and continue
474 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
478 $name = $rule['names'][$matchingCount];
479 if ( $name === null ) {
480 // No element, just literal text
481 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
484 # Note: $parts is already XML, does not need to be encoded further
485 $parts = $piece->parts
;
486 $title = $parts[0]->out
;
489 # The invocation is at the start of the line if lineStart is set in
490 # the stack, and all opening brackets are used up.
491 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
492 $attr = ' lineStart="1"';
497 $element = "<$name$attr>";
498 $element .= "<title>$title</title>";
500 foreach ( $parts as $partIndex => $part ) {
501 if ( isset( $part->eqpos
) ) {
502 $argName = substr( $part->out
, 0, $part->eqpos
);
503 $argValue = substr( $part->out
, $part->eqpos +
1 );
504 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
506 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
510 $element .= "</$name>";
513 # Advance input pointer
514 $i +
= $matchingCount;
518 $accum =& $stack->getAccum();
520 # Re-add the old stack element if it still has unmatched opening characters remaining
521 if ($matchingCount < $piece->count
) {
522 $piece->parts
= array( new PPDPart
);
523 $piece->count
-= $matchingCount;
524 # do we still qualify for any callback with remaining count?
525 $names = $rules[$piece->open
]['names'];
527 $enclosingAccum =& $accum;
528 while ( $piece->count
) {
529 if ( array_key_exists( $piece->count
, $names ) ) {
530 $stack->push( $piece );
531 $accum =& $stack->getAccum();
537 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
540 extract( $stack->getFlags() );
542 # Add XML element to the enclosing accumulator
546 elseif ( $found == 'pipe' ) {
547 $findEquals = true; // shortcut for getFlags()
549 $accum =& $stack->getAccum();
553 elseif ( $found == 'equals' ) {
554 $findEquals = false; // shortcut for getFlags()
555 $stack->getCurrentPart()->eqpos
= strlen( $accum );
561 # Output any remaining unclosed brackets
562 foreach ( $stack->stack
as $piece ) {
563 $stack->rootAccum
.= $piece->breakSyntax();
565 $stack->rootAccum
.= '</root>';
566 $xml = $stack->rootAccum
;
568 wfProfileOut( __METHOD__
.'-makexml' );
569 wfProfileIn( __METHOD__
.'-loadXML' );
570 $dom = new DOMDocument
;
571 wfSuppressWarnings();
572 $result = $dom->loadXML( $xml );
575 // Try running the XML through UtfNormal to get rid of invalid characters
576 $xml = UtfNormal
::cleanUp( $xml );
577 $result = $dom->loadXML( $xml );
579 throw new MWException( __METHOD__
.' generated invalid XML' );
582 $obj = new PPNode_DOM( $dom->documentElement
);
583 wfProfileOut( __METHOD__
.'-loadXML' );
584 wfProfileOut( __METHOD__
);
590 * Stack class to help Preprocessor::preprocessToObj()
594 var $stack, $rootAccum, $top;
596 var $elementClass = 'PPDStackElement';
598 static $false = false;
600 function __construct() {
601 $this->stack
= array();
603 $this->rootAccum
= '';
604 $this->accum
=& $this->rootAccum
;
608 return count( $this->stack
);
611 function &getAccum() {
615 function getCurrentPart() {
616 if ( $this->top
=== false ) {
619 return $this->top
->getCurrentPart();
623 function push( $data ) {
624 if ( $data instanceof $this->elementClass
) {
625 $this->stack
[] = $data;
627 $class = $this->elementClass
;
628 $this->stack
[] = new $class( $data );
630 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
631 $this->accum
=& $this->top
->getAccum();
635 if ( !count( $this->stack
) ) {
636 throw new MWException( __METHOD__
.': no elements remaining' );
638 $temp = array_pop( $this->stack
);
640 if ( count( $this->stack
) ) {
641 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
642 $this->accum
=& $this->top
->getAccum();
644 $this->top
= self
::$false;
645 $this->accum
=& $this->rootAccum
;
650 function addPart( $s = '' ) {
651 $this->top
->addPart( $s );
652 $this->accum
=& $this->top
->getAccum();
655 function getFlags() {
656 if ( !count( $this->stack
) ) {
658 'findEquals' => false,
660 'inHeading' => false,
663 return $this->top
->getFlags();
671 class PPDStackElement
{
672 var $open, // Opening character (\n for heading)
673 $close, // Matching closing character
674 $count, // Number of opening characters found (number of "=" for heading)
675 $parts, // Array of PPDPart objects describing pipe-separated parts.
676 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
678 var $partClass = 'PPDPart';
680 function __construct( $data = array() ) {
681 $class = $this->partClass
;
682 $this->parts
= array( new $class );
684 foreach ( $data as $name => $value ) {
685 $this->$name = $value;
689 function &getAccum() {
690 return $this->parts
[count($this->parts
) - 1]->out
;
693 function addPart( $s = '' ) {
694 $class = $this->partClass
;
695 $this->parts
[] = new $class( $s );
698 function getCurrentPart() {
699 return $this->parts
[count($this->parts
) - 1];
702 function getFlags() {
703 $partCount = count( $this->parts
);
704 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
706 'findPipe' => $findPipe,
707 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
708 'inHeading' => $this->open
== "\n",
713 * Get the output string that would result if the close is not found.
715 function breakSyntax( $openingCount = false ) {
716 if ( $this->open
== "\n" ) {
717 $s = $this->parts
[0]->out
;
719 if ( $openingCount === false ) {
720 $openingCount = $this->count
;
722 $s = str_repeat( $this->open
, $openingCount );
724 foreach ( $this->parts
as $part ) {
741 var $out; // Output accumulator string
743 // Optional member variables:
744 // eqpos Position of equals sign in output accumulator
745 // commentEnd Past-the-end input pointer for the last comment encountered
746 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
748 function __construct( $out = '' ) {
754 * An expansion frame, used as a context to expand the result of preprocessToObj()
757 class PPFrame_DOM
implements PPFrame
{
758 var $preprocessor, $parser, $title;
762 * Hashtable listing templates which are disallowed for expansion in this frame,
763 * having been encountered previously in parent frames.
768 * Recursion depth of this frame, top = 0
774 * Construct a new preprocessor frame.
775 * @param Preprocessor $preprocessor The parent preprocessor
777 function __construct( $preprocessor ) {
778 $this->preprocessor
= $preprocessor;
779 $this->parser
= $preprocessor->parser
;
780 $this->title
= $this->parser
->mTitle
;
781 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
782 $this->loopCheckHash
= array();
787 * Create a new child frame
788 * $args is optionally a multi-root PPNode or array containing the template arguments
790 function newChild( $args = false, $title = false ) {
791 $namedArgs = array();
792 $numberedArgs = array();
793 if ( $title === false ) {
794 $title = $this->title
;
796 if ( $args !== false ) {
798 if ( $args instanceof PPNode
) {
801 foreach ( $args as $arg ) {
803 $xpath = new DOMXPath( $arg->ownerDocument
);
806 $nameNodes = $xpath->query( 'name', $arg );
807 $value = $xpath->query( 'value', $arg );
808 if ( $nameNodes->item( 0 )->hasAttributes() ) {
809 // Numbered parameter
810 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
811 $numberedArgs[$index] = $value->item( 0 );
812 unset( $namedArgs[$index] );
815 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
816 $namedArgs[$name] = $value->item( 0 );
817 unset( $numberedArgs[$name] );
821 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
824 function expand( $root, $flags = 0 ) {
826 if ( is_string( $root ) ) {
830 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
832 return '<span class="error">Node-count limit exceeded</span>';
835 if ( $depth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
836 return '<span class="error">Expansion depth limit exceeded</span>';
840 if ( $root instanceof PPNode_DOM
) {
843 if ( $root instanceof DOMDocument
) {
844 $root = $root->documentElement
;
847 $outStack = array( '', '' );
848 $iteratorStack = array( false, $root );
849 $indexStack = array( 0, 0 );
851 while ( count( $iteratorStack ) > 1 ) {
852 $level = count( $outStack ) - 1;
853 $iteratorNode =& $iteratorStack[ $level ];
854 $out =& $outStack[$level];
855 $index =& $indexStack[$level];
857 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
859 if ( is_array( $iteratorNode ) ) {
860 if ( $index >= count( $iteratorNode ) ) {
861 // All done with this iterator
862 $iteratorStack[$level] = false;
863 $contextNode = false;
865 $contextNode = $iteratorNode[$index];
868 } elseif ( $iteratorNode instanceof DOMNodeList
) {
869 if ( $index >= $iteratorNode->length
) {
870 // All done with this iterator
871 $iteratorStack[$level] = false;
872 $contextNode = false;
874 $contextNode = $iteratorNode->item( $index );
878 // Copy to $contextNode and then delete from iterator stack,
879 // because this is not an iterator but we do have to execute it once
880 $contextNode = $iteratorStack[$level];
881 $iteratorStack[$level] = false;
884 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
886 $newIterator = false;
888 if ( $contextNode === false ) {
890 } elseif ( is_string( $contextNode ) ) {
891 $out .= $contextNode;
892 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
893 $newIterator = $contextNode;
894 } elseif ( $contextNode instanceof DOMNode
) {
895 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
896 $out .= $contextNode->nodeValue
;
897 } elseif ( $contextNode->nodeName
== 'template' ) {
898 # Double-brace expansion
899 $xpath = new DOMXPath( $contextNode->ownerDocument
);
900 $titles = $xpath->query( 'title', $contextNode );
901 $title = $titles->item( 0 );
902 $parts = $xpath->query( 'part', $contextNode );
903 if ( $flags & self
::NO_TEMPLATES
) {
904 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
906 $lineStart = $contextNode->getAttribute( 'lineStart' );
908 'title' => new PPNode_DOM( $title ),
909 'parts' => new PPNode_DOM( $parts ),
910 'lineStart' => $lineStart );
911 $ret = $this->parser
->braceSubstitution( $params, $this );
912 if ( isset( $ret['object'] ) ) {
913 $newIterator = $ret['object'];
915 $out .= $ret['text'];
918 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
919 # Triple-brace expansion
920 $xpath = new DOMXPath( $contextNode->ownerDocument
);
921 $titles = $xpath->query( 'title', $contextNode );
922 $title = $titles->item( 0 );
923 $parts = $xpath->query( 'part', $contextNode );
924 if ( $flags & self
::NO_ARGS
) {
925 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
928 'title' => new PPNode_DOM( $title ),
929 'parts' => new PPNode_DOM( $parts ) );
930 $ret = $this->parser
->argSubstitution( $params, $this );
931 if ( isset( $ret['object'] ) ) {
932 $newIterator = $ret['object'];
934 $out .= $ret['text'];
937 } elseif ( $contextNode->nodeName
== 'comment' ) {
939 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
940 if ( $this->parser
->ot
['html']
941 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
942 ||
( $flags & self
::STRIP_COMMENTS
) )
946 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
947 # Not in RECOVER_COMMENTS mode (extractSections) though
948 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
949 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
951 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
953 $out .= $contextNode->textContent
;
955 } elseif ( $contextNode->nodeName
== 'ignore' ) {
956 # Output suppression used by <includeonly> etc.
957 # OT_WIKI will only respect <ignore> in substed templates.
958 # The other output types respect it unless NO_IGNORE is set.
959 # extractSections() sets NO_IGNORE and so never respects it.
960 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
961 $out .= $contextNode->textContent
;
965 } elseif ( $contextNode->nodeName
== 'ext' ) {
967 $xpath = new DOMXPath( $contextNode->ownerDocument
);
968 $names = $xpath->query( 'name', $contextNode );
969 $attrs = $xpath->query( 'attr', $contextNode );
970 $inners = $xpath->query( 'inner', $contextNode );
971 $closes = $xpath->query( 'close', $contextNode );
973 'name' => new PPNode_DOM( $names->item( 0 ) ),
974 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
975 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
976 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
978 $out .= $this->parser
->extensionSubstitution( $params, $this );
979 } elseif ( $contextNode->nodeName
== 'h' ) {
981 $s = $this->expand( $contextNode->childNodes
, $flags );
983 # Insert a heading marker only for <h> children of <root>
984 # This is to stop extractSections from going over multiple tree levels
985 if ( $contextNode->parentNode
->nodeName
== 'root'
986 && $this->parser
->ot
['html'] )
988 # Insert heading index marker
989 $headingIndex = $contextNode->getAttribute( 'i' );
990 $titleText = $this->title
->getPrefixedDBkey();
991 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
992 $serial = count( $this->parser
->mHeadings
) - 1;
993 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
994 $count = $contextNode->getAttribute( 'level' );
995 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
996 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1000 # Generic recursive expansion
1001 $newIterator = $contextNode->childNodes
;
1004 throw new MWException( __METHOD__
.': Invalid parameter type' );
1007 if ( $newIterator !== false ) {
1008 if ( $newIterator instanceof PPNode_DOM
) {
1009 $newIterator = $newIterator->node
;
1012 $iteratorStack[] = $newIterator;
1014 } elseif ( $iteratorStack[$level] === false ) {
1015 // Return accumulated value to parent
1016 // With tail recursion
1017 while ( $iteratorStack[$level] === false && $level > 0 ) {
1018 $outStack[$level - 1] .= $out;
1019 array_pop( $outStack );
1020 array_pop( $iteratorStack );
1021 array_pop( $indexStack );
1027 return $outStack[0];
1030 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1031 $args = array_slice( func_get_args(), 2 );
1035 foreach ( $args as $root ) {
1036 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1037 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1038 $root = array( $root );
1040 foreach ( $root as $node ) {
1046 $s .= $this->expand( $node, $flags );
1053 * Implode with no flags specified
1054 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1056 function implode( $sep /*, ... */ ) {
1057 $args = array_slice( func_get_args(), 1 );
1061 foreach ( $args as $root ) {
1062 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1063 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1064 $root = array( $root );
1066 foreach ( $root as $node ) {
1072 $s .= $this->expand( $node );
1079 * Makes an object that, when expand()ed, will be the same as one obtained
1082 function virtualImplode( $sep /*, ... */ ) {
1083 $args = array_slice( func_get_args(), 1 );
1086 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1088 foreach ( $args as $root ) {
1089 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1090 $root = array( $root );
1092 foreach ( $root as $node ) {
1105 * Virtual implode with brackets
1107 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1108 $args = array_slice( func_get_args(), 3 );
1109 $out = array( $start );
1112 foreach ( $args as $root ) {
1113 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1114 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1115 $root = array( $root );
1117 foreach ( $root as $node ) {
1130 function __toString() {
1134 function getPDBK( $level = false ) {
1135 if ( $level === false ) {
1136 return $this->title
->getPrefixedDBkey();
1138 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1143 * Returns true if there are no arguments in this frame
1145 function isEmpty() {
1149 function getArgument( $name ) {
1154 * Returns true if the infinite loop check is OK, false if a loop is detected
1156 function loopCheck( $title ) {
1157 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1161 * Return true if the frame is a template frame
1163 function isTemplate() {
1169 * Expansion frame with template arguments
1172 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1173 var $numberedArgs, $namedArgs, $parent;
1174 var $numberedExpansionCache, $namedExpansionCache;
1176 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1177 $this->preprocessor
= $preprocessor;
1178 $this->parser
= $preprocessor->parser
;
1179 $this->parent
= $parent;
1180 $this->numberedArgs
= $numberedArgs;
1181 $this->namedArgs
= $namedArgs;
1182 $this->title
= $title;
1183 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1184 $this->titleCache
= $parent->titleCache
;
1185 $this->titleCache
[] = $pdbk;
1186 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1187 if ( $pdbk !== false ) {
1188 $this->loopCheckHash
[$pdbk] = true;
1190 $this->depth
= $parent->depth +
1;
1191 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1194 function __toString() {
1197 $args = $this->numberedArgs +
$this->namedArgs
;
1198 foreach ( $args as $name => $value ) {
1204 $s .= "\"$name\":\"" .
1205 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1211 * Returns true if there are no arguments in this frame
1213 function isEmpty() {
1214 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1217 function getNumberedArgument( $index ) {
1218 if ( !isset( $this->numberedArgs
[$index] ) ) {
1221 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1222 # No trimming for unnamed arguments
1223 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1225 return $this->numberedExpansionCache
[$index];
1228 function getNamedArgument( $name ) {
1229 if ( !isset( $this->namedArgs
[$name] ) ) {
1232 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1233 # Trim named arguments post-expand, for backwards compatibility
1234 $this->namedExpansionCache
[$name] = trim(
1235 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1237 return $this->namedExpansionCache
[$name];
1240 function getArgument( $name ) {
1241 $text = $this->getNumberedArgument( $name );
1242 if ( $text === false ) {
1243 $text = $this->getNamedArgument( $name );
1249 * Return true if the frame is a template frame
1251 function isTemplate() {
1259 class PPNode_DOM
implements PPNode
{
1262 function __construct( $node, $xpath = false ) {
1263 $this->node
= $node;
1266 function __get( $name ) {
1267 if ( $name == 'xpath' ) {
1268 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1270 return $this->xpath
;
1273 function __toString() {
1274 if ( $this->node
instanceof DOMNodeList
) {
1276 foreach ( $this->node
as $node ) {
1277 $s .= $node->ownerDocument
->saveXML( $node );
1280 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1285 function getChildren() {
1286 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1289 function getFirstChild() {
1290 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1293 function getNextSibling() {
1294 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1297 function getChildrenOfType( $type ) {
1298 return new self( $this->xpath
->query( $type, $this->node
) );
1301 function getLength() {
1302 if ( $this->node
instanceof DOMNodeList
) {
1303 return $this->node
->length
;
1309 function item( $i ) {
1310 $item = $this->node
->item( $i );
1311 return $item ?
new self( $item ) : false;
1314 function getName() {
1315 if ( $this->node
instanceof DOMNodeList
) {
1318 return $this->node
->nodeName
;
1323 * Split a <part> node into an associative array containing:
1325 * index String index
1326 * value PPNode value
1328 function splitArg() {
1329 $names = $this->xpath
->query( 'name', $this->node
);
1330 $values = $this->xpath
->query( 'value', $this->node
);
1331 if ( !$names->length ||
!$values->length
) {
1332 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1334 $name = $names->item( 0 );
1335 $index = $name->getAttribute( 'index' );
1337 'name' => new self( $name ),
1339 'value' => new self( $values->item( 0 ) ) );
1343 * Split an <ext> node into an associative array containing name, attr, inner and close
1344 * All values in the resulting array are PPNodes. Inner and close are optional.
1346 function splitExt() {
1347 $names = $this->xpath
->query( 'name', $this->node
);
1348 $attrs = $this->xpath
->query( 'attr', $this->node
);
1349 $inners = $this->xpath
->query( 'inner', $this->node
);
1350 $closes = $this->xpath
->query( 'close', $this->node
);
1351 if ( !$names->length ||
!$attrs->length
) {
1352 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1355 'name' => new self( $names->item( 0 ) ),
1356 'attr' => new self( $attrs->item( 0 ) ) );
1357 if ( $inners->length
) {
1358 $parts['inner'] = new self( $inners->item( 0 ) );
1360 if ( $closes->length
) {
1361 $parts['close'] = new self( $closes->item( 0 ) );
1369 function splitHeading() {
1370 if ( !$this->nodeName
== 'h' ) {
1371 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1374 'i' => $this->node
->getAttribute( 'i' ),
1375 'level' => $this->node
->getAttribute( 'level' ),
1376 'contents' => $this->getChildren()