6 class Preprocessor_DOM
implements Preprocessor
{
7 var $parser, $memoryLimit;
9 function __construct( $parser ) {
10 $this->parser
= $parser;
11 $mem = ini_get( 'memory_limit' );
12 $this->memoryLimit
= false;
13 if ( strval( $mem ) !== '' && $mem != -1 ) {
14 if ( preg_match( '/^\d+$/', $mem ) ) {
15 $this->memoryLimit
= $mem;
16 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
17 $this->memoryLimit
= $m[1] * 1048576;
23 return new PPFrame_DOM( $this );
26 function newCustomFrame( $args ) {
27 return new PPCustomFrame_DOM( $this, $args );
31 if ( $this->memoryLimit
=== false ) {
34 $usage = memory_get_usage();
35 if ( $usage > $this->memoryLimit
* 0.9 ) {
36 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
37 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
39 return $usage <= $this->memoryLimit
* 0.8;
43 * Preprocess some wikitext and return the document tree.
44 * This is the ghost of Parser::replace_variables().
46 * @param string $text The text to parse
47 * @param integer flags Bitwise combination of:
48 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
49 * included. Default is to assume a direct page view.
51 * The generated DOM tree must depend only on the input text and the flags.
52 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
54 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
55 * change in the DOM tree for a given text, must be passed through the section identifier
56 * in the section edit link and thus back to extractSections().
58 * The output of this function is currently only cached in process memory, but a persistent
59 * cache may be implemented at a later date which takes further advantage of these strict
60 * dependency requirements.
64 function preprocessToObj( $text, $flags = 0 ) {
65 wfProfileIn( __METHOD__
);
66 wfProfileIn( __METHOD__
.'-makexml' );
80 'names' => array( 2 => null ),
86 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
88 $xmlishElements = $this->parser
->getStripList();
89 $enableOnlyinclude = false;
90 if ( $forInclusion ) {
91 $ignoredTags = array( 'includeonly', '/includeonly' );
92 $ignoredElements = array( 'noinclude' );
93 $xmlishElements[] = 'noinclude';
94 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
95 $enableOnlyinclude = true;
98 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
99 $ignoredElements = array( 'includeonly' );
100 $xmlishElements[] = 'includeonly';
102 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
104 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
105 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
107 $stack = new PPDStack
;
109 $searchBase = "[{<\n"; #}
110 $revText = strrev( $text ); // For fast reverse searches
112 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
113 $accum =& $stack->getAccum(); # Current accumulator
115 $findEquals = false; # True to find equals signs in arguments
116 $findPipe = false; # True to take notice of pipe characters
118 $inHeading = false; # True if $i is inside a possible heading
119 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
120 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
121 $fakeLineStart = true; # Do a line-start run without outputting an LF character
126 if ( $findOnlyinclude ) {
127 // Ignore all input up to the next <onlyinclude>
128 $startPos = strpos( $text, '<onlyinclude>', $i );
129 if ( $startPos === false ) {
130 // Ignored section runs to the end
131 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
134 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
135 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
137 $findOnlyinclude = false;
140 if ( $fakeLineStart ) {
141 $found = 'line-start';
144 # Find next opening brace, closing brace or pipe
145 $search = $searchBase;
146 if ( $stack->top
=== false ) {
147 $currentClosing = '';
149 $currentClosing = $stack->top
->close
;
150 $search .= $currentClosing;
156 // First equals will be for the template
160 # Output literal section, advance input counter
161 $literalLength = strcspn( $text, $search, $i );
162 if ( $literalLength > 0 ) {
163 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
164 $i +
= $literalLength;
166 if ( $i >= strlen( $text ) ) {
167 if ( $currentClosing == "\n" ) {
168 // Do a past-the-end run to finish off the heading
176 $curChar = $text[$i];
177 if ( $curChar == '|' ) {
179 } elseif ( $curChar == '=' ) {
181 } elseif ( $curChar == '<' ) {
183 } elseif ( $curChar == "\n" ) {
187 $found = 'line-start';
189 } elseif ( $curChar == $currentClosing ) {
191 } elseif ( isset( $rules[$curChar] ) ) {
193 $rule = $rules[$curChar];
195 # Some versions of PHP have a strcspn which stops on null characters
196 # Ignore and continue
203 if ( $found == 'angle' ) {
205 // Handle </onlyinclude>
206 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
207 $findOnlyinclude = true;
211 // Determine element name
212 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
213 // Element name missing or not listed
219 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
220 // To avoid leaving blank lines, when a comment is both preceded
221 // and followed by a newline (ignoring spaces), trim leading and
222 // trailing spaces and one of the newlines.
225 $endPos = strpos( $text, '-->', $i +
4 );
226 if ( $endPos === false ) {
227 // Unclosed comment in input, runs to end
228 $inner = substr( $text, $i );
229 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
230 $i = strlen( $text );
232 // Search backwards for leading whitespace
233 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
234 // Search forwards for trailing whitespace
235 // $wsEnd will be the position of the last space
236 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
237 // Eat the line if possible
238 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
239 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
240 // it's a possible beneficial b/c break.
241 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
242 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
244 $startPos = $wsStart;
245 $endPos = $wsEnd +
1;
246 // Remove leading whitespace from the end of the accumulator
247 // Sanity check first though
248 $wsLength = $i - $wsStart;
249 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
250 $accum = substr( $accum, 0, -$wsLength );
252 // Do a line-start run next time to look for headings after the comment
253 $fakeLineStart = true;
255 // No line to eat, just take the comment itself
261 $part = $stack->top
->getCurrentPart();
262 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
263 // Comments abutting, no change in visual end
264 $part->commentEnd
= $wsEnd;
266 $part->visualEnd
= $wsStart;
267 $part->commentEnd
= $endPos;
271 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
272 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
277 $lowerName = strtolower( $name );
278 $attrStart = $i +
strlen( $name ) +
1;
281 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
282 if ( $tagEndPos === false ) {
283 // Infinite backtrack
284 // Disable tag search to prevent worst-case O(N^2) performance
291 // Handle ignored tags
292 if ( in_array( $lowerName, $ignoredTags ) ) {
293 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
299 if ( $text[$tagEndPos-1] == '/' ) {
300 $attrEnd = $tagEndPos - 1;
305 $attrEnd = $tagEndPos;
307 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
308 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
309 $i = $matches[0][1] +
strlen( $matches[0][0] );
310 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
312 // No end tag -- let it run out to the end of the text.
313 $inner = substr( $text, $tagEndPos +
1 );
314 $i = strlen( $text );
318 // <includeonly> and <noinclude> just become <ignore> tags
319 if ( in_array( $lowerName, $ignoredElements ) ) {
320 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
326 if ( $attrEnd <= $attrStart ) {
329 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
331 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
332 // Note that the attr element contains the whitespace between name and attribute,
333 // this is necessary for precise reconstruction during pre-save transform.
334 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
335 if ( $inner !== null ) {
336 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
338 $accum .= $close . '</ext>';
341 elseif ( $found == 'line-start' ) {
342 // Is this the start of a heading?
343 // Line break belongs before the heading element in any case
344 if ( $fakeLineStart ) {
345 $fakeLineStart = false;
351 $count = strspn( $text, '=', $i, 6 );
352 if ( $count == 1 && $findEquals ) {
353 // DWIM: This looks kind of like a name/value separator
354 // Let's let the equals handler have it and break the potential heading
355 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
356 } elseif ( $count > 0 ) {
360 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
363 $stack->push( $piece );
364 $accum =& $stack->getAccum();
365 extract( $stack->getFlags() );
370 elseif ( $found == 'line-end' ) {
371 $piece = $stack->top
;
372 // A heading must be open, otherwise \n wouldn't have been in the search list
373 assert( $piece->open
== "\n" );
374 $part = $piece->getCurrentPart();
375 // Search back through the input to see if it has a proper close
376 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
377 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
378 $searchStart = $i - $wsLength;
379 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
380 // Comment found at line end
381 // Search for equals signs before the comment
382 $searchStart = $part->visualEnd
;
383 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
385 $count = $piece->count
;
386 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
387 if ( $equalsLength > 0 ) {
388 if ( $i - $equalsLength == $piece->startPos
) {
389 // This is just a single string of equals signs on its own line
390 // Replicate the doHeadings behaviour /={count}(.+)={count}/
391 // First find out how many equals signs there really are (don't stop at 6)
392 $count = $equalsLength;
396 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
399 $count = min( $equalsLength, $count );
402 // Normal match, output <h>
403 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
406 // Single equals sign on its own line, count=0
410 // No match, no <h>, just pass down the inner text
415 $accum =& $stack->getAccum();
416 extract( $stack->getFlags() );
418 // Append the result to the enclosing accumulator
420 // Note that we do NOT increment the input pointer.
421 // This is because the closing linebreak could be the opening linebreak of
422 // another heading. Infinite loops are avoided because the next iteration MUST
423 // hit the heading open case above, which unconditionally increments the
427 elseif ( $found == 'open' ) {
428 # count opening brace characters
429 $count = strspn( $text, $curChar, $i );
431 # we need to add to stack only if opening brace count is enough for one of the rules
432 if ( $count >= $rule['min'] ) {
433 # Add it to the stack
436 'close' => $rule['end'],
438 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
441 $stack->push( $piece );
442 $accum =& $stack->getAccum();
443 extract( $stack->getFlags() );
445 # Add literal brace(s)
446 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
451 elseif ( $found == 'close' ) {
452 $piece = $stack->top
;
453 # lets check if there are enough characters for closing brace
454 $maxCount = $piece->count
;
455 $count = strspn( $text, $curChar, $i, $maxCount );
457 # check for maximum matching characters (if there are 5 closing
458 # characters, we will probably need only 3 - depending on the rules)
460 $rule = $rules[$piece->open
];
461 if ( $count > $rule['max'] ) {
462 # The specified maximum exists in the callback array, unless the caller
464 $matchingCount = $rule['max'];
466 # Count is less than the maximum
467 # Skip any gaps in the callback array to find the true largest match
468 # Need to use array_key_exists not isset because the callback can be null
469 $matchingCount = $count;
470 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
475 if ($matchingCount <= 0) {
476 # No matching element found in callback array
477 # Output a literal closing brace and continue
478 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
482 $name = $rule['names'][$matchingCount];
483 if ( $name === null ) {
484 // No element, just literal text
485 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
488 # Note: $parts is already XML, does not need to be encoded further
489 $parts = $piece->parts
;
490 $title = $parts[0]->out
;
493 # The invocation is at the start of the line if lineStart is set in
494 # the stack, and all opening brackets are used up.
495 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
496 $attr = ' lineStart="1"';
501 $element = "<$name$attr>";
502 $element .= "<title>$title</title>";
504 foreach ( $parts as $partIndex => $part ) {
505 if ( isset( $part->eqpos
) ) {
506 $argName = substr( $part->out
, 0, $part->eqpos
);
507 $argValue = substr( $part->out
, $part->eqpos +
1 );
508 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
510 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
514 $element .= "</$name>";
517 # Advance input pointer
518 $i +
= $matchingCount;
522 $accum =& $stack->getAccum();
524 # Re-add the old stack element if it still has unmatched opening characters remaining
525 if ($matchingCount < $piece->count
) {
526 $piece->parts
= array( new PPDPart
);
527 $piece->count
-= $matchingCount;
528 # do we still qualify for any callback with remaining count?
529 $names = $rules[$piece->open
]['names'];
531 $enclosingAccum =& $accum;
532 while ( $piece->count
) {
533 if ( array_key_exists( $piece->count
, $names ) ) {
534 $stack->push( $piece );
535 $accum =& $stack->getAccum();
541 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
544 extract( $stack->getFlags() );
546 # Add XML element to the enclosing accumulator
550 elseif ( $found == 'pipe' ) {
551 $findEquals = true; // shortcut for getFlags()
553 $accum =& $stack->getAccum();
557 elseif ( $found == 'equals' ) {
558 $findEquals = false; // shortcut for getFlags()
559 $stack->getCurrentPart()->eqpos
= strlen( $accum );
565 # Output any remaining unclosed brackets
566 foreach ( $stack->stack
as $piece ) {
567 $stack->rootAccum
.= $piece->breakSyntax();
569 $stack->rootAccum
.= '</root>';
570 $xml = $stack->rootAccum
;
572 wfProfileOut( __METHOD__
.'-makexml' );
573 wfProfileIn( __METHOD__
.'-loadXML' );
574 $dom = new DOMDocument
;
575 wfSuppressWarnings();
576 $result = $dom->loadXML( $xml );
579 // Try running the XML through UtfNormal to get rid of invalid characters
580 $xml = UtfNormal
::cleanUp( $xml );
581 $result = $dom->loadXML( $xml );
583 throw new MWException( __METHOD__
.' generated invalid XML' );
586 $obj = new PPNode_DOM( $dom->documentElement
);
587 wfProfileOut( __METHOD__
.'-loadXML' );
588 wfProfileOut( __METHOD__
);
594 * Stack class to help Preprocessor::preprocessToObj()
598 var $stack, $rootAccum, $top;
600 var $elementClass = 'PPDStackElement';
602 static $false = false;
604 function __construct() {
605 $this->stack
= array();
607 $this->rootAccum
= '';
608 $this->accum
=& $this->rootAccum
;
612 return count( $this->stack
);
615 function &getAccum() {
619 function getCurrentPart() {
620 if ( $this->top
=== false ) {
623 return $this->top
->getCurrentPart();
627 function push( $data ) {
628 if ( $data instanceof $this->elementClass
) {
629 $this->stack
[] = $data;
631 $class = $this->elementClass
;
632 $this->stack
[] = new $class( $data );
634 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
635 $this->accum
=& $this->top
->getAccum();
639 if ( !count( $this->stack
) ) {
640 throw new MWException( __METHOD__
.': no elements remaining' );
642 $temp = array_pop( $this->stack
);
644 if ( count( $this->stack
) ) {
645 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
646 $this->accum
=& $this->top
->getAccum();
648 $this->top
= self
::$false;
649 $this->accum
=& $this->rootAccum
;
654 function addPart( $s = '' ) {
655 $this->top
->addPart( $s );
656 $this->accum
=& $this->top
->getAccum();
659 function getFlags() {
660 if ( !count( $this->stack
) ) {
662 'findEquals' => false,
664 'inHeading' => false,
667 return $this->top
->getFlags();
675 class PPDStackElement
{
676 var $open, // Opening character (\n for heading)
677 $close, // Matching closing character
678 $count, // Number of opening characters found (number of "=" for heading)
679 $parts, // Array of PPDPart objects describing pipe-separated parts.
680 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
682 var $partClass = 'PPDPart';
684 function __construct( $data = array() ) {
685 $class = $this->partClass
;
686 $this->parts
= array( new $class );
688 foreach ( $data as $name => $value ) {
689 $this->$name = $value;
693 function &getAccum() {
694 return $this->parts
[count($this->parts
) - 1]->out
;
697 function addPart( $s = '' ) {
698 $class = $this->partClass
;
699 $this->parts
[] = new $class( $s );
702 function getCurrentPart() {
703 return $this->parts
[count($this->parts
) - 1];
706 function getFlags() {
707 $partCount = count( $this->parts
);
708 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
710 'findPipe' => $findPipe,
711 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
712 'inHeading' => $this->open
== "\n",
717 * Get the output string that would result if the close is not found.
719 function breakSyntax( $openingCount = false ) {
720 if ( $this->open
== "\n" ) {
721 $s = $this->parts
[0]->out
;
723 if ( $openingCount === false ) {
724 $openingCount = $this->count
;
726 $s = str_repeat( $this->open
, $openingCount );
728 foreach ( $this->parts
as $part ) {
745 var $out; // Output accumulator string
747 // Optional member variables:
748 // eqpos Position of equals sign in output accumulator
749 // commentEnd Past-the-end input pointer for the last comment encountered
750 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
752 function __construct( $out = '' ) {
758 * An expansion frame, used as a context to expand the result of preprocessToObj()
761 class PPFrame_DOM
implements PPFrame
{
762 var $preprocessor, $parser, $title;
766 * Hashtable listing templates which are disallowed for expansion in this frame,
767 * having been encountered previously in parent frames.
772 * Recursion depth of this frame, top = 0
778 * Construct a new preprocessor frame.
779 * @param Preprocessor $preprocessor The parent preprocessor
781 function __construct( $preprocessor ) {
782 $this->preprocessor
= $preprocessor;
783 $this->parser
= $preprocessor->parser
;
784 $this->title
= $this->parser
->mTitle
;
785 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
786 $this->loopCheckHash
= array();
791 * Create a new child frame
792 * $args is optionally a multi-root PPNode or array containing the template arguments
794 function newChild( $args = false, $title = false ) {
795 $namedArgs = array();
796 $numberedArgs = array();
797 if ( $title === false ) {
798 $title = $this->title
;
800 if ( $args !== false ) {
802 if ( $args instanceof PPNode
) {
805 foreach ( $args as $arg ) {
807 $xpath = new DOMXPath( $arg->ownerDocument
);
810 $nameNodes = $xpath->query( 'name', $arg );
811 $value = $xpath->query( 'value', $arg );
812 if ( $nameNodes->item( 0 )->hasAttributes() ) {
813 // Numbered parameter
814 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
815 $numberedArgs[$index] = $value->item( 0 );
816 unset( $namedArgs[$index] );
819 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
820 $namedArgs[$name] = $value->item( 0 );
821 unset( $numberedArgs[$name] );
825 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
828 function expand( $root, $flags = 0 ) {
830 if ( is_string( $root ) ) {
834 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
836 return '<span class="error">Node-count limit exceeded</span>';
839 if ( $depth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
840 return '<span class="error">Expansion depth limit exceeded</span>';
844 if ( $root instanceof PPNode_DOM
) {
847 if ( $root instanceof DOMDocument
) {
848 $root = $root->documentElement
;
851 $outStack = array( '', '' );
852 $iteratorStack = array( false, $root );
853 $indexStack = array( 0, 0 );
855 while ( count( $iteratorStack ) > 1 ) {
856 $level = count( $outStack ) - 1;
857 $iteratorNode =& $iteratorStack[ $level ];
858 $out =& $outStack[$level];
859 $index =& $indexStack[$level];
861 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
863 if ( is_array( $iteratorNode ) ) {
864 if ( $index >= count( $iteratorNode ) ) {
865 // All done with this iterator
866 $iteratorStack[$level] = false;
867 $contextNode = false;
869 $contextNode = $iteratorNode[$index];
872 } elseif ( $iteratorNode instanceof DOMNodeList
) {
873 if ( $index >= $iteratorNode->length
) {
874 // All done with this iterator
875 $iteratorStack[$level] = false;
876 $contextNode = false;
878 $contextNode = $iteratorNode->item( $index );
882 // Copy to $contextNode and then delete from iterator stack,
883 // because this is not an iterator but we do have to execute it once
884 $contextNode = $iteratorStack[$level];
885 $iteratorStack[$level] = false;
888 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
890 $newIterator = false;
892 if ( $contextNode === false ) {
894 } elseif ( is_string( $contextNode ) ) {
895 $out .= $contextNode;
896 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
897 $newIterator = $contextNode;
898 } elseif ( $contextNode instanceof DOMNode
) {
899 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
900 $out .= $contextNode->nodeValue
;
901 } elseif ( $contextNode->nodeName
== 'template' ) {
902 # Double-brace expansion
903 $xpath = new DOMXPath( $contextNode->ownerDocument
);
904 $titles = $xpath->query( 'title', $contextNode );
905 $title = $titles->item( 0 );
906 $parts = $xpath->query( 'part', $contextNode );
907 if ( $flags & self
::NO_TEMPLATES
) {
908 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
910 $lineStart = $contextNode->getAttribute( 'lineStart' );
912 'title' => new PPNode_DOM( $title ),
913 'parts' => new PPNode_DOM( $parts ),
914 'lineStart' => $lineStart );
915 $ret = $this->parser
->braceSubstitution( $params, $this );
916 if ( isset( $ret['object'] ) ) {
917 $newIterator = $ret['object'];
919 $out .= $ret['text'];
922 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
923 # Triple-brace expansion
924 $xpath = new DOMXPath( $contextNode->ownerDocument
);
925 $titles = $xpath->query( 'title', $contextNode );
926 $title = $titles->item( 0 );
927 $parts = $xpath->query( 'part', $contextNode );
928 if ( $flags & self
::NO_ARGS
) {
929 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
932 'title' => new PPNode_DOM( $title ),
933 'parts' => new PPNode_DOM( $parts ) );
934 $ret = $this->parser
->argSubstitution( $params, $this );
935 if ( isset( $ret['object'] ) ) {
936 $newIterator = $ret['object'];
938 $out .= $ret['text'];
941 } elseif ( $contextNode->nodeName
== 'comment' ) {
943 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
944 if ( $this->parser
->ot
['html']
945 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
946 ||
( $flags & self
::STRIP_COMMENTS
) )
950 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
951 # Not in RECOVER_COMMENTS mode (extractSections) though
952 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
953 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
955 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
957 $out .= $contextNode->textContent
;
959 } elseif ( $contextNode->nodeName
== 'ignore' ) {
960 # Output suppression used by <includeonly> etc.
961 # OT_WIKI will only respect <ignore> in substed templates.
962 # The other output types respect it unless NO_IGNORE is set.
963 # extractSections() sets NO_IGNORE and so never respects it.
964 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
965 $out .= $contextNode->textContent
;
969 } elseif ( $contextNode->nodeName
== 'ext' ) {
971 $xpath = new DOMXPath( $contextNode->ownerDocument
);
972 $names = $xpath->query( 'name', $contextNode );
973 $attrs = $xpath->query( 'attr', $contextNode );
974 $inners = $xpath->query( 'inner', $contextNode );
975 $closes = $xpath->query( 'close', $contextNode );
977 'name' => new PPNode_DOM( $names->item( 0 ) ),
978 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
979 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
980 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
982 $out .= $this->parser
->extensionSubstitution( $params, $this );
983 } elseif ( $contextNode->nodeName
== 'h' ) {
985 $s = $this->expand( $contextNode->childNodes
, $flags );
987 # Insert a heading marker only for <h> children of <root>
988 # This is to stop extractSections from going over multiple tree levels
989 if ( $contextNode->parentNode
->nodeName
== 'root'
990 && $this->parser
->ot
['html'] )
992 # Insert heading index marker
993 $headingIndex = $contextNode->getAttribute( 'i' );
994 $titleText = $this->title
->getPrefixedDBkey();
995 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
996 $serial = count( $this->parser
->mHeadings
) - 1;
997 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
998 $count = $contextNode->getAttribute( 'level' );
999 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1000 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1004 # Generic recursive expansion
1005 $newIterator = $contextNode->childNodes
;
1008 throw new MWException( __METHOD__
.': Invalid parameter type' );
1011 if ( $newIterator !== false ) {
1012 if ( $newIterator instanceof PPNode_DOM
) {
1013 $newIterator = $newIterator->node
;
1016 $iteratorStack[] = $newIterator;
1018 } elseif ( $iteratorStack[$level] === false ) {
1019 // Return accumulated value to parent
1020 // With tail recursion
1021 while ( $iteratorStack[$level] === false && $level > 0 ) {
1022 $outStack[$level - 1] .= $out;
1023 array_pop( $outStack );
1024 array_pop( $iteratorStack );
1025 array_pop( $indexStack );
1031 return $outStack[0];
1034 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1035 $args = array_slice( func_get_args(), 2 );
1039 foreach ( $args as $root ) {
1040 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1041 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1042 $root = array( $root );
1044 foreach ( $root as $node ) {
1050 $s .= $this->expand( $node, $flags );
1057 * Implode with no flags specified
1058 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1060 function implode( $sep /*, ... */ ) {
1061 $args = array_slice( func_get_args(), 1 );
1065 foreach ( $args as $root ) {
1066 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1067 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1068 $root = array( $root );
1070 foreach ( $root as $node ) {
1076 $s .= $this->expand( $node );
1083 * Makes an object that, when expand()ed, will be the same as one obtained
1086 function virtualImplode( $sep /*, ... */ ) {
1087 $args = array_slice( func_get_args(), 1 );
1090 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1092 foreach ( $args as $root ) {
1093 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1094 $root = array( $root );
1096 foreach ( $root as $node ) {
1109 * Virtual implode with brackets
1111 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1112 $args = array_slice( func_get_args(), 3 );
1113 $out = array( $start );
1116 foreach ( $args as $root ) {
1117 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1118 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1119 $root = array( $root );
1121 foreach ( $root as $node ) {
1134 function __toString() {
1138 function getPDBK( $level = false ) {
1139 if ( $level === false ) {
1140 return $this->title
->getPrefixedDBkey();
1142 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1147 * Returns true if there are no arguments in this frame
1149 function isEmpty() {
1153 function getArgument( $name ) {
1158 * Returns true if the infinite loop check is OK, false if a loop is detected
1160 function loopCheck( $title ) {
1161 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1165 * Return true if the frame is a template frame
1167 function isTemplate() {
1173 * Expansion frame with template arguments
1176 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1177 var $numberedArgs, $namedArgs, $parent;
1178 var $numberedExpansionCache, $namedExpansionCache;
1180 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1181 $this->preprocessor
= $preprocessor;
1182 $this->parser
= $preprocessor->parser
;
1183 $this->parent
= $parent;
1184 $this->numberedArgs
= $numberedArgs;
1185 $this->namedArgs
= $namedArgs;
1186 $this->title
= $title;
1187 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1188 $this->titleCache
= $parent->titleCache
;
1189 $this->titleCache
[] = $pdbk;
1190 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1191 if ( $pdbk !== false ) {
1192 $this->loopCheckHash
[$pdbk] = true;
1194 $this->depth
= $parent->depth +
1;
1195 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1198 function __toString() {
1201 $args = $this->numberedArgs +
$this->namedArgs
;
1202 foreach ( $args as $name => $value ) {
1208 $s .= "\"$name\":\"" .
1209 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1215 * Returns true if there are no arguments in this frame
1217 function isEmpty() {
1218 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1221 function getArguments() {
1222 $arguments = array();
1223 foreach ( array_merge(
1224 array_keys($this->numberedArgs
),
1225 array_keys($this->namedArgs
)) as $key ) {
1226 $arguments[$key] = $this->getArgument($key);
1231 function getNumberedArguments() {
1232 $arguments = array();
1233 foreach ( array_keys($this->numberedArgs
) as $key ) {
1234 $arguments[$key] = $this->getArgument($key);
1239 function getNamedArguments() {
1240 $arguments = array();
1241 foreach ( array_keys($this->namedArgs
) as $key ) {
1242 $arguments[$key] = $this->getArgument($key);
1247 function getNumberedArgument( $index ) {
1248 if ( !isset( $this->numberedArgs
[$index] ) ) {
1251 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1252 # No trimming for unnamed arguments
1253 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1255 return $this->numberedExpansionCache
[$index];
1258 function getNamedArgument( $name ) {
1259 if ( !isset( $this->namedArgs
[$name] ) ) {
1262 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1263 # Trim named arguments post-expand, for backwards compatibility
1264 $this->namedExpansionCache
[$name] = trim(
1265 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1267 return $this->namedExpansionCache
[$name];
1270 function getArgument( $name ) {
1271 $text = $this->getNumberedArgument( $name );
1272 if ( $text === false ) {
1273 $text = $this->getNamedArgument( $name );
1279 * Return true if the frame is a template frame
1281 function isTemplate() {
1287 * Expansion frame with custom arguments
1290 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1293 function __construct( $preprocessor, $args ) {
1294 $this->preprocessor
= $preprocessor;
1295 $this->parser
= $preprocessor->parser
;
1296 $this->args
= $args;
1299 function __toString() {
1302 foreach ( $this->args
as $name => $value ) {
1308 $s .= "\"$name\":\"" .
1309 str_replace( '"', '\\"', $value->__toString() ) . '"';
1315 function isEmpty() {
1316 return !count( $this->args
);
1319 function getArgument( $index ) {
1320 return $this->args
[$index];
1327 class PPNode_DOM
implements PPNode
{
1330 function __construct( $node, $xpath = false ) {
1331 $this->node
= $node;
1334 function __get( $name ) {
1335 if ( $name == 'xpath' ) {
1336 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1338 return $this->xpath
;
1341 function __toString() {
1342 if ( $this->node
instanceof DOMNodeList
) {
1344 foreach ( $this->node
as $node ) {
1345 $s .= $node->ownerDocument
->saveXML( $node );
1348 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1353 function getChildren() {
1354 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1357 function getFirstChild() {
1358 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1361 function getNextSibling() {
1362 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1365 function getChildrenOfType( $type ) {
1366 return new self( $this->xpath
->query( $type, $this->node
) );
1369 function getLength() {
1370 if ( $this->node
instanceof DOMNodeList
) {
1371 return $this->node
->length
;
1377 function item( $i ) {
1378 $item = $this->node
->item( $i );
1379 return $item ?
new self( $item ) : false;
1382 function getName() {
1383 if ( $this->node
instanceof DOMNodeList
) {
1386 return $this->node
->nodeName
;
1391 * Split a <part> node into an associative array containing:
1393 * index String index
1394 * value PPNode value
1396 function splitArg() {
1397 $names = $this->xpath
->query( 'name', $this->node
);
1398 $values = $this->xpath
->query( 'value', $this->node
);
1399 if ( !$names->length ||
!$values->length
) {
1400 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1402 $name = $names->item( 0 );
1403 $index = $name->getAttribute( 'index' );
1405 'name' => new self( $name ),
1407 'value' => new self( $values->item( 0 ) ) );
1411 * Split an <ext> node into an associative array containing name, attr, inner and close
1412 * All values in the resulting array are PPNodes. Inner and close are optional.
1414 function splitExt() {
1415 $names = $this->xpath
->query( 'name', $this->node
);
1416 $attrs = $this->xpath
->query( 'attr', $this->node
);
1417 $inners = $this->xpath
->query( 'inner', $this->node
);
1418 $closes = $this->xpath
->query( 'close', $this->node
);
1419 if ( !$names->length ||
!$attrs->length
) {
1420 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1423 'name' => new self( $names->item( 0 ) ),
1424 'attr' => new self( $attrs->item( 0 ) ) );
1425 if ( $inners->length
) {
1426 $parts['inner'] = new self( $inners->item( 0 ) );
1428 if ( $closes->length
) {
1429 $parts['close'] = new self( $closes->item( 0 ) );
1437 function splitHeading() {
1438 if ( !$this->nodeName
== 'h' ) {
1439 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1442 'i' => $this->node
->getAttribute( 'i' ),
1443 'level' => $this->node
->getAttribute( 'level' ),
1444 'contents' => $this->getChildren()