3 * Preprocessor using PHP's dom extension
12 class Preprocessor_DOM
implements Preprocessor
{
13 var $parser, $memoryLimit;
15 const CACHE_VERSION
= 1;
17 function __construct( $parser ) {
18 $this->parser
= $parser;
19 $mem = ini_get( 'memory_limit' );
20 $this->memoryLimit
= false;
21 if ( strval( $mem ) !== '' && $mem != -1 ) {
22 if ( preg_match( '/^\d+$/', $mem ) ) {
23 $this->memoryLimit
= $mem;
24 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
25 $this->memoryLimit
= $m[1] * 1048576;
34 return new PPFrame_DOM( $this );
39 * @return PPCustomFrame_DOM
41 function newCustomFrame( $args ) {
42 return new PPCustomFrame_DOM( $this, $args );
45 function newPartNodeArray( $values ) {
46 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
49 foreach ( $values as $k => $val ) {
52 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
54 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
60 $dom = new DOMDocument();
61 $dom->loadXML( $xml );
62 $root = $dom->documentElement
;
64 $node = new PPNode_DOM( $root->childNodes
);
69 if ( $this->memoryLimit
=== false ) {
72 $usage = memory_get_usage();
73 if ( $usage > $this->memoryLimit
* 0.9 ) {
74 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
75 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
77 return $usage <= $this->memoryLimit
* 0.8;
81 * Preprocess some wikitext and return the document tree.
82 * This is the ghost of Parser::replace_variables().
84 * @param $text String: the text to parse
85 * @param $flags Integer: bitwise combination of:
86 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
87 * included. Default is to assume a direct page view.
89 * The generated DOM tree must depend only on the input text and the flags.
90 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
92 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
93 * change in the DOM tree for a given text, must be passed through the section identifier
94 * in the section edit link and thus back to extractSections().
96 * The output of this function is currently only cached in process memory, but a persistent
97 * cache may be implemented at a later date which takes further advantage of these strict
98 * dependency requirements.
102 function preprocessToObj( $text, $flags = 0 ) {
103 wfProfileIn( __METHOD__
);
104 global $wgMemc, $wgPreprocessorCacheThreshold;
107 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
109 wfProfileIn( __METHOD__
.'-cacheable' );
111 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
112 $cacheValue = $wgMemc->get( $cacheKey );
114 $version = substr( $cacheValue, 0, 8 );
115 if ( intval( $version ) == self
::CACHE_VERSION
) {
116 $xml = substr( $cacheValue, 8 );
118 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
122 if ( $xml === false ) {
124 wfProfileIn( __METHOD__
.'-cache-miss' );
125 $xml = $this->preprocessToXml( $text, $flags );
126 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
127 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
128 wfProfileOut( __METHOD__
.'-cache-miss' );
129 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
131 $xml = $this->preprocessToXml( $text, $flags );
135 wfProfileIn( __METHOD__
.'-loadXML' );
136 $dom = new DOMDocument
;
137 wfSuppressWarnings();
138 $result = $dom->loadXML( $xml );
141 // Try running the XML through UtfNormal to get rid of invalid characters
142 $xml = UtfNormal
::cleanUp( $xml );
143 $result = $dom->loadXML( $xml );
145 throw new MWException( __METHOD__
.' generated invalid XML' );
148 $obj = new PPNode_DOM( $dom->documentElement
);
149 wfProfileOut( __METHOD__
.'-loadXML' );
151 wfProfileOut( __METHOD__
.'-cacheable' );
153 wfProfileOut( __METHOD__
);
157 function preprocessToXml( $text, $flags = 0 ) {
158 wfProfileIn( __METHOD__
);
171 'names' => array( 2 => null ),
177 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
179 $xmlishElements = $this->parser
->getStripList();
180 $enableOnlyinclude = false;
181 if ( $forInclusion ) {
182 $ignoredTags = array( 'includeonly', '/includeonly' );
183 $ignoredElements = array( 'noinclude' );
184 $xmlishElements[] = 'noinclude';
185 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
186 $enableOnlyinclude = true;
188 } else if ( isset( $this->parser
->ot
) && $this->parser
->ot
['wiki'] ) {
189 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude', 'includeonly', '/includeonly' );
190 $ignoredElements = array();
192 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
193 $ignoredElements = array( 'includeonly' );
194 $xmlishElements[] = 'includeonly';
196 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
198 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
199 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
201 $stack = new PPDStack
;
203 $searchBase = "[{<\n"; #}
204 $revText = strrev( $text ); // For fast reverse searches
206 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
207 $accum =& $stack->getAccum(); # Current accumulator
209 $findEquals = false; # True to find equals signs in arguments
210 $findPipe = false; # True to take notice of pipe characters
212 $inHeading = false; # True if $i is inside a possible heading
213 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
214 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
215 $fakeLineStart = true; # Do a line-start run without outputting an LF character
220 if ( $findOnlyinclude ) {
221 // Ignore all input up to the next <onlyinclude>
222 $startPos = strpos( $text, '<onlyinclude>', $i );
223 if ( $startPos === false ) {
224 // Ignored section runs to the end
225 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
228 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
229 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
231 $findOnlyinclude = false;
234 if ( $fakeLineStart ) {
235 $found = 'line-start';
238 # Find next opening brace, closing brace or pipe
239 $search = $searchBase;
240 if ( $stack->top
=== false ) {
241 $currentClosing = '';
243 $currentClosing = $stack->top
->close
;
244 $search .= $currentClosing;
250 // First equals will be for the template
254 # Output literal section, advance input counter
255 $literalLength = strcspn( $text, $search, $i );
256 if ( $literalLength > 0 ) {
257 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
258 $i +
= $literalLength;
260 if ( $i >= strlen( $text ) ) {
261 if ( $currentClosing == "\n" ) {
262 // Do a past-the-end run to finish off the heading
270 $curChar = $text[$i];
271 if ( $curChar == '|' ) {
273 } elseif ( $curChar == '=' ) {
275 } elseif ( $curChar == '<' ) {
277 } elseif ( $curChar == "\n" ) {
281 $found = 'line-start';
283 } elseif ( $curChar == $currentClosing ) {
285 } elseif ( isset( $rules[$curChar] ) ) {
287 $rule = $rules[$curChar];
289 # Some versions of PHP have a strcspn which stops on null characters
290 # Ignore and continue
297 if ( $found == 'angle' ) {
299 // Handle </onlyinclude>
300 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
301 $findOnlyinclude = true;
305 // Determine element name
306 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
307 // Element name missing or not listed
313 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
314 // To avoid leaving blank lines, when a comment is both preceded
315 // and followed by a newline (ignoring spaces), trim leading and
316 // trailing spaces and one of the newlines.
319 $endPos = strpos( $text, '-->', $i +
4 );
320 if ( $endPos === false ) {
321 // Unclosed comment in input, runs to end
322 $inner = substr( $text, $i );
323 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
324 $i = strlen( $text );
326 // Search backwards for leading whitespace
327 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
328 // Search forwards for trailing whitespace
329 // $wsEnd will be the position of the last space (or the '>' if there's none)
330 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
331 // Eat the line if possible
332 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
333 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
334 // it's a possible beneficial b/c break.
335 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
336 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
338 $startPos = $wsStart;
339 $endPos = $wsEnd +
1;
340 // Remove leading whitespace from the end of the accumulator
341 // Sanity check first though
342 $wsLength = $i - $wsStart;
343 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
344 $accum = substr( $accum, 0, -$wsLength );
346 // Do a line-start run next time to look for headings after the comment
347 $fakeLineStart = true;
349 // No line to eat, just take the comment itself
355 $part = $stack->top
->getCurrentPart();
356 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
357 $part->visualEnd
= $wsStart;
359 // Else comments abutting, no change in visual end
360 $part->commentEnd
= $endPos;
363 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
364 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
369 $lowerName = strtolower( $name );
370 $attrStart = $i +
strlen( $name ) +
1;
373 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
374 if ( $tagEndPos === false ) {
375 // Infinite backtrack
376 // Disable tag search to prevent worst-case O(N^2) performance
383 // Handle ignored tags
384 if ( in_array( $lowerName, $ignoredTags ) ) {
385 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
391 if ( $text[$tagEndPos-1] == '/' ) {
392 $attrEnd = $tagEndPos - 1;
397 $attrEnd = $tagEndPos;
399 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
400 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
402 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
403 $i = $matches[0][1] +
strlen( $matches[0][0] );
404 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
406 // No end tag -- let it run out to the end of the text.
407 $inner = substr( $text, $tagEndPos +
1 );
408 $i = strlen( $text );
412 // <includeonly> and <noinclude> just become <ignore> tags
413 if ( in_array( $lowerName, $ignoredElements ) ) {
414 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
420 if ( $attrEnd <= $attrStart ) {
423 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
425 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
426 // Note that the attr element contains the whitespace between name and attribute,
427 // this is necessary for precise reconstruction during pre-save transform.
428 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
429 if ( $inner !== null ) {
430 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
432 $accum .= $close . '</ext>';
435 elseif ( $found == 'line-start' ) {
436 // Is this the start of a heading?
437 // Line break belongs before the heading element in any case
438 if ( $fakeLineStart ) {
439 $fakeLineStart = false;
445 $count = strspn( $text, '=', $i, 6 );
446 if ( $count == 1 && $findEquals ) {
447 // DWIM: This looks kind of like a name/value separator
448 // Let's let the equals handler have it and break the potential heading
449 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
450 } elseif ( $count > 0 ) {
454 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
457 $stack->push( $piece );
458 $accum =& $stack->getAccum();
459 $flags = $stack->getFlags();
465 elseif ( $found == 'line-end' ) {
466 $piece = $stack->top
;
467 // A heading must be open, otherwise \n wouldn't have been in the search list
468 assert( $piece->open
== "\n" );
469 $part = $piece->getCurrentPart();
470 // Search back through the input to see if it has a proper close
471 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
472 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
473 $searchStart = $i - $wsLength;
474 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
475 // Comment found at line end
476 // Search for equals signs before the comment
477 $searchStart = $part->visualEnd
;
478 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
480 $count = $piece->count
;
481 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
482 if ( $equalsLength > 0 ) {
483 if ( $searchStart - $equalsLength == $piece->startPos
) {
484 // This is just a single string of equals signs on its own line
485 // Replicate the doHeadings behaviour /={count}(.+)={count}/
486 // First find out how many equals signs there really are (don't stop at 6)
487 $count = $equalsLength;
491 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
494 $count = min( $equalsLength, $count );
497 // Normal match, output <h>
498 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
501 // Single equals sign on its own line, count=0
505 // No match, no <h>, just pass down the inner text
510 $accum =& $stack->getAccum();
511 $flags = $stack->getFlags();
514 // Append the result to the enclosing accumulator
516 // Note that we do NOT increment the input pointer.
517 // This is because the closing linebreak could be the opening linebreak of
518 // another heading. Infinite loops are avoided because the next iteration MUST
519 // hit the heading open case above, which unconditionally increments the
521 } elseif ( $found == 'open' ) {
522 # count opening brace characters
523 $count = strspn( $text, $curChar, $i );
525 # we need to add to stack only if opening brace count is enough for one of the rules
526 if ( $count >= $rule['min'] ) {
527 # Add it to the stack
530 'close' => $rule['end'],
532 'lineStart' => ($i == 0 ||
$text[$i-1] == "\n"),
535 $stack->push( $piece );
536 $accum =& $stack->getAccum();
537 $flags = $stack->getFlags();
540 # Add literal brace(s)
541 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
544 } elseif ( $found == 'close' ) {
545 $piece = $stack->top
;
546 # lets check if there are enough characters for closing brace
547 $maxCount = $piece->count
;
548 $count = strspn( $text, $curChar, $i, $maxCount );
550 # check for maximum matching characters (if there are 5 closing
551 # characters, we will probably need only 3 - depending on the rules)
552 $rule = $rules[$piece->open
];
553 if ( $count > $rule['max'] ) {
554 # The specified maximum exists in the callback array, unless the caller
556 $matchingCount = $rule['max'];
558 # Count is less than the maximum
559 # Skip any gaps in the callback array to find the true largest match
560 # Need to use array_key_exists not isset because the callback can be null
561 $matchingCount = $count;
562 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
567 if ($matchingCount <= 0) {
568 # No matching element found in callback array
569 # Output a literal closing brace and continue
570 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
574 $name = $rule['names'][$matchingCount];
575 if ( $name === null ) {
576 // No element, just literal text
577 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
580 # Note: $parts is already XML, does not need to be encoded further
581 $parts = $piece->parts
;
582 $title = $parts[0]->out
;
585 # The invocation is at the start of the line if lineStart is set in
586 # the stack, and all opening brackets are used up.
587 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
588 $attr = ' lineStart="1"';
593 $element = "<$name$attr>";
594 $element .= "<title>$title</title>";
596 foreach ( $parts as $part ) {
597 if ( isset( $part->eqpos
) ) {
598 $argName = substr( $part->out
, 0, $part->eqpos
);
599 $argValue = substr( $part->out
, $part->eqpos +
1 );
600 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
602 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
606 $element .= "</$name>";
609 # Advance input pointer
610 $i +
= $matchingCount;
614 $accum =& $stack->getAccum();
616 # Re-add the old stack element if it still has unmatched opening characters remaining
617 if ($matchingCount < $piece->count
) {
618 $piece->parts
= array( new PPDPart
);
619 $piece->count
-= $matchingCount;
620 # do we still qualify for any callback with remaining count?
621 $names = $rules[$piece->open
]['names'];
623 $enclosingAccum =& $accum;
624 while ( $piece->count
) {
625 if ( array_key_exists( $piece->count
, $names ) ) {
626 $stack->push( $piece );
627 $accum =& $stack->getAccum();
633 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
635 $flags = $stack->getFlags();
638 # Add XML element to the enclosing accumulator
642 elseif ( $found == 'pipe' ) {
643 $findEquals = true; // shortcut for getFlags()
645 $accum =& $stack->getAccum();
649 elseif ( $found == 'equals' ) {
650 $findEquals = false; // shortcut for getFlags()
651 $stack->getCurrentPart()->eqpos
= strlen( $accum );
657 # Output any remaining unclosed brackets
658 foreach ( $stack->stack
as $piece ) {
659 $stack->rootAccum
.= $piece->breakSyntax();
661 $stack->rootAccum
.= '</root>';
662 $xml = $stack->rootAccum
;
664 wfProfileOut( __METHOD__
);
671 * Stack class to help Preprocessor::preprocessToObj()
675 var $stack, $rootAccum, $top;
677 var $elementClass = 'PPDStackElement';
679 static $false = false;
681 function __construct() {
682 $this->stack
= array();
684 $this->rootAccum
= '';
685 $this->accum
=& $this->rootAccum
;
689 return count( $this->stack
);
692 function &getAccum() {
696 function getCurrentPart() {
697 if ( $this->top
=== false ) {
700 return $this->top
->getCurrentPart();
704 function push( $data ) {
705 if ( $data instanceof $this->elementClass
) {
706 $this->stack
[] = $data;
708 $class = $this->elementClass
;
709 $this->stack
[] = new $class( $data );
711 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
712 $this->accum
=& $this->top
->getAccum();
716 if ( !count( $this->stack
) ) {
717 throw new MWException( __METHOD__
.': no elements remaining' );
719 $temp = array_pop( $this->stack
);
721 if ( count( $this->stack
) ) {
722 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
723 $this->accum
=& $this->top
->getAccum();
725 $this->top
= self
::$false;
726 $this->accum
=& $this->rootAccum
;
731 function addPart( $s = '' ) {
732 $this->top
->addPart( $s );
733 $this->accum
=& $this->top
->getAccum();
736 function getFlags() {
737 if ( !count( $this->stack
) ) {
739 'findEquals' => false,
741 'inHeading' => false,
744 return $this->top
->getFlags();
752 class PPDStackElement
{
753 var $open, // Opening character (\n for heading)
754 $close, // Matching closing character
755 $count, // Number of opening characters found (number of "=" for heading)
756 $parts, // Array of PPDPart objects describing pipe-separated parts.
757 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
759 var $partClass = 'PPDPart';
761 function __construct( $data = array() ) {
762 $class = $this->partClass
;
763 $this->parts
= array( new $class );
765 foreach ( $data as $name => $value ) {
766 $this->$name = $value;
770 function &getAccum() {
771 return $this->parts
[count($this->parts
) - 1]->out
;
774 function addPart( $s = '' ) {
775 $class = $this->partClass
;
776 $this->parts
[] = new $class( $s );
779 function getCurrentPart() {
780 return $this->parts
[count($this->parts
) - 1];
783 function getFlags() {
784 $partCount = count( $this->parts
);
785 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
787 'findPipe' => $findPipe,
788 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
789 'inHeading' => $this->open
== "\n",
794 * Get the output string that would result if the close is not found.
796 function breakSyntax( $openingCount = false ) {
797 if ( $this->open
== "\n" ) {
798 $s = $this->parts
[0]->out
;
800 if ( $openingCount === false ) {
801 $openingCount = $this->count
;
803 $s = str_repeat( $this->open
, $openingCount );
805 foreach ( $this->parts
as $part ) {
822 var $out; // Output accumulator string
824 // Optional member variables:
825 // eqpos Position of equals sign in output accumulator
826 // commentEnd Past-the-end input pointer for the last comment encountered
827 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
829 function __construct( $out = '' ) {
835 * An expansion frame, used as a context to expand the result of preprocessToObj()
838 class PPFrame_DOM
implements PPFrame
{
839 var $preprocessor, $parser, $title;
843 * Hashtable listing templates which are disallowed for expansion in this frame,
844 * having been encountered previously in parent frames.
849 * Recursion depth of this frame, top = 0
850 * Note that this is NOT the same as expansion depth in expand()
856 * Construct a new preprocessor frame.
857 * @param $preprocessor Preprocessor: The parent preprocessor
859 function __construct( $preprocessor ) {
860 $this->preprocessor
= $preprocessor;
861 $this->parser
= $preprocessor->parser
;
862 $this->title
= $this->parser
->mTitle
;
863 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
864 $this->loopCheckHash
= array();
869 * Create a new child frame
870 * $args is optionally a multi-root PPNode or array containing the template arguments
872 function newChild( $args = false, $title = false ) {
873 $namedArgs = array();
874 $numberedArgs = array();
875 if ( $title === false ) {
876 $title = $this->title
;
878 if ( $args !== false ) {
880 if ( $args instanceof PPNode
) {
883 foreach ( $args as $arg ) {
885 $xpath = new DOMXPath( $arg->ownerDocument
);
888 $nameNodes = $xpath->query( 'name', $arg );
889 $value = $xpath->query( 'value', $arg );
890 if ( $nameNodes->item( 0 )->hasAttributes() ) {
891 // Numbered parameter
892 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
893 $numberedArgs[$index] = $value->item( 0 );
894 unset( $namedArgs[$index] );
897 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
898 $namedArgs[$name] = $value->item( 0 );
899 unset( $numberedArgs[$name] );
903 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
906 function expand( $root, $flags = 0 ) {
907 static $expansionDepth = 0;
908 if ( is_string( $root ) ) {
912 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
914 return '<span class="error">Node-count limit exceeded</span>';
917 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
918 return '<span class="error">Expansion depth limit exceeded</span>';
920 wfProfileIn( __METHOD__
);
923 if ( $root instanceof PPNode_DOM
) {
926 if ( $root instanceof DOMDocument
) {
927 $root = $root->documentElement
;
930 $outStack = array( '', '' );
931 $iteratorStack = array( false, $root );
932 $indexStack = array( 0, 0 );
934 while ( count( $iteratorStack ) > 1 ) {
935 $level = count( $outStack ) - 1;
936 $iteratorNode =& $iteratorStack[ $level ];
937 $out =& $outStack[$level];
938 $index =& $indexStack[$level];
940 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
942 if ( is_array( $iteratorNode ) ) {
943 if ( $index >= count( $iteratorNode ) ) {
944 // All done with this iterator
945 $iteratorStack[$level] = false;
946 $contextNode = false;
948 $contextNode = $iteratorNode[$index];
951 } elseif ( $iteratorNode instanceof DOMNodeList
) {
952 if ( $index >= $iteratorNode->length
) {
953 // All done with this iterator
954 $iteratorStack[$level] = false;
955 $contextNode = false;
957 $contextNode = $iteratorNode->item( $index );
961 // Copy to $contextNode and then delete from iterator stack,
962 // because this is not an iterator but we do have to execute it once
963 $contextNode = $iteratorStack[$level];
964 $iteratorStack[$level] = false;
967 if ( $contextNode instanceof PPNode_DOM
) {
968 $contextNode = $contextNode->node
;
971 $newIterator = false;
973 if ( $contextNode === false ) {
975 } elseif ( is_string( $contextNode ) ) {
976 $out .= $contextNode;
977 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
978 $newIterator = $contextNode;
979 } elseif ( $contextNode instanceof DOMNode
) {
980 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
981 $out .= $contextNode->nodeValue
;
982 } elseif ( $contextNode->nodeName
== 'template' ) {
983 # Double-brace expansion
984 $xpath = new DOMXPath( $contextNode->ownerDocument
);
985 $titles = $xpath->query( 'title', $contextNode );
986 $title = $titles->item( 0 );
987 $parts = $xpath->query( 'part', $contextNode );
988 if ( $flags & PPFrame
::NO_TEMPLATES
) {
989 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
991 $lineStart = $contextNode->getAttribute( 'lineStart' );
993 'title' => new PPNode_DOM( $title ),
994 'parts' => new PPNode_DOM( $parts ),
995 'lineStart' => $lineStart );
996 $ret = $this->parser
->braceSubstitution( $params, $this );
997 if ( isset( $ret['object'] ) ) {
998 $newIterator = $ret['object'];
1000 $out .= $ret['text'];
1003 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1004 # Triple-brace expansion
1005 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1006 $titles = $xpath->query( 'title', $contextNode );
1007 $title = $titles->item( 0 );
1008 $parts = $xpath->query( 'part', $contextNode );
1009 if ( $flags & PPFrame
::NO_ARGS
) {
1010 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1013 'title' => new PPNode_DOM( $title ),
1014 'parts' => new PPNode_DOM( $parts ) );
1015 $ret = $this->parser
->argSubstitution( $params, $this );
1016 if ( isset( $ret['object'] ) ) {
1017 $newIterator = $ret['object'];
1019 $out .= $ret['text'];
1022 } elseif ( $contextNode->nodeName
== 'comment' ) {
1023 # HTML-style comment
1024 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1025 if ( $this->parser
->ot
['html']
1026 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1027 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1031 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1032 # Not in RECOVER_COMMENTS mode (extractSections) though
1033 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1034 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1036 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1038 $out .= $contextNode->textContent
;
1040 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1041 # Output suppression used by <includeonly> etc.
1042 # OT_WIKI will only respect <ignore> in substed templates.
1043 # The other output types respect it unless NO_IGNORE is set.
1044 # extractSections() sets NO_IGNORE and so never respects it.
1045 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1046 $out .= $contextNode->textContent
;
1050 } elseif ( $contextNode->nodeName
== 'ext' ) {
1052 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1053 $names = $xpath->query( 'name', $contextNode );
1054 $attrs = $xpath->query( 'attr', $contextNode );
1055 $inners = $xpath->query( 'inner', $contextNode );
1056 $closes = $xpath->query( 'close', $contextNode );
1058 'name' => new PPNode_DOM( $names->item( 0 ) ),
1059 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1060 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1061 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1063 $out .= $this->parser
->extensionSubstitution( $params, $this );
1064 } elseif ( $contextNode->nodeName
== 'h' ) {
1066 $s = $this->expand( $contextNode->childNodes
, $flags );
1068 # Insert a heading marker only for <h> children of <root>
1069 # This is to stop extractSections from going over multiple tree levels
1070 if ( $contextNode->parentNode
->nodeName
== 'root'
1071 && $this->parser
->ot
['html'] )
1073 # Insert heading index marker
1074 $headingIndex = $contextNode->getAttribute( 'i' );
1075 $titleText = $this->title
->getPrefixedDBkey();
1076 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1077 $serial = count( $this->parser
->mHeadings
) - 1;
1078 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1079 $count = $contextNode->getAttribute( 'level' );
1080 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1081 $this->parser
->mStripState
->addGeneral( $marker, '' );
1085 # Generic recursive expansion
1086 $newIterator = $contextNode->childNodes
;
1089 wfProfileOut( __METHOD__
);
1090 throw new MWException( __METHOD__
.': Invalid parameter type' );
1093 if ( $newIterator !== false ) {
1094 if ( $newIterator instanceof PPNode_DOM
) {
1095 $newIterator = $newIterator->node
;
1098 $iteratorStack[] = $newIterator;
1100 } elseif ( $iteratorStack[$level] === false ) {
1101 // Return accumulated value to parent
1102 // With tail recursion
1103 while ( $iteratorStack[$level] === false && $level > 0 ) {
1104 $outStack[$level - 1] .= $out;
1105 array_pop( $outStack );
1106 array_pop( $iteratorStack );
1107 array_pop( $indexStack );
1113 wfProfileOut( __METHOD__
);
1114 return $outStack[0];
1117 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1118 $args = array_slice( func_get_args(), 2 );
1122 foreach ( $args as $root ) {
1123 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1124 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1125 $root = array( $root );
1127 foreach ( $root as $node ) {
1133 $s .= $this->expand( $node, $flags );
1140 * Implode with no flags specified
1141 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1143 function implode( $sep /*, ... */ ) {
1144 $args = array_slice( func_get_args(), 1 );
1148 foreach ( $args as $root ) {
1149 if ( $root instanceof PPNode_DOM
) {
1150 $root = $root->node
;
1152 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1153 $root = array( $root );
1155 foreach ( $root as $node ) {
1161 $s .= $this->expand( $node );
1168 * Makes an object that, when expand()ed, will be the same as one obtained
1173 function virtualImplode( $sep /*, ... */ ) {
1174 $args = array_slice( func_get_args(), 1 );
1178 foreach ( $args as $root ) {
1179 if ( $root instanceof PPNode_DOM
) {
1180 $root = $root->node
;
1182 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1183 $root = array( $root );
1185 foreach ( $root as $node ) {
1198 * Virtual implode with brackets
1200 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1201 $args = array_slice( func_get_args(), 3 );
1202 $out = array( $start );
1205 foreach ( $args as $root ) {
1206 if ( $root instanceof PPNode_DOM
) {
1207 $root = $root->node
;
1209 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1210 $root = array( $root );
1212 foreach ( $root as $node ) {
1225 function __toString() {
1229 function getPDBK( $level = false ) {
1230 if ( $level === false ) {
1231 return $this->title
->getPrefixedDBkey();
1233 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1237 function getArguments() {
1241 function getNumberedArguments() {
1245 function getNamedArguments() {
1250 * Returns true if there are no arguments in this frame
1252 function isEmpty() {
1256 function getArgument( $name ) {
1261 * Returns true if the infinite loop check is OK, false if a loop is detected
1263 function loopCheck( $title ) {
1264 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1268 * Return true if the frame is a template frame
1270 function isTemplate() {
1276 * Expansion frame with template arguments
1279 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1280 var $numberedArgs, $namedArgs, $parent;
1281 var $numberedExpansionCache, $namedExpansionCache;
1283 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1284 parent
::__construct( $preprocessor );
1286 $this->parent
= $parent;
1287 $this->numberedArgs
= $numberedArgs;
1288 $this->namedArgs
= $namedArgs;
1289 $this->title
= $title;
1290 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1291 $this->titleCache
= $parent->titleCache
;
1292 $this->titleCache
[] = $pdbk;
1293 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1294 if ( $pdbk !== false ) {
1295 $this->loopCheckHash
[$pdbk] = true;
1297 $this->depth
= $parent->depth +
1;
1298 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1301 function __toString() {
1304 $args = $this->numberedArgs +
$this->namedArgs
;
1305 foreach ( $args as $name => $value ) {
1311 $s .= "\"$name\":\"" .
1312 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1318 * Returns true if there are no arguments in this frame
1320 function isEmpty() {
1321 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1324 function getArguments() {
1325 $arguments = array();
1326 foreach ( array_merge(
1327 array_keys($this->numberedArgs
),
1328 array_keys($this->namedArgs
)) as $key ) {
1329 $arguments[$key] = $this->getArgument($key);
1334 function getNumberedArguments() {
1335 $arguments = array();
1336 foreach ( array_keys($this->numberedArgs
) as $key ) {
1337 $arguments[$key] = $this->getArgument($key);
1342 function getNamedArguments() {
1343 $arguments = array();
1344 foreach ( array_keys($this->namedArgs
) as $key ) {
1345 $arguments[$key] = $this->getArgument($key);
1350 function getNumberedArgument( $index ) {
1351 if ( !isset( $this->numberedArgs
[$index] ) ) {
1354 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1355 # No trimming for unnamed arguments
1356 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1358 return $this->numberedExpansionCache
[$index];
1361 function getNamedArgument( $name ) {
1362 if ( !isset( $this->namedArgs
[$name] ) ) {
1365 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1366 # Trim named arguments post-expand, for backwards compatibility
1367 $this->namedExpansionCache
[$name] = trim(
1368 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1370 return $this->namedExpansionCache
[$name];
1373 function getArgument( $name ) {
1374 $text = $this->getNumberedArgument( $name );
1375 if ( $text === false ) {
1376 $text = $this->getNamedArgument( $name );
1382 * Return true if the frame is a template frame
1384 function isTemplate() {
1390 * Expansion frame with custom arguments
1393 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1396 function __construct( $preprocessor, $args ) {
1397 parent
::__construct( $preprocessor );
1398 $this->args
= $args;
1401 function __toString() {
1404 foreach ( $this->args
as $name => $value ) {
1410 $s .= "\"$name\":\"" .
1411 str_replace( '"', '\\"', $value->__toString() ) . '"';
1417 function isEmpty() {
1418 return !count( $this->args
);
1421 function getArgument( $index ) {
1422 if ( !isset( $this->args
[$index] ) ) {
1425 return $this->args
[$index];
1432 class PPNode_DOM
implements PPNode
{
1435 function __construct( $node, $xpath = false ) {
1436 $this->node
= $node;
1442 function getXPath() {
1443 if ( $this->xpath
=== null ) {
1444 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1446 return $this->xpath
;
1449 function __toString() {
1450 if ( $this->node
instanceof DOMNodeList
) {
1452 foreach ( $this->node
as $node ) {
1453 $s .= $node->ownerDocument
->saveXML( $node );
1456 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1462 * @return bool|PPNode_DOM
1464 function getChildren() {
1465 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1469 * @return bool|PPNode_DOM
1471 function getFirstChild() {
1472 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1476 * @return bool|PPNode_DOM
1478 function getNextSibling() {
1479 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1485 * @return bool|PPNode_DOM
1487 function getChildrenOfType( $type ) {
1488 return new self( $this->getXPath()->query( $type, $this->node
) );
1494 function getLength() {
1495 if ( $this->node
instanceof DOMNodeList
) {
1496 return $this->node
->length
;
1504 * @return bool|PPNode_DOM
1506 function item( $i ) {
1507 $item = $this->node
->item( $i );
1508 return $item ?
new self( $item ) : false;
1514 function getName() {
1515 if ( $this->node
instanceof DOMNodeList
) {
1518 return $this->node
->nodeName
;
1523 * Split a <part> node into an associative array containing:
1525 * index String index
1526 * value PPNode value
1530 function splitArg() {
1531 $xpath = $this->getXPath();
1532 $names = $xpath->query( 'name', $this->node
);
1533 $values = $xpath->query( 'value', $this->node
);
1534 if ( !$names->length ||
!$values->length
) {
1535 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1537 $name = $names->item( 0 );
1538 $index = $name->getAttribute( 'index' );
1540 'name' => new self( $name ),
1542 'value' => new self( $values->item( 0 ) ) );
1546 * Split an <ext> node into an associative array containing name, attr, inner and close
1547 * All values in the resulting array are PPNodes. Inner and close are optional.
1551 function splitExt() {
1552 $xpath = $this->getXPath();
1553 $names = $xpath->query( 'name', $this->node
);
1554 $attrs = $xpath->query( 'attr', $this->node
);
1555 $inners = $xpath->query( 'inner', $this->node
);
1556 $closes = $xpath->query( 'close', $this->node
);
1557 if ( !$names->length ||
!$attrs->length
) {
1558 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1561 'name' => new self( $names->item( 0 ) ),
1562 'attr' => new self( $attrs->item( 0 ) ) );
1563 if ( $inners->length
) {
1564 $parts['inner'] = new self( $inners->item( 0 ) );
1566 if ( $closes->length
) {
1567 $parts['close'] = new self( $closes->item( 0 ) );
1575 function splitHeading() {
1576 if ( $this->getName() !== 'h' ) {
1577 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1580 'i' => $this->node
->getAttribute( 'i' ),
1581 'level' => $this->node
->getAttribute( 'level' ),
1582 'contents' => $this->getChildren()