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;
31 return new PPFrame_DOM( $this );
34 function newCustomFrame( $args ) {
35 return new PPCustomFrame_DOM( $this, $args );
38 function newPartNodeArray( $values ) {
39 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
43 foreach ( $values as $k => $val ) {
46 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
48 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
54 $dom = new DOMDocument();
55 $dom->loadXML( $xml );
56 $root = $dom->documentElement
;
58 $node = new PPNode_DOM( $root->childNodes
);
63 if ( $this->memoryLimit
=== false ) {
66 $usage = memory_get_usage();
67 if ( $usage > $this->memoryLimit
* 0.9 ) {
68 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
69 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
71 return $usage <= $this->memoryLimit
* 0.8;
75 * Preprocess some wikitext and return the document tree.
76 * This is the ghost of Parser::replace_variables().
78 * @param $text String: the text to parse
79 * @param $flags Integer: bitwise combination of:
80 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
81 * included. Default is to assume a direct page view.
83 * The generated DOM tree must depend only on the input text and the flags.
84 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
86 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
87 * change in the DOM tree for a given text, must be passed through the section identifier
88 * in the section edit link and thus back to extractSections().
90 * The output of this function is currently only cached in process memory, but a persistent
91 * cache may be implemented at a later date which takes further advantage of these strict
92 * dependency requirements.
96 function preprocessToObj( $text, $flags = 0 ) {
97 wfProfileIn( __METHOD__
);
98 global $wgMemc, $wgPreprocessorCacheThreshold;
101 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
103 wfProfileIn( __METHOD__
.'-cacheable' );
105 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
106 $cacheValue = $wgMemc->get( $cacheKey );
108 $version = substr( $cacheValue, 0, 8 );
109 if ( intval( $version ) == self
::CACHE_VERSION
) {
110 $xml = substr( $cacheValue, 8 );
112 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
116 if ( $xml === false ) {
118 wfProfileIn( __METHOD__
.'-cache-miss' );
119 $xml = $this->preprocessToXml( $text, $flags );
120 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
121 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
122 wfProfileOut( __METHOD__
.'-cache-miss' );
123 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
125 $xml = $this->preprocessToXml( $text, $flags );
129 wfProfileIn( __METHOD__
.'-loadXML' );
130 $dom = new DOMDocument
;
131 wfSuppressWarnings();
132 $result = $dom->loadXML( $xml );
135 // Try running the XML through UtfNormal to get rid of invalid characters
136 $xml = UtfNormal
::cleanUp( $xml );
137 $result = $dom->loadXML( $xml );
139 throw new MWException( __METHOD__
.' generated invalid XML' );
142 $obj = new PPNode_DOM( $dom->documentElement
);
143 wfProfileOut( __METHOD__
.'-loadXML' );
145 wfProfileOut( __METHOD__
.'-cacheable' );
147 wfProfileOut( __METHOD__
);
151 function preprocessToXml( $text, $flags = 0 ) {
152 wfProfileIn( __METHOD__
);
165 'names' => array( 2 => null ),
171 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
173 $xmlishElements = $this->parser
->getStripList();
174 $enableOnlyinclude = false;
175 if ( $forInclusion ) {
176 $ignoredTags = array( 'includeonly', '/includeonly' );
177 $ignoredElements = array( 'noinclude' );
178 $xmlishElements[] = 'noinclude';
179 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
180 $enableOnlyinclude = true;
183 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
184 $ignoredElements = array( 'includeonly' );
185 $xmlishElements[] = 'includeonly';
187 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
189 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
190 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
192 $stack = new PPDStack
;
194 $searchBase = "[{<\n"; #}
195 $revText = strrev( $text ); // For fast reverse searches
197 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
198 $accum =& $stack->getAccum(); # Current accumulator
200 $findEquals = false; # True to find equals signs in arguments
201 $findPipe = false; # True to take notice of pipe characters
203 $inHeading = false; # True if $i is inside a possible heading
204 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
205 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
206 $fakeLineStart = true; # Do a line-start run without outputting an LF character
211 if ( $findOnlyinclude ) {
212 // Ignore all input up to the next <onlyinclude>
213 $startPos = strpos( $text, '<onlyinclude>', $i );
214 if ( $startPos === false ) {
215 // Ignored section runs to the end
216 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
219 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
220 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
222 $findOnlyinclude = false;
225 if ( $fakeLineStart ) {
226 $found = 'line-start';
229 # Find next opening brace, closing brace or pipe
230 $search = $searchBase;
231 if ( $stack->top
=== false ) {
232 $currentClosing = '';
234 $currentClosing = $stack->top
->close
;
235 $search .= $currentClosing;
241 // First equals will be for the template
245 # Output literal section, advance input counter
246 $literalLength = strcspn( $text, $search, $i );
247 if ( $literalLength > 0 ) {
248 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
249 $i +
= $literalLength;
251 if ( $i >= strlen( $text ) ) {
252 if ( $currentClosing == "\n" ) {
253 // Do a past-the-end run to finish off the heading
261 $curChar = $text[$i];
262 if ( $curChar == '|' ) {
264 } elseif ( $curChar == '=' ) {
266 } elseif ( $curChar == '<' ) {
268 } elseif ( $curChar == "\n" ) {
272 $found = 'line-start';
274 } elseif ( $curChar == $currentClosing ) {
276 } elseif ( isset( $rules[$curChar] ) ) {
278 $rule = $rules[$curChar];
280 # Some versions of PHP have a strcspn which stops on null characters
281 # Ignore and continue
288 if ( $found == 'angle' ) {
290 // Handle </onlyinclude>
291 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
292 $findOnlyinclude = true;
296 // Determine element name
297 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
298 // Element name missing or not listed
304 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
305 // To avoid leaving blank lines, when a comment is both preceded
306 // and followed by a newline (ignoring spaces), trim leading and
307 // trailing spaces and one of the newlines.
310 $endPos = strpos( $text, '-->', $i +
4 );
311 if ( $endPos === false ) {
312 // Unclosed comment in input, runs to end
313 $inner = substr( $text, $i );
314 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
315 $i = strlen( $text );
317 // Search backwards for leading whitespace
318 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
319 // Search forwards for trailing whitespace
320 // $wsEnd will be the position of the last space
321 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
322 // Eat the line if possible
323 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
324 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
325 // it's a possible beneficial b/c break.
326 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
327 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
329 $startPos = $wsStart;
330 $endPos = $wsEnd +
1;
331 // Remove leading whitespace from the end of the accumulator
332 // Sanity check first though
333 $wsLength = $i - $wsStart;
334 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
335 $accum = substr( $accum, 0, -$wsLength );
337 // Do a line-start run next time to look for headings after the comment
338 $fakeLineStart = true;
340 // No line to eat, just take the comment itself
346 $part = $stack->top
->getCurrentPart();
347 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
348 // Comments abutting, no change in visual end
349 $part->commentEnd
= $wsEnd;
351 $part->visualEnd
= $wsStart;
352 $part->commentEnd
= $endPos;
356 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
357 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
362 $lowerName = strtolower( $name );
363 $attrStart = $i +
strlen( $name ) +
1;
366 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
367 if ( $tagEndPos === false ) {
368 // Infinite backtrack
369 // Disable tag search to prevent worst-case O(N^2) performance
376 // Handle ignored tags
377 if ( in_array( $lowerName, $ignoredTags ) ) {
378 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
384 if ( $text[$tagEndPos-1] == '/' ) {
385 $attrEnd = $tagEndPos - 1;
390 $attrEnd = $tagEndPos;
392 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
393 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
395 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
396 $i = $matches[0][1] +
strlen( $matches[0][0] );
397 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
399 // No end tag -- let it run out to the end of the text.
400 $inner = substr( $text, $tagEndPos +
1 );
401 $i = strlen( $text );
405 // <includeonly> and <noinclude> just become <ignore> tags
406 if ( in_array( $lowerName, $ignoredElements ) ) {
407 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
413 if ( $attrEnd <= $attrStart ) {
416 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
418 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
419 // Note that the attr element contains the whitespace between name and attribute,
420 // this is necessary for precise reconstruction during pre-save transform.
421 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
422 if ( $inner !== null ) {
423 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
425 $accum .= $close . '</ext>';
428 elseif ( $found == 'line-start' ) {
429 // Is this the start of a heading?
430 // Line break belongs before the heading element in any case
431 if ( $fakeLineStart ) {
432 $fakeLineStart = false;
438 $count = strspn( $text, '=', $i, 6 );
439 if ( $count == 1 && $findEquals ) {
440 // DWIM: This looks kind of like a name/value separator
441 // Let's let the equals handler have it and break the potential heading
442 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
443 } elseif ( $count > 0 ) {
447 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
450 $stack->push( $piece );
451 $accum =& $stack->getAccum();
452 $flags = $stack->getFlags();
458 elseif ( $found == 'line-end' ) {
459 $piece = $stack->top
;
460 // A heading must be open, otherwise \n wouldn't have been in the search list
461 assert( $piece->open
== "\n" );
462 $part = $piece->getCurrentPart();
463 // Search back through the input to see if it has a proper close
464 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
465 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
466 $searchStart = $i - $wsLength;
467 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
468 // Comment found at line end
469 // Search for equals signs before the comment
470 $searchStart = $part->visualEnd
;
471 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
473 $count = $piece->count
;
474 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
475 if ( $equalsLength > 0 ) {
476 if ( $searchStart - $equalsLength == $piece->startPos
) {
477 // This is just a single string of equals signs on its own line
478 // Replicate the doHeadings behaviour /={count}(.+)={count}/
479 // First find out how many equals signs there really are (don't stop at 6)
480 $count = $equalsLength;
484 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
487 $count = min( $equalsLength, $count );
490 // Normal match, output <h>
491 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
494 // Single equals sign on its own line, count=0
498 // No match, no <h>, just pass down the inner text
503 $accum =& $stack->getAccum();
504 $flags = $stack->getFlags();
507 // Append the result to the enclosing accumulator
509 // Note that we do NOT increment the input pointer.
510 // This is because the closing linebreak could be the opening linebreak of
511 // another heading. Infinite loops are avoided because the next iteration MUST
512 // hit the heading open case above, which unconditionally increments the
514 } elseif ( $found == 'open' ) {
515 # count opening brace characters
516 $count = strspn( $text, $curChar, $i );
518 # we need to add to stack only if opening brace count is enough for one of the rules
519 if ( $count >= $rule['min'] ) {
520 # Add it to the stack
523 'close' => $rule['end'],
525 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
528 $stack->push( $piece );
529 $accum =& $stack->getAccum();
530 $flags = $stack->getFlags();
533 # Add literal brace(s)
534 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
537 } elseif ( $found == 'close' ) {
538 $piece = $stack->top
;
539 # lets check if there are enough characters for closing brace
540 $maxCount = $piece->count
;
541 $count = strspn( $text, $curChar, $i, $maxCount );
543 # check for maximum matching characters (if there are 5 closing
544 # characters, we will probably need only 3 - depending on the rules)
545 $rule = $rules[$piece->open
];
546 if ( $count > $rule['max'] ) {
547 # The specified maximum exists in the callback array, unless the caller
549 $matchingCount = $rule['max'];
551 # Count is less than the maximum
552 # Skip any gaps in the callback array to find the true largest match
553 # Need to use array_key_exists not isset because the callback can be null
554 $matchingCount = $count;
555 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
560 if ($matchingCount <= 0) {
561 # No matching element found in callback array
562 # Output a literal closing brace and continue
563 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
567 $name = $rule['names'][$matchingCount];
568 if ( $name === null ) {
569 // No element, just literal text
570 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
573 # Note: $parts is already XML, does not need to be encoded further
574 $parts = $piece->parts
;
575 $title = $parts[0]->out
;
578 # The invocation is at the start of the line if lineStart is set in
579 # the stack, and all opening brackets are used up.
580 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
581 $attr = ' lineStart="1"';
586 $element = "<$name$attr>";
587 $element .= "<title>$title</title>";
589 foreach ( $parts as $part ) {
590 if ( isset( $part->eqpos
) ) {
591 $argName = substr( $part->out
, 0, $part->eqpos
);
592 $argValue = substr( $part->out
, $part->eqpos +
1 );
593 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
595 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
599 $element .= "</$name>";
602 # Advance input pointer
603 $i +
= $matchingCount;
607 $accum =& $stack->getAccum();
609 # Re-add the old stack element if it still has unmatched opening characters remaining
610 if ($matchingCount < $piece->count
) {
611 $piece->parts
= array( new PPDPart
);
612 $piece->count
-= $matchingCount;
613 # do we still qualify for any callback with remaining count?
614 $names = $rules[$piece->open
]['names'];
616 $enclosingAccum =& $accum;
617 while ( $piece->count
) {
618 if ( array_key_exists( $piece->count
, $names ) ) {
619 $stack->push( $piece );
620 $accum =& $stack->getAccum();
626 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
628 $flags = $stack->getFlags();
631 # Add XML element to the enclosing accumulator
635 elseif ( $found == 'pipe' ) {
636 $findEquals = true; // shortcut for getFlags()
638 $accum =& $stack->getAccum();
642 elseif ( $found == 'equals' ) {
643 $findEquals = false; // shortcut for getFlags()
644 $stack->getCurrentPart()->eqpos
= strlen( $accum );
650 # Output any remaining unclosed brackets
651 foreach ( $stack->stack
as $piece ) {
652 $stack->rootAccum
.= $piece->breakSyntax();
654 $stack->rootAccum
.= '</root>';
655 $xml = $stack->rootAccum
;
657 wfProfileOut( __METHOD__
);
664 * Stack class to help Preprocessor::preprocessToObj()
668 var $stack, $rootAccum, $top;
670 var $elementClass = 'PPDStackElement';
672 static $false = false;
674 function __construct() {
675 $this->stack
= array();
677 $this->rootAccum
= '';
678 $this->accum
=& $this->rootAccum
;
682 return count( $this->stack
);
685 function &getAccum() {
689 function getCurrentPart() {
690 if ( $this->top
=== false ) {
693 return $this->top
->getCurrentPart();
697 function push( $data ) {
698 if ( $data instanceof $this->elementClass
) {
699 $this->stack
[] = $data;
701 $class = $this->elementClass
;
702 $this->stack
[] = new $class( $data );
704 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
705 $this->accum
=& $this->top
->getAccum();
709 if ( !count( $this->stack
) ) {
710 throw new MWException( __METHOD__
.': no elements remaining' );
712 $temp = array_pop( $this->stack
);
714 if ( count( $this->stack
) ) {
715 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
716 $this->accum
=& $this->top
->getAccum();
718 $this->top
= self
::$false;
719 $this->accum
=& $this->rootAccum
;
724 function addPart( $s = '' ) {
725 $this->top
->addPart( $s );
726 $this->accum
=& $this->top
->getAccum();
729 function getFlags() {
730 if ( !count( $this->stack
) ) {
732 'findEquals' => false,
734 'inHeading' => false,
737 return $this->top
->getFlags();
745 class PPDStackElement
{
746 var $open, // Opening character (\n for heading)
747 $close, // Matching closing character
748 $count, // Number of opening characters found (number of "=" for heading)
749 $parts, // Array of PPDPart objects describing pipe-separated parts.
750 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
752 var $partClass = 'PPDPart';
754 function __construct( $data = array() ) {
755 $class = $this->partClass
;
756 $this->parts
= array( new $class );
758 foreach ( $data as $name => $value ) {
759 $this->$name = $value;
763 function &getAccum() {
764 return $this->parts
[count($this->parts
) - 1]->out
;
767 function addPart( $s = '' ) {
768 $class = $this->partClass
;
769 $this->parts
[] = new $class( $s );
772 function getCurrentPart() {
773 return $this->parts
[count($this->parts
) - 1];
776 function getFlags() {
777 $partCount = count( $this->parts
);
778 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
780 'findPipe' => $findPipe,
781 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
782 'inHeading' => $this->open
== "\n",
787 * Get the output string that would result if the close is not found.
789 function breakSyntax( $openingCount = false ) {
790 if ( $this->open
== "\n" ) {
791 $s = $this->parts
[0]->out
;
793 if ( $openingCount === false ) {
794 $openingCount = $this->count
;
796 $s = str_repeat( $this->open
, $openingCount );
798 foreach ( $this->parts
as $part ) {
815 var $out; // Output accumulator string
817 // Optional member variables:
818 // eqpos Position of equals sign in output accumulator
819 // commentEnd Past-the-end input pointer for the last comment encountered
820 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
822 function __construct( $out = '' ) {
828 * An expansion frame, used as a context to expand the result of preprocessToObj()
831 class PPFrame_DOM
implements PPFrame
{
832 var $preprocessor, $parser, $title;
836 * Hashtable listing templates which are disallowed for expansion in this frame,
837 * having been encountered previously in parent frames.
842 * Recursion depth of this frame, top = 0
843 * Note that this is NOT the same as expansion depth in expand()
849 * Construct a new preprocessor frame.
850 * @param $preprocessor Preprocessor: The parent preprocessor
852 function __construct( $preprocessor ) {
853 $this->preprocessor
= $preprocessor;
854 $this->parser
= $preprocessor->parser
;
855 $this->title
= $this->parser
->mTitle
;
856 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
857 $this->loopCheckHash
= array();
862 * Create a new child frame
863 * $args is optionally a multi-root PPNode or array containing the template arguments
865 function newChild( $args = false, $title = false ) {
866 $namedArgs = array();
867 $numberedArgs = array();
868 if ( $title === false ) {
869 $title = $this->title
;
871 if ( $args !== false ) {
873 if ( $args instanceof PPNode
) {
876 foreach ( $args as $arg ) {
878 $xpath = new DOMXPath( $arg->ownerDocument
);
881 $nameNodes = $xpath->query( 'name', $arg );
882 $value = $xpath->query( 'value', $arg );
883 if ( $nameNodes->item( 0 )->hasAttributes() ) {
884 // Numbered parameter
885 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
886 $numberedArgs[$index] = $value->item( 0 );
887 unset( $namedArgs[$index] );
890 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
891 $namedArgs[$name] = $value->item( 0 );
892 unset( $numberedArgs[$name] );
896 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
899 function expand( $root, $flags = 0 ) {
900 static $expansionDepth = 0;
901 if ( is_string( $root ) ) {
905 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
907 return '<span class="error">Node-count limit exceeded</span>';
910 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
911 return '<span class="error">Expansion depth limit exceeded</span>';
913 wfProfileIn( __METHOD__
);
916 if ( $root instanceof PPNode_DOM
) {
919 if ( $root instanceof DOMDocument
) {
920 $root = $root->documentElement
;
923 $outStack = array( '', '' );
924 $iteratorStack = array( false, $root );
925 $indexStack = array( 0, 0 );
927 while ( count( $iteratorStack ) > 1 ) {
928 $level = count( $outStack ) - 1;
929 $iteratorNode =& $iteratorStack[ $level ];
930 $out =& $outStack[$level];
931 $index =& $indexStack[$level];
933 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
935 if ( is_array( $iteratorNode ) ) {
936 if ( $index >= count( $iteratorNode ) ) {
937 // All done with this iterator
938 $iteratorStack[$level] = false;
939 $contextNode = false;
941 $contextNode = $iteratorNode[$index];
944 } elseif ( $iteratorNode instanceof DOMNodeList
) {
945 if ( $index >= $iteratorNode->length
) {
946 // All done with this iterator
947 $iteratorStack[$level] = false;
948 $contextNode = false;
950 $contextNode = $iteratorNode->item( $index );
954 // Copy to $contextNode and then delete from iterator stack,
955 // because this is not an iterator but we do have to execute it once
956 $contextNode = $iteratorStack[$level];
957 $iteratorStack[$level] = false;
960 if ( $contextNode instanceof PPNode_DOM
) {
961 $contextNode = $contextNode->node
;
964 $newIterator = false;
966 if ( $contextNode === false ) {
968 } elseif ( is_string( $contextNode ) ) {
969 $out .= $contextNode;
970 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
971 $newIterator = $contextNode;
972 } elseif ( $contextNode instanceof DOMNode
) {
973 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
974 $out .= $contextNode->nodeValue
;
975 } elseif ( $contextNode->nodeName
== 'template' ) {
976 # Double-brace expansion
977 $xpath = new DOMXPath( $contextNode->ownerDocument
);
978 $titles = $xpath->query( 'title', $contextNode );
979 $title = $titles->item( 0 );
980 $parts = $xpath->query( 'part', $contextNode );
981 if ( $flags & PPFrame
::NO_TEMPLATES
) {
982 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
984 $lineStart = $contextNode->getAttribute( 'lineStart' );
986 'title' => new PPNode_DOM( $title ),
987 'parts' => new PPNode_DOM( $parts ),
988 'lineStart' => $lineStart );
989 $ret = $this->parser
->braceSubstitution( $params, $this );
990 if ( isset( $ret['object'] ) ) {
991 $newIterator = $ret['object'];
993 $out .= $ret['text'];
996 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
997 # Triple-brace expansion
998 $xpath = new DOMXPath( $contextNode->ownerDocument
);
999 $titles = $xpath->query( 'title', $contextNode );
1000 $title = $titles->item( 0 );
1001 $parts = $xpath->query( 'part', $contextNode );
1002 if ( $flags & PPFrame
::NO_ARGS
) {
1003 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1006 'title' => new PPNode_DOM( $title ),
1007 'parts' => new PPNode_DOM( $parts ) );
1008 $ret = $this->parser
->argSubstitution( $params, $this );
1009 if ( isset( $ret['object'] ) ) {
1010 $newIterator = $ret['object'];
1012 $out .= $ret['text'];
1015 } elseif ( $contextNode->nodeName
== 'comment' ) {
1016 # HTML-style comment
1017 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1018 if ( $this->parser
->ot
['html']
1019 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1020 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1024 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1025 # Not in RECOVER_COMMENTS mode (extractSections) though
1026 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1027 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1029 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1031 $out .= $contextNode->textContent
;
1033 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1034 # Output suppression used by <includeonly> etc.
1035 # OT_WIKI will only respect <ignore> in substed templates.
1036 # The other output types respect it unless NO_IGNORE is set.
1037 # extractSections() sets NO_IGNORE and so never respects it.
1038 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1039 $out .= $contextNode->textContent
;
1043 } elseif ( $contextNode->nodeName
== 'ext' ) {
1045 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1046 $names = $xpath->query( 'name', $contextNode );
1047 $attrs = $xpath->query( 'attr', $contextNode );
1048 $inners = $xpath->query( 'inner', $contextNode );
1049 $closes = $xpath->query( 'close', $contextNode );
1051 'name' => new PPNode_DOM( $names->item( 0 ) ),
1052 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1053 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1054 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1056 $out .= $this->parser
->extensionSubstitution( $params, $this );
1057 } elseif ( $contextNode->nodeName
== 'h' ) {
1059 $s = $this->expand( $contextNode->childNodes
, $flags );
1061 # Insert a heading marker only for <h> children of <root>
1062 # This is to stop extractSections from going over multiple tree levels
1063 if ( $contextNode->parentNode
->nodeName
== 'root'
1064 && $this->parser
->ot
['html'] )
1066 # Insert heading index marker
1067 $headingIndex = $contextNode->getAttribute( 'i' );
1068 $titleText = $this->title
->getPrefixedDBkey();
1069 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1070 $serial = count( $this->parser
->mHeadings
) - 1;
1071 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1072 $count = $contextNode->getAttribute( 'level' );
1073 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1074 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1078 # Generic recursive expansion
1079 $newIterator = $contextNode->childNodes
;
1082 wfProfileOut( __METHOD__
);
1083 throw new MWException( __METHOD__
.': Invalid parameter type' );
1086 if ( $newIterator !== false ) {
1087 if ( $newIterator instanceof PPNode_DOM
) {
1088 $newIterator = $newIterator->node
;
1091 $iteratorStack[] = $newIterator;
1093 } elseif ( $iteratorStack[$level] === false ) {
1094 // Return accumulated value to parent
1095 // With tail recursion
1096 while ( $iteratorStack[$level] === false && $level > 0 ) {
1097 $outStack[$level - 1] .= $out;
1098 array_pop( $outStack );
1099 array_pop( $iteratorStack );
1100 array_pop( $indexStack );
1106 wfProfileOut( __METHOD__
);
1107 return $outStack[0];
1110 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1111 $args = array_slice( func_get_args(), 2 );
1115 foreach ( $args as $root ) {
1116 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1117 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1118 $root = array( $root );
1120 foreach ( $root as $node ) {
1126 $s .= $this->expand( $node, $flags );
1133 * Implode with no flags specified
1134 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1136 function implode( $sep /*, ... */ ) {
1137 $args = array_slice( func_get_args(), 1 );
1141 foreach ( $args as $root ) {
1142 if ( $root instanceof PPNode_DOM
) {
1143 $root = $root->node
;
1145 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1146 $root = array( $root );
1148 foreach ( $root as $node ) {
1154 $s .= $this->expand( $node );
1161 * Makes an object that, when expand()ed, will be the same as one obtained
1164 function virtualImplode( $sep /*, ... */ ) {
1165 $args = array_slice( func_get_args(), 1 );
1169 foreach ( $args as $root ) {
1170 if ( $root instanceof PPNode_DOM
) {
1171 $root = $root->node
;
1173 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1174 $root = array( $root );
1176 foreach ( $root as $node ) {
1189 * Virtual implode with brackets
1191 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1192 $args = array_slice( func_get_args(), 3 );
1193 $out = array( $start );
1196 foreach ( $args as $root ) {
1197 if ( $root instanceof PPNode_DOM
) {
1198 $root = $root->node
;
1200 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1201 $root = array( $root );
1203 foreach ( $root as $node ) {
1216 function __toString() {
1220 function getPDBK( $level = false ) {
1221 if ( $level === false ) {
1222 return $this->title
->getPrefixedDBkey();
1224 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1228 function getArguments() {
1232 function getNumberedArguments() {
1236 function getNamedArguments() {
1241 * Returns true if there are no arguments in this frame
1243 function isEmpty() {
1247 function getArgument( $name ) {
1252 * Returns true if the infinite loop check is OK, false if a loop is detected
1254 function loopCheck( $title ) {
1255 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1259 * Return true if the frame is a template frame
1261 function isTemplate() {
1267 * Expansion frame with template arguments
1270 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1271 var $numberedArgs, $namedArgs, $parent;
1272 var $numberedExpansionCache, $namedExpansionCache;
1274 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1275 parent
::__construct( $preprocessor );
1277 $this->parent
= $parent;
1278 $this->numberedArgs
= $numberedArgs;
1279 $this->namedArgs
= $namedArgs;
1280 $this->title
= $title;
1281 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1282 $this->titleCache
= $parent->titleCache
;
1283 $this->titleCache
[] = $pdbk;
1284 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1285 if ( $pdbk !== false ) {
1286 $this->loopCheckHash
[$pdbk] = true;
1288 $this->depth
= $parent->depth +
1;
1289 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1292 function __toString() {
1295 $args = $this->numberedArgs +
$this->namedArgs
;
1296 foreach ( $args as $name => $value ) {
1302 $s .= "\"$name\":\"" .
1303 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1309 * Returns true if there are no arguments in this frame
1311 function isEmpty() {
1312 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1315 function getArguments() {
1316 $arguments = array();
1317 foreach ( array_merge(
1318 array_keys($this->numberedArgs
),
1319 array_keys($this->namedArgs
)) as $key ) {
1320 $arguments[$key] = $this->getArgument($key);
1325 function getNumberedArguments() {
1326 $arguments = array();
1327 foreach ( array_keys($this->numberedArgs
) as $key ) {
1328 $arguments[$key] = $this->getArgument($key);
1333 function getNamedArguments() {
1334 $arguments = array();
1335 foreach ( array_keys($this->namedArgs
) as $key ) {
1336 $arguments[$key] = $this->getArgument($key);
1341 function getNumberedArgument( $index ) {
1342 if ( !isset( $this->numberedArgs
[$index] ) ) {
1345 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1346 # No trimming for unnamed arguments
1347 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1349 return $this->numberedExpansionCache
[$index];
1352 function getNamedArgument( $name ) {
1353 if ( !isset( $this->namedArgs
[$name] ) ) {
1356 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1357 # Trim named arguments post-expand, for backwards compatibility
1358 $this->namedExpansionCache
[$name] = trim(
1359 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1361 return $this->namedExpansionCache
[$name];
1364 function getArgument( $name ) {
1365 $text = $this->getNumberedArgument( $name );
1366 if ( $text === false ) {
1367 $text = $this->getNamedArgument( $name );
1373 * Return true if the frame is a template frame
1375 function isTemplate() {
1381 * Expansion frame with custom arguments
1384 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1387 function __construct( $preprocessor, $args ) {
1388 parent
::__construct( $preprocessor );
1389 $this->args
= $args;
1392 function __toString() {
1395 foreach ( $this->args
as $name => $value ) {
1401 $s .= "\"$name\":\"" .
1402 str_replace( '"', '\\"', $value->__toString() ) . '"';
1408 function isEmpty() {
1409 return !count( $this->args
);
1412 function getArgument( $index ) {
1413 if ( !isset( $this->args
[$index] ) ) {
1416 return $this->args
[$index];
1423 class PPNode_DOM
implements PPNode
{
1426 function __construct( $node, $xpath = false ) {
1427 $this->node
= $node;
1430 function __get( $name ) {
1431 if ( $name == 'xpath' ) {
1432 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1434 return $this->xpath
;
1437 function __toString() {
1438 if ( $this->node
instanceof DOMNodeList
) {
1440 foreach ( $this->node
as $node ) {
1441 $s .= $node->ownerDocument
->saveXML( $node );
1444 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1449 function getChildren() {
1450 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1453 function getFirstChild() {
1454 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1457 function getNextSibling() {
1458 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1461 function getChildrenOfType( $type ) {
1462 return new self( $this->xpath
->query( $type, $this->node
) );
1465 function getLength() {
1466 if ( $this->node
instanceof DOMNodeList
) {
1467 return $this->node
->length
;
1473 function item( $i ) {
1474 $item = $this->node
->item( $i );
1475 return $item ?
new self( $item ) : false;
1478 function getName() {
1479 if ( $this->node
instanceof DOMNodeList
) {
1482 return $this->node
->nodeName
;
1487 * Split a <part> node into an associative array containing:
1489 * index String index
1490 * value PPNode value
1492 function splitArg() {
1493 $names = $this->xpath
->query( 'name', $this->node
);
1494 $values = $this->xpath
->query( 'value', $this->node
);
1495 if ( !$names->length ||
!$values->length
) {
1496 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1498 $name = $names->item( 0 );
1499 $index = $name->getAttribute( 'index' );
1501 'name' => new self( $name ),
1503 'value' => new self( $values->item( 0 ) ) );
1507 * Split an <ext> node into an associative array containing name, attr, inner and close
1508 * All values in the resulting array are PPNodes. Inner and close are optional.
1510 function splitExt() {
1511 $names = $this->xpath
->query( 'name', $this->node
);
1512 $attrs = $this->xpath
->query( 'attr', $this->node
);
1513 $inners = $this->xpath
->query( 'inner', $this->node
);
1514 $closes = $this->xpath
->query( 'close', $this->node
);
1515 if ( !$names->length ||
!$attrs->length
) {
1516 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1519 'name' => new self( $names->item( 0 ) ),
1520 'attr' => new self( $attrs->item( 0 ) ) );
1521 if ( $inners->length
) {
1522 $parts['inner'] = new self( $inners->item( 0 ) );
1524 if ( $closes->length
) {
1525 $parts['close'] = new self( $closes->item( 0 ) );
1533 function splitHeading() {
1534 if ( !$this->nodeName
== 'h' ) {
1535 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1538 'i' => $this->node
->getAttribute( 'i' ),
1539 'level' => $this->node
->getAttribute( 'level' ),
1540 'contents' => $this->getChildren()