3 class Preprocessor_DOM
implements Preprocessor
{
4 var $parser, $memoryLimit;
6 function __construct( $parser ) {
7 $this->parser
= $parser;
8 $mem = ini_get( 'memory_limit' );
9 $this->memoryLimit
= false;
10 if ( strval( $mem ) !== '' && $mem != -1 ) {
11 if ( preg_match( '/^\d+$/', $mem ) ) {
12 $this->memoryLimit
= $mem;
13 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
14 $this->memoryLimit
= $m[1] * 1048576;
20 return new PPFrame_DOM( $this );
24 if ( $this->memoryLimit
=== false ) {
27 $usage = memory_get_usage();
28 if ( $usage > $this->memoryLimit
* 0.9 ) {
29 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
30 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
32 return $usage <= $this->memoryLimit
* 0.8;
36 * Preprocess some wikitext and return the document tree.
37 * This is the ghost of Parser::replace_variables().
39 * @param string $text The text to parse
40 * @param integer flags Bitwise combination of:
41 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
42 * included. Default is to assume a direct page view.
44 * The generated DOM tree must depend only on the input text and the flags.
45 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
47 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
48 * change in the DOM tree for a given text, must be passed through the section identifier
49 * in the section edit link and thus back to extractSections().
51 * The output of this function is currently only cached in process memory, but a persistent
52 * cache may be implemented at a later date which takes further advantage of these strict
53 * dependency requirements.
57 function preprocessToObj( $text, $flags = 0 ) {
58 wfProfileIn( __METHOD__
);
59 wfProfileIn( __METHOD__
.'-makexml' );
73 'names' => array( 2 => null ),
79 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
81 $xmlishElements = $this->parser
->getStripList();
82 $enableOnlyinclude = false;
83 if ( $forInclusion ) {
84 $ignoredTags = array( 'includeonly', '/includeonly' );
85 $ignoredElements = array( 'noinclude' );
86 $xmlishElements[] = 'noinclude';
87 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
88 $enableOnlyinclude = true;
91 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
92 $ignoredElements = array( 'includeonly' );
93 $xmlishElements[] = 'includeonly';
95 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
97 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
98 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
100 $stack = new PPDStack
;
102 $searchBase = "[{<\n"; #}
103 $revText = strrev( $text ); // For fast reverse searches
105 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
106 $accum =& $stack->getAccum(); # Current accumulator
108 $findEquals = false; # True to find equals signs in arguments
109 $findPipe = false; # True to take notice of pipe characters
111 $inHeading = false; # True if $i is inside a possible heading
112 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
113 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
114 $fakeLineStart = true; # Do a line-start run without outputting an LF character
119 if ( $findOnlyinclude ) {
120 // Ignore all input up to the next <onlyinclude>
121 $startPos = strpos( $text, '<onlyinclude>', $i );
122 if ( $startPos === false ) {
123 // Ignored section runs to the end
124 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
127 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
128 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
130 $findOnlyinclude = false;
133 if ( $fakeLineStart ) {
134 $found = 'line-start';
137 # Find next opening brace, closing brace or pipe
138 $search = $searchBase;
139 if ( $stack->top
=== false ) {
140 $currentClosing = '';
142 $currentClosing = $stack->top
->close
;
143 $search .= $currentClosing;
149 // First equals will be for the template
153 # Output literal section, advance input counter
154 $literalLength = strcspn( $text, $search, $i );
155 if ( $literalLength > 0 ) {
156 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
157 $i +
= $literalLength;
159 if ( $i >= strlen( $text ) ) {
160 if ( $currentClosing == "\n" ) {
161 // Do a past-the-end run to finish off the heading
169 $curChar = $text[$i];
170 if ( $curChar == '|' ) {
172 } elseif ( $curChar == '=' ) {
174 } elseif ( $curChar == '<' ) {
176 } elseif ( $curChar == "\n" ) {
180 $found = 'line-start';
182 } elseif ( $curChar == $currentClosing ) {
184 } elseif ( isset( $rules[$curChar] ) ) {
186 $rule = $rules[$curChar];
188 # Some versions of PHP have a strcspn which stops on null characters
189 # Ignore and continue
196 if ( $found == 'angle' ) {
198 // Handle </onlyinclude>
199 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
200 $findOnlyinclude = true;
204 // Determine element name
205 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
206 // Element name missing or not listed
212 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
213 // To avoid leaving blank lines, when a comment is both preceded
214 // and followed by a newline (ignoring spaces), trim leading and
215 // trailing spaces and one of the newlines.
218 $endPos = strpos( $text, '-->', $i +
4 );
219 if ( $endPos === false ) {
220 // Unclosed comment in input, runs to end
221 $inner = substr( $text, $i );
222 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
223 $i = strlen( $text );
225 // Search backwards for leading whitespace
226 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
227 // Search forwards for trailing whitespace
228 // $wsEnd will be the position of the last space
229 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
230 // Eat the line if possible
231 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
232 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
233 // it's a possible beneficial b/c break.
234 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
235 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
237 $startPos = $wsStart;
238 $endPos = $wsEnd +
1;
239 // Remove leading whitespace from the end of the accumulator
240 // Sanity check first though
241 $wsLength = $i - $wsStart;
242 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
243 $accum = substr( $accum, 0, -$wsLength );
245 // Do a line-start run next time to look for headings after the comment
246 $fakeLineStart = true;
248 // No line to eat, just take the comment itself
254 $part = $stack->top
->getCurrentPart();
255 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
256 // Comments abutting, no change in visual end
257 $part->commentEnd
= $wsEnd;
259 $part->visualEnd
= $wsStart;
260 $part->commentEnd
= $endPos;
264 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
265 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
270 $lowerName = strtolower( $name );
271 $attrStart = $i +
strlen( $name ) +
1;
274 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
275 if ( $tagEndPos === false ) {
276 // Infinite backtrack
277 // Disable tag search to prevent worst-case O(N^2) performance
284 // Handle ignored tags
285 if ( in_array( $lowerName, $ignoredTags ) ) {
286 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
292 if ( $text[$tagEndPos-1] == '/' ) {
293 $attrEnd = $tagEndPos - 1;
298 $attrEnd = $tagEndPos;
300 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
301 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
302 $i = $matches[0][1] +
strlen( $matches[0][0] );
303 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
305 // No end tag -- let it run out to the end of the text.
306 $inner = substr( $text, $tagEndPos +
1 );
307 $i = strlen( $text );
311 // <includeonly> and <noinclude> just become <ignore> tags
312 if ( in_array( $lowerName, $ignoredElements ) ) {
313 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
319 if ( $attrEnd <= $attrStart ) {
322 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
324 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
325 // Note that the attr element contains the whitespace between name and attribute,
326 // this is necessary for precise reconstruction during pre-save transform.
327 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
328 if ( $inner !== null ) {
329 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
331 $accum .= $close . '</ext>';
334 elseif ( $found == 'line-start' ) {
335 // Is this the start of a heading?
336 // Line break belongs before the heading element in any case
337 if ( $fakeLineStart ) {
338 $fakeLineStart = false;
344 $count = strspn( $text, '=', $i, 6 );
345 if ( $count == 1 && $findEquals ) {
346 // DWIM: This looks kind of like a name/value separator
347 // Let's let the equals handler have it and break the potential heading
348 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
349 } elseif ( $count > 0 ) {
353 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
356 $stack->push( $piece );
357 $accum =& $stack->getAccum();
358 extract( $stack->getFlags() );
363 elseif ( $found == 'line-end' ) {
364 $piece = $stack->top
;
365 // A heading must be open, otherwise \n wouldn't have been in the search list
366 assert( $piece->open
== "\n" );
367 $part = $piece->getCurrentPart();
368 // Search back through the input to see if it has a proper close
369 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
370 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
371 $searchStart = $i - $wsLength;
372 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
373 // Comment found at line end
374 // Search for equals signs before the comment
375 $searchStart = $part->visualEnd
;
376 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
378 $count = $piece->count
;
379 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
380 if ( $equalsLength > 0 ) {
381 if ( $i - $equalsLength == $piece->startPos
) {
382 // This is just a single string of equals signs on its own line
383 // Replicate the doHeadings behaviour /={count}(.+)={count}/
384 // First find out how many equals signs there really are (don't stop at 6)
385 $count = $equalsLength;
389 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
392 $count = min( $equalsLength, $count );
395 // Normal match, output <h>
396 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
399 // Single equals sign on its own line, count=0
403 // No match, no <h>, just pass down the inner text
408 $accum =& $stack->getAccum();
409 extract( $stack->getFlags() );
411 // Append the result to the enclosing accumulator
413 // Note that we do NOT increment the input pointer.
414 // This is because the closing linebreak could be the opening linebreak of
415 // another heading. Infinite loops are avoided because the next iteration MUST
416 // hit the heading open case above, which unconditionally increments the
420 elseif ( $found == 'open' ) {
421 # count opening brace characters
422 $count = strspn( $text, $curChar, $i );
424 # we need to add to stack only if opening brace count is enough for one of the rules
425 if ( $count >= $rule['min'] ) {
426 # Add it to the stack
429 'close' => $rule['end'],
431 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
434 $stack->push( $piece );
435 $accum =& $stack->getAccum();
436 extract( $stack->getFlags() );
438 # Add literal brace(s)
439 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
444 elseif ( $found == 'close' ) {
445 $piece = $stack->top
;
446 # lets check if there are enough characters for closing brace
447 $maxCount = $piece->count
;
448 $count = strspn( $text, $curChar, $i, $maxCount );
450 # check for maximum matching characters (if there are 5 closing
451 # characters, we will probably need only 3 - depending on the rules)
453 $rule = $rules[$piece->open
];
454 if ( $count > $rule['max'] ) {
455 # The specified maximum exists in the callback array, unless the caller
457 $matchingCount = $rule['max'];
459 # Count is less than the maximum
460 # Skip any gaps in the callback array to find the true largest match
461 # Need to use array_key_exists not isset because the callback can be null
462 $matchingCount = $count;
463 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
468 if ($matchingCount <= 0) {
469 # No matching element found in callback array
470 # Output a literal closing brace and continue
471 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
475 $name = $rule['names'][$matchingCount];
476 if ( $name === null ) {
477 // No element, just literal text
478 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
481 # Note: $parts is already XML, does not need to be encoded further
482 $parts = $piece->parts
;
483 $title = $parts[0]->out
;
486 # The invocation is at the start of the line if lineStart is set in
487 # the stack, and all opening brackets are used up.
488 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
489 $attr = ' lineStart="1"';
494 $element = "<$name$attr>";
495 $element .= "<title>$title</title>";
497 foreach ( $parts as $partIndex => $part ) {
498 if ( isset( $part->eqpos
) ) {
499 $argName = substr( $part->out
, 0, $part->eqpos
);
500 $argValue = substr( $part->out
, $part->eqpos +
1 );
501 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
503 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
507 $element .= "</$name>";
510 # Advance input pointer
511 $i +
= $matchingCount;
515 $accum =& $stack->getAccum();
517 # Re-add the old stack element if it still has unmatched opening characters remaining
518 if ($matchingCount < $piece->count
) {
519 $piece->parts
= array( new PPDPart
);
520 $piece->count
-= $matchingCount;
521 # do we still qualify for any callback with remaining count?
522 $names = $rules[$piece->open
]['names'];
524 $enclosingAccum =& $accum;
525 while ( $piece->count
) {
526 if ( array_key_exists( $piece->count
, $names ) ) {
527 $stack->push( $piece );
528 $accum =& $stack->getAccum();
534 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
537 extract( $stack->getFlags() );
539 # Add XML element to the enclosing accumulator
543 elseif ( $found == 'pipe' ) {
544 $findEquals = true; // shortcut for getFlags()
546 $accum =& $stack->getAccum();
550 elseif ( $found == 'equals' ) {
551 $findEquals = false; // shortcut for getFlags()
552 $stack->getCurrentPart()->eqpos
= strlen( $accum );
558 # Output any remaining unclosed brackets
559 foreach ( $stack->stack
as $piece ) {
560 $stack->rootAccum
.= $piece->breakSyntax();
562 $stack->rootAccum
.= '</root>';
563 $xml = $stack->rootAccum
;
565 wfProfileOut( __METHOD__
.'-makexml' );
566 wfProfileIn( __METHOD__
.'-loadXML' );
567 $dom = new DOMDocument
;
568 wfSuppressWarnings();
569 $result = $dom->loadXML( $xml );
572 // Try running the XML through UtfNormal to get rid of invalid characters
573 $xml = UtfNormal
::cleanUp( $xml );
574 $result = $dom->loadXML( $xml );
576 throw new MWException( __METHOD__
.' generated invalid XML' );
579 $obj = new PPNode_DOM( $dom->documentElement
);
580 wfProfileOut( __METHOD__
.'-loadXML' );
581 wfProfileOut( __METHOD__
);
587 * Stack class to help Preprocessor::preprocessToObj()
590 var $stack, $rootAccum, $top;
592 var $elementClass = 'PPDStackElement';
594 static $false = false;
596 function __construct() {
597 $this->stack
= array();
599 $this->rootAccum
= '';
600 $this->accum
=& $this->rootAccum
;
604 return count( $this->stack
);
607 function &getAccum() {
611 function getCurrentPart() {
612 if ( $this->top
=== false ) {
615 return $this->top
->getCurrentPart();
619 function push( $data ) {
620 if ( $data instanceof $this->elementClass
) {
621 $this->stack
[] = $data;
623 $class = $this->elementClass
;
624 $this->stack
[] = new $class( $data );
626 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
627 $this->accum
=& $this->top
->getAccum();
631 if ( !count( $this->stack
) ) {
632 throw new MWException( __METHOD__
.': no elements remaining' );
634 $temp = array_pop( $this->stack
);
636 if ( count( $this->stack
) ) {
637 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
638 $this->accum
=& $this->top
->getAccum();
640 $this->top
= self
::$false;
641 $this->accum
=& $this->rootAccum
;
646 function addPart( $s = '' ) {
647 $this->top
->addPart( $s );
648 $this->accum
=& $this->top
->getAccum();
651 function getFlags() {
652 if ( !count( $this->stack
) ) {
654 'findEquals' => false,
656 'inHeading' => false,
659 return $this->top
->getFlags();
664 class PPDStackElement
{
665 var $open, // Opening character (\n for heading)
666 $close, // Matching closing character
667 $count, // Number of opening characters found (number of "=" for heading)
668 $parts, // Array of PPDPart objects describing pipe-separated parts.
669 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
671 var $partClass = 'PPDPart';
673 function __construct( $data = array() ) {
674 $class = $this->partClass
;
675 $this->parts
= array( new $class );
677 foreach ( $data as $name => $value ) {
678 $this->$name = $value;
682 function &getAccum() {
683 return $this->parts
[count($this->parts
) - 1]->out
;
686 function addPart( $s = '' ) {
687 $class = $this->partClass
;
688 $this->parts
[] = new $class( $s );
691 function getCurrentPart() {
692 return $this->parts
[count($this->parts
) - 1];
695 function getFlags() {
696 $partCount = count( $this->parts
);
697 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
699 'findPipe' => $findPipe,
700 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
701 'inHeading' => $this->open
== "\n",
706 * Get the output string that would result if the close is not found.
708 function breakSyntax( $openingCount = false ) {
709 if ( $this->open
== "\n" ) {
710 $s = $this->parts
[0]->out
;
712 if ( $openingCount === false ) {
713 $openingCount = $this->count
;
715 $s = str_repeat( $this->open
, $openingCount );
717 foreach ( $this->parts
as $part ) {
731 var $out; // Output accumulator string
733 // Optional member variables:
734 // eqpos Position of equals sign in output accumulator
735 // commentEnd Past-the-end input pointer for the last comment encountered
736 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
738 function __construct( $out = '' ) {
744 * An expansion frame, used as a context to expand the result of preprocessToObj()
746 class PPFrame_DOM
implements PPFrame
{
747 var $preprocessor, $parser, $title;
751 * Hashtable listing templates which are disallowed for expansion in this frame,
752 * having been encountered previously in parent frames.
757 * Recursion depth of this frame, top = 0
763 * Construct a new preprocessor frame.
764 * @param Preprocessor $preprocessor The parent preprocessor
766 function __construct( $preprocessor ) {
767 $this->preprocessor
= $preprocessor;
768 $this->parser
= $preprocessor->parser
;
769 $this->title
= $this->parser
->mTitle
;
770 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
771 $this->loopCheckHash
= array();
776 * Create a new child frame
777 * $args is optionally a multi-root PPNode or array containing the template arguments
779 function newChild( $args = false, $title = false ) {
780 $namedArgs = array();
781 $numberedArgs = array();
782 if ( $title === false ) {
783 $title = $this->title
;
785 if ( $args !== false ) {
787 if ( $args instanceof PPNode
) {
790 foreach ( $args as $arg ) {
792 $xpath = new DOMXPath( $arg->ownerDocument
);
795 $nameNodes = $xpath->query( 'name', $arg );
796 $value = $xpath->query( 'value', $arg );
797 if ( $nameNodes->item( 0 )->hasAttributes() ) {
798 // Numbered parameter
799 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
800 $numberedArgs[$index] = $value->item( 0 );
801 unset( $namedArgs[$index] );
804 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
805 $namedArgs[$name] = $value->item( 0 );
806 unset( $numberedArgs[$name] );
810 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
813 function expand( $root, $flags = 0 ) {
815 if ( is_string( $root ) ) {
819 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
821 return '<span class="error">Node-count limit exceeded</span>';
824 if ( $depth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
825 return '<span class="error">Expansion depth limit exceeded</span>';
829 if ( $root instanceof PPNode_DOM
) {
832 if ( $root instanceof DOMDocument
) {
833 $root = $root->documentElement
;
836 $outStack = array( '', '' );
837 $iteratorStack = array( false, $root );
838 $indexStack = array( 0, 0 );
840 while ( count( $iteratorStack ) > 1 ) {
841 $level = count( $outStack ) - 1;
842 $iteratorNode =& $iteratorStack[ $level ];
843 $out =& $outStack[$level];
844 $index =& $indexStack[$level];
846 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
848 if ( is_array( $iteratorNode ) ) {
849 if ( $index >= count( $iteratorNode ) ) {
850 // All done with this iterator
851 $iteratorStack[$level] = false;
852 $contextNode = false;
854 $contextNode = $iteratorNode[$index];
857 } elseif ( $iteratorNode instanceof DOMNodeList
) {
858 if ( $index >= $iteratorNode->length
) {
859 // All done with this iterator
860 $iteratorStack[$level] = false;
861 $contextNode = false;
863 $contextNode = $iteratorNode->item( $index );
867 // Copy to $contextNode and then delete from iterator stack,
868 // because this is not an iterator but we do have to execute it once
869 $contextNode = $iteratorStack[$level];
870 $iteratorStack[$level] = false;
873 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
875 $newIterator = false;
877 if ( $contextNode === false ) {
879 } elseif ( is_string( $contextNode ) ) {
880 $out .= $contextNode;
881 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
882 $newIterator = $contextNode;
883 } elseif ( $contextNode instanceof DOMNode
) {
884 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
885 $out .= $contextNode->nodeValue
;
886 } elseif ( $contextNode->nodeName
== 'template' ) {
887 # Double-brace expansion
888 $xpath = new DOMXPath( $contextNode->ownerDocument
);
889 $titles = $xpath->query( 'title', $contextNode );
890 $title = $titles->item( 0 );
891 $parts = $xpath->query( 'part', $contextNode );
892 if ( $flags & self
::NO_TEMPLATES
) {
893 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
895 $lineStart = $contextNode->getAttribute( 'lineStart' );
897 'title' => new PPNode_DOM( $title ),
898 'parts' => new PPNode_DOM( $parts ),
899 'lineStart' => $lineStart );
900 $ret = $this->parser
->braceSubstitution( $params, $this );
901 if ( isset( $ret['object'] ) ) {
902 $newIterator = $ret['object'];
904 $out .= $ret['text'];
907 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
908 # Triple-brace expansion
909 $xpath = new DOMXPath( $contextNode->ownerDocument
);
910 $titles = $xpath->query( 'title', $contextNode );
911 $title = $titles->item( 0 );
912 $parts = $xpath->query( 'part', $contextNode );
913 if ( $flags & self
::NO_ARGS
) {
914 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
917 'title' => new PPNode_DOM( $title ),
918 'parts' => new PPNode_DOM( $parts ) );
919 $ret = $this->parser
->argSubstitution( $params, $this );
920 if ( isset( $ret['object'] ) ) {
921 $newIterator = $ret['object'];
923 $out .= $ret['text'];
926 } elseif ( $contextNode->nodeName
== 'comment' ) {
928 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
929 if ( $this->parser
->ot
['html']
930 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
931 ||
( $flags & self
::STRIP_COMMENTS
) )
935 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
936 # Not in RECOVER_COMMENTS mode (extractSections) though
937 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
938 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
940 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
942 $out .= $contextNode->textContent
;
944 } elseif ( $contextNode->nodeName
== 'ignore' ) {
945 # Output suppression used by <includeonly> etc.
946 # OT_WIKI will only respect <ignore> in substed templates.
947 # The other output types respect it unless NO_IGNORE is set.
948 # extractSections() sets NO_IGNORE and so never respects it.
949 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
950 $out .= $contextNode->textContent
;
954 } elseif ( $contextNode->nodeName
== 'ext' ) {
956 $xpath = new DOMXPath( $contextNode->ownerDocument
);
957 $names = $xpath->query( 'name', $contextNode );
958 $attrs = $xpath->query( 'attr', $contextNode );
959 $inners = $xpath->query( 'inner', $contextNode );
960 $closes = $xpath->query( 'close', $contextNode );
962 'name' => new PPNode_DOM( $names->item( 0 ) ),
963 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
964 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
965 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
967 $out .= $this->parser
->extensionSubstitution( $params, $this );
968 } elseif ( $contextNode->nodeName
== 'h' ) {
970 $s = $this->expand( $contextNode->childNodes
, $flags );
972 # Insert a heading marker only for <h> children of <root>
973 # This is to stop extractSections from going over multiple tree levels
974 if ( $contextNode->parentNode
->nodeName
== 'root'
975 && $this->parser
->ot
['html'] )
977 # Insert heading index marker
978 $headingIndex = $contextNode->getAttribute( 'i' );
979 $titleText = $this->title
->getPrefixedDBkey();
980 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
981 $serial = count( $this->parser
->mHeadings
) - 1;
982 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
983 $count = $contextNode->getAttribute( 'level' );
984 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
985 $this->parser
->mStripState
->general
->setPair( $marker, '' );
989 # Generic recursive expansion
990 $newIterator = $contextNode->childNodes
;
993 throw new MWException( __METHOD__
.': Invalid parameter type' );
996 if ( $newIterator !== false ) {
997 if ( $newIterator instanceof PPNode_DOM
) {
998 $newIterator = $newIterator->node
;
1001 $iteratorStack[] = $newIterator;
1003 } elseif ( $iteratorStack[$level] === false ) {
1004 // Return accumulated value to parent
1005 // With tail recursion
1006 while ( $iteratorStack[$level] === false && $level > 0 ) {
1007 $outStack[$level - 1] .= $out;
1008 array_pop( $outStack );
1009 array_pop( $iteratorStack );
1010 array_pop( $indexStack );
1016 return $outStack[0];
1019 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1020 $args = array_slice( func_get_args(), 2 );
1024 foreach ( $args as $root ) {
1025 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1026 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1027 $root = array( $root );
1029 foreach ( $root as $node ) {
1035 $s .= $this->expand( $node, $flags );
1042 * Implode with no flags specified
1043 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1045 function implode( $sep /*, ... */ ) {
1046 $args = array_slice( func_get_args(), 1 );
1050 foreach ( $args as $root ) {
1051 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1052 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1053 $root = array( $root );
1055 foreach ( $root as $node ) {
1061 $s .= $this->expand( $node );
1068 * Makes an object that, when expand()ed, will be the same as one obtained
1071 function virtualImplode( $sep /*, ... */ ) {
1072 $args = array_slice( func_get_args(), 1 );
1075 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1077 foreach ( $args as $root ) {
1078 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1079 $root = array( $root );
1081 foreach ( $root as $node ) {
1094 * Virtual implode with brackets
1096 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1097 $args = array_slice( func_get_args(), 3 );
1098 $out = array( $start );
1101 foreach ( $args as $root ) {
1102 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1103 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1104 $root = array( $root );
1106 foreach ( $root as $node ) {
1119 function __toString() {
1123 function getPDBK( $level = false ) {
1124 if ( $level === false ) {
1125 return $this->title
->getPrefixedDBkey();
1127 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1132 * Returns true if there are no arguments in this frame
1134 function isEmpty() {
1138 function getArgument( $name ) {
1143 * Returns true if the infinite loop check is OK, false if a loop is detected
1145 function loopCheck( $title ) {
1146 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1150 * Return true if the frame is a template frame
1152 function isTemplate() {
1158 * Expansion frame with template arguments
1160 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1161 var $numberedArgs, $namedArgs, $parent;
1162 var $numberedExpansionCache, $namedExpansionCache;
1164 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1165 $this->preprocessor
= $preprocessor;
1166 $this->parser
= $preprocessor->parser
;
1167 $this->parent
= $parent;
1168 $this->numberedArgs
= $numberedArgs;
1169 $this->namedArgs
= $namedArgs;
1170 $this->title
= $title;
1171 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1172 $this->titleCache
= $parent->titleCache
;
1173 $this->titleCache
[] = $pdbk;
1174 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1175 if ( $pdbk !== false ) {
1176 $this->loopCheckHash
[$pdbk] = true;
1178 $this->depth
= $parent->depth +
1;
1179 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1182 function __toString() {
1185 $args = $this->numberedArgs +
$this->namedArgs
;
1186 foreach ( $args as $name => $value ) {
1192 $s .= "\"$name\":\"" .
1193 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1199 * Returns true if there are no arguments in this frame
1201 function isEmpty() {
1202 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1205 function getNumberedArgument( $index ) {
1206 if ( !isset( $this->numberedArgs
[$index] ) ) {
1209 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1210 # No trimming for unnamed arguments
1211 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1213 return $this->numberedExpansionCache
[$index];
1216 function getNamedArgument( $name ) {
1217 if ( !isset( $this->namedArgs
[$name] ) ) {
1220 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1221 # Trim named arguments post-expand, for backwards compatibility
1222 $this->namedExpansionCache
[$name] = trim(
1223 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1225 return $this->namedExpansionCache
[$name];
1228 function getArgument( $name ) {
1229 $text = $this->getNumberedArgument( $name );
1230 if ( $text === false ) {
1231 $text = $this->getNamedArgument( $name );
1237 * Return true if the frame is a template frame
1239 function isTemplate() {
1244 class PPNode_DOM
implements PPNode
{
1247 function __construct( $node, $xpath = false ) {
1248 $this->node
= $node;
1251 function __get( $name ) {
1252 if ( $name == 'xpath' ) {
1253 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1255 return $this->xpath
;
1258 function __toString() {
1259 if ( $this->node
instanceof DOMNodeList
) {
1261 foreach ( $this->node
as $node ) {
1262 $s .= $node->ownerDocument
->saveXML( $node );
1265 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1270 function getChildren() {
1271 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1274 function getFirstChild() {
1275 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1278 function getNextSibling() {
1279 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1282 function getChildrenOfType( $type ) {
1283 return new self( $this->xpath
->query( $type, $this->node
) );
1286 function getLength() {
1287 if ( $this->node
instanceof DOMNodeList
) {
1288 return $this->node
->length
;
1294 function item( $i ) {
1295 $item = $this->node
->item( $i );
1296 return $item ?
new self( $item ) : false;
1299 function getName() {
1300 if ( $this->node
instanceof DOMNodeList
) {
1303 return $this->node
->nodeName
;
1308 * Split a <part> node into an associative array containing:
1310 * index String index
1311 * value PPNode value
1313 function splitArg() {
1314 $names = $this->xpath
->query( 'name', $this->node
);
1315 $values = $this->xpath
->query( 'value', $this->node
);
1316 if ( !$names->length ||
!$values->length
) {
1317 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1319 $name = $names->item( 0 );
1320 $index = $name->getAttribute( 'index' );
1322 'name' => new self( $name ),
1324 'value' => new self( $values->item( 0 ) ) );
1328 * Split an <ext> node into an associative array containing name, attr, inner and close
1329 * All values in the resulting array are PPNodes. Inner and close are optional.
1331 function splitExt() {
1332 $names = $this->xpath
->query( 'name', $this->node
);
1333 $attrs = $this->xpath
->query( 'attr', $this->node
);
1334 $inners = $this->xpath
->query( 'inner', $this->node
);
1335 $closes = $this->xpath
->query( 'close', $this->node
);
1336 if ( !$names->length ||
!$attrs->length
) {
1337 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1340 'name' => new self( $names->item( 0 ) ),
1341 'attr' => new self( $attrs->item( 0 ) ) );
1342 if ( $inners->length
) {
1343 $parts['inner'] = new self( $inners->item( 0 ) );
1345 if ( $closes->length
) {
1346 $parts['close'] = new self( $closes->item( 0 ) );
1354 function splitHeading() {
1355 if ( !$this->nodeName
== 'h' ) {
1356 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1359 'i' => $this->node
->getAttribute( 'i' ),
1360 'level' => $this->node
->getAttribute( 'level' ),
1361 'contents' => $this->getChildren()