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
516 elseif ( $found == 'open' ) {
517 # count opening brace characters
518 $count = strspn( $text, $curChar, $i );
520 # we need to add to stack only if opening brace count is enough for one of the rules
521 if ( $count >= $rule['min'] ) {
522 # Add it to the stack
525 'close' => $rule['end'],
527 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
530 $stack->push( $piece );
531 $accum =& $stack->getAccum();
532 $flags = $stack->getFlags();
535 # Add literal brace(s)
536 $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)
550 $rule = $rules[$piece->open
];
551 if ( $count > $rule['max'] ) {
552 # The specified maximum exists in the callback array, unless the caller
554 $matchingCount = $rule['max'];
556 # Count is less than the maximum
557 # Skip any gaps in the callback array to find the true largest match
558 # Need to use array_key_exists not isset because the callback can be null
559 $matchingCount = $count;
560 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
565 if ($matchingCount <= 0) {
566 # No matching element found in callback array
567 # Output a literal closing brace and continue
568 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
572 $name = $rule['names'][$matchingCount];
573 if ( $name === null ) {
574 // No element, just literal text
575 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
578 # Note: $parts is already XML, does not need to be encoded further
579 $parts = $piece->parts
;
580 $title = $parts[0]->out
;
583 # The invocation is at the start of the line if lineStart is set in
584 # the stack, and all opening brackets are used up.
585 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
586 $attr = ' lineStart="1"';
591 $element = "<$name$attr>";
592 $element .= "<title>$title</title>";
594 foreach ( $parts as $partIndex => $part ) {
595 if ( isset( $part->eqpos
) ) {
596 $argName = substr( $part->out
, 0, $part->eqpos
);
597 $argValue = substr( $part->out
, $part->eqpos +
1 );
598 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
600 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
604 $element .= "</$name>";
607 # Advance input pointer
608 $i +
= $matchingCount;
612 $accum =& $stack->getAccum();
614 # Re-add the old stack element if it still has unmatched opening characters remaining
615 if ($matchingCount < $piece->count
) {
616 $piece->parts
= array( new PPDPart
);
617 $piece->count
-= $matchingCount;
618 # do we still qualify for any callback with remaining count?
619 $names = $rules[$piece->open
]['names'];
621 $enclosingAccum =& $accum;
622 while ( $piece->count
) {
623 if ( array_key_exists( $piece->count
, $names ) ) {
624 $stack->push( $piece );
625 $accum =& $stack->getAccum();
631 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
633 $flags = $stack->getFlags();
636 # Add XML element to the enclosing accumulator
640 elseif ( $found == 'pipe' ) {
641 $findEquals = true; // shortcut for getFlags()
643 $accum =& $stack->getAccum();
647 elseif ( $found == 'equals' ) {
648 $findEquals = false; // shortcut for getFlags()
649 $stack->getCurrentPart()->eqpos
= strlen( $accum );
655 # Output any remaining unclosed brackets
656 foreach ( $stack->stack
as $piece ) {
657 $stack->rootAccum
.= $piece->breakSyntax();
659 $stack->rootAccum
.= '</root>';
660 $xml = $stack->rootAccum
;
662 wfProfileOut( __METHOD__
);
669 * Stack class to help Preprocessor::preprocessToObj()
673 var $stack, $rootAccum, $top;
675 var $elementClass = 'PPDStackElement';
677 static $false = false;
679 function __construct() {
680 $this->stack
= array();
682 $this->rootAccum
= '';
683 $this->accum
=& $this->rootAccum
;
687 return count( $this->stack
);
690 function &getAccum() {
694 function getCurrentPart() {
695 if ( $this->top
=== false ) {
698 return $this->top
->getCurrentPart();
702 function push( $data ) {
703 if ( $data instanceof $this->elementClass
) {
704 $this->stack
[] = $data;
706 $class = $this->elementClass
;
707 $this->stack
[] = new $class( $data );
709 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
710 $this->accum
=& $this->top
->getAccum();
714 if ( !count( $this->stack
) ) {
715 throw new MWException( __METHOD__
.': no elements remaining' );
717 $temp = array_pop( $this->stack
);
719 if ( count( $this->stack
) ) {
720 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
721 $this->accum
=& $this->top
->getAccum();
723 $this->top
= self
::$false;
724 $this->accum
=& $this->rootAccum
;
729 function addPart( $s = '' ) {
730 $this->top
->addPart( $s );
731 $this->accum
=& $this->top
->getAccum();
734 function getFlags() {
735 if ( !count( $this->stack
) ) {
737 'findEquals' => false,
739 'inHeading' => false,
742 return $this->top
->getFlags();
750 class PPDStackElement
{
751 var $open, // Opening character (\n for heading)
752 $close, // Matching closing character
753 $count, // Number of opening characters found (number of "=" for heading)
754 $parts, // Array of PPDPart objects describing pipe-separated parts.
755 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
757 var $partClass = 'PPDPart';
759 function __construct( $data = array() ) {
760 $class = $this->partClass
;
761 $this->parts
= array( new $class );
763 foreach ( $data as $name => $value ) {
764 $this->$name = $value;
768 function &getAccum() {
769 return $this->parts
[count($this->parts
) - 1]->out
;
772 function addPart( $s = '' ) {
773 $class = $this->partClass
;
774 $this->parts
[] = new $class( $s );
777 function getCurrentPart() {
778 return $this->parts
[count($this->parts
) - 1];
781 function getFlags() {
782 $partCount = count( $this->parts
);
783 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
785 'findPipe' => $findPipe,
786 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
787 'inHeading' => $this->open
== "\n",
792 * Get the output string that would result if the close is not found.
794 function breakSyntax( $openingCount = false ) {
795 if ( $this->open
== "\n" ) {
796 $s = $this->parts
[0]->out
;
798 if ( $openingCount === false ) {
799 $openingCount = $this->count
;
801 $s = str_repeat( $this->open
, $openingCount );
803 foreach ( $this->parts
as $part ) {
820 var $out; // Output accumulator string
822 // Optional member variables:
823 // eqpos Position of equals sign in output accumulator
824 // commentEnd Past-the-end input pointer for the last comment encountered
825 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
827 function __construct( $out = '' ) {
833 * An expansion frame, used as a context to expand the result of preprocessToObj()
836 class PPFrame_DOM
implements PPFrame
{
837 var $preprocessor, $parser, $title;
841 * Hashtable listing templates which are disallowed for expansion in this frame,
842 * having been encountered previously in parent frames.
847 * Recursion depth of this frame, top = 0
848 * Note that this is NOT the same as expansion depth in expand()
854 * Construct a new preprocessor frame.
855 * @param $preprocessor Preprocessor: The parent preprocessor
857 function __construct( $preprocessor ) {
858 $this->preprocessor
= $preprocessor;
859 $this->parser
= $preprocessor->parser
;
860 $this->title
= $this->parser
->mTitle
;
861 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
862 $this->loopCheckHash
= array();
867 * Create a new child frame
868 * $args is optionally a multi-root PPNode or array containing the template arguments
870 function newChild( $args = false, $title = false ) {
871 $namedArgs = array();
872 $numberedArgs = array();
873 if ( $title === false ) {
874 $title = $this->title
;
876 if ( $args !== false ) {
878 if ( $args instanceof PPNode
) {
881 foreach ( $args as $arg ) {
883 $xpath = new DOMXPath( $arg->ownerDocument
);
886 $nameNodes = $xpath->query( 'name', $arg );
887 $value = $xpath->query( 'value', $arg );
888 if ( $nameNodes->item( 0 )->hasAttributes() ) {
889 // Numbered parameter
890 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
891 $numberedArgs[$index] = $value->item( 0 );
892 unset( $namedArgs[$index] );
895 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
896 $namedArgs[$name] = $value->item( 0 );
897 unset( $numberedArgs[$name] );
901 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
904 function expand( $root, $flags = 0 ) {
905 static $expansionDepth = 0;
906 if ( is_string( $root ) ) {
910 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
912 return '<span class="error">Node-count limit exceeded</span>';
915 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
916 return '<span class="error">Expansion depth limit exceeded</span>';
918 wfProfileIn( __METHOD__
);
921 if ( $root instanceof PPNode_DOM
) {
924 if ( $root instanceof DOMDocument
) {
925 $root = $root->documentElement
;
928 $outStack = array( '', '' );
929 $iteratorStack = array( false, $root );
930 $indexStack = array( 0, 0 );
932 while ( count( $iteratorStack ) > 1 ) {
933 $level = count( $outStack ) - 1;
934 $iteratorNode =& $iteratorStack[ $level ];
935 $out =& $outStack[$level];
936 $index =& $indexStack[$level];
938 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
940 if ( is_array( $iteratorNode ) ) {
941 if ( $index >= count( $iteratorNode ) ) {
942 // All done with this iterator
943 $iteratorStack[$level] = false;
944 $contextNode = false;
946 $contextNode = $iteratorNode[$index];
949 } elseif ( $iteratorNode instanceof DOMNodeList
) {
950 if ( $index >= $iteratorNode->length
) {
951 // All done with this iterator
952 $iteratorStack[$level] = false;
953 $contextNode = false;
955 $contextNode = $iteratorNode->item( $index );
959 // Copy to $contextNode and then delete from iterator stack,
960 // because this is not an iterator but we do have to execute it once
961 $contextNode = $iteratorStack[$level];
962 $iteratorStack[$level] = false;
965 if ( $contextNode instanceof PPNode_DOM
) $contextNode = $contextNode->node
;
967 $newIterator = false;
969 if ( $contextNode === false ) {
971 } elseif ( is_string( $contextNode ) ) {
972 $out .= $contextNode;
973 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
974 $newIterator = $contextNode;
975 } elseif ( $contextNode instanceof DOMNode
) {
976 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
977 $out .= $contextNode->nodeValue
;
978 } elseif ( $contextNode->nodeName
== 'template' ) {
979 # Double-brace expansion
980 $xpath = new DOMXPath( $contextNode->ownerDocument
);
981 $titles = $xpath->query( 'title', $contextNode );
982 $title = $titles->item( 0 );
983 $parts = $xpath->query( 'part', $contextNode );
984 if ( $flags & PPFrame
::NO_TEMPLATES
) {
985 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
987 $lineStart = $contextNode->getAttribute( 'lineStart' );
989 'title' => new PPNode_DOM( $title ),
990 'parts' => new PPNode_DOM( $parts ),
991 'lineStart' => $lineStart );
992 $ret = $this->parser
->braceSubstitution( $params, $this );
993 if ( isset( $ret['object'] ) ) {
994 $newIterator = $ret['object'];
996 $out .= $ret['text'];
999 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1000 # Triple-brace expansion
1001 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1002 $titles = $xpath->query( 'title', $contextNode );
1003 $title = $titles->item( 0 );
1004 $parts = $xpath->query( 'part', $contextNode );
1005 if ( $flags & PPFrame
::NO_ARGS
) {
1006 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1009 'title' => new PPNode_DOM( $title ),
1010 'parts' => new PPNode_DOM( $parts ) );
1011 $ret = $this->parser
->argSubstitution( $params, $this );
1012 if ( isset( $ret['object'] ) ) {
1013 $newIterator = $ret['object'];
1015 $out .= $ret['text'];
1018 } elseif ( $contextNode->nodeName
== 'comment' ) {
1019 # HTML-style comment
1020 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1021 if ( $this->parser
->ot
['html']
1022 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1023 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1027 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1028 # Not in RECOVER_COMMENTS mode (extractSections) though
1029 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1030 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1032 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1034 $out .= $contextNode->textContent
;
1036 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1037 # Output suppression used by <includeonly> etc.
1038 # OT_WIKI will only respect <ignore> in substed templates.
1039 # The other output types respect it unless NO_IGNORE is set.
1040 # extractSections() sets NO_IGNORE and so never respects it.
1041 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1042 $out .= $contextNode->textContent
;
1046 } elseif ( $contextNode->nodeName
== 'ext' ) {
1048 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1049 $names = $xpath->query( 'name', $contextNode );
1050 $attrs = $xpath->query( 'attr', $contextNode );
1051 $inners = $xpath->query( 'inner', $contextNode );
1052 $closes = $xpath->query( 'close', $contextNode );
1054 'name' => new PPNode_DOM( $names->item( 0 ) ),
1055 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1056 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1057 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1059 $out .= $this->parser
->extensionSubstitution( $params, $this );
1060 } elseif ( $contextNode->nodeName
== 'h' ) {
1062 $s = $this->expand( $contextNode->childNodes
, $flags );
1064 # Insert a heading marker only for <h> children of <root>
1065 # This is to stop extractSections from going over multiple tree levels
1066 if ( $contextNode->parentNode
->nodeName
== 'root'
1067 && $this->parser
->ot
['html'] )
1069 # Insert heading index marker
1070 $headingIndex = $contextNode->getAttribute( 'i' );
1071 $titleText = $this->title
->getPrefixedDBkey();
1072 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1073 $serial = count( $this->parser
->mHeadings
) - 1;
1074 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1075 $count = $contextNode->getAttribute( 'level' );
1076 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1077 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1081 # Generic recursive expansion
1082 $newIterator = $contextNode->childNodes
;
1085 wfProfileOut( __METHOD__
);
1086 throw new MWException( __METHOD__
.': Invalid parameter type' );
1089 if ( $newIterator !== false ) {
1090 if ( $newIterator instanceof PPNode_DOM
) {
1091 $newIterator = $newIterator->node
;
1094 $iteratorStack[] = $newIterator;
1096 } elseif ( $iteratorStack[$level] === false ) {
1097 // Return accumulated value to parent
1098 // With tail recursion
1099 while ( $iteratorStack[$level] === false && $level > 0 ) {
1100 $outStack[$level - 1] .= $out;
1101 array_pop( $outStack );
1102 array_pop( $iteratorStack );
1103 array_pop( $indexStack );
1109 wfProfileOut( __METHOD__
);
1110 return $outStack[0];
1113 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1114 $args = array_slice( func_get_args(), 2 );
1118 foreach ( $args as $root ) {
1119 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1120 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1121 $root = array( $root );
1123 foreach ( $root as $node ) {
1129 $s .= $this->expand( $node, $flags );
1136 * Implode with no flags specified
1137 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1139 function implode( $sep /*, ... */ ) {
1140 $args = array_slice( func_get_args(), 1 );
1144 foreach ( $args as $root ) {
1145 if ( $root instanceof PPNode_DOM
) {
1146 $root = $root->node
;
1148 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1149 $root = array( $root );
1151 foreach ( $root as $node ) {
1157 $s .= $this->expand( $node );
1164 * Makes an object that, when expand()ed, will be the same as one obtained
1167 function virtualImplode( $sep /*, ... */ ) {
1168 $args = array_slice( func_get_args(), 1 );
1172 foreach ( $args as $root ) {
1173 if ( $root instanceof PPNode_DOM
) {
1174 $root = $root->node
;
1176 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1177 $root = array( $root );
1179 foreach ( $root as $node ) {
1192 * Virtual implode with brackets
1194 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1195 $args = array_slice( func_get_args(), 3 );
1196 $out = array( $start );
1199 foreach ( $args as $root ) {
1200 if ( $root instanceof PPNode_DOM
) {
1201 $root = $root->node
;
1203 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1204 $root = array( $root );
1206 foreach ( $root as $node ) {
1219 function __toString() {
1223 function getPDBK( $level = false ) {
1224 if ( $level === false ) {
1225 return $this->title
->getPrefixedDBkey();
1227 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1231 function getArguments() {
1235 function getNumberedArguments() {
1239 function getNamedArguments() {
1244 * Returns true if there are no arguments in this frame
1246 function isEmpty() {
1250 function getArgument( $name ) {
1255 * Returns true if the infinite loop check is OK, false if a loop is detected
1257 function loopCheck( $title ) {
1258 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1262 * Return true if the frame is a template frame
1264 function isTemplate() {
1270 * Expansion frame with template arguments
1273 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1274 var $numberedArgs, $namedArgs, $parent;
1275 var $numberedExpansionCache, $namedExpansionCache;
1277 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1278 parent
::__construct( $preprocessor );
1280 $this->parent
= $parent;
1281 $this->numberedArgs
= $numberedArgs;
1282 $this->namedArgs
= $namedArgs;
1283 $this->title
= $title;
1284 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1285 $this->titleCache
= $parent->titleCache
;
1286 $this->titleCache
[] = $pdbk;
1287 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1288 if ( $pdbk !== false ) {
1289 $this->loopCheckHash
[$pdbk] = true;
1291 $this->depth
= $parent->depth +
1;
1292 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1295 function __toString() {
1298 $args = $this->numberedArgs +
$this->namedArgs
;
1299 foreach ( $args as $name => $value ) {
1305 $s .= "\"$name\":\"" .
1306 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1312 * Returns true if there are no arguments in this frame
1314 function isEmpty() {
1315 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1318 function getArguments() {
1319 $arguments = array();
1320 foreach ( array_merge(
1321 array_keys($this->numberedArgs
),
1322 array_keys($this->namedArgs
)) as $key ) {
1323 $arguments[$key] = $this->getArgument($key);
1328 function getNumberedArguments() {
1329 $arguments = array();
1330 foreach ( array_keys($this->numberedArgs
) as $key ) {
1331 $arguments[$key] = $this->getArgument($key);
1336 function getNamedArguments() {
1337 $arguments = array();
1338 foreach ( array_keys($this->namedArgs
) as $key ) {
1339 $arguments[$key] = $this->getArgument($key);
1344 function getNumberedArgument( $index ) {
1345 if ( !isset( $this->numberedArgs
[$index] ) ) {
1348 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1349 # No trimming for unnamed arguments
1350 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1352 return $this->numberedExpansionCache
[$index];
1355 function getNamedArgument( $name ) {
1356 if ( !isset( $this->namedArgs
[$name] ) ) {
1359 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1360 # Trim named arguments post-expand, for backwards compatibility
1361 $this->namedExpansionCache
[$name] = trim(
1362 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1364 return $this->namedExpansionCache
[$name];
1367 function getArgument( $name ) {
1368 $text = $this->getNumberedArgument( $name );
1369 if ( $text === false ) {
1370 $text = $this->getNamedArgument( $name );
1376 * Return true if the frame is a template frame
1378 function isTemplate() {
1384 * Expansion frame with custom arguments
1387 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1390 function __construct( $preprocessor, $args ) {
1391 parent
::__construct( $preprocessor );
1392 $this->args
= $args;
1395 function __toString() {
1398 foreach ( $this->args
as $name => $value ) {
1404 $s .= "\"$name\":\"" .
1405 str_replace( '"', '\\"', $value->__toString() ) . '"';
1411 function isEmpty() {
1412 return !count( $this->args
);
1415 function getArgument( $index ) {
1416 if ( !isset( $this->args
[$index] ) ) {
1419 return $this->args
[$index];
1426 class PPNode_DOM
implements PPNode
{
1429 function __construct( $node, $xpath = false ) {
1430 $this->node
= $node;
1433 function __get( $name ) {
1434 if ( $name == 'xpath' ) {
1435 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1437 return $this->xpath
;
1440 function __toString() {
1441 if ( $this->node
instanceof DOMNodeList
) {
1443 foreach ( $this->node
as $node ) {
1444 $s .= $node->ownerDocument
->saveXML( $node );
1447 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1452 function getChildren() {
1453 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1456 function getFirstChild() {
1457 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1460 function getNextSibling() {
1461 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1464 function getChildrenOfType( $type ) {
1465 return new self( $this->xpath
->query( $type, $this->node
) );
1468 function getLength() {
1469 if ( $this->node
instanceof DOMNodeList
) {
1470 return $this->node
->length
;
1476 function item( $i ) {
1477 $item = $this->node
->item( $i );
1478 return $item ?
new self( $item ) : false;
1481 function getName() {
1482 if ( $this->node
instanceof DOMNodeList
) {
1485 return $this->node
->nodeName
;
1490 * Split a <part> node into an associative array containing:
1492 * index String index
1493 * value PPNode value
1495 function splitArg() {
1496 $names = $this->xpath
->query( 'name', $this->node
);
1497 $values = $this->xpath
->query( 'value', $this->node
);
1498 if ( !$names->length ||
!$values->length
) {
1499 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1501 $name = $names->item( 0 );
1502 $index = $name->getAttribute( 'index' );
1504 'name' => new self( $name ),
1506 'value' => new self( $values->item( 0 ) ) );
1510 * Split an <ext> node into an associative array containing name, attr, inner and close
1511 * All values in the resulting array are PPNodes. Inner and close are optional.
1513 function splitExt() {
1514 $names = $this->xpath
->query( 'name', $this->node
);
1515 $attrs = $this->xpath
->query( 'attr', $this->node
);
1516 $inners = $this->xpath
->query( 'inner', $this->node
);
1517 $closes = $this->xpath
->query( 'close', $this->node
);
1518 if ( !$names->length ||
!$attrs->length
) {
1519 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1522 'name' => new self( $names->item( 0 ) ),
1523 'attr' => new self( $attrs->item( 0 ) ) );
1524 if ( $inners->length
) {
1525 $parts['inner'] = new self( $inners->item( 0 ) );
1527 if ( $closes->length
) {
1528 $parts['close'] = new self( $closes->item( 0 ) );
1536 function splitHeading() {
1537 if ( !$this->nodeName
== 'h' ) {
1538 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1541 'i' => $this->node
->getAttribute( 'i' ),
1542 'level' => $this->node
->getAttribute( 'level' ),
1543 'contents' => $this->getChildren()