6 class Preprocessor_DOM
implements Preprocessor
{
7 var $parser, $memoryLimit;
9 const CACHE_VERSION
= 1;
11 function __construct( $parser ) {
12 $this->parser
= $parser;
13 $mem = ini_get( 'memory_limit' );
14 $this->memoryLimit
= false;
15 if ( strval( $mem ) !== '' && $mem != -1 ) {
16 if ( preg_match( '/^\d+$/', $mem ) ) {
17 $this->memoryLimit
= $mem;
18 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
19 $this->memoryLimit
= $m[1] * 1048576;
25 return new PPFrame_DOM( $this );
28 function newCustomFrame( $args ) {
29 return new PPCustomFrame_DOM( $this, $args );
32 function newPartNodeArray( $values ) {
33 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
37 foreach ( $values as $k => $val ) {
40 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
42 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
48 $dom = new DOMDocument();
49 $dom->loadXML( $xml );
50 $root = $dom->documentElement
;
52 $node = new PPNode_DOM( $root->childNodes
);
57 if ( $this->memoryLimit
=== false ) {
60 $usage = memory_get_usage();
61 if ( $usage > $this->memoryLimit
* 0.9 ) {
62 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
63 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
65 return $usage <= $this->memoryLimit
* 0.8;
69 * Preprocess some wikitext and return the document tree.
70 * This is the ghost of Parser::replace_variables().
72 * @param $text String: the text to parse
73 * @param $flags Integer: bitwise combination of:
74 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
75 * included. Default is to assume a direct page view.
77 * The generated DOM tree must depend only on the input text and the flags.
78 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
80 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
81 * change in the DOM tree for a given text, must be passed through the section identifier
82 * in the section edit link and thus back to extractSections().
84 * The output of this function is currently only cached in process memory, but a persistent
85 * cache may be implemented at a later date which takes further advantage of these strict
86 * dependency requirements.
90 function preprocessToObj( $text, $flags = 0 ) {
91 wfProfileIn( __METHOD__
);
92 global $wgMemc, $wgPreprocessorCacheThreshold;
95 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
97 wfProfileIn( __METHOD__
.'-cacheable' );
99 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
100 $cacheValue = $wgMemc->get( $cacheKey );
102 $version = substr( $cacheValue, 0, 8 );
103 if ( intval( $version ) == self
::CACHE_VERSION
) {
104 $xml = substr( $cacheValue, 8 );
106 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
110 if ( $xml === false ) {
112 wfProfileIn( __METHOD__
.'-cache-miss' );
113 $xml = $this->preprocessToXml( $text, $flags );
114 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
115 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
116 wfProfileOut( __METHOD__
.'-cache-miss' );
117 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
119 $xml = $this->preprocessToXml( $text, $flags );
123 wfProfileIn( __METHOD__
.'-loadXML' );
124 $dom = new DOMDocument
;
125 wfSuppressWarnings();
126 $result = $dom->loadXML( $xml );
129 // Try running the XML through UtfNormal to get rid of invalid characters
130 $xml = UtfNormal
::cleanUp( $xml );
131 $result = $dom->loadXML( $xml );
133 throw new MWException( __METHOD__
.' generated invalid XML' );
136 $obj = new PPNode_DOM( $dom->documentElement
);
137 wfProfileOut( __METHOD__
.'-loadXML' );
139 wfProfileOut( __METHOD__
.'-cacheable' );
141 wfProfileOut( __METHOD__
);
145 function preprocessToXml( $text, $flags = 0 ) {
146 wfProfileIn( __METHOD__
);
159 'names' => array( 2 => null ),
165 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
167 $xmlishElements = $this->parser
->getStripList();
168 $enableOnlyinclude = false;
169 if ( $forInclusion ) {
170 $ignoredTags = array( 'includeonly', '/includeonly' );
171 $ignoredElements = array( 'noinclude' );
172 $xmlishElements[] = 'noinclude';
173 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
174 $enableOnlyinclude = true;
177 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
178 $ignoredElements = array( 'includeonly' );
179 $xmlishElements[] = 'includeonly';
181 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
183 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
184 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
186 $stack = new PPDStack
;
188 $searchBase = "[{<\n"; #}
189 $revText = strrev( $text ); // For fast reverse searches
191 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
192 $accum =& $stack->getAccum(); # Current accumulator
194 $findEquals = false; # True to find equals signs in arguments
195 $findPipe = false; # True to take notice of pipe characters
197 $inHeading = false; # True if $i is inside a possible heading
198 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
199 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
200 $fakeLineStart = true; # Do a line-start run without outputting an LF character
205 if ( $findOnlyinclude ) {
206 // Ignore all input up to the next <onlyinclude>
207 $startPos = strpos( $text, '<onlyinclude>', $i );
208 if ( $startPos === false ) {
209 // Ignored section runs to the end
210 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
213 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
214 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
216 $findOnlyinclude = false;
219 if ( $fakeLineStart ) {
220 $found = 'line-start';
223 # Find next opening brace, closing brace or pipe
224 $search = $searchBase;
225 if ( $stack->top
=== false ) {
226 $currentClosing = '';
228 $currentClosing = $stack->top
->close
;
229 $search .= $currentClosing;
235 // First equals will be for the template
239 # Output literal section, advance input counter
240 $literalLength = strcspn( $text, $search, $i );
241 if ( $literalLength > 0 ) {
242 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
243 $i +
= $literalLength;
245 if ( $i >= strlen( $text ) ) {
246 if ( $currentClosing == "\n" ) {
247 // Do a past-the-end run to finish off the heading
255 $curChar = $text[$i];
256 if ( $curChar == '|' ) {
258 } elseif ( $curChar == '=' ) {
260 } elseif ( $curChar == '<' ) {
262 } elseif ( $curChar == "\n" ) {
266 $found = 'line-start';
268 } elseif ( $curChar == $currentClosing ) {
270 } elseif ( isset( $rules[$curChar] ) ) {
272 $rule = $rules[$curChar];
274 # Some versions of PHP have a strcspn which stops on null characters
275 # Ignore and continue
282 if ( $found == 'angle' ) {
284 // Handle </onlyinclude>
285 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
286 $findOnlyinclude = true;
290 // Determine element name
291 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
292 // Element name missing or not listed
298 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
299 // To avoid leaving blank lines, when a comment is both preceded
300 // and followed by a newline (ignoring spaces), trim leading and
301 // trailing spaces and one of the newlines.
304 $endPos = strpos( $text, '-->', $i +
4 );
305 if ( $endPos === false ) {
306 // Unclosed comment in input, runs to end
307 $inner = substr( $text, $i );
308 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
309 $i = strlen( $text );
311 // Search backwards for leading whitespace
312 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
313 // Search forwards for trailing whitespace
314 // $wsEnd will be the position of the last space
315 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
316 // Eat the line if possible
317 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
318 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
319 // it's a possible beneficial b/c break.
320 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
321 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
323 $startPos = $wsStart;
324 $endPos = $wsEnd +
1;
325 // Remove leading whitespace from the end of the accumulator
326 // Sanity check first though
327 $wsLength = $i - $wsStart;
328 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
329 $accum = substr( $accum, 0, -$wsLength );
331 // Do a line-start run next time to look for headings after the comment
332 $fakeLineStart = true;
334 // No line to eat, just take the comment itself
340 $part = $stack->top
->getCurrentPart();
341 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
342 // Comments abutting, no change in visual end
343 $part->commentEnd
= $wsEnd;
345 $part->visualEnd
= $wsStart;
346 $part->commentEnd
= $endPos;
350 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
351 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
356 $lowerName = strtolower( $name );
357 $attrStart = $i +
strlen( $name ) +
1;
360 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
361 if ( $tagEndPos === false ) {
362 // Infinite backtrack
363 // Disable tag search to prevent worst-case O(N^2) performance
370 // Handle ignored tags
371 if ( in_array( $lowerName, $ignoredTags ) ) {
372 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
378 if ( $text[$tagEndPos-1] == '/' ) {
379 $attrEnd = $tagEndPos - 1;
384 $attrEnd = $tagEndPos;
386 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
387 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
389 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
390 $i = $matches[0][1] +
strlen( $matches[0][0] );
391 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
393 // No end tag -- let it run out to the end of the text.
394 $inner = substr( $text, $tagEndPos +
1 );
395 $i = strlen( $text );
399 // <includeonly> and <noinclude> just become <ignore> tags
400 if ( in_array( $lowerName, $ignoredElements ) ) {
401 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
407 if ( $attrEnd <= $attrStart ) {
410 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
412 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
413 // Note that the attr element contains the whitespace between name and attribute,
414 // this is necessary for precise reconstruction during pre-save transform.
415 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
416 if ( $inner !== null ) {
417 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
419 $accum .= $close . '</ext>';
422 elseif ( $found == 'line-start' ) {
423 // Is this the start of a heading?
424 // Line break belongs before the heading element in any case
425 if ( $fakeLineStart ) {
426 $fakeLineStart = false;
432 $count = strspn( $text, '=', $i, 6 );
433 if ( $count == 1 && $findEquals ) {
434 // DWIM: This looks kind of like a name/value separator
435 // Let's let the equals handler have it and break the potential heading
436 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
437 } elseif ( $count > 0 ) {
441 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
444 $stack->push( $piece );
445 $accum =& $stack->getAccum();
446 $flags = $stack->getFlags();
452 elseif ( $found == 'line-end' ) {
453 $piece = $stack->top
;
454 // A heading must be open, otherwise \n wouldn't have been in the search list
455 assert( $piece->open
== "\n" );
456 $part = $piece->getCurrentPart();
457 // Search back through the input to see if it has a proper close
458 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
459 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
460 $searchStart = $i - $wsLength;
461 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
462 // Comment found at line end
463 // Search for equals signs before the comment
464 $searchStart = $part->visualEnd
;
465 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
467 $count = $piece->count
;
468 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
469 if ( $equalsLength > 0 ) {
470 if ( $searchStart - $equalsLength == $piece->startPos
) {
471 // This is just a single string of equals signs on its own line
472 // Replicate the doHeadings behaviour /={count}(.+)={count}/
473 // First find out how many equals signs there really are (don't stop at 6)
474 $count = $equalsLength;
478 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
481 $count = min( $equalsLength, $count );
484 // Normal match, output <h>
485 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
488 // Single equals sign on its own line, count=0
492 // No match, no <h>, just pass down the inner text
497 $accum =& $stack->getAccum();
498 $flags = $stack->getFlags();
501 // Append the result to the enclosing accumulator
503 // Note that we do NOT increment the input pointer.
504 // This is because the closing linebreak could be the opening linebreak of
505 // another heading. Infinite loops are avoided because the next iteration MUST
506 // hit the heading open case above, which unconditionally increments the
510 elseif ( $found == 'open' ) {
511 # count opening brace characters
512 $count = strspn( $text, $curChar, $i );
514 # we need to add to stack only if opening brace count is enough for one of the rules
515 if ( $count >= $rule['min'] ) {
516 # Add it to the stack
519 'close' => $rule['end'],
521 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
524 $stack->push( $piece );
525 $accum =& $stack->getAccum();
526 $flags = $stack->getFlags();
529 # Add literal brace(s)
530 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
535 elseif ( $found == 'close' ) {
536 $piece = $stack->top
;
537 # lets check if there are enough characters for closing brace
538 $maxCount = $piece->count
;
539 $count = strspn( $text, $curChar, $i, $maxCount );
541 # check for maximum matching characters (if there are 5 closing
542 # characters, we will probably need only 3 - depending on the rules)
544 $rule = $rules[$piece->open
];
545 if ( $count > $rule['max'] ) {
546 # The specified maximum exists in the callback array, unless the caller
548 $matchingCount = $rule['max'];
550 # Count is less than the maximum
551 # Skip any gaps in the callback array to find the true largest match
552 # Need to use array_key_exists not isset because the callback can be null
553 $matchingCount = $count;
554 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
559 if ($matchingCount <= 0) {
560 # No matching element found in callback array
561 # Output a literal closing brace and continue
562 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
566 $name = $rule['names'][$matchingCount];
567 if ( $name === null ) {
568 // No element, just literal text
569 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
572 # Note: $parts is already XML, does not need to be encoded further
573 $parts = $piece->parts
;
574 $title = $parts[0]->out
;
577 # The invocation is at the start of the line if lineStart is set in
578 # the stack, and all opening brackets are used up.
579 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
580 $attr = ' lineStart="1"';
585 $element = "<$name$attr>";
586 $element .= "<title>$title</title>";
588 foreach ( $parts as $partIndex => $part ) {
589 if ( isset( $part->eqpos
) ) {
590 $argName = substr( $part->out
, 0, $part->eqpos
);
591 $argValue = substr( $part->out
, $part->eqpos +
1 );
592 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
594 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
598 $element .= "</$name>";
601 # Advance input pointer
602 $i +
= $matchingCount;
606 $accum =& $stack->getAccum();
608 # Re-add the old stack element if it still has unmatched opening characters remaining
609 if ($matchingCount < $piece->count
) {
610 $piece->parts
= array( new PPDPart
);
611 $piece->count
-= $matchingCount;
612 # do we still qualify for any callback with remaining count?
613 $names = $rules[$piece->open
]['names'];
615 $enclosingAccum =& $accum;
616 while ( $piece->count
) {
617 if ( array_key_exists( $piece->count
, $names ) ) {
618 $stack->push( $piece );
619 $accum =& $stack->getAccum();
625 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
627 $flags = $stack->getFlags();
630 # Add XML element to the enclosing accumulator
634 elseif ( $found == 'pipe' ) {
635 $findEquals = true; // shortcut for getFlags()
637 $accum =& $stack->getAccum();
641 elseif ( $found == 'equals' ) {
642 $findEquals = false; // shortcut for getFlags()
643 $stack->getCurrentPart()->eqpos
= strlen( $accum );
649 # Output any remaining unclosed brackets
650 foreach ( $stack->stack
as $piece ) {
651 $stack->rootAccum
.= $piece->breakSyntax();
653 $stack->rootAccum
.= '</root>';
654 $xml = $stack->rootAccum
;
656 wfProfileOut( __METHOD__
);
663 * Stack class to help Preprocessor::preprocessToObj()
667 var $stack, $rootAccum, $top;
669 var $elementClass = 'PPDStackElement';
671 static $false = false;
673 function __construct() {
674 $this->stack
= array();
676 $this->rootAccum
= '';
677 $this->accum
=& $this->rootAccum
;
681 return count( $this->stack
);
684 function &getAccum() {
688 function getCurrentPart() {
689 if ( $this->top
=== false ) {
692 return $this->top
->getCurrentPart();
696 function push( $data ) {
697 if ( $data instanceof $this->elementClass
) {
698 $this->stack
[] = $data;
700 $class = $this->elementClass
;
701 $this->stack
[] = new $class( $data );
703 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
704 $this->accum
=& $this->top
->getAccum();
708 if ( !count( $this->stack
) ) {
709 throw new MWException( __METHOD__
.': no elements remaining' );
711 $temp = array_pop( $this->stack
);
713 if ( count( $this->stack
) ) {
714 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
715 $this->accum
=& $this->top
->getAccum();
717 $this->top
= self
::$false;
718 $this->accum
=& $this->rootAccum
;
723 function addPart( $s = '' ) {
724 $this->top
->addPart( $s );
725 $this->accum
=& $this->top
->getAccum();
728 function getFlags() {
729 if ( !count( $this->stack
) ) {
731 'findEquals' => false,
733 'inHeading' => false,
736 return $this->top
->getFlags();
744 class PPDStackElement
{
745 var $open, // Opening character (\n for heading)
746 $close, // Matching closing character
747 $count, // Number of opening characters found (number of "=" for heading)
748 $parts, // Array of PPDPart objects describing pipe-separated parts.
749 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
751 var $partClass = 'PPDPart';
753 function __construct( $data = array() ) {
754 $class = $this->partClass
;
755 $this->parts
= array( new $class );
757 foreach ( $data as $name => $value ) {
758 $this->$name = $value;
762 function &getAccum() {
763 return $this->parts
[count($this->parts
) - 1]->out
;
766 function addPart( $s = '' ) {
767 $class = $this->partClass
;
768 $this->parts
[] = new $class( $s );
771 function getCurrentPart() {
772 return $this->parts
[count($this->parts
) - 1];
775 function getFlags() {
776 $partCount = count( $this->parts
);
777 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
779 'findPipe' => $findPipe,
780 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
781 'inHeading' => $this->open
== "\n",
786 * Get the output string that would result if the close is not found.
788 function breakSyntax( $openingCount = false ) {
789 if ( $this->open
== "\n" ) {
790 $s = $this->parts
[0]->out
;
792 if ( $openingCount === false ) {
793 $openingCount = $this->count
;
795 $s = str_repeat( $this->open
, $openingCount );
797 foreach ( $this->parts
as $part ) {
814 var $out; // Output accumulator string
816 // Optional member variables:
817 // eqpos Position of equals sign in output accumulator
818 // commentEnd Past-the-end input pointer for the last comment encountered
819 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
821 function __construct( $out = '' ) {
827 * An expansion frame, used as a context to expand the result of preprocessToObj()
830 class PPFrame_DOM
implements PPFrame
{
831 var $preprocessor, $parser, $title;
835 * Hashtable listing templates which are disallowed for expansion in this frame,
836 * having been encountered previously in parent frames.
841 * Recursion depth of this frame, top = 0
842 * Note that this is NOT the same as expansion depth in expand()
848 * Construct a new preprocessor frame.
849 * @param $preprocessor Preprocessor: The parent preprocessor
851 function __construct( $preprocessor ) {
852 $this->preprocessor
= $preprocessor;
853 $this->parser
= $preprocessor->parser
;
854 $this->title
= $this->parser
->mTitle
;
855 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
856 $this->loopCheckHash
= array();
861 * Create a new child frame
862 * $args is optionally a multi-root PPNode or array containing the template arguments
864 function newChild( $args = false, $title = false ) {
865 $namedArgs = array();
866 $numberedArgs = array();
867 if ( $title === false ) {
868 $title = $this->title
;
870 if ( $args !== false ) {
872 if ( $args instanceof PPNode
) {
875 foreach ( $args as $arg ) {
877 $xpath = new DOMXPath( $arg->ownerDocument
);
880 $nameNodes = $xpath->query( 'name', $arg );
881 $value = $xpath->query( 'value', $arg );
882 if ( $nameNodes->item( 0 )->hasAttributes() ) {
883 // Numbered parameter
884 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
885 $numberedArgs[$index] = $value->item( 0 );
886 unset( $namedArgs[$index] );
889 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
890 $namedArgs[$name] = $value->item( 0 );
891 unset( $numberedArgs[$name] );
895 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
898 function expand( $root, $flags = 0 ) {
899 static $expansionDepth = 0;
900 if ( is_string( $root ) ) {
904 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
906 return '<span class="error">Node-count limit exceeded</span>';
909 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
910 return '<span class="error">Expansion depth limit exceeded</span>';
912 wfProfileIn( __METHOD__
);
915 if ( $root instanceof PPNode_DOM
) {
918 if ( $root instanceof DOMDocument
) {
919 $root = $root->documentElement
;
922 $outStack = array( '', '' );
923 $iteratorStack = array( false, $root );
924 $indexStack = array( 0, 0 );
926 while ( count( $iteratorStack ) > 1 ) {
927 $level = count( $outStack ) - 1;
928 $iteratorNode =& $iteratorStack[ $level ];
929 $out =& $outStack[$level];
930 $index =& $indexStack[$level];
932 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
934 if ( is_array( $iteratorNode ) ) {
935 if ( $index >= count( $iteratorNode ) ) {
936 // All done with this iterator
937 $iteratorStack[$level] = false;
938 $contextNode = false;
940 $contextNode = $iteratorNode[$index];
943 } elseif ( $iteratorNode instanceof DOMNodeList
) {
944 if ( $index >= $iteratorNode->length
) {
945 // All done with this iterator
946 $iteratorStack[$level] = false;
947 $contextNode = false;
949 $contextNode = $iteratorNode->item( $index );
953 // Copy to $contextNode and then delete from iterator stack,
954 // because this is not an iterator but we do have to execute it once
955 $contextNode = $iteratorStack[$level];
956 $iteratorStack[$level] = false;
959 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
961 $newIterator = false;
963 if ( $contextNode === false ) {
965 } elseif ( is_string( $contextNode ) ) {
966 $out .= $contextNode;
967 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
968 $newIterator = $contextNode;
969 } elseif ( $contextNode instanceof DOMNode
) {
970 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
971 $out .= $contextNode->nodeValue
;
972 } elseif ( $contextNode->nodeName
== 'template' ) {
973 # Double-brace expansion
974 $xpath = new DOMXPath( $contextNode->ownerDocument
);
975 $titles = $xpath->query( 'title', $contextNode );
976 $title = $titles->item( 0 );
977 $parts = $xpath->query( 'part', $contextNode );
978 if ( $flags & PPFrame
::NO_TEMPLATES
) {
979 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
981 $lineStart = $contextNode->getAttribute( 'lineStart' );
983 'title' => new PPNode_DOM( $title ),
984 'parts' => new PPNode_DOM( $parts ),
985 'lineStart' => $lineStart );
986 $ret = $this->parser
->braceSubstitution( $params, $this );
987 if ( isset( $ret['object'] ) ) {
988 $newIterator = $ret['object'];
990 $out .= $ret['text'];
993 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
994 # Triple-brace expansion
995 $xpath = new DOMXPath( $contextNode->ownerDocument
);
996 $titles = $xpath->query( 'title', $contextNode );
997 $title = $titles->item( 0 );
998 $parts = $xpath->query( 'part', $contextNode );
999 if ( $flags & PPFrame
::NO_ARGS
) {
1000 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1003 'title' => new PPNode_DOM( $title ),
1004 'parts' => new PPNode_DOM( $parts ) );
1005 $ret = $this->parser
->argSubstitution( $params, $this );
1006 if ( isset( $ret['object'] ) ) {
1007 $newIterator = $ret['object'];
1009 $out .= $ret['text'];
1012 } elseif ( $contextNode->nodeName
== 'comment' ) {
1013 # HTML-style comment
1014 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1015 if ( $this->parser
->ot
['html']
1016 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1017 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1021 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1022 # Not in RECOVER_COMMENTS mode (extractSections) though
1023 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1024 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1026 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1028 $out .= $contextNode->textContent
;
1030 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1031 # Output suppression used by <includeonly> etc.
1032 # OT_WIKI will only respect <ignore> in substed templates.
1033 # The other output types respect it unless NO_IGNORE is set.
1034 # extractSections() sets NO_IGNORE and so never respects it.
1035 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1036 $out .= $contextNode->textContent
;
1040 } elseif ( $contextNode->nodeName
== 'ext' ) {
1042 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1043 $names = $xpath->query( 'name', $contextNode );
1044 $attrs = $xpath->query( 'attr', $contextNode );
1045 $inners = $xpath->query( 'inner', $contextNode );
1046 $closes = $xpath->query( 'close', $contextNode );
1048 'name' => new PPNode_DOM( $names->item( 0 ) ),
1049 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1050 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1051 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1053 $out .= $this->parser
->extensionSubstitution( $params, $this );
1054 } elseif ( $contextNode->nodeName
== 'h' ) {
1056 $s = $this->expand( $contextNode->childNodes
, $flags );
1058 # Insert a heading marker only for <h> children of <root>
1059 # This is to stop extractSections from going over multiple tree levels
1060 if ( $contextNode->parentNode
->nodeName
== 'root'
1061 && $this->parser
->ot
['html'] )
1063 # Insert heading index marker
1064 $headingIndex = $contextNode->getAttribute( 'i' );
1065 $titleText = $this->title
->getPrefixedDBkey();
1066 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1067 $serial = count( $this->parser
->mHeadings
) - 1;
1068 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1069 $count = $contextNode->getAttribute( 'level' );
1070 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1071 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1075 # Generic recursive expansion
1076 $newIterator = $contextNode->childNodes
;
1079 wfProfileOut( __METHOD__
);
1080 throw new MWException( __METHOD__
.': Invalid parameter type' );
1083 if ( $newIterator !== false ) {
1084 if ( $newIterator instanceof PPNode_DOM
) {
1085 $newIterator = $newIterator->node
;
1088 $iteratorStack[] = $newIterator;
1090 } elseif ( $iteratorStack[$level] === false ) {
1091 // Return accumulated value to parent
1092 // With tail recursion
1093 while ( $iteratorStack[$level] === false && $level > 0 ) {
1094 $outStack[$level - 1] .= $out;
1095 array_pop( $outStack );
1096 array_pop( $iteratorStack );
1097 array_pop( $indexStack );
1103 wfProfileOut( __METHOD__
);
1104 return $outStack[0];
1107 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1108 $args = array_slice( func_get_args(), 2 );
1112 foreach ( $args as $root ) {
1113 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1114 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1115 $root = array( $root );
1117 foreach ( $root as $node ) {
1123 $s .= $this->expand( $node, $flags );
1130 * Implode with no flags specified
1131 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1133 function implode( $sep /*, ... */ ) {
1134 $args = array_slice( func_get_args(), 1 );
1138 foreach ( $args as $root ) {
1139 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1140 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1141 $root = array( $root );
1143 foreach ( $root as $node ) {
1149 $s .= $this->expand( $node );
1156 * Makes an object that, when expand()ed, will be the same as one obtained
1159 function virtualImplode( $sep /*, ... */ ) {
1160 $args = array_slice( func_get_args(), 1 );
1163 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1165 foreach ( $args as $root ) {
1166 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1167 $root = array( $root );
1169 foreach ( $root as $node ) {
1182 * Virtual implode with brackets
1184 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1185 $args = array_slice( func_get_args(), 3 );
1186 $out = array( $start );
1189 foreach ( $args as $root ) {
1190 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1191 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1192 $root = array( $root );
1194 foreach ( $root as $node ) {
1207 function __toString() {
1211 function getPDBK( $level = false ) {
1212 if ( $level === false ) {
1213 return $this->title
->getPrefixedDBkey();
1215 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1219 function getArguments() {
1223 function getNumberedArguments() {
1227 function getNamedArguments() {
1232 * Returns true if there are no arguments in this frame
1234 function isEmpty() {
1238 function getArgument( $name ) {
1243 * Returns true if the infinite loop check is OK, false if a loop is detected
1245 function loopCheck( $title ) {
1246 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1250 * Return true if the frame is a template frame
1252 function isTemplate() {
1258 * Expansion frame with template arguments
1261 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1262 var $numberedArgs, $namedArgs, $parent;
1263 var $numberedExpansionCache, $namedExpansionCache;
1265 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1266 parent
::__construct( $preprocessor );
1268 $this->parent
= $parent;
1269 $this->numberedArgs
= $numberedArgs;
1270 $this->namedArgs
= $namedArgs;
1271 $this->title
= $title;
1272 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1273 $this->titleCache
= $parent->titleCache
;
1274 $this->titleCache
[] = $pdbk;
1275 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1276 if ( $pdbk !== false ) {
1277 $this->loopCheckHash
[$pdbk] = true;
1279 $this->depth
= $parent->depth +
1;
1280 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1283 function __toString() {
1286 $args = $this->numberedArgs +
$this->namedArgs
;
1287 foreach ( $args as $name => $value ) {
1293 $s .= "\"$name\":\"" .
1294 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1300 * Returns true if there are no arguments in this frame
1302 function isEmpty() {
1303 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1306 function getArguments() {
1307 $arguments = array();
1308 foreach ( array_merge(
1309 array_keys($this->numberedArgs
),
1310 array_keys($this->namedArgs
)) as $key ) {
1311 $arguments[$key] = $this->getArgument($key);
1316 function getNumberedArguments() {
1317 $arguments = array();
1318 foreach ( array_keys($this->numberedArgs
) as $key ) {
1319 $arguments[$key] = $this->getArgument($key);
1324 function getNamedArguments() {
1325 $arguments = array();
1326 foreach ( array_keys($this->namedArgs
) as $key ) {
1327 $arguments[$key] = $this->getArgument($key);
1332 function getNumberedArgument( $index ) {
1333 if ( !isset( $this->numberedArgs
[$index] ) ) {
1336 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1337 # No trimming for unnamed arguments
1338 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1340 return $this->numberedExpansionCache
[$index];
1343 function getNamedArgument( $name ) {
1344 if ( !isset( $this->namedArgs
[$name] ) ) {
1347 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1348 # Trim named arguments post-expand, for backwards compatibility
1349 $this->namedExpansionCache
[$name] = trim(
1350 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1352 return $this->namedExpansionCache
[$name];
1355 function getArgument( $name ) {
1356 $text = $this->getNumberedArgument( $name );
1357 if ( $text === false ) {
1358 $text = $this->getNamedArgument( $name );
1364 * Return true if the frame is a template frame
1366 function isTemplate() {
1372 * Expansion frame with custom arguments
1375 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1378 function __construct( $preprocessor, $args ) {
1379 parent
::__construct( $preprocessor );
1380 $this->args
= $args;
1383 function __toString() {
1386 foreach ( $this->args
as $name => $value ) {
1392 $s .= "\"$name\":\"" .
1393 str_replace( '"', '\\"', $value->__toString() ) . '"';
1399 function isEmpty() {
1400 return !count( $this->args
);
1403 function getArgument( $index ) {
1404 if ( !isset( $this->args
[$index] ) ) {
1407 return $this->args
[$index];
1414 class PPNode_DOM
implements PPNode
{
1417 function __construct( $node, $xpath = false ) {
1418 $this->node
= $node;
1421 function __get( $name ) {
1422 if ( $name == 'xpath' ) {
1423 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1425 return $this->xpath
;
1428 function __toString() {
1429 if ( $this->node
instanceof DOMNodeList
) {
1431 foreach ( $this->node
as $node ) {
1432 $s .= $node->ownerDocument
->saveXML( $node );
1435 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1440 function getChildren() {
1441 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1444 function getFirstChild() {
1445 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1448 function getNextSibling() {
1449 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1452 function getChildrenOfType( $type ) {
1453 return new self( $this->xpath
->query( $type, $this->node
) );
1456 function getLength() {
1457 if ( $this->node
instanceof DOMNodeList
) {
1458 return $this->node
->length
;
1464 function item( $i ) {
1465 $item = $this->node
->item( $i );
1466 return $item ?
new self( $item ) : false;
1469 function getName() {
1470 if ( $this->node
instanceof DOMNodeList
) {
1473 return $this->node
->nodeName
;
1478 * Split a <part> node into an associative array containing:
1480 * index String index
1481 * value PPNode value
1483 function splitArg() {
1484 $names = $this->xpath
->query( 'name', $this->node
);
1485 $values = $this->xpath
->query( 'value', $this->node
);
1486 if ( !$names->length ||
!$values->length
) {
1487 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1489 $name = $names->item( 0 );
1490 $index = $name->getAttribute( 'index' );
1492 'name' => new self( $name ),
1494 'value' => new self( $values->item( 0 ) ) );
1498 * Split an <ext> node into an associative array containing name, attr, inner and close
1499 * All values in the resulting array are PPNodes. Inner and close are optional.
1501 function splitExt() {
1502 $names = $this->xpath
->query( 'name', $this->node
);
1503 $attrs = $this->xpath
->query( 'attr', $this->node
);
1504 $inners = $this->xpath
->query( 'inner', $this->node
);
1505 $closes = $this->xpath
->query( 'close', $this->node
);
1506 if ( !$names->length ||
!$attrs->length
) {
1507 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1510 'name' => new self( $names->item( 0 ) ),
1511 'attr' => new self( $attrs->item( 0 ) ) );
1512 if ( $inners->length
) {
1513 $parts['inner'] = new self( $inners->item( 0 ) );
1515 if ( $closes->length
) {
1516 $parts['close'] = new self( $closes->item( 0 ) );
1524 function splitHeading() {
1525 if ( !$this->nodeName
== 'h' ) {
1526 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1529 'i' => $this->node
->getAttribute( 'i' ),
1530 'level' => $this->node
->getAttribute( 'level' ),
1531 'contents' => $this->getChildren()