2dd3efd27c8f7537f6299894d2742e009b155135
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;
189 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
190 $ignoredElements = array( 'includeonly' );
191 $xmlishElements[] = 'includeonly';
193 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
195 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
196 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
198 $stack = new PPDStack
;
200 $searchBase = "[{<\n"; #}
201 $revText = strrev( $text ); // For fast reverse searches
203 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
204 $accum =& $stack->getAccum(); # Current accumulator
206 $findEquals = false; # True to find equals signs in arguments
207 $findPipe = false; # True to take notice of pipe characters
209 $inHeading = false; # True if $i is inside a possible heading
210 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
211 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
212 $fakeLineStart = true; # Do a line-start run without outputting an LF character
217 if ( $findOnlyinclude ) {
218 // Ignore all input up to the next <onlyinclude>
219 $startPos = strpos( $text, '<onlyinclude>', $i );
220 if ( $startPos === false ) {
221 // Ignored section runs to the end
222 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
225 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
226 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
228 $findOnlyinclude = false;
231 if ( $fakeLineStart ) {
232 $found = 'line-start';
235 # Find next opening brace, closing brace or pipe
236 $search = $searchBase;
237 if ( $stack->top
=== false ) {
238 $currentClosing = '';
240 $currentClosing = $stack->top
->close
;
241 $search .= $currentClosing;
247 // First equals will be for the template
251 # Output literal section, advance input counter
252 $literalLength = strcspn( $text, $search, $i );
253 if ( $literalLength > 0 ) {
254 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
255 $i +
= $literalLength;
257 if ( $i >= strlen( $text ) ) {
258 if ( $currentClosing == "\n" ) {
259 // Do a past-the-end run to finish off the heading
267 $curChar = $text[$i];
268 if ( $curChar == '|' ) {
270 } elseif ( $curChar == '=' ) {
272 } elseif ( $curChar == '<' ) {
274 } elseif ( $curChar == "\n" ) {
278 $found = 'line-start';
280 } elseif ( $curChar == $currentClosing ) {
282 } elseif ( isset( $rules[$curChar] ) ) {
284 $rule = $rules[$curChar];
286 # Some versions of PHP have a strcspn which stops on null characters
287 # Ignore and continue
294 if ( $found == 'angle' ) {
296 // Handle </onlyinclude>
297 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
298 $findOnlyinclude = true;
302 // Determine element name
303 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
304 // Element name missing or not listed
310 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
311 // To avoid leaving blank lines, when a comment is both preceded
312 // and followed by a newline (ignoring spaces), trim leading and
313 // trailing spaces and one of the newlines.
316 $endPos = strpos( $text, '-->', $i +
4 );
317 if ( $endPos === false ) {
318 // Unclosed comment in input, runs to end
319 $inner = substr( $text, $i );
320 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
321 $i = strlen( $text );
323 // Search backwards for leading whitespace
324 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
325 // Search forwards for trailing whitespace
326 // $wsEnd will be the position of the last space (or the '>' if there's none)
327 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
328 // Eat the line if possible
329 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
330 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
331 // it's a possible beneficial b/c break.
332 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
333 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
335 $startPos = $wsStart;
336 $endPos = $wsEnd +
1;
337 // Remove leading whitespace from the end of the accumulator
338 // Sanity check first though
339 $wsLength = $i - $wsStart;
340 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
341 $accum = substr( $accum, 0, -$wsLength );
343 // Do a line-start run next time to look for headings after the comment
344 $fakeLineStart = true;
346 // No line to eat, just take the comment itself
352 $part = $stack->top
->getCurrentPart();
353 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
354 $part->visualEnd
= $wsStart;
356 // Else comments abutting, no change in visual end
357 $part->commentEnd
= $endPos;
360 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
361 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
366 $lowerName = strtolower( $name );
367 $attrStart = $i +
strlen( $name ) +
1;
370 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
371 if ( $tagEndPos === false ) {
372 // Infinite backtrack
373 // Disable tag search to prevent worst-case O(N^2) performance
380 // Handle ignored tags
381 if ( in_array( $lowerName, $ignoredTags ) ) {
382 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
388 if ( $text[$tagEndPos-1] == '/' ) {
389 $attrEnd = $tagEndPos - 1;
394 $attrEnd = $tagEndPos;
396 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
397 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
399 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
400 $i = $matches[0][1] +
strlen( $matches[0][0] );
401 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
403 // No end tag -- let it run out to the end of the text.
404 $inner = substr( $text, $tagEndPos +
1 );
405 $i = strlen( $text );
409 // <includeonly> and <noinclude> just become <ignore> tags
410 if ( in_array( $lowerName, $ignoredElements ) ) {
411 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
417 if ( $attrEnd <= $attrStart ) {
420 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
422 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
423 // Note that the attr element contains the whitespace between name and attribute,
424 // this is necessary for precise reconstruction during pre-save transform.
425 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
426 if ( $inner !== null ) {
427 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
429 $accum .= $close . '</ext>';
432 elseif ( $found == 'line-start' ) {
433 // Is this the start of a heading?
434 // Line break belongs before the heading element in any case
435 if ( $fakeLineStart ) {
436 $fakeLineStart = false;
442 $count = strspn( $text, '=', $i, 6 );
443 if ( $count == 1 && $findEquals ) {
444 // DWIM: This looks kind of like a name/value separator
445 // Let's let the equals handler have it and break the potential heading
446 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
447 } elseif ( $count > 0 ) {
451 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
454 $stack->push( $piece );
455 $accum =& $stack->getAccum();
456 $flags = $stack->getFlags();
462 elseif ( $found == 'line-end' ) {
463 $piece = $stack->top
;
464 // A heading must be open, otherwise \n wouldn't have been in the search list
465 assert( $piece->open
== "\n" );
466 $part = $piece->getCurrentPart();
467 // Search back through the input to see if it has a proper close
468 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
469 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
470 $searchStart = $i - $wsLength;
471 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
472 // Comment found at line end
473 // Search for equals signs before the comment
474 $searchStart = $part->visualEnd
;
475 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
477 $count = $piece->count
;
478 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
479 if ( $equalsLength > 0 ) {
480 if ( $searchStart - $equalsLength == $piece->startPos
) {
481 // This is just a single string of equals signs on its own line
482 // Replicate the doHeadings behaviour /={count}(.+)={count}/
483 // First find out how many equals signs there really are (don't stop at 6)
484 $count = $equalsLength;
488 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
491 $count = min( $equalsLength, $count );
494 // Normal match, output <h>
495 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
498 // Single equals sign on its own line, count=0
502 // No match, no <h>, just pass down the inner text
507 $accum =& $stack->getAccum();
508 $flags = $stack->getFlags();
511 // Append the result to the enclosing accumulator
513 // Note that we do NOT increment the input pointer.
514 // This is because the closing linebreak could be the opening linebreak of
515 // another heading. Infinite loops are avoided because the next iteration MUST
516 // hit the heading open case above, which unconditionally increments the
518 } elseif ( $found == 'open' ) {
519 # count opening brace characters
520 $count = strspn( $text, $curChar, $i );
522 # we need to add to stack only if opening brace count is enough for one of the rules
523 if ( $count >= $rule['min'] ) {
524 # Add it to the stack
527 'close' => $rule['end'],
529 'lineStart' => ($i == 0 ||
$text[$i-1] == "\n"),
532 $stack->push( $piece );
533 $accum =& $stack->getAccum();
534 $flags = $stack->getFlags();
537 # Add literal brace(s)
538 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
541 } elseif ( $found == 'close' ) {
542 $piece = $stack->top
;
543 # lets check if there are enough characters for closing brace
544 $maxCount = $piece->count
;
545 $count = strspn( $text, $curChar, $i, $maxCount );
547 # check for maximum matching characters (if there are 5 closing
548 # characters, we will probably need only 3 - depending on the rules)
549 $rule = $rules[$piece->open
];
550 if ( $count > $rule['max'] ) {
551 # The specified maximum exists in the callback array, unless the caller
553 $matchingCount = $rule['max'];
555 # Count is less than the maximum
556 # Skip any gaps in the callback array to find the true largest match
557 # Need to use array_key_exists not isset because the callback can be null
558 $matchingCount = $count;
559 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
564 if ($matchingCount <= 0) {
565 # No matching element found in callback array
566 # Output a literal closing brace and continue
567 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
571 $name = $rule['names'][$matchingCount];
572 if ( $name === null ) {
573 // No element, just literal text
574 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
577 # Note: $parts is already XML, does not need to be encoded further
578 $parts = $piece->parts
;
579 $title = $parts[0]->out
;
582 # The invocation is at the start of the line if lineStart is set in
583 # the stack, and all opening brackets are used up.
584 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
585 $attr = ' lineStart="1"';
590 $element = "<$name$attr>";
591 $element .= "<title>$title</title>";
593 foreach ( $parts as $part ) {
594 if ( isset( $part->eqpos
) ) {
595 $argName = substr( $part->out
, 0, $part->eqpos
);
596 $argValue = substr( $part->out
, $part->eqpos +
1 );
597 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
599 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
603 $element .= "</$name>";
606 # Advance input pointer
607 $i +
= $matchingCount;
611 $accum =& $stack->getAccum();
613 # Re-add the old stack element if it still has unmatched opening characters remaining
614 if ($matchingCount < $piece->count
) {
615 $piece->parts
= array( new PPDPart
);
616 $piece->count
-= $matchingCount;
617 # do we still qualify for any callback with remaining count?
618 $names = $rules[$piece->open
]['names'];
620 $enclosingAccum =& $accum;
621 while ( $piece->count
) {
622 if ( array_key_exists( $piece->count
, $names ) ) {
623 $stack->push( $piece );
624 $accum =& $stack->getAccum();
630 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
632 $flags = $stack->getFlags();
635 # Add XML element to the enclosing accumulator
639 elseif ( $found == 'pipe' ) {
640 $findEquals = true; // shortcut for getFlags()
642 $accum =& $stack->getAccum();
646 elseif ( $found == 'equals' ) {
647 $findEquals = false; // shortcut for getFlags()
648 $stack->getCurrentPart()->eqpos
= strlen( $accum );
654 # Output any remaining unclosed brackets
655 foreach ( $stack->stack
as $piece ) {
656 $stack->rootAccum
.= $piece->breakSyntax();
658 $stack->rootAccum
.= '</root>';
659 $xml = $stack->rootAccum
;
661 wfProfileOut( __METHOD__
);
668 * Stack class to help Preprocessor::preprocessToObj()
672 var $stack, $rootAccum, $top;
674 var $elementClass = 'PPDStackElement';
676 static $false = false;
678 function __construct() {
679 $this->stack
= array();
681 $this->rootAccum
= '';
682 $this->accum
=& $this->rootAccum
;
686 return count( $this->stack
);
689 function &getAccum() {
693 function getCurrentPart() {
694 if ( $this->top
=== false ) {
697 return $this->top
->getCurrentPart();
701 function push( $data ) {
702 if ( $data instanceof $this->elementClass
) {
703 $this->stack
[] = $data;
705 $class = $this->elementClass
;
706 $this->stack
[] = new $class( $data );
708 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
709 $this->accum
=& $this->top
->getAccum();
713 if ( !count( $this->stack
) ) {
714 throw new MWException( __METHOD__
.': no elements remaining' );
716 $temp = array_pop( $this->stack
);
718 if ( count( $this->stack
) ) {
719 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
720 $this->accum
=& $this->top
->getAccum();
722 $this->top
= self
::$false;
723 $this->accum
=& $this->rootAccum
;
728 function addPart( $s = '' ) {
729 $this->top
->addPart( $s );
730 $this->accum
=& $this->top
->getAccum();
733 function getFlags() {
734 if ( !count( $this->stack
) ) {
736 'findEquals' => false,
738 'inHeading' => false,
741 return $this->top
->getFlags();
749 class PPDStackElement
{
750 var $open, // Opening character (\n for heading)
751 $close, // Matching closing character
752 $count, // Number of opening characters found (number of "=" for heading)
753 $parts, // Array of PPDPart objects describing pipe-separated parts.
754 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
756 var $partClass = 'PPDPart';
758 function __construct( $data = array() ) {
759 $class = $this->partClass
;
760 $this->parts
= array( new $class );
762 foreach ( $data as $name => $value ) {
763 $this->$name = $value;
767 function &getAccum() {
768 return $this->parts
[count($this->parts
) - 1]->out
;
771 function addPart( $s = '' ) {
772 $class = $this->partClass
;
773 $this->parts
[] = new $class( $s );
776 function getCurrentPart() {
777 return $this->parts
[count($this->parts
) - 1];
780 function getFlags() {
781 $partCount = count( $this->parts
);
782 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
784 'findPipe' => $findPipe,
785 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
786 'inHeading' => $this->open
== "\n",
791 * Get the output string that would result if the close is not found.
793 function breakSyntax( $openingCount = false ) {
794 if ( $this->open
== "\n" ) {
795 $s = $this->parts
[0]->out
;
797 if ( $openingCount === false ) {
798 $openingCount = $this->count
;
800 $s = str_repeat( $this->open
, $openingCount );
802 foreach ( $this->parts
as $part ) {
819 var $out; // Output accumulator string
821 // Optional member variables:
822 // eqpos Position of equals sign in output accumulator
823 // commentEnd Past-the-end input pointer for the last comment encountered
824 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
826 function __construct( $out = '' ) {
832 * An expansion frame, used as a context to expand the result of preprocessToObj()
835 class PPFrame_DOM
implements PPFrame
{
836 var $preprocessor, $parser, $title;
840 * Hashtable listing templates which are disallowed for expansion in this frame,
841 * having been encountered previously in parent frames.
846 * Recursion depth of this frame, top = 0
847 * Note that this is NOT the same as expansion depth in expand()
853 * Construct a new preprocessor frame.
854 * @param $preprocessor Preprocessor: The parent preprocessor
856 function __construct( $preprocessor ) {
857 $this->preprocessor
= $preprocessor;
858 $this->parser
= $preprocessor->parser
;
859 $this->title
= $this->parser
->mTitle
;
860 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
861 $this->loopCheckHash
= array();
866 * Create a new child frame
867 * $args is optionally a multi-root PPNode or array containing the template arguments
869 function newChild( $args = false, $title = false ) {
870 $namedArgs = array();
871 $numberedArgs = array();
872 if ( $title === false ) {
873 $title = $this->title
;
875 if ( $args !== false ) {
877 if ( $args instanceof PPNode
) {
880 foreach ( $args as $arg ) {
882 $xpath = new DOMXPath( $arg->ownerDocument
);
885 $nameNodes = $xpath->query( 'name', $arg );
886 $value = $xpath->query( 'value', $arg );
887 if ( $nameNodes->item( 0 )->hasAttributes() ) {
888 // Numbered parameter
889 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
890 $numberedArgs[$index] = $value->item( 0 );
891 unset( $namedArgs[$index] );
894 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
895 $namedArgs[$name] = $value->item( 0 );
896 unset( $numberedArgs[$name] );
900 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
903 function expand( $root, $flags = 0 ) {
904 static $expansionDepth = 0;
905 if ( is_string( $root ) ) {
909 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
911 return '<span class="error">Node-count limit exceeded</span>';
914 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
915 return '<span class="error">Expansion depth limit exceeded</span>';
917 wfProfileIn( __METHOD__
);
920 if ( $root instanceof PPNode_DOM
) {
923 if ( $root instanceof DOMDocument
) {
924 $root = $root->documentElement
;
927 $outStack = array( '', '' );
928 $iteratorStack = array( false, $root );
929 $indexStack = array( 0, 0 );
931 while ( count( $iteratorStack ) > 1 ) {
932 $level = count( $outStack ) - 1;
933 $iteratorNode =& $iteratorStack[ $level ];
934 $out =& $outStack[$level];
935 $index =& $indexStack[$level];
937 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
939 if ( is_array( $iteratorNode ) ) {
940 if ( $index >= count( $iteratorNode ) ) {
941 // All done with this iterator
942 $iteratorStack[$level] = false;
943 $contextNode = false;
945 $contextNode = $iteratorNode[$index];
948 } elseif ( $iteratorNode instanceof DOMNodeList
) {
949 if ( $index >= $iteratorNode->length
) {
950 // All done with this iterator
951 $iteratorStack[$level] = false;
952 $contextNode = false;
954 $contextNode = $iteratorNode->item( $index );
958 // Copy to $contextNode and then delete from iterator stack,
959 // because this is not an iterator but we do have to execute it once
960 $contextNode = $iteratorStack[$level];
961 $iteratorStack[$level] = false;
964 if ( $contextNode instanceof PPNode_DOM
) {
965 $contextNode = $contextNode->node
;
968 $newIterator = false;
970 if ( $contextNode === false ) {
972 } elseif ( is_string( $contextNode ) ) {
973 $out .= $contextNode;
974 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
975 $newIterator = $contextNode;
976 } elseif ( $contextNode instanceof DOMNode
) {
977 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
978 $out .= $contextNode->nodeValue
;
979 } elseif ( $contextNode->nodeName
== 'template' ) {
980 # Double-brace expansion
981 $xpath = new DOMXPath( $contextNode->ownerDocument
);
982 $titles = $xpath->query( 'title', $contextNode );
983 $title = $titles->item( 0 );
984 $parts = $xpath->query( 'part', $contextNode );
985 if ( $flags & PPFrame
::NO_TEMPLATES
) {
986 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
988 $lineStart = $contextNode->getAttribute( 'lineStart' );
990 'title' => new PPNode_DOM( $title ),
991 'parts' => new PPNode_DOM( $parts ),
992 'lineStart' => $lineStart );
993 $ret = $this->parser
->braceSubstitution( $params, $this );
994 if ( isset( $ret['object'] ) ) {
995 $newIterator = $ret['object'];
997 $out .= $ret['text'];
1000 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1001 # Triple-brace expansion
1002 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1003 $titles = $xpath->query( 'title', $contextNode );
1004 $title = $titles->item( 0 );
1005 $parts = $xpath->query( 'part', $contextNode );
1006 if ( $flags & PPFrame
::NO_ARGS
) {
1007 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1010 'title' => new PPNode_DOM( $title ),
1011 'parts' => new PPNode_DOM( $parts ) );
1012 $ret = $this->parser
->argSubstitution( $params, $this );
1013 if ( isset( $ret['object'] ) ) {
1014 $newIterator = $ret['object'];
1016 $out .= $ret['text'];
1019 } elseif ( $contextNode->nodeName
== 'comment' ) {
1020 # HTML-style comment
1021 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1022 if ( $this->parser
->ot
['html']
1023 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1024 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1028 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1029 # Not in RECOVER_COMMENTS mode (extractSections) though
1030 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1031 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1033 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1035 $out .= $contextNode->textContent
;
1037 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1038 # Output suppression used by <includeonly> etc.
1039 # OT_WIKI will only respect <ignore> in substed templates.
1040 # The other output types respect it unless NO_IGNORE is set.
1041 # extractSections() sets NO_IGNORE and so never respects it.
1042 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1043 $out .= $contextNode->textContent
;
1047 } elseif ( $contextNode->nodeName
== 'ext' ) {
1049 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1050 $names = $xpath->query( 'name', $contextNode );
1051 $attrs = $xpath->query( 'attr', $contextNode );
1052 $inners = $xpath->query( 'inner', $contextNode );
1053 $closes = $xpath->query( 'close', $contextNode );
1055 'name' => new PPNode_DOM( $names->item( 0 ) ),
1056 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1057 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1058 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1060 $out .= $this->parser
->extensionSubstitution( $params, $this );
1061 } elseif ( $contextNode->nodeName
== 'h' ) {
1063 $s = $this->expand( $contextNode->childNodes
, $flags );
1065 # Insert a heading marker only for <h> children of <root>
1066 # This is to stop extractSections from going over multiple tree levels
1067 if ( $contextNode->parentNode
->nodeName
== 'root'
1068 && $this->parser
->ot
['html'] )
1070 # Insert heading index marker
1071 $headingIndex = $contextNode->getAttribute( 'i' );
1072 $titleText = $this->title
->getPrefixedDBkey();
1073 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1074 $serial = count( $this->parser
->mHeadings
) - 1;
1075 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1076 $count = $contextNode->getAttribute( 'level' );
1077 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1078 $this->parser
->mStripState
->addGeneral( $marker, '' );
1082 # Generic recursive expansion
1083 $newIterator = $contextNode->childNodes
;
1086 wfProfileOut( __METHOD__
);
1087 throw new MWException( __METHOD__
.': Invalid parameter type' );
1090 if ( $newIterator !== false ) {
1091 if ( $newIterator instanceof PPNode_DOM
) {
1092 $newIterator = $newIterator->node
;
1095 $iteratorStack[] = $newIterator;
1097 } elseif ( $iteratorStack[$level] === false ) {
1098 // Return accumulated value to parent
1099 // With tail recursion
1100 while ( $iteratorStack[$level] === false && $level > 0 ) {
1101 $outStack[$level - 1] .= $out;
1102 array_pop( $outStack );
1103 array_pop( $iteratorStack );
1104 array_pop( $indexStack );
1110 wfProfileOut( __METHOD__
);
1111 return $outStack[0];
1114 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1115 $args = array_slice( func_get_args(), 2 );
1119 foreach ( $args as $root ) {
1120 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1121 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1122 $root = array( $root );
1124 foreach ( $root as $node ) {
1130 $s .= $this->expand( $node, $flags );
1137 * Implode with no flags specified
1138 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1140 function implode( $sep /*, ... */ ) {
1141 $args = array_slice( func_get_args(), 1 );
1145 foreach ( $args as $root ) {
1146 if ( $root instanceof PPNode_DOM
) {
1147 $root = $root->node
;
1149 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1150 $root = array( $root );
1152 foreach ( $root as $node ) {
1158 $s .= $this->expand( $node );
1165 * Makes an object that, when expand()ed, will be the same as one obtained
1170 function virtualImplode( $sep /*, ... */ ) {
1171 $args = array_slice( func_get_args(), 1 );
1175 foreach ( $args as $root ) {
1176 if ( $root instanceof PPNode_DOM
) {
1177 $root = $root->node
;
1179 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1180 $root = array( $root );
1182 foreach ( $root as $node ) {
1195 * Virtual implode with brackets
1197 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1198 $args = array_slice( func_get_args(), 3 );
1199 $out = array( $start );
1202 foreach ( $args as $root ) {
1203 if ( $root instanceof PPNode_DOM
) {
1204 $root = $root->node
;
1206 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1207 $root = array( $root );
1209 foreach ( $root as $node ) {
1222 function __toString() {
1226 function getPDBK( $level = false ) {
1227 if ( $level === false ) {
1228 return $this->title
->getPrefixedDBkey();
1230 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1234 function getArguments() {
1238 function getNumberedArguments() {
1242 function getNamedArguments() {
1247 * Returns true if there are no arguments in this frame
1249 function isEmpty() {
1253 function getArgument( $name ) {
1258 * Returns true if the infinite loop check is OK, false if a loop is detected
1260 function loopCheck( $title ) {
1261 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1265 * Return true if the frame is a template frame
1267 function isTemplate() {
1273 * Expansion frame with template arguments
1276 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1277 var $numberedArgs, $namedArgs, $parent;
1278 var $numberedExpansionCache, $namedExpansionCache;
1280 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1281 parent
::__construct( $preprocessor );
1283 $this->parent
= $parent;
1284 $this->numberedArgs
= $numberedArgs;
1285 $this->namedArgs
= $namedArgs;
1286 $this->title
= $title;
1287 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1288 $this->titleCache
= $parent->titleCache
;
1289 $this->titleCache
[] = $pdbk;
1290 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1291 if ( $pdbk !== false ) {
1292 $this->loopCheckHash
[$pdbk] = true;
1294 $this->depth
= $parent->depth +
1;
1295 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1298 function __toString() {
1301 $args = $this->numberedArgs +
$this->namedArgs
;
1302 foreach ( $args as $name => $value ) {
1308 $s .= "\"$name\":\"" .
1309 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1315 * Returns true if there are no arguments in this frame
1317 function isEmpty() {
1318 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1321 function getArguments() {
1322 $arguments = array();
1323 foreach ( array_merge(
1324 array_keys($this->numberedArgs
),
1325 array_keys($this->namedArgs
)) as $key ) {
1326 $arguments[$key] = $this->getArgument($key);
1331 function getNumberedArguments() {
1332 $arguments = array();
1333 foreach ( array_keys($this->numberedArgs
) as $key ) {
1334 $arguments[$key] = $this->getArgument($key);
1339 function getNamedArguments() {
1340 $arguments = array();
1341 foreach ( array_keys($this->namedArgs
) as $key ) {
1342 $arguments[$key] = $this->getArgument($key);
1347 function getNumberedArgument( $index ) {
1348 if ( !isset( $this->numberedArgs
[$index] ) ) {
1351 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1352 # No trimming for unnamed arguments
1353 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1355 return $this->numberedExpansionCache
[$index];
1358 function getNamedArgument( $name ) {
1359 if ( !isset( $this->namedArgs
[$name] ) ) {
1362 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1363 # Trim named arguments post-expand, for backwards compatibility
1364 $this->namedExpansionCache
[$name] = trim(
1365 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1367 return $this->namedExpansionCache
[$name];
1370 function getArgument( $name ) {
1371 $text = $this->getNumberedArgument( $name );
1372 if ( $text === false ) {
1373 $text = $this->getNamedArgument( $name );
1379 * Return true if the frame is a template frame
1381 function isTemplate() {
1387 * Expansion frame with custom arguments
1390 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1393 function __construct( $preprocessor, $args ) {
1394 parent
::__construct( $preprocessor );
1395 $this->args
= $args;
1398 function __toString() {
1401 foreach ( $this->args
as $name => $value ) {
1407 $s .= "\"$name\":\"" .
1408 str_replace( '"', '\\"', $value->__toString() ) . '"';
1414 function isEmpty() {
1415 return !count( $this->args
);
1418 function getArgument( $index ) {
1419 if ( !isset( $this->args
[$index] ) ) {
1422 return $this->args
[$index];
1429 class PPNode_DOM
implements PPNode
{
1432 function __construct( $node, $xpath = false ) {
1433 $this->node
= $node;
1439 function getXPath() {
1440 if ( $this->xpath
=== null ) {
1441 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1443 return $this->xpath
;
1446 function __toString() {
1447 if ( $this->node
instanceof DOMNodeList
) {
1449 foreach ( $this->node
as $node ) {
1450 $s .= $node->ownerDocument
->saveXML( $node );
1453 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1459 * @return bool|PPNode_DOM
1461 function getChildren() {
1462 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1466 * @return bool|PPNode_DOM
1468 function getFirstChild() {
1469 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1473 * @return bool|PPNode_DOM
1475 function getNextSibling() {
1476 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1482 * @return bool|PPNode_DOM
1484 function getChildrenOfType( $type ) {
1485 return new self( $this->getXPath()->query( $type, $this->node
) );
1491 function getLength() {
1492 if ( $this->node
instanceof DOMNodeList
) {
1493 return $this->node
->length
;
1501 * @return bool|PPNode_DOM
1503 function item( $i ) {
1504 $item = $this->node
->item( $i );
1505 return $item ?
new self( $item ) : false;
1511 function getName() {
1512 if ( $this->node
instanceof DOMNodeList
) {
1515 return $this->node
->nodeName
;
1520 * Split a <part> node into an associative array containing:
1522 * index String index
1523 * value PPNode value
1527 function splitArg() {
1528 $xpath = $this->getXPath();
1529 $names = $xpath->query( 'name', $this->node
);
1530 $values = $xpath->query( 'value', $this->node
);
1531 if ( !$names->length ||
!$values->length
) {
1532 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1534 $name = $names->item( 0 );
1535 $index = $name->getAttribute( 'index' );
1537 'name' => new self( $name ),
1539 'value' => new self( $values->item( 0 ) ) );
1543 * Split an <ext> node into an associative array containing name, attr, inner and close
1544 * All values in the resulting array are PPNodes. Inner and close are optional.
1548 function splitExt() {
1549 $xpath = $this->getXPath();
1550 $names = $xpath->query( 'name', $this->node
);
1551 $attrs = $xpath->query( 'attr', $this->node
);
1552 $inners = $xpath->query( 'inner', $this->node
);
1553 $closes = $xpath->query( 'close', $this->node
);
1554 if ( !$names->length ||
!$attrs->length
) {
1555 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1558 'name' => new self( $names->item( 0 ) ),
1559 'attr' => new self( $attrs->item( 0 ) ) );
1560 if ( $inners->length
) {
1561 $parts['inner'] = new self( $inners->item( 0 ) );
1563 if ( $closes->length
) {
1564 $parts['close'] = new self( $closes->item( 0 ) );
1572 function splitHeading() {
1573 if ( $this->getName() !== 'h' ) {
1574 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1577 'i' => $this->node
->getAttribute( 'i' ),
1578 'level' => $this->node
->getAttribute( 'level' ),
1579 'contents' => $this->getChildren()