3 * Preprocessor using PHP's dom extension
12 class Preprocessor_DOM
implements Preprocessor
{
21 const CACHE_VERSION
= 1;
23 function __construct( $parser ) {
24 $this->parser
= $parser;
25 $mem = ini_get( 'memory_limit' );
26 $this->memoryLimit
= false;
27 if ( strval( $mem ) !== '' && $mem != -1 ) {
28 if ( preg_match( '/^\d+$/', $mem ) ) {
29 $this->memoryLimit
= $mem;
30 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
31 $this->memoryLimit
= $m[1] * 1048576;
40 return new PPFrame_DOM( $this );
45 * @return PPCustomFrame_DOM
47 function newCustomFrame( $args ) {
48 return new PPCustomFrame_DOM( $this, $args );
55 function newPartNodeArray( $values ) {
56 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
59 foreach ( $values as $k => $val ) {
62 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
64 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
70 $dom = new DOMDocument();
71 $dom->loadXML( $xml );
72 $root = $dom->documentElement
;
74 $node = new PPNode_DOM( $root->childNodes
);
83 if ( $this->memoryLimit
=== false ) {
86 $usage = memory_get_usage();
87 if ( $usage > $this->memoryLimit
* 0.9 ) {
88 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
89 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
91 return $usage <= $this->memoryLimit
* 0.8;
95 * Preprocess some wikitext and return the document tree.
96 * This is the ghost of Parser::replace_variables().
98 * @param $text String: the text to parse
99 * @param $flags Integer: bitwise combination of:
100 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
101 * included. Default is to assume a direct page view.
103 * The generated DOM tree must depend only on the input text and the flags.
104 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
106 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
107 * change in the DOM tree for a given text, must be passed through the section identifier
108 * in the section edit link and thus back to extractSections().
110 * The output of this function is currently only cached in process memory, but a persistent
111 * cache may be implemented at a later date which takes further advantage of these strict
112 * dependency requirements.
116 function preprocessToObj( $text, $flags = 0 ) {
117 wfProfileIn( __METHOD__
);
118 global $wgMemc, $wgPreprocessorCacheThreshold;
121 $cacheable = ( $wgPreprocessorCacheThreshold !== false
122 && strlen( $text ) > $wgPreprocessorCacheThreshold );
124 wfProfileIn( __METHOD__
.'-cacheable' );
126 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
127 $cacheValue = $wgMemc->get( $cacheKey );
129 $version = substr( $cacheValue, 0, 8 );
130 if ( intval( $version ) == self
::CACHE_VERSION
) {
131 $xml = substr( $cacheValue, 8 );
133 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
137 if ( $xml === false ) {
139 wfProfileIn( __METHOD__
.'-cache-miss' );
140 $xml = $this->preprocessToXml( $text, $flags );
141 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
142 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
143 wfProfileOut( __METHOD__
.'-cache-miss' );
144 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
146 $xml = $this->preprocessToXml( $text, $flags );
150 wfProfileIn( __METHOD__
.'-loadXML' );
151 $dom = new DOMDocument
;
152 wfSuppressWarnings();
153 $result = $dom->loadXML( $xml );
156 // Try running the XML through UtfNormal to get rid of invalid characters
157 $xml = UtfNormal
::cleanUp( $xml );
158 $result = $dom->loadXML( $xml );
160 throw new MWException( __METHOD__
.' generated invalid XML' );
163 $obj = new PPNode_DOM( $dom->documentElement
);
164 wfProfileOut( __METHOD__
.'-loadXML' );
166 wfProfileOut( __METHOD__
.'-cacheable' );
168 wfProfileOut( __METHOD__
);
173 * @param $text string
177 function preprocessToXml( $text, $flags = 0 ) {
178 wfProfileIn( __METHOD__
);
191 'names' => array( 2 => null ),
197 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
199 $xmlishElements = $this->parser
->getStripList();
200 $enableOnlyinclude = false;
201 if ( $forInclusion ) {
202 $ignoredTags = array( 'includeonly', '/includeonly' );
203 $ignoredElements = array( 'noinclude' );
204 $xmlishElements[] = 'noinclude';
205 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
206 $enableOnlyinclude = true;
209 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
210 $ignoredElements = array( 'includeonly' );
211 $xmlishElements[] = 'includeonly';
213 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
215 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
216 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
218 $stack = new PPDStack
;
220 $searchBase = "[{<\n"; #}
221 $revText = strrev( $text ); // For fast reverse searches
223 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
224 $accum =& $stack->getAccum(); # Current accumulator
226 $findEquals = false; # True to find equals signs in arguments
227 $findPipe = false; # True to take notice of pipe characters
229 $inHeading = false; # True if $i is inside a possible heading
230 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
231 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
232 $fakeLineStart = true; # Do a line-start run without outputting an LF character
237 if ( $findOnlyinclude ) {
238 // Ignore all input up to the next <onlyinclude>
239 $startPos = strpos( $text, '<onlyinclude>', $i );
240 if ( $startPos === false ) {
241 // Ignored section runs to the end
242 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
245 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
246 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
248 $findOnlyinclude = false;
251 if ( $fakeLineStart ) {
252 $found = 'line-start';
255 # Find next opening brace, closing brace or pipe
256 $search = $searchBase;
257 if ( $stack->top
=== false ) {
258 $currentClosing = '';
260 $currentClosing = $stack->top
->close
;
261 $search .= $currentClosing;
267 // First equals will be for the template
271 # Output literal section, advance input counter
272 $literalLength = strcspn( $text, $search, $i );
273 if ( $literalLength > 0 ) {
274 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
275 $i +
= $literalLength;
277 if ( $i >= strlen( $text ) ) {
278 if ( $currentClosing == "\n" ) {
279 // Do a past-the-end run to finish off the heading
287 $curChar = $text[$i];
288 if ( $curChar == '|' ) {
290 } elseif ( $curChar == '=' ) {
292 } elseif ( $curChar == '<' ) {
294 } elseif ( $curChar == "\n" ) {
298 $found = 'line-start';
300 } elseif ( $curChar == $currentClosing ) {
302 } elseif ( isset( $rules[$curChar] ) ) {
304 $rule = $rules[$curChar];
306 # Some versions of PHP have a strcspn which stops on null characters
307 # Ignore and continue
314 if ( $found == 'angle' ) {
316 // Handle </onlyinclude>
317 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
318 $findOnlyinclude = true;
322 // Determine element name
323 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
324 // Element name missing or not listed
330 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
331 // To avoid leaving blank lines, when a comment is both preceded
332 // and followed by a newline (ignoring spaces), trim leading and
333 // trailing spaces and one of the newlines.
336 $endPos = strpos( $text, '-->', $i +
4 );
337 if ( $endPos === false ) {
338 // Unclosed comment in input, runs to end
339 $inner = substr( $text, $i );
340 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
341 $i = strlen( $text );
343 // Search backwards for leading whitespace
344 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
345 // Search forwards for trailing whitespace
346 // $wsEnd will be the position of the last space (or the '>' if there's none)
347 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
348 // Eat the line if possible
349 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
350 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
351 // it's a possible beneficial b/c break.
352 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
353 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
355 $startPos = $wsStart;
356 $endPos = $wsEnd +
1;
357 // Remove leading whitespace from the end of the accumulator
358 // Sanity check first though
359 $wsLength = $i - $wsStart;
360 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
361 $accum = substr( $accum, 0, -$wsLength );
363 // Do a line-start run next time to look for headings after the comment
364 $fakeLineStart = true;
366 // No line to eat, just take the comment itself
372 $part = $stack->top
->getCurrentPart();
373 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
374 $part->visualEnd
= $wsStart;
376 // Else comments abutting, no change in visual end
377 $part->commentEnd
= $endPos;
380 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
381 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
386 $lowerName = strtolower( $name );
387 $attrStart = $i +
strlen( $name ) +
1;
390 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
391 if ( $tagEndPos === false ) {
392 // Infinite backtrack
393 // Disable tag search to prevent worst-case O(N^2) performance
400 // Handle ignored tags
401 if ( in_array( $lowerName, $ignoredTags ) ) {
402 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
408 if ( $text[$tagEndPos-1] == '/' ) {
409 $attrEnd = $tagEndPos - 1;
414 $attrEnd = $tagEndPos;
416 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
417 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
419 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
420 $i = $matches[0][1] +
strlen( $matches[0][0] );
421 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
423 // No end tag -- let it run out to the end of the text.
424 $inner = substr( $text, $tagEndPos +
1 );
425 $i = strlen( $text );
429 // <includeonly> and <noinclude> just become <ignore> tags
430 if ( in_array( $lowerName, $ignoredElements ) ) {
431 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
437 if ( $attrEnd <= $attrStart ) {
440 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
442 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
443 // Note that the attr element contains the whitespace between name and attribute,
444 // this is necessary for precise reconstruction during pre-save transform.
445 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
446 if ( $inner !== null ) {
447 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
449 $accum .= $close . '</ext>';
450 } elseif ( $found == 'line-start' ) {
451 // Is this the start of a heading?
452 // Line break belongs before the heading element in any case
453 if ( $fakeLineStart ) {
454 $fakeLineStart = false;
460 $count = strspn( $text, '=', $i, 6 );
461 if ( $count == 1 && $findEquals ) {
462 // DWIM: This looks kind of like a name/value separator
463 // Let's let the equals handler have it and break the potential heading
464 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
465 } elseif ( $count > 0 ) {
469 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
472 $stack->push( $piece );
473 $accum =& $stack->getAccum();
474 $flags = $stack->getFlags();
478 } elseif ( $found == 'line-end' ) {
479 $piece = $stack->top
;
480 // A heading must be open, otherwise \n wouldn't have been in the search list
481 assert( $piece->open
== "\n" );
482 $part = $piece->getCurrentPart();
483 // Search back through the input to see if it has a proper close
484 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
485 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
486 $searchStart = $i - $wsLength;
487 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
488 // Comment found at line end
489 // Search for equals signs before the comment
490 $searchStart = $part->visualEnd
;
491 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
493 $count = $piece->count
;
494 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
495 if ( $equalsLength > 0 ) {
496 if ( $searchStart - $equalsLength == $piece->startPos
) {
497 // This is just a single string of equals signs on its own line
498 // Replicate the doHeadings behaviour /={count}(.+)={count}/
499 // First find out how many equals signs there really are (don't stop at 6)
500 $count = $equalsLength;
504 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
507 $count = min( $equalsLength, $count );
510 // Normal match, output <h>
511 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
514 // Single equals sign on its own line, count=0
518 // No match, no <h>, just pass down the inner text
523 $accum =& $stack->getAccum();
524 $flags = $stack->getFlags();
527 // Append the result to the enclosing accumulator
529 // Note that we do NOT increment the input pointer.
530 // This is because the closing linebreak could be the opening linebreak of
531 // another heading. Infinite loops are avoided because the next iteration MUST
532 // hit the heading open case above, which unconditionally increments the
534 } elseif ( $found == 'open' ) {
535 # count opening brace characters
536 $count = strspn( $text, $curChar, $i );
538 # we need to add to stack only if opening brace count is enough for one of the rules
539 if ( $count >= $rule['min'] ) {
540 # Add it to the stack
543 'close' => $rule['end'],
545 'lineStart' => ($i == 0 ||
$text[$i-1] == "\n"),
548 $stack->push( $piece );
549 $accum =& $stack->getAccum();
550 $flags = $stack->getFlags();
553 # Add literal brace(s)
554 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
557 } elseif ( $found == 'close' ) {
558 $piece = $stack->top
;
559 # lets check if there are enough characters for closing brace
560 $maxCount = $piece->count
;
561 $count = strspn( $text, $curChar, $i, $maxCount );
563 # check for maximum matching characters (if there are 5 closing
564 # characters, we will probably need only 3 - depending on the rules)
565 $rule = $rules[$piece->open
];
566 if ( $count > $rule['max'] ) {
567 # The specified maximum exists in the callback array, unless the caller
569 $matchingCount = $rule['max'];
571 # Count is less than the maximum
572 # Skip any gaps in the callback array to find the true largest match
573 # Need to use array_key_exists not isset because the callback can be null
574 $matchingCount = $count;
575 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
580 if ( $matchingCount <= 0 ) {
581 # No matching element found in callback array
582 # Output a literal closing brace and continue
583 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
587 $name = $rule['names'][$matchingCount];
588 if ( $name === null ) {
589 // No element, just literal text
590 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
593 # Note: $parts is already XML, does not need to be encoded further
594 $parts = $piece->parts
;
595 $title = $parts[0]->out
;
598 # The invocation is at the start of the line if lineStart is set in
599 # the stack, and all opening brackets are used up.
600 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
601 $attr = ' lineStart="1"';
606 $element = "<$name$attr>";
607 $element .= "<title>$title</title>";
609 foreach ( $parts as $part ) {
610 if ( isset( $part->eqpos
) ) {
611 $argName = substr( $part->out
, 0, $part->eqpos
);
612 $argValue = substr( $part->out
, $part->eqpos +
1 );
613 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
615 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
619 $element .= "</$name>";
622 # Advance input pointer
623 $i +
= $matchingCount;
627 $accum =& $stack->getAccum();
629 # Re-add the old stack element if it still has unmatched opening characters remaining
630 if ( $matchingCount < $piece->count
) {
631 $piece->parts
= array( new PPDPart
);
632 $piece->count
-= $matchingCount;
633 # do we still qualify for any callback with remaining count?
634 $names = $rules[$piece->open
]['names'];
636 $enclosingAccum =& $accum;
637 while ( $piece->count
) {
638 if ( array_key_exists( $piece->count
, $names ) ) {
639 $stack->push( $piece );
640 $accum =& $stack->getAccum();
646 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
648 $flags = $stack->getFlags();
651 # Add XML element to the enclosing accumulator
653 } elseif ( $found == 'pipe' ) {
654 $findEquals = true; // shortcut for getFlags()
656 $accum =& $stack->getAccum();
658 } elseif ( $found == 'equals' ) {
659 $findEquals = false; // shortcut for getFlags()
660 $stack->getCurrentPart()->eqpos
= strlen( $accum );
666 # Output any remaining unclosed brackets
667 foreach ( $stack->stack
as $piece ) {
668 $stack->rootAccum
.= $piece->breakSyntax();
670 $stack->rootAccum
.= '</root>';
671 $xml = $stack->rootAccum
;
673 wfProfileOut( __METHOD__
);
680 * Stack class to help Preprocessor::preprocessToObj()
684 var $stack, $rootAccum;
691 var $elementClass = 'PPDStackElement';
693 static $false = false;
695 function __construct() {
696 $this->stack
= array();
698 $this->rootAccum
= '';
699 $this->accum
=& $this->rootAccum
;
706 return count( $this->stack
);
709 function &getAccum() {
713 function getCurrentPart() {
714 if ( $this->top
=== false ) {
717 return $this->top
->getCurrentPart();
721 function push( $data ) {
722 if ( $data instanceof $this->elementClass
) {
723 $this->stack
[] = $data;
725 $class = $this->elementClass
;
726 $this->stack
[] = new $class( $data );
728 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
729 $this->accum
=& $this->top
->getAccum();
733 if ( !count( $this->stack
) ) {
734 throw new MWException( __METHOD__
.': no elements remaining' );
736 $temp = array_pop( $this->stack
);
738 if ( count( $this->stack
) ) {
739 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
740 $this->accum
=& $this->top
->getAccum();
742 $this->top
= self
::$false;
743 $this->accum
=& $this->rootAccum
;
748 function addPart( $s = '' ) {
749 $this->top
->addPart( $s );
750 $this->accum
=& $this->top
->getAccum();
756 function getFlags() {
757 if ( !count( $this->stack
) ) {
759 'findEquals' => false,
761 'inHeading' => false,
764 return $this->top
->getFlags();
772 class PPDStackElement
{
773 var $open, // Opening character (\n for heading)
774 $close, // Matching closing character
775 $count, // Number of opening characters found (number of "=" for heading)
776 $parts, // Array of PPDPart objects describing pipe-separated parts.
777 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
779 var $partClass = 'PPDPart';
781 function __construct( $data = array() ) {
782 $class = $this->partClass
;
783 $this->parts
= array( new $class );
785 foreach ( $data as $name => $value ) {
786 $this->$name = $value;
790 function &getAccum() {
791 return $this->parts
[count($this->parts
) - 1]->out
;
794 function addPart( $s = '' ) {
795 $class = $this->partClass
;
796 $this->parts
[] = new $class( $s );
799 function getCurrentPart() {
800 return $this->parts
[count($this->parts
) - 1];
806 function getFlags() {
807 $partCount = count( $this->parts
);
808 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
810 'findPipe' => $findPipe,
811 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
812 'inHeading' => $this->open
== "\n",
817 * Get the output string that would result if the close is not found.
821 function breakSyntax( $openingCount = false ) {
822 if ( $this->open
== "\n" ) {
823 $s = $this->parts
[0]->out
;
825 if ( $openingCount === false ) {
826 $openingCount = $this->count
;
828 $s = str_repeat( $this->open
, $openingCount );
830 foreach ( $this->parts
as $part ) {
847 var $out; // Output accumulator string
849 // Optional member variables:
850 // eqpos Position of equals sign in output accumulator
851 // commentEnd Past-the-end input pointer for the last comment encountered
852 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
854 function __construct( $out = '' ) {
860 * An expansion frame, used as a context to expand the result of preprocessToObj()
863 class PPFrame_DOM
implements PPFrame
{
882 * Hashtable listing templates which are disallowed for expansion in this frame,
883 * having been encountered previously in parent frames.
888 * Recursion depth of this frame, top = 0
889 * Note that this is NOT the same as expansion depth in expand()
895 * Construct a new preprocessor frame.
896 * @param $preprocessor Preprocessor The parent preprocessor
898 function __construct( $preprocessor ) {
899 $this->preprocessor
= $preprocessor;
900 $this->parser
= $preprocessor->parser
;
901 $this->title
= $this->parser
->mTitle
;
902 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
903 $this->loopCheckHash
= array();
908 * Create a new child frame
909 * $args is optionally a multi-root PPNode or array containing the template arguments
911 * @return PPTemplateFrame_DOM
913 function newChild( $args = false, $title = false ) {
914 $namedArgs = array();
915 $numberedArgs = array();
916 if ( $title === false ) {
917 $title = $this->title
;
919 if ( $args !== false ) {
921 if ( $args instanceof PPNode
) {
924 foreach ( $args as $arg ) {
926 $xpath = new DOMXPath( $arg->ownerDocument
);
929 $nameNodes = $xpath->query( 'name', $arg );
930 $value = $xpath->query( 'value', $arg );
931 if ( $nameNodes->item( 0 )->hasAttributes() ) {
932 // Numbered parameter
933 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
934 $numberedArgs[$index] = $value->item( 0 );
935 unset( $namedArgs[$index] );
938 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
939 $namedArgs[$name] = $value->item( 0 );
940 unset( $numberedArgs[$name] );
944 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
948 * @throws MWException
953 function expand( $root, $flags = 0 ) {
954 static $expansionDepth = 0;
955 if ( is_string( $root ) ) {
959 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
960 return '<span class="error">Node-count limit exceeded</span>';
963 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
964 return '<span class="error">Expansion depth limit exceeded</span>';
966 wfProfileIn( __METHOD__
);
969 if ( $root instanceof PPNode_DOM
) {
972 if ( $root instanceof DOMDocument
) {
973 $root = $root->documentElement
;
976 $outStack = array( '', '' );
977 $iteratorStack = array( false, $root );
978 $indexStack = array( 0, 0 );
980 while ( count( $iteratorStack ) > 1 ) {
981 $level = count( $outStack ) - 1;
982 $iteratorNode =& $iteratorStack[ $level ];
983 $out =& $outStack[$level];
984 $index =& $indexStack[$level];
986 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
988 if ( is_array( $iteratorNode ) ) {
989 if ( $index >= count( $iteratorNode ) ) {
990 // All done with this iterator
991 $iteratorStack[$level] = false;
992 $contextNode = false;
994 $contextNode = $iteratorNode[$index];
997 } elseif ( $iteratorNode instanceof DOMNodeList
) {
998 if ( $index >= $iteratorNode->length
) {
999 // All done with this iterator
1000 $iteratorStack[$level] = false;
1001 $contextNode = false;
1003 $contextNode = $iteratorNode->item( $index );
1007 // Copy to $contextNode and then delete from iterator stack,
1008 // because this is not an iterator but we do have to execute it once
1009 $contextNode = $iteratorStack[$level];
1010 $iteratorStack[$level] = false;
1013 if ( $contextNode instanceof PPNode_DOM
) {
1014 $contextNode = $contextNode->node
;
1017 $newIterator = false;
1019 if ( $contextNode === false ) {
1021 } elseif ( is_string( $contextNode ) ) {
1022 $out .= $contextNode;
1023 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1024 $newIterator = $contextNode;
1025 } elseif ( $contextNode instanceof DOMNode
) {
1026 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1027 $out .= $contextNode->nodeValue
;
1028 } elseif ( $contextNode->nodeName
== 'template' ) {
1029 # Double-brace expansion
1030 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1031 $titles = $xpath->query( 'title', $contextNode );
1032 $title = $titles->item( 0 );
1033 $parts = $xpath->query( 'part', $contextNode );
1034 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1035 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1037 $lineStart = $contextNode->getAttribute( 'lineStart' );
1039 'title' => new PPNode_DOM( $title ),
1040 'parts' => new PPNode_DOM( $parts ),
1041 'lineStart' => $lineStart );
1042 $ret = $this->parser
->braceSubstitution( $params, $this );
1043 if ( isset( $ret['object'] ) ) {
1044 $newIterator = $ret['object'];
1046 $out .= $ret['text'];
1049 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1050 # Triple-brace expansion
1051 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1052 $titles = $xpath->query( 'title', $contextNode );
1053 $title = $titles->item( 0 );
1054 $parts = $xpath->query( 'part', $contextNode );
1055 if ( $flags & PPFrame
::NO_ARGS
) {
1056 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1059 'title' => new PPNode_DOM( $title ),
1060 'parts' => new PPNode_DOM( $parts ) );
1061 $ret = $this->parser
->argSubstitution( $params, $this );
1062 if ( isset( $ret['object'] ) ) {
1063 $newIterator = $ret['object'];
1065 $out .= $ret['text'];
1068 } elseif ( $contextNode->nodeName
== 'comment' ) {
1069 # HTML-style comment
1070 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1071 if ( $this->parser
->ot
['html']
1072 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1073 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1077 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1078 # Not in RECOVER_COMMENTS mode (extractSections) though
1079 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1080 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1082 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1084 $out .= $contextNode->textContent
;
1086 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1087 # Output suppression used by <includeonly> etc.
1088 # OT_WIKI will only respect <ignore> in substed templates.
1089 # The other output types respect it unless NO_IGNORE is set.
1090 # extractSections() sets NO_IGNORE and so never respects it.
1091 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1092 $out .= $contextNode->textContent
;
1096 } elseif ( $contextNode->nodeName
== 'ext' ) {
1098 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1099 $names = $xpath->query( 'name', $contextNode );
1100 $attrs = $xpath->query( 'attr', $contextNode );
1101 $inners = $xpath->query( 'inner', $contextNode );
1102 $closes = $xpath->query( 'close', $contextNode );
1104 'name' => new PPNode_DOM( $names->item( 0 ) ),
1105 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1106 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1107 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1109 $out .= $this->parser
->extensionSubstitution( $params, $this );
1110 } elseif ( $contextNode->nodeName
== 'h' ) {
1112 $s = $this->expand( $contextNode->childNodes
, $flags );
1114 # Insert a heading marker only for <h> children of <root>
1115 # This is to stop extractSections from going over multiple tree levels
1116 if ( $contextNode->parentNode
->nodeName
== 'root'
1117 && $this->parser
->ot
['html'] )
1119 # Insert heading index marker
1120 $headingIndex = $contextNode->getAttribute( 'i' );
1121 $titleText = $this->title
->getPrefixedDBkey();
1122 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1123 $serial = count( $this->parser
->mHeadings
) - 1;
1124 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1125 $count = $contextNode->getAttribute( 'level' );
1126 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1127 $this->parser
->mStripState
->addGeneral( $marker, '' );
1131 # Generic recursive expansion
1132 $newIterator = $contextNode->childNodes
;
1135 wfProfileOut( __METHOD__
);
1136 throw new MWException( __METHOD__
.': Invalid parameter type' );
1139 if ( $newIterator !== false ) {
1140 if ( $newIterator instanceof PPNode_DOM
) {
1141 $newIterator = $newIterator->node
;
1144 $iteratorStack[] = $newIterator;
1146 } elseif ( $iteratorStack[$level] === false ) {
1147 // Return accumulated value to parent
1148 // With tail recursion
1149 while ( $iteratorStack[$level] === false && $level > 0 ) {
1150 $outStack[$level - 1] .= $out;
1151 array_pop( $outStack );
1152 array_pop( $iteratorStack );
1153 array_pop( $indexStack );
1159 wfProfileOut( __METHOD__
);
1160 return $outStack[0];
1168 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1169 $args = array_slice( func_get_args(), 2 );
1173 foreach ( $args as $root ) {
1174 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1175 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1176 $root = array( $root );
1178 foreach ( $root as $node ) {
1184 $s .= $this->expand( $node, $flags );
1191 * Implode with no flags specified
1192 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1196 function implode( $sep /*, ... */ ) {
1197 $args = array_slice( func_get_args(), 1 );
1201 foreach ( $args as $root ) {
1202 if ( $root instanceof PPNode_DOM
) {
1203 $root = $root->node
;
1205 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1206 $root = array( $root );
1208 foreach ( $root as $node ) {
1214 $s .= $this->expand( $node );
1221 * Makes an object that, when expand()ed, will be the same as one obtained
1226 function virtualImplode( $sep /*, ... */ ) {
1227 $args = array_slice( func_get_args(), 1 );
1231 foreach ( $args as $root ) {
1232 if ( $root instanceof PPNode_DOM
) {
1233 $root = $root->node
;
1235 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1236 $root = array( $root );
1238 foreach ( $root as $node ) {
1251 * Virtual implode with brackets
1253 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1254 $args = array_slice( func_get_args(), 3 );
1255 $out = array( $start );
1258 foreach ( $args as $root ) {
1259 if ( $root instanceof PPNode_DOM
) {
1260 $root = $root->node
;
1262 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1263 $root = array( $root );
1265 foreach ( $root as $node ) {
1278 function __toString() {
1282 function getPDBK( $level = false ) {
1283 if ( $level === false ) {
1284 return $this->title
->getPrefixedDBkey();
1286 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1293 function getArguments() {
1300 function getNumberedArguments() {
1307 function getNamedArguments() {
1312 * Returns true if there are no arguments in this frame
1316 function isEmpty() {
1320 function getArgument( $name ) {
1325 * Returns true if the infinite loop check is OK, false if a loop is detected
1329 function loopCheck( $title ) {
1330 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1334 * Return true if the frame is a template frame
1338 function isTemplate() {
1344 * Expansion frame with template arguments
1347 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1348 var $numberedArgs, $namedArgs;
1354 var $numberedExpansionCache, $namedExpansionCache;
1357 * @param $preprocessor
1358 * @param $parent PPFrame_DOM
1359 * @param $numberedArgs array
1360 * @param $namedArgs array
1361 * @param $title Title
1363 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1364 parent
::__construct( $preprocessor );
1366 $this->parent
= $parent;
1367 $this->numberedArgs
= $numberedArgs;
1368 $this->namedArgs
= $namedArgs;
1369 $this->title
= $title;
1370 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1371 $this->titleCache
= $parent->titleCache
;
1372 $this->titleCache
[] = $pdbk;
1373 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1374 if ( $pdbk !== false ) {
1375 $this->loopCheckHash
[$pdbk] = true;
1377 $this->depth
= $parent->depth +
1;
1378 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1381 function __toString() {
1384 $args = $this->numberedArgs +
$this->namedArgs
;
1385 foreach ( $args as $name => $value ) {
1391 $s .= "\"$name\":\"" .
1392 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1399 * Returns true if there are no arguments in this frame
1403 function isEmpty() {
1404 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1407 function getArguments() {
1408 $arguments = array();
1409 foreach ( array_merge(
1410 array_keys($this->numberedArgs
),
1411 array_keys($this->namedArgs
)) as $key ) {
1412 $arguments[$key] = $this->getArgument($key);
1417 function getNumberedArguments() {
1418 $arguments = array();
1419 foreach ( array_keys($this->numberedArgs
) as $key ) {
1420 $arguments[$key] = $this->getArgument($key);
1425 function getNamedArguments() {
1426 $arguments = array();
1427 foreach ( array_keys($this->namedArgs
) as $key ) {
1428 $arguments[$key] = $this->getArgument($key);
1433 function getNumberedArgument( $index ) {
1434 if ( !isset( $this->numberedArgs
[$index] ) ) {
1437 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1438 # No trimming for unnamed arguments
1439 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1441 return $this->numberedExpansionCache
[$index];
1444 function getNamedArgument( $name ) {
1445 if ( !isset( $this->namedArgs
[$name] ) ) {
1448 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1449 # Trim named arguments post-expand, for backwards compatibility
1450 $this->namedExpansionCache
[$name] = trim(
1451 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1453 return $this->namedExpansionCache
[$name];
1456 function getArgument( $name ) {
1457 $text = $this->getNumberedArgument( $name );
1458 if ( $text === false ) {
1459 $text = $this->getNamedArgument( $name );
1465 * Return true if the frame is a template frame
1469 function isTemplate() {
1475 * Expansion frame with custom arguments
1478 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1481 function __construct( $preprocessor, $args ) {
1482 parent
::__construct( $preprocessor );
1483 $this->args
= $args;
1486 function __toString() {
1489 foreach ( $this->args
as $name => $value ) {
1495 $s .= "\"$name\":\"" .
1496 str_replace( '"', '\\"', $value->__toString() ) . '"';
1505 function isEmpty() {
1506 return !count( $this->args
);
1509 function getArgument( $index ) {
1510 if ( !isset( $this->args
[$index] ) ) {
1513 return $this->args
[$index];
1520 class PPNode_DOM
implements PPNode
{
1528 function __construct( $node, $xpath = false ) {
1529 $this->node
= $node;
1535 function getXPath() {
1536 if ( $this->xpath
=== null ) {
1537 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1539 return $this->xpath
;
1542 function __toString() {
1543 if ( $this->node
instanceof DOMNodeList
) {
1545 foreach ( $this->node
as $node ) {
1546 $s .= $node->ownerDocument
->saveXML( $node );
1549 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1555 * @return bool|PPNode_DOM
1557 function getChildren() {
1558 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1562 * @return bool|PPNode_DOM
1564 function getFirstChild() {
1565 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1569 * @return bool|PPNode_DOM
1571 function getNextSibling() {
1572 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1578 * @return bool|PPNode_DOM
1580 function getChildrenOfType( $type ) {
1581 return new self( $this->getXPath()->query( $type, $this->node
) );
1587 function getLength() {
1588 if ( $this->node
instanceof DOMNodeList
) {
1589 return $this->node
->length
;
1597 * @return bool|PPNode_DOM
1599 function item( $i ) {
1600 $item = $this->node
->item( $i );
1601 return $item ?
new self( $item ) : false;
1607 function getName() {
1608 if ( $this->node
instanceof DOMNodeList
) {
1611 return $this->node
->nodeName
;
1616 * Split a <part> node into an associative array containing:
1618 * index String index
1619 * value PPNode value
1623 function splitArg() {
1624 $xpath = $this->getXPath();
1625 $names = $xpath->query( 'name', $this->node
);
1626 $values = $xpath->query( 'value', $this->node
);
1627 if ( !$names->length ||
!$values->length
) {
1628 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1630 $name = $names->item( 0 );
1631 $index = $name->getAttribute( 'index' );
1633 'name' => new self( $name ),
1635 'value' => new self( $values->item( 0 ) ) );
1639 * Split an <ext> node into an associative array containing name, attr, inner and close
1640 * All values in the resulting array are PPNodes. Inner and close are optional.
1644 function splitExt() {
1645 $xpath = $this->getXPath();
1646 $names = $xpath->query( 'name', $this->node
);
1647 $attrs = $xpath->query( 'attr', $this->node
);
1648 $inners = $xpath->query( 'inner', $this->node
);
1649 $closes = $xpath->query( 'close', $this->node
);
1650 if ( !$names->length ||
!$attrs->length
) {
1651 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1654 'name' => new self( $names->item( 0 ) ),
1655 'attr' => new self( $attrs->item( 0 ) ) );
1656 if ( $inners->length
) {
1657 $parts['inner'] = new self( $inners->item( 0 ) );
1659 if ( $closes->length
) {
1660 $parts['close'] = new self( $closes->item( 0 ) );
1668 function splitHeading() {
1669 if ( $this->getName() !== 'h' ) {
1670 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1673 'i' => $this->node
->getAttribute( 'i' ),
1674 'level' => $this->node
->getAttribute( 'level' ),
1675 'contents' => $this->getChildren()