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 $attrStart = $i +
strlen( $name ) +
1;
273 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
274 if ( $tagEndPos === false ) {
275 // Infinite backtrack
276 // Disable tag search to prevent worst-case O(N^2) performance
283 // Handle ignored tags
284 if ( in_array( $name, $ignoredTags ) ) {
285 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
291 if ( $text[$tagEndPos-1] == '/' ) {
292 $attrEnd = $tagEndPos - 1;
297 $attrEnd = $tagEndPos;
299 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
300 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
301 $i = $matches[0][1] +
strlen( $matches[0][0] );
302 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
304 // No end tag -- let it run out to the end of the text.
305 $inner = substr( $text, $tagEndPos +
1 );
306 $i = strlen( $text );
310 // <includeonly> and <noinclude> just become <ignore> tags
311 if ( in_array( $name, $ignoredElements ) ) {
312 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
318 if ( $attrEnd <= $attrStart ) {
321 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
323 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
324 // Note that the attr element contains the whitespace between name and attribute,
325 // this is necessary for precise reconstruction during pre-save transform.
326 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
327 if ( $inner !== null ) {
328 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
330 $accum .= $close . '</ext>';
333 elseif ( $found == 'line-start' ) {
334 // Is this the start of a heading?
335 // Line break belongs before the heading element in any case
336 if ( $fakeLineStart ) {
337 $fakeLineStart = false;
343 $count = strspn( $text, '=', $i, 6 );
344 if ( $count == 1 && $findEquals ) {
345 // DWIM: This looks kind of like a name/value separator
346 // Let's let the equals handler have it and break the potential heading
347 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
348 } elseif ( $count > 0 ) {
352 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
355 $stack->push( $piece );
356 $accum =& $stack->getAccum();
357 extract( $stack->getFlags() );
362 elseif ( $found == 'line-end' ) {
363 $piece = $stack->top
;
364 // A heading must be open, otherwise \n wouldn't have been in the search list
365 assert( $piece->open
== "\n" );
366 $part = $piece->getCurrentPart();
367 // Search back through the input to see if it has a proper close
368 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
369 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
370 $searchStart = $i - $wsLength;
371 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
372 // Comment found at line end
373 // Search for equals signs before the comment
374 $searchStart = $part->visualEnd
;
375 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
377 $count = $piece->count
;
378 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
379 if ( $equalsLength > 0 ) {
380 if ( $i - $equalsLength == $piece->startPos
) {
381 // This is just a single string of equals signs on its own line
382 // Replicate the doHeadings behaviour /={count}(.+)={count}/
383 // First find out how many equals signs there really are (don't stop at 6)
384 $count = $equalsLength;
388 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
391 $count = min( $equalsLength, $count );
394 // Normal match, output <h>
395 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
398 // Single equals sign on its own line, count=0
402 // No match, no <h>, just pass down the inner text
407 $accum =& $stack->getAccum();
408 extract( $stack->getFlags() );
410 // Append the result to the enclosing accumulator
412 // Note that we do NOT increment the input pointer.
413 // This is because the closing linebreak could be the opening linebreak of
414 // another heading. Infinite loops are avoided because the next iteration MUST
415 // hit the heading open case above, which unconditionally increments the
419 elseif ( $found == 'open' ) {
420 # count opening brace characters
421 $count = strspn( $text, $curChar, $i );
423 # we need to add to stack only if opening brace count is enough for one of the rules
424 if ( $count >= $rule['min'] ) {
425 # Add it to the stack
428 'close' => $rule['end'],
430 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
433 $stack->push( $piece );
434 $accum =& $stack->getAccum();
435 extract( $stack->getFlags() );
437 # Add literal brace(s)
438 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
443 elseif ( $found == 'close' ) {
444 $piece = $stack->top
;
445 # lets check if there are enough characters for closing brace
446 $maxCount = $piece->count
;
447 $count = strspn( $text, $curChar, $i, $maxCount );
449 # check for maximum matching characters (if there are 5 closing
450 # characters, we will probably need only 3 - depending on the rules)
452 $rule = $rules[$piece->open
];
453 if ( $count > $rule['max'] ) {
454 # The specified maximum exists in the callback array, unless the caller
456 $matchingCount = $rule['max'];
458 # Count is less than the maximum
459 # Skip any gaps in the callback array to find the true largest match
460 # Need to use array_key_exists not isset because the callback can be null
461 $matchingCount = $count;
462 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
467 if ($matchingCount <= 0) {
468 # No matching element found in callback array
469 # Output a literal closing brace and continue
470 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
474 $name = $rule['names'][$matchingCount];
475 if ( $name === null ) {
476 // No element, just literal text
477 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
480 # Note: $parts is already XML, does not need to be encoded further
481 $parts = $piece->parts
;
482 $title = $parts[0]->out
;
485 # The invocation is at the start of the line if lineStart is set in
486 # the stack, and all opening brackets are used up.
487 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
488 $attr = ' lineStart="1"';
493 $element = "<$name$attr>";
494 $element .= "<title>$title</title>";
496 foreach ( $parts as $partIndex => $part ) {
497 if ( isset( $part->eqpos
) ) {
498 $argName = substr( $part->out
, 0, $part->eqpos
);
499 $argValue = substr( $part->out
, $part->eqpos +
1 );
500 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
502 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
506 $element .= "</$name>";
509 # Advance input pointer
510 $i +
= $matchingCount;
514 $accum =& $stack->getAccum();
516 # Re-add the old stack element if it still has unmatched opening characters remaining
517 if ($matchingCount < $piece->count
) {
518 $piece->parts
= array( new PPDPart
);
519 $piece->count
-= $matchingCount;
520 # do we still qualify for any callback with remaining count?
521 $names = $rules[$piece->open
]['names'];
523 $enclosingAccum =& $accum;
524 while ( $piece->count
) {
525 if ( array_key_exists( $piece->count
, $names ) ) {
526 $stack->push( $piece );
527 $accum =& $stack->getAccum();
533 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
536 extract( $stack->getFlags() );
538 # Add XML element to the enclosing accumulator
542 elseif ( $found == 'pipe' ) {
543 $findEquals = true; // shortcut for getFlags()
545 $accum =& $stack->getAccum();
549 elseif ( $found == 'equals' ) {
550 $findEquals = false; // shortcut for getFlags()
551 $stack->getCurrentPart()->eqpos
= strlen( $accum );
557 # Output any remaining unclosed brackets
558 foreach ( $stack->stack
as $piece ) {
559 $stack->rootAccum
.= $piece->breakSyntax();
561 $stack->rootAccum
.= '</root>';
562 $xml = $stack->rootAccum
;
564 wfProfileOut( __METHOD__
.'-makexml' );
565 wfProfileIn( __METHOD__
.'-loadXML' );
566 $dom = new DOMDocument
;
567 wfSuppressWarnings();
568 $result = $dom->loadXML( $xml );
571 // Try running the XML through UtfNormal to get rid of invalid characters
572 $xml = UtfNormal
::cleanUp( $xml );
573 $result = $dom->loadXML( $xml );
575 throw new MWException( __METHOD__
.' generated invalid XML' );
578 $obj = new PPNode_DOM( $dom->documentElement
);
579 wfProfileOut( __METHOD__
.'-loadXML' );
580 wfProfileOut( __METHOD__
);
586 * Stack class to help Preprocessor::preprocessToObj()
589 var $stack, $rootAccum, $top;
591 var $elementClass = 'PPDStackElement';
593 static $false = false;
595 function __construct() {
596 $this->stack
= array();
598 $this->rootAccum
= '';
599 $this->accum
=& $this->rootAccum
;
603 return count( $this->stack
);
606 function &getAccum() {
610 function getCurrentPart() {
611 if ( $this->top
=== false ) {
614 return $this->top
->getCurrentPart();
618 function push( $data ) {
619 if ( $data instanceof $this->elementClass
) {
620 $this->stack
[] = $data;
622 $class = $this->elementClass
;
623 $this->stack
[] = new $class( $data );
625 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
626 $this->accum
=& $this->top
->getAccum();
630 if ( !count( $this->stack
) ) {
631 throw new MWException( __METHOD__
.': no elements remaining' );
633 $temp = array_pop( $this->stack
);
635 if ( count( $this->stack
) ) {
636 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
637 $this->accum
=& $this->top
->getAccum();
639 $this->top
= self
::$false;
640 $this->accum
=& $this->rootAccum
;
645 function addPart( $s = '' ) {
646 $this->top
->addPart( $s );
647 $this->accum
=& $this->top
->getAccum();
650 function getFlags() {
651 if ( !count( $this->stack
) ) {
653 'findEquals' => false,
655 'inHeading' => false,
658 return $this->top
->getFlags();
663 class PPDStackElement
{
664 var $open, // Opening character (\n for heading)
665 $close, // Matching closing character
666 $count, // Number of opening characters found (number of "=" for heading)
667 $parts, // Array of PPDPart objects describing pipe-separated parts.
668 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
670 var $partClass = 'PPDPart';
672 function __construct( $data = array() ) {
673 $class = $this->partClass
;
674 $this->parts
= array( new $class );
676 foreach ( $data as $name => $value ) {
677 $this->$name = $value;
681 function &getAccum() {
682 return $this->parts
[count($this->parts
) - 1]->out
;
685 function addPart( $s = '' ) {
686 $class = $this->partClass
;
687 $this->parts
[] = new $class( $s );
690 function getCurrentPart() {
691 return $this->parts
[count($this->parts
) - 1];
694 function getFlags() {
695 $partCount = count( $this->parts
);
696 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
698 'findPipe' => $findPipe,
699 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
700 'inHeading' => $this->open
== "\n",
705 * Get the output string that would result if the close is not found.
707 function breakSyntax( $openingCount = false ) {
708 if ( $this->open
== "\n" ) {
709 $s = $this->parts
[0]->out
;
711 if ( $openingCount === false ) {
712 $openingCount = $this->count
;
714 $s = str_repeat( $this->open
, $openingCount );
716 foreach ( $this->parts
as $part ) {
730 var $out; // Output accumulator string
732 // Optional member variables:
733 // eqpos Position of equals sign in output accumulator
734 // commentEnd Past-the-end input pointer for the last comment encountered
735 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
737 function __construct( $out = '' ) {
743 * An expansion frame, used as a context to expand the result of preprocessToObj()
745 class PPFrame_DOM
implements PPFrame
{
746 var $preprocessor, $parser, $title;
750 * Hashtable listing templates which are disallowed for expansion in this frame,
751 * having been encountered previously in parent frames.
756 * Recursion depth of this frame, top = 0
762 * Construct a new preprocessor frame.
763 * @param Preprocessor $preprocessor The parent preprocessor
765 function __construct( $preprocessor ) {
766 $this->preprocessor
= $preprocessor;
767 $this->parser
= $preprocessor->parser
;
768 $this->title
= $this->parser
->mTitle
;
769 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
770 $this->loopCheckHash
= array();
775 * Create a new child frame
776 * $args is optionally a multi-root PPNode or array containing the template arguments
778 function newChild( $args = false, $title = false ) {
779 $namedArgs = array();
780 $numberedArgs = array();
781 if ( $title === false ) {
782 $title = $this->title
;
784 if ( $args !== false ) {
786 if ( $args instanceof PPNode
) {
789 foreach ( $args as $arg ) {
791 $xpath = new DOMXPath( $arg->ownerDocument
);
794 $nameNodes = $xpath->query( 'name', $arg );
795 $value = $xpath->query( 'value', $arg );
796 if ( $nameNodes->item( 0 )->hasAttributes() ) {
797 // Numbered parameter
798 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
799 $numberedArgs[$index] = $value->item( 0 );
800 unset( $namedArgs[$index] );
803 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
804 $namedArgs[$name] = $value->item( 0 );
805 unset( $numberedArgs[$name] );
809 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
812 function expand( $root, $flags = 0 ) {
813 if ( is_string( $root ) ) {
817 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
819 return '<span class="error">Node-count limit exceeded</span>';
822 if ( $root instanceof PPNode_DOM
) {
825 if ( $root instanceof DOMDocument
) {
826 $root = $root->documentElement
;
829 $outStack = array( '', '' );
830 $iteratorStack = array( false, $root );
831 $indexStack = array( 0, 0 );
833 while ( count( $iteratorStack ) > 1 ) {
834 $level = count( $outStack ) - 1;
835 $iteratorNode =& $iteratorStack[ $level ];
836 $out =& $outStack[$level];
837 $index =& $indexStack[$level];
839 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
841 if ( is_array( $iteratorNode ) ) {
842 if ( $index >= count( $iteratorNode ) ) {
843 // All done with this iterator
844 $iteratorStack[$level] = false;
845 $contextNode = false;
847 $contextNode = $iteratorNode[$index];
850 } elseif ( $iteratorNode instanceof DOMNodeList
) {
851 if ( $index >= $iteratorNode->length
) {
852 // All done with this iterator
853 $iteratorStack[$level] = false;
854 $contextNode = false;
856 $contextNode = $iteratorNode->item( $index );
860 // Copy to $contextNode and then delete from iterator stack,
861 // because this is not an iterator but we do have to execute it once
862 $contextNode = $iteratorStack[$level];
863 $iteratorStack[$level] = false;
866 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
868 $newIterator = false;
870 if ( $contextNode === false ) {
872 } elseif ( is_string( $contextNode ) ) {
873 $out .= $contextNode;
874 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
875 $newIterator = $contextNode;
876 } elseif ( $contextNode instanceof DOMNode
) {
877 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
878 $out .= $contextNode->nodeValue
;
879 } elseif ( $contextNode->nodeName
== 'template' ) {
880 # Double-brace expansion
881 $xpath = new DOMXPath( $contextNode->ownerDocument
);
882 $titles = $xpath->query( 'title', $contextNode );
883 $title = $titles->item( 0 );
884 $parts = $xpath->query( 'part', $contextNode );
885 if ( $flags & self
::NO_TEMPLATES
) {
886 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
888 $lineStart = $contextNode->getAttribute( 'lineStart' );
890 'title' => new PPNode_DOM( $title ),
891 'parts' => new PPNode_DOM( $parts ),
892 'lineStart' => $lineStart );
893 $ret = $this->parser
->braceSubstitution( $params, $this );
894 if ( isset( $ret['object'] ) ) {
895 $newIterator = $ret['object'];
897 $out .= $ret['text'];
900 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
901 # Triple-brace expansion
902 $xpath = new DOMXPath( $contextNode->ownerDocument
);
903 $titles = $xpath->query( 'title', $contextNode );
904 $title = $titles->item( 0 );
905 $parts = $xpath->query( 'part', $contextNode );
906 if ( $flags & self
::NO_ARGS
) {
907 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
910 'title' => new PPNode_DOM( $title ),
911 'parts' => new PPNode_DOM( $parts ) );
912 $ret = $this->parser
->argSubstitution( $params, $this );
913 if ( isset( $ret['object'] ) ) {
914 $newIterator = $ret['object'];
916 $out .= $ret['text'];
919 } elseif ( $contextNode->nodeName
== 'comment' ) {
921 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
922 if ( $this->parser
->ot
['html']
923 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
924 ||
( $flags & self
::STRIP_COMMENTS
) )
928 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
929 # Not in RECOVER_COMMENTS mode (extractSections) though
930 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
931 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
933 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
935 $out .= $contextNode->textContent
;
937 } elseif ( $contextNode->nodeName
== 'ignore' ) {
938 # Output suppression used by <includeonly> etc.
939 # OT_WIKI will only respect <ignore> in substed templates.
940 # The other output types respect it unless NO_IGNORE is set.
941 # extractSections() sets NO_IGNORE and so never respects it.
942 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
943 $out .= $contextNode->textContent
;
947 } elseif ( $contextNode->nodeName
== 'ext' ) {
949 $xpath = new DOMXPath( $contextNode->ownerDocument
);
950 $names = $xpath->query( 'name', $contextNode );
951 $attrs = $xpath->query( 'attr', $contextNode );
952 $inners = $xpath->query( 'inner', $contextNode );
953 $closes = $xpath->query( 'close', $contextNode );
955 'name' => new PPNode_DOM( $names->item( 0 ) ),
956 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
957 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
958 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
960 $out .= $this->parser
->extensionSubstitution( $params, $this );
961 } elseif ( $contextNode->nodeName
== 'h' ) {
963 $s = $this->expand( $contextNode->childNodes
, $flags );
965 # Insert a heading marker only for <h> children of <root>
966 # This is to stop extractSections from going over multiple tree levels
967 if ( $contextNode->parentNode
->nodeName
== 'root'
968 && $this->parser
->ot
['html'] )
970 # Insert heading index marker
971 $headingIndex = $contextNode->getAttribute( 'i' );
972 $titleText = $this->title
->getPrefixedDBkey();
973 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
974 $serial = count( $this->parser
->mHeadings
) - 1;
975 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
976 $count = $contextNode->getAttribute( 'level' );
977 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
978 $this->parser
->mStripState
->general
->setPair( $marker, '' );
982 # Generic recursive expansion
983 $newIterator = $contextNode->childNodes
;
986 throw new MWException( __METHOD__
.': Invalid parameter type' );
989 if ( $newIterator !== false ) {
990 if ( $newIterator instanceof PPNode_DOM
) {
991 $newIterator = $newIterator->node
;
994 $iteratorStack[] = $newIterator;
996 } elseif ( $iteratorStack[$level] === false ) {
997 // Return accumulated value to parent
998 // With tail recursion
999 while ( $iteratorStack[$level] === false && $level > 0 ) {
1000 $outStack[$level - 1] .= $out;
1001 array_pop( $outStack );
1002 array_pop( $iteratorStack );
1003 array_pop( $indexStack );
1008 return $outStack[0];
1011 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1012 $args = array_slice( func_get_args(), 2 );
1016 foreach ( $args as $root ) {
1017 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1018 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1019 $root = array( $root );
1021 foreach ( $root as $node ) {
1027 $s .= $this->expand( $node, $flags );
1034 * Implode with no flags specified
1035 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1037 function implode( $sep /*, ... */ ) {
1038 $args = array_slice( func_get_args(), 1 );
1042 foreach ( $args as $root ) {
1043 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1044 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1045 $root = array( $root );
1047 foreach ( $root as $node ) {
1053 $s .= $this->expand( $node );
1060 * Makes an object that, when expand()ed, will be the same as one obtained
1063 function virtualImplode( $sep /*, ... */ ) {
1064 $args = array_slice( func_get_args(), 1 );
1067 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1069 foreach ( $args as $root ) {
1070 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1071 $root = array( $root );
1073 foreach ( $root as $node ) {
1086 * Virtual implode with brackets
1088 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1089 $args = array_slice( func_get_args(), 3 );
1090 $out = array( $start );
1093 foreach ( $args as $root ) {
1094 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1095 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1096 $root = array( $root );
1098 foreach ( $root as $node ) {
1111 function __toString() {
1115 function getPDBK( $level = false ) {
1116 if ( $level === false ) {
1117 return $this->title
->getPrefixedDBkey();
1119 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1124 * Returns true if there are no arguments in this frame
1126 function isEmpty() {
1130 function getArgument( $name ) {
1135 * Returns true if the infinite loop check is OK, false if a loop is detected
1137 function loopCheck( $title ) {
1138 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1142 * Return true if the frame is a template frame
1144 function isTemplate() {
1150 * Expansion frame with template arguments
1152 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1153 var $numberedArgs, $namedArgs, $parent;
1154 var $numberedExpansionCache, $namedExpansionCache;
1156 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1157 $this->preprocessor
= $preprocessor;
1158 $this->parser
= $preprocessor->parser
;
1159 $this->parent
= $parent;
1160 $this->numberedArgs
= $numberedArgs;
1161 $this->namedArgs
= $namedArgs;
1162 $this->title
= $title;
1163 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1164 $this->titleCache
= $parent->titleCache
;
1165 $this->titleCache
[] = $pdbk;
1166 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1167 if ( $pdbk !== false ) {
1168 $this->loopCheckHash
[$pdbk] = true;
1170 $this->depth
= $parent->depth +
1;
1171 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1174 function __toString() {
1177 $args = $this->numberedArgs +
$this->namedArgs
;
1178 foreach ( $args as $name => $value ) {
1184 $s .= "\"$name\":\"" .
1185 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1191 * Returns true if there are no arguments in this frame
1193 function isEmpty() {
1194 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1197 function getNumberedArgument( $index ) {
1198 if ( !isset( $this->numberedArgs
[$index] ) ) {
1201 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1202 # No trimming for unnamed arguments
1203 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1205 return $this->numberedExpansionCache
[$index];
1208 function getNamedArgument( $name ) {
1209 if ( !isset( $this->namedArgs
[$name] ) ) {
1212 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1213 # Trim named arguments post-expand, for backwards compatibility
1214 $this->namedExpansionCache
[$name] = trim(
1215 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1217 return $this->namedExpansionCache
[$name];
1220 function getArgument( $name ) {
1221 $text = $this->getNumberedArgument( $name );
1222 if ( $text === false ) {
1223 $text = $this->getNamedArgument( $name );
1229 * Return true if the frame is a template frame
1231 function isTemplate() {
1236 class PPNode_DOM
implements PPNode
{
1239 function __construct( $node, $xpath = false ) {
1240 $this->node
= $node;
1243 function __get( $name ) {
1244 if ( $name == 'xpath' ) {
1245 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1247 return $this->xpath
;
1250 function __toString() {
1251 if ( $this->node
instanceof DOMNodeList
) {
1253 foreach ( $this->node
as $node ) {
1254 $s .= $node->ownerDocument
->saveXML( $node );
1257 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1262 function getChildren() {
1263 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1266 function getFirstChild() {
1267 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1270 function getNextSibling() {
1271 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1274 function getChildrenOfType( $type ) {
1275 return new self( $this->xpath
->query( $type, $this->node
) );
1278 function getLength() {
1279 if ( $this->node
instanceof DOMNodeList
) {
1280 return $this->node
->length
;
1286 function item( $i ) {
1287 $item = $this->node
->item( $i );
1288 return $item ?
new self( $item ) : false;
1291 function getName() {
1292 if ( $this->node
instanceof DOMNodeList
) {
1295 return $this->node
->nodeName
;
1300 * Split a <part> node into an associative array containing:
1302 * index String index
1303 * value PPNode value
1305 function splitArg() {
1306 $names = $this->xpath
->query( 'name', $this->node
);
1307 $values = $this->xpath
->query( 'value', $this->node
);
1308 if ( !$names->length ||
!$values->length
) {
1309 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1311 $name = $names->item( 0 );
1312 $index = $name->getAttribute( 'index' );
1314 'name' => new self( $name ),
1316 'value' => new self( $values->item( 0 ) ) );
1320 * Split an <ext> node into an associative array containing name, attr, inner and close
1321 * All values in the resulting array are PPNodes. Inner and close are optional.
1323 function splitExt() {
1324 $names = $this->xpath
->query( 'name', $this->node
);
1325 $attrs = $this->xpath
->query( 'attr', $this->node
);
1326 $inners = $this->xpath
->query( 'inner', $this->node
);
1327 $closes = $this->xpath
->query( 'close', $this->node
);
1328 if ( !$names->length ||
!$attrs->length
) {
1329 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1332 'name' => new self( $names->item( 0 ) ),
1333 'attr' => new self( $attrs->item( 0 ) ) );
1334 if ( $inners->length
) {
1335 $parts['inner'] = new self( $inners->item( 0 ) );
1337 if ( $closes->length
) {
1338 $parts['close'] = new self( $closes->item( 0 ) );
1346 function splitHeading() {
1347 if ( !$this->nodeName
== 'h' ) {
1348 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1351 'i' => $this->node
->getAttribute( 'i' ),
1352 'level' => $this->node
->getAttribute( 'level' ),
1353 'contents' => $this->getChildren()