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 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
159 $result = $dom->loadXML( $xml, 1 << 19 );
161 throw new MWException( __METHOD__
.' generated invalid XML' );
164 $obj = new PPNode_DOM( $dom->documentElement
);
165 wfProfileOut( __METHOD__
.'-loadXML' );
167 wfProfileOut( __METHOD__
.'-cacheable' );
169 wfProfileOut( __METHOD__
);
174 * @param $text string
178 function preprocessToXml( $text, $flags = 0 ) {
179 wfProfileIn( __METHOD__
);
192 'names' => array( 2 => null ),
198 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
200 $xmlishElements = $this->parser
->getStripList();
201 $enableOnlyinclude = false;
202 if ( $forInclusion ) {
203 $ignoredTags = array( 'includeonly', '/includeonly' );
204 $ignoredElements = array( 'noinclude' );
205 $xmlishElements[] = 'noinclude';
206 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
207 $enableOnlyinclude = true;
210 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
211 $ignoredElements = array( 'includeonly' );
212 $xmlishElements[] = 'includeonly';
214 // `dws' stands for "discard white spaces". `<dws>' and all the whitespaces afer it are
216 $xmlishElements[] = 'dws';
217 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
219 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
220 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
222 $stack = new PPDStack
;
224 $searchBase = "[{<\n"; #}
225 $revText = strrev( $text ); // For fast reverse searches
227 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
228 $accum =& $stack->getAccum(); # Current accumulator
230 $findEquals = false; # True to find equals signs in arguments
231 $findPipe = false; # True to take notice of pipe characters
233 $inHeading = false; # True if $i is inside a possible heading
234 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
235 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
236 $fakeLineStart = true; # Do a line-start run without outputting an LF character
241 if ( $findOnlyinclude ) {
242 // Ignore all input up to the next <onlyinclude>
243 $startPos = strpos( $text, '<onlyinclude>', $i );
244 if ( $startPos === false ) {
245 // Ignored section runs to the end
246 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
249 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
250 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
252 $findOnlyinclude = false;
255 if ( $fakeLineStart ) {
256 $found = 'line-start';
259 # Find next opening brace, closing brace or pipe
260 $search = $searchBase;
261 if ( $stack->top
=== false ) {
262 $currentClosing = '';
264 $currentClosing = $stack->top
->close
;
265 $search .= $currentClosing;
271 // First equals will be for the template
275 # Output literal section, advance input counter
276 $literalLength = strcspn( $text, $search, $i );
277 if ( $literalLength > 0 ) {
278 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
279 $i +
= $literalLength;
281 if ( $i >= strlen( $text ) ) {
282 if ( $currentClosing == "\n" ) {
283 // Do a past-the-end run to finish off the heading
291 $curChar = $text[$i];
292 if ( $curChar == '|' ) {
294 } elseif ( $curChar == '=' ) {
296 } elseif ( $curChar == '<' ) {
298 } elseif ( $curChar == "\n" ) {
302 $found = 'line-start';
304 } elseif ( $curChar == $currentClosing ) {
306 } elseif ( isset( $rules[$curChar] ) ) {
308 $rule = $rules[$curChar];
310 # Some versions of PHP have a strcspn which stops on null characters
311 # Ignore and continue
318 if ( $found == 'angle' ) {
320 // Handle </onlyinclude>
321 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
322 $findOnlyinclude = true;
326 // Determine element name
327 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
328 // Element name missing or not listed
334 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
335 // To avoid leaving blank lines, when a comment is both preceded
336 // and followed by a newline (ignoring spaces), trim leading and
337 // trailing spaces and one of the newlines.
340 $endPos = strpos( $text, '-->', $i +
4 );
341 if ( $endPos === false ) {
342 // Unclosed comment in input, runs to end
343 $inner = substr( $text, $i );
344 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
345 $i = strlen( $text );
347 // Search backwards for leading whitespace
348 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
349 // Search forwards for trailing whitespace
350 // $wsEnd will be the position of the last space (or the '>' if there's none)
351 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
352 // Eat the line if possible
353 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
354 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
355 // it's a possible beneficial b/c break.
356 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
357 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
359 $startPos = $wsStart;
360 $endPos = $wsEnd +
1;
361 // Remove leading whitespace from the end of the accumulator
362 // Sanity check first though
363 $wsLength = $i - $wsStart;
364 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
365 $accum = substr( $accum, 0, -$wsLength );
367 // Do a line-start run next time to look for headings after the comment
368 $fakeLineStart = true;
370 // No line to eat, just take the comment itself
376 $part = $stack->top
->getCurrentPart();
377 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
378 $part->visualEnd
= $wsStart;
380 // Else comments abutting, no change in visual end
381 $part->commentEnd
= $endPos;
384 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
385 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
390 $lowerName = strtolower( $name );
391 $attrStart = $i +
strlen( $name ) +
1;
394 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
395 if ( $tagEndPos === false ) {
396 // Infinite backtrack
397 // Disable tag search to prevent worst-case O(N^2) performance
404 // Handle ignored tags
405 if ( in_array( $lowerName, $ignoredTags ) ) {
406 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
414 if ( $name == 'dws' ) {
416 if ( preg_match( '/\s*/', $text, $matches, 0, $i ) ) {
417 $i +
= strlen( $matches[0] );
421 htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) ) .
426 if ( $text[$tagEndPos-1] == '/' ) {
427 $attrEnd = $tagEndPos - 1;
432 $attrEnd = $tagEndPos;
434 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
435 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
437 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
438 $i = $matches[0][1] +
strlen( $matches[0][0] );
439 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
441 // No end tag -- let it run out to the end of the text.
442 $inner = substr( $text, $tagEndPos +
1 );
443 $i = strlen( $text );
447 // <includeonly> and <noinclude> just become <ignore> tags
448 if ( in_array( $lowerName, $ignoredElements ) ) {
449 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
455 if ( $attrEnd <= $attrStart ) {
458 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
460 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
461 // Note that the attr element contains the whitespace between name and attribute,
462 // this is necessary for precise reconstruction during pre-save transform.
463 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
464 if ( $inner !== null ) {
465 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
467 $accum .= $close . '</ext>';
468 } elseif ( $found == 'line-start' ) {
469 // Is this the start of a heading?
470 // Line break belongs before the heading element in any case
471 if ( $fakeLineStart ) {
472 $fakeLineStart = false;
478 $count = strspn( $text, '=', $i, 6 );
479 if ( $count == 1 && $findEquals ) {
480 // DWIM: This looks kind of like a name/value separator
481 // Let's let the equals handler have it and break the potential heading
482 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
483 } elseif ( $count > 0 ) {
487 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
490 $stack->push( $piece );
491 $accum =& $stack->getAccum();
492 $flags = $stack->getFlags();
496 } elseif ( $found == 'line-end' ) {
497 $piece = $stack->top
;
498 // A heading must be open, otherwise \n wouldn't have been in the search list
499 assert( $piece->open
== "\n" );
500 $part = $piece->getCurrentPart();
501 // Search back through the input to see if it has a proper close
502 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
503 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
504 $searchStart = $i - $wsLength;
505 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
506 // Comment found at line end
507 // Search for equals signs before the comment
508 $searchStart = $part->visualEnd
;
509 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
511 $count = $piece->count
;
512 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
513 if ( $equalsLength > 0 ) {
514 if ( $searchStart - $equalsLength == $piece->startPos
) {
515 // This is just a single string of equals signs on its own line
516 // Replicate the doHeadings behaviour /={count}(.+)={count}/
517 // First find out how many equals signs there really are (don't stop at 6)
518 $count = $equalsLength;
522 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
525 $count = min( $equalsLength, $count );
528 // Normal match, output <h>
529 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
532 // Single equals sign on its own line, count=0
536 // No match, no <h>, just pass down the inner text
541 $accum =& $stack->getAccum();
542 $flags = $stack->getFlags();
545 // Append the result to the enclosing accumulator
547 // Note that we do NOT increment the input pointer.
548 // This is because the closing linebreak could be the opening linebreak of
549 // another heading. Infinite loops are avoided because the next iteration MUST
550 // hit the heading open case above, which unconditionally increments the
552 } elseif ( $found == 'open' ) {
553 # count opening brace characters
554 $count = strspn( $text, $curChar, $i );
556 # we need to add to stack only if opening brace count is enough for one of the rules
557 if ( $count >= $rule['min'] ) {
558 # Add it to the stack
561 'close' => $rule['end'],
563 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
566 $stack->push( $piece );
567 $accum =& $stack->getAccum();
568 $flags = $stack->getFlags();
571 # Add literal brace(s)
572 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
575 } elseif ( $found == 'close' ) {
576 $piece = $stack->top
;
577 # lets check if there are enough characters for closing brace
578 $maxCount = $piece->count
;
579 $count = strspn( $text, $curChar, $i, $maxCount );
581 # check for maximum matching characters (if there are 5 closing
582 # characters, we will probably need only 3 - depending on the rules)
583 $rule = $rules[$piece->open
];
584 if ( $count > $rule['max'] ) {
585 # The specified maximum exists in the callback array, unless the caller
587 $matchingCount = $rule['max'];
589 # Count is less than the maximum
590 # Skip any gaps in the callback array to find the true largest match
591 # Need to use array_key_exists not isset because the callback can be null
592 $matchingCount = $count;
593 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
598 if ( $matchingCount <= 0 ) {
599 # No matching element found in callback array
600 # Output a literal closing brace and continue
601 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
605 $name = $rule['names'][$matchingCount];
606 if ( $name === null ) {
607 // No element, just literal text
608 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
611 # Note: $parts is already XML, does not need to be encoded further
612 $parts = $piece->parts
;
613 $title = $parts[0]->out
;
616 # The invocation is at the start of the line if lineStart is set in
617 # the stack, and all opening brackets are used up.
618 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
619 $attr = ' lineStart="1"';
624 $element = "<$name$attr>";
625 $element .= "<title>$title</title>";
627 foreach ( $parts as $part ) {
628 if ( isset( $part->eqpos
) ) {
629 $argName = substr( $part->out
, 0, $part->eqpos
);
630 $argValue = substr( $part->out
, $part->eqpos +
1 );
631 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
633 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
637 $element .= "</$name>";
640 # Advance input pointer
641 $i +
= $matchingCount;
645 $accum =& $stack->getAccum();
647 # Re-add the old stack element if it still has unmatched opening characters remaining
648 if ( $matchingCount < $piece->count
) {
649 $piece->parts
= array( new PPDPart
);
650 $piece->count
-= $matchingCount;
651 # do we still qualify for any callback with remaining count?
652 $names = $rules[$piece->open
]['names'];
654 $enclosingAccum =& $accum;
655 while ( $piece->count
) {
656 if ( array_key_exists( $piece->count
, $names ) ) {
657 $stack->push( $piece );
658 $accum =& $stack->getAccum();
664 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
666 $flags = $stack->getFlags();
669 # Add XML element to the enclosing accumulator
671 } elseif ( $found == 'pipe' ) {
672 $findEquals = true; // shortcut for getFlags()
674 $accum =& $stack->getAccum();
676 } elseif ( $found == 'equals' ) {
677 $findEquals = false; // shortcut for getFlags()
678 $stack->getCurrentPart()->eqpos
= strlen( $accum );
684 # Output any remaining unclosed brackets
685 foreach ( $stack->stack
as $piece ) {
686 $stack->rootAccum
.= $piece->breakSyntax();
688 $stack->rootAccum
.= '</root>';
689 $xml = $stack->rootAccum
;
691 wfProfileOut( __METHOD__
);
698 * Stack class to help Preprocessor::preprocessToObj()
702 var $stack, $rootAccum;
709 var $elementClass = 'PPDStackElement';
711 static $false = false;
713 function __construct() {
714 $this->stack
= array();
716 $this->rootAccum
= '';
717 $this->accum
=& $this->rootAccum
;
724 return count( $this->stack
);
727 function &getAccum() {
731 function getCurrentPart() {
732 if ( $this->top
=== false ) {
735 return $this->top
->getCurrentPart();
739 function push( $data ) {
740 if ( $data instanceof $this->elementClass
) {
741 $this->stack
[] = $data;
743 $class = $this->elementClass
;
744 $this->stack
[] = new $class( $data );
746 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
747 $this->accum
=& $this->top
->getAccum();
751 if ( !count( $this->stack
) ) {
752 throw new MWException( __METHOD__
.': no elements remaining' );
754 $temp = array_pop( $this->stack
);
756 if ( count( $this->stack
) ) {
757 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
758 $this->accum
=& $this->top
->getAccum();
760 $this->top
= self
::$false;
761 $this->accum
=& $this->rootAccum
;
766 function addPart( $s = '' ) {
767 $this->top
->addPart( $s );
768 $this->accum
=& $this->top
->getAccum();
774 function getFlags() {
775 if ( !count( $this->stack
) ) {
777 'findEquals' => false,
779 'inHeading' => false,
782 return $this->top
->getFlags();
790 class PPDStackElement
{
791 var $open, // Opening character (\n for heading)
792 $close, // Matching closing character
793 $count, // Number of opening characters found (number of "=" for heading)
794 $parts, // Array of PPDPart objects describing pipe-separated parts.
795 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
797 var $partClass = 'PPDPart';
799 function __construct( $data = array() ) {
800 $class = $this->partClass
;
801 $this->parts
= array( new $class );
803 foreach ( $data as $name => $value ) {
804 $this->$name = $value;
808 function &getAccum() {
809 return $this->parts
[count($this->parts
) - 1]->out
;
812 function addPart( $s = '' ) {
813 $class = $this->partClass
;
814 $this->parts
[] = new $class( $s );
817 function getCurrentPart() {
818 return $this->parts
[count($this->parts
) - 1];
824 function getFlags() {
825 $partCount = count( $this->parts
);
826 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
828 'findPipe' => $findPipe,
829 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
830 'inHeading' => $this->open
== "\n",
835 * Get the output string that would result if the close is not found.
839 function breakSyntax( $openingCount = false ) {
840 if ( $this->open
== "\n" ) {
841 $s = $this->parts
[0]->out
;
843 if ( $openingCount === false ) {
844 $openingCount = $this->count
;
846 $s = str_repeat( $this->open
, $openingCount );
848 foreach ( $this->parts
as $part ) {
865 var $out; // Output accumulator string
867 // Optional member variables:
868 // eqpos Position of equals sign in output accumulator
869 // commentEnd Past-the-end input pointer for the last comment encountered
870 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
872 function __construct( $out = '' ) {
878 * An expansion frame, used as a context to expand the result of preprocessToObj()
881 class PPFrame_DOM
implements PPFrame
{
900 * Hashtable listing templates which are disallowed for expansion in this frame,
901 * having been encountered previously in parent frames.
906 * Recursion depth of this frame, top = 0
907 * Note that this is NOT the same as expansion depth in expand()
913 * Construct a new preprocessor frame.
914 * @param $preprocessor Preprocessor The parent preprocessor
916 function __construct( $preprocessor ) {
917 $this->preprocessor
= $preprocessor;
918 $this->parser
= $preprocessor->parser
;
919 $this->title
= $this->parser
->mTitle
;
920 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
921 $this->loopCheckHash
= array();
926 * Create a new child frame
927 * $args is optionally a multi-root PPNode or array containing the template arguments
929 * @return PPTemplateFrame_DOM
931 function newChild( $args = false, $title = false ) {
932 $namedArgs = array();
933 $numberedArgs = array();
934 if ( $title === false ) {
935 $title = $this->title
;
937 if ( $args !== false ) {
939 if ( $args instanceof PPNode
) {
942 foreach ( $args as $arg ) {
944 $xpath = new DOMXPath( $arg->ownerDocument
);
947 $nameNodes = $xpath->query( 'name', $arg );
948 $value = $xpath->query( 'value', $arg );
949 if ( $nameNodes->item( 0 )->hasAttributes() ) {
950 // Numbered parameter
951 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
952 $numberedArgs[$index] = $value->item( 0 );
953 unset( $namedArgs[$index] );
956 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
957 $namedArgs[$name] = $value->item( 0 );
958 unset( $numberedArgs[$name] );
962 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
966 * @throws MWException
971 function expand( $root, $flags = 0 ) {
972 static $expansionDepth = 0;
973 if ( is_string( $root ) ) {
977 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
978 return '<span class="error">Node-count limit exceeded</span>';
981 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
982 return '<span class="error">Expansion depth limit exceeded</span>';
984 wfProfileIn( __METHOD__
);
987 if ( $root instanceof PPNode_DOM
) {
990 if ( $root instanceof DOMDocument
) {
991 $root = $root->documentElement
;
994 $outStack = array( '', '' );
995 $iteratorStack = array( false, $root );
996 $indexStack = array( 0, 0 );
998 while ( count( $iteratorStack ) > 1 ) {
999 $level = count( $outStack ) - 1;
1000 $iteratorNode =& $iteratorStack[ $level ];
1001 $out =& $outStack[$level];
1002 $index =& $indexStack[$level];
1004 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
1006 if ( is_array( $iteratorNode ) ) {
1007 if ( $index >= count( $iteratorNode ) ) {
1008 // All done with this iterator
1009 $iteratorStack[$level] = false;
1010 $contextNode = false;
1012 $contextNode = $iteratorNode[$index];
1015 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1016 if ( $index >= $iteratorNode->length
) {
1017 // All done with this iterator
1018 $iteratorStack[$level] = false;
1019 $contextNode = false;
1021 $contextNode = $iteratorNode->item( $index );
1025 // Copy to $contextNode and then delete from iterator stack,
1026 // because this is not an iterator but we do have to execute it once
1027 $contextNode = $iteratorStack[$level];
1028 $iteratorStack[$level] = false;
1031 if ( $contextNode instanceof PPNode_DOM
) {
1032 $contextNode = $contextNode->node
;
1035 $newIterator = false;
1037 if ( $contextNode === false ) {
1039 } elseif ( is_string( $contextNode ) ) {
1040 $out .= $contextNode;
1041 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1042 $newIterator = $contextNode;
1043 } elseif ( $contextNode instanceof DOMNode
) {
1044 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1045 $out .= $contextNode->nodeValue
;
1046 } elseif ( $contextNode->nodeName
== 'template' ) {
1047 # Double-brace expansion
1048 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1049 $titles = $xpath->query( 'title', $contextNode );
1050 $title = $titles->item( 0 );
1051 $parts = $xpath->query( 'part', $contextNode );
1052 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1053 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1055 $lineStart = $contextNode->getAttribute( 'lineStart' );
1057 'title' => new PPNode_DOM( $title ),
1058 'parts' => new PPNode_DOM( $parts ),
1059 'lineStart' => $lineStart );
1060 $ret = $this->parser
->braceSubstitution( $params, $this );
1061 if ( isset( $ret['object'] ) ) {
1062 $newIterator = $ret['object'];
1064 $out .= $ret['text'];
1067 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1068 # Triple-brace expansion
1069 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1070 $titles = $xpath->query( 'title', $contextNode );
1071 $title = $titles->item( 0 );
1072 $parts = $xpath->query( 'part', $contextNode );
1073 if ( $flags & PPFrame
::NO_ARGS
) {
1074 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1077 'title' => new PPNode_DOM( $title ),
1078 'parts' => new PPNode_DOM( $parts ) );
1079 $ret = $this->parser
->argSubstitution( $params, $this );
1080 if ( isset( $ret['object'] ) ) {
1081 $newIterator = $ret['object'];
1083 $out .= $ret['text'];
1086 } elseif ( $contextNode->nodeName
== 'comment' ) {
1087 # HTML-style comment
1088 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1089 if ( $this->parser
->ot
['html']
1090 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1091 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1095 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1096 # Not in RECOVER_COMMENTS mode (extractSections) though
1097 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1098 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1100 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1102 $out .= $contextNode->textContent
;
1104 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1105 # Output suppression used by <includeonly> etc.
1106 # OT_WIKI will only respect <ignore> in substed templates.
1107 # The other output types respect it unless NO_IGNORE is set.
1108 # extractSections() sets NO_IGNORE and so never respects it.
1109 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1110 $out .= $contextNode->textContent
;
1114 } elseif ( $contextNode->nodeName
== 'ext' ) {
1116 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1117 $names = $xpath->query( 'name', $contextNode );
1118 $attrs = $xpath->query( 'attr', $contextNode );
1119 $inners = $xpath->query( 'inner', $contextNode );
1120 $closes = $xpath->query( 'close', $contextNode );
1122 'name' => new PPNode_DOM( $names->item( 0 ) ),
1123 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1124 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1125 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1127 $out .= $this->parser
->extensionSubstitution( $params, $this );
1128 } elseif ( $contextNode->nodeName
== 'h' ) {
1130 $s = $this->expand( $contextNode->childNodes
, $flags );
1132 # Insert a heading marker only for <h> children of <root>
1133 # This is to stop extractSections from going over multiple tree levels
1134 if ( $contextNode->parentNode
->nodeName
== 'root'
1135 && $this->parser
->ot
['html'] )
1137 # Insert heading index marker
1138 $headingIndex = $contextNode->getAttribute( 'i' );
1139 $titleText = $this->title
->getPrefixedDBkey();
1140 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1141 $serial = count( $this->parser
->mHeadings
) - 1;
1142 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1143 $count = $contextNode->getAttribute( 'level' );
1144 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1145 $this->parser
->mStripState
->addGeneral( $marker, '' );
1149 # Generic recursive expansion
1150 $newIterator = $contextNode->childNodes
;
1153 wfProfileOut( __METHOD__
);
1154 throw new MWException( __METHOD__
.': Invalid parameter type' );
1157 if ( $newIterator !== false ) {
1158 if ( $newIterator instanceof PPNode_DOM
) {
1159 $newIterator = $newIterator->node
;
1162 $iteratorStack[] = $newIterator;
1164 } elseif ( $iteratorStack[$level] === false ) {
1165 // Return accumulated value to parent
1166 // With tail recursion
1167 while ( $iteratorStack[$level] === false && $level > 0 ) {
1168 $outStack[$level - 1] .= $out;
1169 array_pop( $outStack );
1170 array_pop( $iteratorStack );
1171 array_pop( $indexStack );
1177 wfProfileOut( __METHOD__
);
1178 return $outStack[0];
1186 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1187 $args = array_slice( func_get_args(), 2 );
1191 foreach ( $args as $root ) {
1192 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1193 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1194 $root = array( $root );
1196 foreach ( $root as $node ) {
1202 $s .= $this->expand( $node, $flags );
1209 * Implode with no flags specified
1210 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1214 function implode( $sep /*, ... */ ) {
1215 $args = array_slice( func_get_args(), 1 );
1219 foreach ( $args as $root ) {
1220 if ( $root instanceof PPNode_DOM
) {
1221 $root = $root->node
;
1223 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1224 $root = array( $root );
1226 foreach ( $root as $node ) {
1232 $s .= $this->expand( $node );
1239 * Makes an object that, when expand()ed, will be the same as one obtained
1244 function virtualImplode( $sep /*, ... */ ) {
1245 $args = array_slice( func_get_args(), 1 );
1249 foreach ( $args as $root ) {
1250 if ( $root instanceof PPNode_DOM
) {
1251 $root = $root->node
;
1253 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1254 $root = array( $root );
1256 foreach ( $root as $node ) {
1269 * Virtual implode with brackets
1271 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1272 $args = array_slice( func_get_args(), 3 );
1273 $out = array( $start );
1276 foreach ( $args as $root ) {
1277 if ( $root instanceof PPNode_DOM
) {
1278 $root = $root->node
;
1280 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1281 $root = array( $root );
1283 foreach ( $root as $node ) {
1296 function __toString() {
1300 function getPDBK( $level = false ) {
1301 if ( $level === false ) {
1302 return $this->title
->getPrefixedDBkey();
1304 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1311 function getArguments() {
1318 function getNumberedArguments() {
1325 function getNamedArguments() {
1330 * Returns true if there are no arguments in this frame
1334 function isEmpty() {
1338 function getArgument( $name ) {
1343 * Returns true if the infinite loop check is OK, false if a loop is detected
1347 function loopCheck( $title ) {
1348 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1352 * Return true if the frame is a template frame
1356 function isTemplate() {
1361 * Get a title of frame
1365 function getTitle() {
1366 return $this->title
;
1371 * Expansion frame with template arguments
1374 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1375 var $numberedArgs, $namedArgs;
1381 var $numberedExpansionCache, $namedExpansionCache;
1384 * @param $preprocessor
1385 * @param $parent PPFrame_DOM
1386 * @param $numberedArgs array
1387 * @param $namedArgs array
1388 * @param $title Title
1390 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1391 parent
::__construct( $preprocessor );
1393 $this->parent
= $parent;
1394 $this->numberedArgs
= $numberedArgs;
1395 $this->namedArgs
= $namedArgs;
1396 $this->title
= $title;
1397 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1398 $this->titleCache
= $parent->titleCache
;
1399 $this->titleCache
[] = $pdbk;
1400 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1401 if ( $pdbk !== false ) {
1402 $this->loopCheckHash
[$pdbk] = true;
1404 $this->depth
= $parent->depth +
1;
1405 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1408 function __toString() {
1411 $args = $this->numberedArgs +
$this->namedArgs
;
1412 foreach ( $args as $name => $value ) {
1418 $s .= "\"$name\":\"" .
1419 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1426 * Returns true if there are no arguments in this frame
1430 function isEmpty() {
1431 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1434 function getArguments() {
1435 $arguments = array();
1436 foreach ( array_merge(
1437 array_keys($this->numberedArgs
),
1438 array_keys($this->namedArgs
)) as $key ) {
1439 $arguments[$key] = $this->getArgument($key);
1444 function getNumberedArguments() {
1445 $arguments = array();
1446 foreach ( array_keys($this->numberedArgs
) as $key ) {
1447 $arguments[$key] = $this->getArgument($key);
1452 function getNamedArguments() {
1453 $arguments = array();
1454 foreach ( array_keys($this->namedArgs
) as $key ) {
1455 $arguments[$key] = $this->getArgument($key);
1460 function getNumberedArgument( $index ) {
1461 if ( !isset( $this->numberedArgs
[$index] ) ) {
1464 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1465 # No trimming for unnamed arguments
1466 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1468 return $this->numberedExpansionCache
[$index];
1471 function getNamedArgument( $name ) {
1472 if ( !isset( $this->namedArgs
[$name] ) ) {
1475 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1476 # Trim named arguments post-expand, for backwards compatibility
1477 $this->namedExpansionCache
[$name] = trim(
1478 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1480 return $this->namedExpansionCache
[$name];
1483 function getArgument( $name ) {
1484 $text = $this->getNumberedArgument( $name );
1485 if ( $text === false ) {
1486 $text = $this->getNamedArgument( $name );
1492 * Return true if the frame is a template frame
1496 function isTemplate() {
1502 * Expansion frame with custom arguments
1505 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1508 function __construct( $preprocessor, $args ) {
1509 parent
::__construct( $preprocessor );
1510 $this->args
= $args;
1513 function __toString() {
1516 foreach ( $this->args
as $name => $value ) {
1522 $s .= "\"$name\":\"" .
1523 str_replace( '"', '\\"', $value->__toString() ) . '"';
1532 function isEmpty() {
1533 return !count( $this->args
);
1536 function getArgument( $index ) {
1537 if ( !isset( $this->args
[$index] ) ) {
1540 return $this->args
[$index];
1547 class PPNode_DOM
implements PPNode
{
1555 function __construct( $node, $xpath = false ) {
1556 $this->node
= $node;
1562 function getXPath() {
1563 if ( $this->xpath
=== null ) {
1564 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1566 return $this->xpath
;
1569 function __toString() {
1570 if ( $this->node
instanceof DOMNodeList
) {
1572 foreach ( $this->node
as $node ) {
1573 $s .= $node->ownerDocument
->saveXML( $node );
1576 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1582 * @return bool|PPNode_DOM
1584 function getChildren() {
1585 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1589 * @return bool|PPNode_DOM
1591 function getFirstChild() {
1592 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1596 * @return bool|PPNode_DOM
1598 function getNextSibling() {
1599 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1605 * @return bool|PPNode_DOM
1607 function getChildrenOfType( $type ) {
1608 return new self( $this->getXPath()->query( $type, $this->node
) );
1614 function getLength() {
1615 if ( $this->node
instanceof DOMNodeList
) {
1616 return $this->node
->length
;
1624 * @return bool|PPNode_DOM
1626 function item( $i ) {
1627 $item = $this->node
->item( $i );
1628 return $item ?
new self( $item ) : false;
1634 function getName() {
1635 if ( $this->node
instanceof DOMNodeList
) {
1638 return $this->node
->nodeName
;
1643 * Split a <part> node into an associative array containing:
1645 * index String index
1646 * value PPNode value
1650 function splitArg() {
1651 $xpath = $this->getXPath();
1652 $names = $xpath->query( 'name', $this->node
);
1653 $values = $xpath->query( 'value', $this->node
);
1654 if ( !$names->length ||
!$values->length
) {
1655 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1657 $name = $names->item( 0 );
1658 $index = $name->getAttribute( 'index' );
1660 'name' => new self( $name ),
1662 'value' => new self( $values->item( 0 ) ) );
1666 * Split an <ext> node into an associative array containing name, attr, inner and close
1667 * All values in the resulting array are PPNodes. Inner and close are optional.
1671 function splitExt() {
1672 $xpath = $this->getXPath();
1673 $names = $xpath->query( 'name', $this->node
);
1674 $attrs = $xpath->query( 'attr', $this->node
);
1675 $inners = $xpath->query( 'inner', $this->node
);
1676 $closes = $xpath->query( 'close', $this->node
);
1677 if ( !$names->length ||
!$attrs->length
) {
1678 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1681 'name' => new self( $names->item( 0 ) ),
1682 'attr' => new self( $attrs->item( 0 ) ) );
1683 if ( $inners->length
) {
1684 $parts['inner'] = new self( $inners->item( 0 ) );
1686 if ( $closes->length
) {
1687 $parts['close'] = new self( $closes->item( 0 ) );
1695 function splitHeading() {
1696 if ( $this->getName() !== 'h' ) {
1697 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1700 'i' => $this->node
->getAttribute( 'i' ),
1701 'level' => $this->node
->getAttribute( 'level' ),
1702 'contents' => $this->getChildren()