3 * Preprocessor using PHP's dom extension
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
27 class Preprocessor_DOM
implements Preprocessor
{
36 const CACHE_VERSION
= 1;
38 function __construct( $parser ) {
39 $this->parser
= $parser;
40 $mem = ini_get( 'memory_limit' );
41 $this->memoryLimit
= false;
42 if ( strval( $mem ) !== '' && $mem != -1 ) {
43 if ( preg_match( '/^\d+$/', $mem ) ) {
44 $this->memoryLimit
= $mem;
45 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
46 $this->memoryLimit
= $m[1] * 1048576;
55 return new PPFrame_DOM( $this );
60 * @return PPCustomFrame_DOM
62 function newCustomFrame( $args ) {
63 return new PPCustomFrame_DOM( $this, $args );
67 * @param array $values
70 function newPartNodeArray( $values ) {
71 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
74 foreach ( $values as $k => $val ) {
76 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) . "</value></part>";
78 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
84 $dom = new DOMDocument();
85 $dom->loadXML( $xml );
86 $root = $dom->documentElement
;
88 $node = new PPNode_DOM( $root->childNodes
);
97 if ( $this->memoryLimit
=== false ) {
100 $usage = memory_get_usage();
101 if ( $usage > $this->memoryLimit
* 0.9 ) {
102 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
103 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
105 return $usage <= $this->memoryLimit
* 0.8;
109 * Preprocess some wikitext and return the document tree.
110 * This is the ghost of Parser::replace_variables().
112 * @param string $text The text to parse
113 * @param int $flags Bitwise combination of:
114 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
115 * included. Default is to assume a direct page view.
117 * The generated DOM tree must depend only on the input text and the flags.
118 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
120 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
121 * change in the DOM tree for a given text, must be passed through the section identifier
122 * in the section edit link and thus back to extractSections().
124 * The output of this function is currently only cached in process memory, but a persistent
125 * cache may be implemented at a later date which takes further advantage of these strict
126 * dependency requirements.
128 * @throws MWException
131 function preprocessToObj( $text, $flags = 0 ) {
132 wfProfileIn( __METHOD__
);
133 global $wgMemc, $wgPreprocessorCacheThreshold;
136 $cacheable = ( $wgPreprocessorCacheThreshold !== false
137 && strlen( $text ) > $wgPreprocessorCacheThreshold );
139 wfProfileIn( __METHOD__
. '-cacheable' );
141 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
142 $cacheValue = $wgMemc->get( $cacheKey );
144 $version = substr( $cacheValue, 0, 8 );
145 if ( intval( $version ) == self
::CACHE_VERSION
) {
146 $xml = substr( $cacheValue, 8 );
148 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
151 if ( $xml === false ) {
152 wfProfileIn( __METHOD__
. '-cache-miss' );
153 $xml = $this->preprocessToXml( $text, $flags );
154 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
155 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
156 wfProfileOut( __METHOD__
. '-cache-miss' );
157 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
160 $xml = $this->preprocessToXml( $text, $flags );
163 // Fail if the number of elements exceeds acceptable limits
164 // Do not attempt to generate the DOM
165 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
166 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
167 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
169 wfProfileOut( __METHOD__
. '-cacheable' );
171 wfProfileOut( __METHOD__
);
172 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
175 wfProfileIn( __METHOD__
. '-loadXML' );
176 $dom = new DOMDocument
;
177 wfSuppressWarnings();
178 $result = $dom->loadXML( $xml );
181 // Try running the XML through UtfNormal to get rid of invalid characters
182 $xml = UtfNormal
::cleanUp( $xml );
183 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
184 $result = $dom->loadXML( $xml, 1 << 19 );
187 $obj = new PPNode_DOM( $dom->documentElement
);
189 wfProfileOut( __METHOD__
. '-loadXML' );
192 wfProfileOut( __METHOD__
. '-cacheable' );
195 wfProfileOut( __METHOD__
);
198 throw new MWException( __METHOD__
. ' generated invalid XML' );
204 * @param string $text
208 function preprocessToXml( $text, $flags = 0 ) {
209 wfProfileIn( __METHOD__
);
222 'names' => array( 2 => null ),
228 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
230 $xmlishElements = $this->parser
->getStripList();
231 $enableOnlyinclude = false;
232 if ( $forInclusion ) {
233 $ignoredTags = array( 'includeonly', '/includeonly' );
234 $ignoredElements = array( 'noinclude' );
235 $xmlishElements[] = 'noinclude';
236 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
237 $enableOnlyinclude = true;
240 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
241 $ignoredElements = array( 'includeonly' );
242 $xmlishElements[] = 'includeonly';
244 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
246 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
247 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
249 $stack = new PPDStack
;
251 $searchBase = "[{<\n"; #}
252 $revText = strrev( $text ); // For fast reverse searches
253 $lengthText = strlen( $text );
255 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
256 $accum =& $stack->getAccum(); # Current accumulator
258 $findEquals = false; # True to find equals signs in arguments
259 $findPipe = false; # True to take notice of pipe characters
261 $inHeading = false; # True if $i is inside a possible heading
262 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
263 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
264 $fakeLineStart = true; # Do a line-start run without outputting an LF character
269 if ( $findOnlyinclude ) {
270 // Ignore all input up to the next <onlyinclude>
271 $startPos = strpos( $text, '<onlyinclude>', $i );
272 if ( $startPos === false ) {
273 // Ignored section runs to the end
274 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
277 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
278 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
280 $findOnlyinclude = false;
283 if ( $fakeLineStart ) {
284 $found = 'line-start';
287 # Find next opening brace, closing brace or pipe
288 $search = $searchBase;
289 if ( $stack->top
=== false ) {
290 $currentClosing = '';
292 $currentClosing = $stack->top
->close
;
293 $search .= $currentClosing;
299 // First equals will be for the template
303 # Output literal section, advance input counter
304 $literalLength = strcspn( $text, $search, $i );
305 if ( $literalLength > 0 ) {
306 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
307 $i +
= $literalLength;
309 if ( $i >= $lengthText ) {
310 if ( $currentClosing == "\n" ) {
311 // Do a past-the-end run to finish off the heading
319 $curChar = $text[$i];
320 if ( $curChar == '|' ) {
322 } elseif ( $curChar == '=' ) {
324 } elseif ( $curChar == '<' ) {
326 } elseif ( $curChar == "\n" ) {
330 $found = 'line-start';
332 } elseif ( $curChar == $currentClosing ) {
334 } elseif ( isset( $rules[$curChar] ) ) {
336 $rule = $rules[$curChar];
338 # Some versions of PHP have a strcspn which stops on null characters
339 # Ignore and continue
346 if ( $found == 'angle' ) {
348 // Handle </onlyinclude>
349 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
350 $findOnlyinclude = true;
354 // Determine element name
355 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
356 // Element name missing or not listed
362 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
364 // To avoid leaving blank lines, when a sequence of
365 // space-separated comments is both preceded and followed by
366 // a newline (ignoring spaces), then
367 // trim leading and trailing spaces and the trailing newline.
370 $endPos = strpos( $text, '-->', $i +
4 );
371 if ( $endPos === false ) {
372 // Unclosed comment in input, runs to end
373 $inner = substr( $text, $i );
374 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
377 // Search backwards for leading whitespace
378 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
380 // Search forwards for trailing whitespace
381 // $wsEnd will be the position of the last space (or the '>' if there's none)
382 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
384 // Keep looking forward as long as we're finding more
386 $comments = array( array( $wsStart, $wsEnd ) );
387 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
388 $c = strpos( $text, '-->', $wsEnd +
4 );
389 if ( $c === false ) {
392 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
393 $comments[] = array( $wsEnd +
1, $c );
397 // Eat the line if possible
398 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
399 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
400 // it's a possible beneficial b/c break.
401 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
402 && substr( $text, $wsEnd +
1, 1 ) == "\n"
404 // Remove leading whitespace from the end of the accumulator
405 // Sanity check first though
406 $wsLength = $i - $wsStart;
408 && strspn( $accum, " \t", -$wsLength ) === $wsLength
410 $accum = substr( $accum, 0, -$wsLength );
413 // Dump all but the last comment to the accumulator
414 foreach ( $comments as $j => $com ) {
416 $endPos = $com[1] +
1;
417 if ( $j == ( count( $comments ) - 1 ) ) {
420 $inner = substr( $text, $startPos, $endPos - $startPos );
421 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
424 // Do a line-start run next time to look for headings after the comment
425 $fakeLineStart = true;
427 // No line to eat, just take the comment itself
433 $part = $stack->top
->getCurrentPart();
434 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
435 $part->visualEnd
= $wsStart;
437 // Else comments abutting, no change in visual end
438 $part->commentEnd
= $endPos;
441 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
442 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
447 $lowerName = strtolower( $name );
448 $attrStart = $i +
strlen( $name ) +
1;
451 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
452 if ( $tagEndPos === false ) {
453 // Infinite backtrack
454 // Disable tag search to prevent worst-case O(N^2) performance
461 // Handle ignored tags
462 if ( in_array( $lowerName, $ignoredTags ) ) {
463 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
469 if ( $text[$tagEndPos - 1] == '/' ) {
470 $attrEnd = $tagEndPos - 1;
475 $attrEnd = $tagEndPos;
477 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
478 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
480 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
481 $i = $matches[0][1] +
strlen( $matches[0][0] );
482 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
484 // No end tag -- let it run out to the end of the text.
485 $inner = substr( $text, $tagEndPos +
1 );
490 // <includeonly> and <noinclude> just become <ignore> tags
491 if ( in_array( $lowerName, $ignoredElements ) ) {
492 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
498 if ( $attrEnd <= $attrStart ) {
501 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
503 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
504 // Note that the attr element contains the whitespace between name and attribute,
505 // this is necessary for precise reconstruction during pre-save transform.
506 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
507 if ( $inner !== null ) {
508 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
510 $accum .= $close . '</ext>';
511 } elseif ( $found == 'line-start' ) {
512 // Is this the start of a heading?
513 // Line break belongs before the heading element in any case
514 if ( $fakeLineStart ) {
515 $fakeLineStart = false;
521 $count = strspn( $text, '=', $i, 6 );
522 if ( $count == 1 && $findEquals ) {
523 // DWIM: This looks kind of like a name/value separator
524 // Let's let the equals handler have it and break the potential heading
525 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
526 } elseif ( $count > 0 ) {
530 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
533 $stack->push( $piece );
534 $accum =& $stack->getAccum();
535 $flags = $stack->getFlags();
539 } elseif ( $found == 'line-end' ) {
540 $piece = $stack->top
;
541 // A heading must be open, otherwise \n wouldn't have been in the search list
542 assert( '$piece->open == "\n"' );
543 $part = $piece->getCurrentPart();
544 // Search back through the input to see if it has a proper close
545 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
546 $wsLength = strspn( $revText, " \t", $lengthText - $i );
547 $searchStart = $i - $wsLength;
548 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
549 // Comment found at line end
550 // Search for equals signs before the comment
551 $searchStart = $part->visualEnd
;
552 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
554 $count = $piece->count
;
555 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
556 if ( $equalsLength > 0 ) {
557 if ( $searchStart - $equalsLength == $piece->startPos
) {
558 // This is just a single string of equals signs on its own line
559 // Replicate the doHeadings behavior /={count}(.+)={count}/
560 // First find out how many equals signs there really are (don't stop at 6)
561 $count = $equalsLength;
565 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
568 $count = min( $equalsLength, $count );
571 // Normal match, output <h>
572 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
575 // Single equals sign on its own line, count=0
579 // No match, no <h>, just pass down the inner text
584 $accum =& $stack->getAccum();
585 $flags = $stack->getFlags();
588 // Append the result to the enclosing accumulator
590 // Note that we do NOT increment the input pointer.
591 // This is because the closing linebreak could be the opening linebreak of
592 // another heading. Infinite loops are avoided because the next iteration MUST
593 // hit the heading open case above, which unconditionally increments the
595 } elseif ( $found == 'open' ) {
596 # count opening brace characters
597 $count = strspn( $text, $curChar, $i );
599 # we need to add to stack only if opening brace count is enough for one of the rules
600 if ( $count >= $rule['min'] ) {
601 # Add it to the stack
604 'close' => $rule['end'],
606 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
609 $stack->push( $piece );
610 $accum =& $stack->getAccum();
611 $flags = $stack->getFlags();
614 # Add literal brace(s)
615 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
618 } elseif ( $found == 'close' ) {
619 $piece = $stack->top
;
620 # lets check if there are enough characters for closing brace
621 $maxCount = $piece->count
;
622 $count = strspn( $text, $curChar, $i, $maxCount );
624 # check for maximum matching characters (if there are 5 closing
625 # characters, we will probably need only 3 - depending on the rules)
626 $rule = $rules[$piece->open
];
627 if ( $count > $rule['max'] ) {
628 # The specified maximum exists in the callback array, unless the caller
630 $matchingCount = $rule['max'];
632 # Count is less than the maximum
633 # Skip any gaps in the callback array to find the true largest match
634 # Need to use array_key_exists not isset because the callback can be null
635 $matchingCount = $count;
636 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
641 if ( $matchingCount <= 0 ) {
642 # No matching element found in callback array
643 # Output a literal closing brace and continue
644 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
648 $name = $rule['names'][$matchingCount];
649 if ( $name === null ) {
650 // No element, just literal text
651 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
654 # Note: $parts is already XML, does not need to be encoded further
655 $parts = $piece->parts
;
656 $title = $parts[0]->out
;
659 # The invocation is at the start of the line if lineStart is set in
660 # the stack, and all opening brackets are used up.
661 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
662 $attr = ' lineStart="1"';
667 $element = "<$name$attr>";
668 $element .= "<title>$title</title>";
670 foreach ( $parts as $part ) {
671 if ( isset( $part->eqpos
) ) {
672 $argName = substr( $part->out
, 0, $part->eqpos
);
673 $argValue = substr( $part->out
, $part->eqpos +
1 );
674 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
676 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
680 $element .= "</$name>";
683 # Advance input pointer
684 $i +
= $matchingCount;
688 $accum =& $stack->getAccum();
690 # Re-add the old stack element if it still has unmatched opening characters remaining
691 if ( $matchingCount < $piece->count
) {
692 $piece->parts
= array( new PPDPart
);
693 $piece->count
-= $matchingCount;
694 # do we still qualify for any callback with remaining count?
695 $min = $rules[$piece->open
]['min'];
696 if ( $piece->count
>= $min ) {
697 $stack->push( $piece );
698 $accum =& $stack->getAccum();
700 $accum .= str_repeat( $piece->open
, $piece->count
);
703 $flags = $stack->getFlags();
706 # Add XML element to the enclosing accumulator
708 } elseif ( $found == 'pipe' ) {
709 $findEquals = true; // shortcut for getFlags()
711 $accum =& $stack->getAccum();
713 } elseif ( $found == 'equals' ) {
714 $findEquals = false; // shortcut for getFlags()
715 $stack->getCurrentPart()->eqpos
= strlen( $accum );
721 # Output any remaining unclosed brackets
722 foreach ( $stack->stack
as $piece ) {
723 $stack->rootAccum
.= $piece->breakSyntax();
725 $stack->rootAccum
.= '</root>';
726 $xml = $stack->rootAccum
;
728 wfProfileOut( __METHOD__
);
735 * Stack class to help Preprocessor::preprocessToObj()
739 var $stack, $rootAccum;
746 var $elementClass = 'PPDStackElement';
748 static $false = false;
750 function __construct() {
751 $this->stack
= array();
753 $this->rootAccum
= '';
754 $this->accum
=& $this->rootAccum
;
761 return count( $this->stack
);
764 function &getAccum() {
768 function getCurrentPart() {
769 if ( $this->top
=== false ) {
772 return $this->top
->getCurrentPart();
776 function push( $data ) {
777 if ( $data instanceof $this->elementClass
) {
778 $this->stack
[] = $data;
780 $class = $this->elementClass
;
781 $this->stack
[] = new $class( $data );
783 $this->top
= $this->stack
[count( $this->stack
) - 1];
784 $this->accum
=& $this->top
->getAccum();
788 if ( !count( $this->stack
) ) {
789 throw new MWException( __METHOD__
. ': no elements remaining' );
791 $temp = array_pop( $this->stack
);
793 if ( count( $this->stack
) ) {
794 $this->top
= $this->stack
[count( $this->stack
) - 1];
795 $this->accum
=& $this->top
->getAccum();
797 $this->top
= self
::$false;
798 $this->accum
=& $this->rootAccum
;
803 function addPart( $s = '' ) {
804 $this->top
->addPart( $s );
805 $this->accum
=& $this->top
->getAccum();
811 function getFlags() {
812 if ( !count( $this->stack
) ) {
814 'findEquals' => false,
816 'inHeading' => false,
819 return $this->top
->getFlags();
827 class PPDStackElement
{
828 var $open, // Opening character (\n for heading)
829 $close, // Matching closing character
830 $count, // Number of opening characters found (number of "=" for heading)
831 $parts, // Array of PPDPart objects describing pipe-separated parts.
832 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
834 var $partClass = 'PPDPart';
836 function __construct( $data = array() ) {
837 $class = $this->partClass
;
838 $this->parts
= array( new $class );
840 foreach ( $data as $name => $value ) {
841 $this->$name = $value;
845 function &getAccum() {
846 return $this->parts
[count( $this->parts
) - 1]->out
;
849 function addPart( $s = '' ) {
850 $class = $this->partClass
;
851 $this->parts
[] = new $class( $s );
854 function getCurrentPart() {
855 return $this->parts
[count( $this->parts
) - 1];
861 function getFlags() {
862 $partCount = count( $this->parts
);
863 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
865 'findPipe' => $findPipe,
866 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
867 'inHeading' => $this->open
== "\n",
872 * Get the output string that would result if the close is not found.
876 function breakSyntax( $openingCount = false ) {
877 if ( $this->open
== "\n" ) {
878 $s = $this->parts
[0]->out
;
880 if ( $openingCount === false ) {
881 $openingCount = $this->count
;
883 $s = str_repeat( $this->open
, $openingCount );
885 foreach ( $this->parts
as $part ) {
902 var $out; // Output accumulator string
904 // Optional member variables:
905 // eqpos Position of equals sign in output accumulator
906 // commentEnd Past-the-end input pointer for the last comment encountered
907 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
909 function __construct( $out = '' ) {
915 * An expansion frame, used as a context to expand the result of preprocessToObj()
918 class PPFrame_DOM
implements PPFrame
{
937 * Hashtable listing templates which are disallowed for expansion in this frame,
938 * having been encountered previously in parent frames.
943 * Recursion depth of this frame, top = 0
944 * Note that this is NOT the same as expansion depth in expand()
949 * Construct a new preprocessor frame.
950 * @param Preprocessor $preprocessor The parent preprocessor
952 function __construct( $preprocessor ) {
953 $this->preprocessor
= $preprocessor;
954 $this->parser
= $preprocessor->parser
;
955 $this->title
= $this->parser
->mTitle
;
956 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
957 $this->loopCheckHash
= array();
962 * Create a new child frame
963 * $args is optionally a multi-root PPNode or array containing the template arguments
965 * @param bool|array $args
966 * @param Title|bool $title
967 * @param int $indexOffset
968 * @return PPTemplateFrame_DOM
970 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
971 $namedArgs = array();
972 $numberedArgs = array();
973 if ( $title === false ) {
974 $title = $this->title
;
976 if ( $args !== false ) {
978 if ( $args instanceof PPNode
) {
981 foreach ( $args as $arg ) {
982 if ( $arg instanceof PPNode
) {
986 $xpath = new DOMXPath( $arg->ownerDocument
);
989 $nameNodes = $xpath->query( 'name', $arg );
990 $value = $xpath->query( 'value', $arg );
991 if ( $nameNodes->item( 0 )->hasAttributes() ) {
992 // Numbered parameter
993 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
994 $index = $index - $indexOffset;
995 $numberedArgs[$index] = $value->item( 0 );
996 unset( $namedArgs[$index] );
999 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1000 $namedArgs[$name] = $value->item( 0 );
1001 unset( $numberedArgs[$name] );
1005 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1009 * @throws MWException
1010 * @param string|PPNode_DOM|DOMDocument $root
1014 function expand( $root, $flags = 0 ) {
1015 static $expansionDepth = 0;
1016 if ( is_string( $root ) ) {
1020 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1021 $this->parser
->limitationWarn( 'node-count-exceeded',
1022 $this->parser
->mPPNodeCount
,
1023 $this->parser
->mOptions
->getMaxPPNodeCount()
1025 return '<span class="error">Node-count limit exceeded</span>';
1028 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1029 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1031 $this->parser
->mOptions
->getMaxPPExpandDepth()
1033 return '<span class="error">Expansion depth limit exceeded</span>';
1035 wfProfileIn( __METHOD__
);
1037 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1038 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1041 if ( $root instanceof PPNode_DOM
) {
1042 $root = $root->node
;
1044 if ( $root instanceof DOMDocument
) {
1045 $root = $root->documentElement
;
1048 $outStack = array( '', '' );
1049 $iteratorStack = array( false, $root );
1050 $indexStack = array( 0, 0 );
1052 while ( count( $iteratorStack ) > 1 ) {
1053 $level = count( $outStack ) - 1;
1054 $iteratorNode =& $iteratorStack[$level];
1055 $out =& $outStack[$level];
1056 $index =& $indexStack[$level];
1058 if ( $iteratorNode instanceof PPNode_DOM
) {
1059 $iteratorNode = $iteratorNode->node
;
1062 if ( is_array( $iteratorNode ) ) {
1063 if ( $index >= count( $iteratorNode ) ) {
1064 // All done with this iterator
1065 $iteratorStack[$level] = false;
1066 $contextNode = false;
1068 $contextNode = $iteratorNode[$index];
1071 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1072 if ( $index >= $iteratorNode->length
) {
1073 // All done with this iterator
1074 $iteratorStack[$level] = false;
1075 $contextNode = false;
1077 $contextNode = $iteratorNode->item( $index );
1081 // Copy to $contextNode and then delete from iterator stack,
1082 // because this is not an iterator but we do have to execute it once
1083 $contextNode = $iteratorStack[$level];
1084 $iteratorStack[$level] = false;
1087 if ( $contextNode instanceof PPNode_DOM
) {
1088 $contextNode = $contextNode->node
;
1091 $newIterator = false;
1093 if ( $contextNode === false ) {
1095 } elseif ( is_string( $contextNode ) ) {
1096 $out .= $contextNode;
1097 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1098 $newIterator = $contextNode;
1099 } elseif ( $contextNode instanceof DOMNode
) {
1100 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1101 $out .= $contextNode->nodeValue
;
1102 } elseif ( $contextNode->nodeName
== 'template' ) {
1103 # Double-brace expansion
1104 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1105 $titles = $xpath->query( 'title', $contextNode );
1106 $title = $titles->item( 0 );
1107 $parts = $xpath->query( 'part', $contextNode );
1108 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1109 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1111 $lineStart = $contextNode->getAttribute( 'lineStart' );
1113 'title' => new PPNode_DOM( $title ),
1114 'parts' => new PPNode_DOM( $parts ),
1115 'lineStart' => $lineStart );
1116 $ret = $this->parser
->braceSubstitution( $params, $this );
1117 if ( isset( $ret['object'] ) ) {
1118 $newIterator = $ret['object'];
1120 $out .= $ret['text'];
1123 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1124 # Triple-brace expansion
1125 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1126 $titles = $xpath->query( 'title', $contextNode );
1127 $title = $titles->item( 0 );
1128 $parts = $xpath->query( 'part', $contextNode );
1129 if ( $flags & PPFrame
::NO_ARGS
) {
1130 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1133 'title' => new PPNode_DOM( $title ),
1134 'parts' => new PPNode_DOM( $parts ) );
1135 $ret = $this->parser
->argSubstitution( $params, $this );
1136 if ( isset( $ret['object'] ) ) {
1137 $newIterator = $ret['object'];
1139 $out .= $ret['text'];
1142 } elseif ( $contextNode->nodeName
== 'comment' ) {
1143 # HTML-style comment
1144 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1145 if ( $this->parser
->ot
['html']
1146 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1147 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1150 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1151 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1152 # Not in RECOVER_COMMENTS mode (extractSections) though
1153 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1155 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1156 $out .= $contextNode->textContent
;
1158 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1159 # Output suppression used by <includeonly> etc.
1160 # OT_WIKI will only respect <ignore> in substed templates.
1161 # The other output types respect it unless NO_IGNORE is set.
1162 # extractSections() sets NO_IGNORE and so never respects it.
1163 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1164 $out .= $contextNode->textContent
;
1168 } elseif ( $contextNode->nodeName
== 'ext' ) {
1170 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1171 $names = $xpath->query( 'name', $contextNode );
1172 $attrs = $xpath->query( 'attr', $contextNode );
1173 $inners = $xpath->query( 'inner', $contextNode );
1174 $closes = $xpath->query( 'close', $contextNode );
1176 'name' => new PPNode_DOM( $names->item( 0 ) ),
1177 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1178 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1179 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1181 $out .= $this->parser
->extensionSubstitution( $params, $this );
1182 } elseif ( $contextNode->nodeName
== 'h' ) {
1184 $s = $this->expand( $contextNode->childNodes
, $flags );
1186 # Insert a heading marker only for <h> children of <root>
1187 # This is to stop extractSections from going over multiple tree levels
1188 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1189 # Insert heading index marker
1190 $headingIndex = $contextNode->getAttribute( 'i' );
1191 $titleText = $this->title
->getPrefixedDBkey();
1192 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1193 $serial = count( $this->parser
->mHeadings
) - 1;
1194 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1195 $count = $contextNode->getAttribute( 'level' );
1196 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1197 $this->parser
->mStripState
->addGeneral( $marker, '' );
1201 # Generic recursive expansion
1202 $newIterator = $contextNode->childNodes
;
1205 wfProfileOut( __METHOD__
);
1206 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1209 if ( $newIterator !== false ) {
1210 if ( $newIterator instanceof PPNode_DOM
) {
1211 $newIterator = $newIterator->node
;
1214 $iteratorStack[] = $newIterator;
1216 } elseif ( $iteratorStack[$level] === false ) {
1217 // Return accumulated value to parent
1218 // With tail recursion
1219 while ( $iteratorStack[$level] === false && $level > 0 ) {
1220 $outStack[$level - 1] .= $out;
1221 array_pop( $outStack );
1222 array_pop( $iteratorStack );
1223 array_pop( $indexStack );
1229 wfProfileOut( __METHOD__
);
1230 return $outStack[0];
1234 * @param string $sep
1238 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1239 $args = array_slice( func_get_args(), 2 );
1243 foreach ( $args as $root ) {
1244 if ( $root instanceof PPNode_DOM
) {
1245 $root = $root->node
;
1247 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1248 $root = array( $root );
1250 foreach ( $root as $node ) {
1256 $s .= $this->expand( $node, $flags );
1263 * Implode with no flags specified
1264 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1266 * @param string $sep
1269 function implode( $sep /*, ... */ ) {
1270 $args = array_slice( func_get_args(), 1 );
1274 foreach ( $args as $root ) {
1275 if ( $root instanceof PPNode_DOM
) {
1276 $root = $root->node
;
1278 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1279 $root = array( $root );
1281 foreach ( $root as $node ) {
1287 $s .= $this->expand( $node );
1294 * Makes an object that, when expand()ed, will be the same as one obtained
1297 * @param string $sep
1300 function virtualImplode( $sep /*, ... */ ) {
1301 $args = array_slice( func_get_args(), 1 );
1305 foreach ( $args as $root ) {
1306 if ( $root instanceof PPNode_DOM
) {
1307 $root = $root->node
;
1309 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1310 $root = array( $root );
1312 foreach ( $root as $node ) {
1325 * Virtual implode with brackets
1326 * @param string $start
1327 * @param string $sep
1328 * @param string $end
1331 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1332 $args = array_slice( func_get_args(), 3 );
1333 $out = array( $start );
1336 foreach ( $args as $root ) {
1337 if ( $root instanceof PPNode_DOM
) {
1338 $root = $root->node
;
1340 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1341 $root = array( $root );
1343 foreach ( $root as $node ) {
1356 function __toString() {
1360 function getPDBK( $level = false ) {
1361 if ( $level === false ) {
1362 return $this->title
->getPrefixedDBkey();
1364 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1371 function getArguments() {
1378 function getNumberedArguments() {
1385 function getNamedArguments() {
1390 * Returns true if there are no arguments in this frame
1394 function isEmpty() {
1398 function getArgument( $name ) {
1403 * Returns true if the infinite loop check is OK, false if a loop is detected
1405 * @param Title $title
1408 function loopCheck( $title ) {
1409 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1413 * Return true if the frame is a template frame
1417 function isTemplate() {
1422 * Get a title of frame
1426 function getTitle() {
1427 return $this->title
;
1432 * Expansion frame with template arguments
1435 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1436 var $numberedArgs, $namedArgs;
1442 var $numberedExpansionCache, $namedExpansionCache;
1445 * @param Preprocessor $preprocessor
1446 * @param PPFrame_DOM $parent
1447 * @param array $numberedArgs
1448 * @param array $namedArgs
1449 * @param Title $title
1451 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1452 parent
::__construct( $preprocessor );
1454 $this->parent
= $parent;
1455 $this->numberedArgs
= $numberedArgs;
1456 $this->namedArgs
= $namedArgs;
1457 $this->title
= $title;
1458 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1459 $this->titleCache
= $parent->titleCache
;
1460 $this->titleCache
[] = $pdbk;
1461 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1462 if ( $pdbk !== false ) {
1463 $this->loopCheckHash
[$pdbk] = true;
1465 $this->depth
= $parent->depth +
1;
1466 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1469 function __toString() {
1472 $args = $this->numberedArgs +
$this->namedArgs
;
1473 foreach ( $args as $name => $value ) {
1479 $s .= "\"$name\":\"" .
1480 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1487 * Returns true if there are no arguments in this frame
1491 function isEmpty() {
1492 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1495 function getArguments() {
1496 $arguments = array();
1497 foreach ( array_merge(
1498 array_keys( $this->numberedArgs
),
1499 array_keys( $this->namedArgs
) ) as $key ) {
1500 $arguments[$key] = $this->getArgument( $key );
1505 function getNumberedArguments() {
1506 $arguments = array();
1507 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1508 $arguments[$key] = $this->getArgument( $key );
1513 function getNamedArguments() {
1514 $arguments = array();
1515 foreach ( array_keys( $this->namedArgs
) as $key ) {
1516 $arguments[$key] = $this->getArgument( $key );
1521 function getNumberedArgument( $index ) {
1522 if ( !isset( $this->numberedArgs
[$index] ) ) {
1525 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1526 # No trimming for unnamed arguments
1527 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1529 return $this->numberedExpansionCache
[$index];
1532 function getNamedArgument( $name ) {
1533 if ( !isset( $this->namedArgs
[$name] ) ) {
1536 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1537 # Trim named arguments post-expand, for backwards compatibility
1538 $this->namedExpansionCache
[$name] = trim(
1539 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1541 return $this->namedExpansionCache
[$name];
1544 function getArgument( $name ) {
1545 $text = $this->getNumberedArgument( $name );
1546 if ( $text === false ) {
1547 $text = $this->getNamedArgument( $name );
1553 * Return true if the frame is a template frame
1557 function isTemplate() {
1563 * Expansion frame with custom arguments
1566 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1569 function __construct( $preprocessor, $args ) {
1570 parent
::__construct( $preprocessor );
1571 $this->args
= $args;
1574 function __toString() {
1577 foreach ( $this->args
as $name => $value ) {
1583 $s .= "\"$name\":\"" .
1584 str_replace( '"', '\\"', $value->__toString() ) . '"';
1593 function isEmpty() {
1594 return !count( $this->args
);
1597 function getArgument( $index ) {
1598 if ( !isset( $this->args
[$index] ) ) {
1601 return $this->args
[$index];
1604 function getArguments() {
1612 class PPNode_DOM
implements PPNode
{
1620 function __construct( $node, $xpath = false ) {
1621 $this->node
= $node;
1627 function getXPath() {
1628 if ( $this->xpath
=== null ) {
1629 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1631 return $this->xpath
;
1634 function __toString() {
1635 if ( $this->node
instanceof DOMNodeList
) {
1637 foreach ( $this->node
as $node ) {
1638 $s .= $node->ownerDocument
->saveXML( $node );
1641 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1647 * @return bool|PPNode_DOM
1649 function getChildren() {
1650 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1654 * @return bool|PPNode_DOM
1656 function getFirstChild() {
1657 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1661 * @return bool|PPNode_DOM
1663 function getNextSibling() {
1664 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1668 * @param string $type
1670 * @return bool|PPNode_DOM
1672 function getChildrenOfType( $type ) {
1673 return new self( $this->getXPath()->query( $type, $this->node
) );
1679 function getLength() {
1680 if ( $this->node
instanceof DOMNodeList
) {
1681 return $this->node
->length
;
1689 * @return bool|PPNode_DOM
1691 function item( $i ) {
1692 $item = $this->node
->item( $i );
1693 return $item ?
new self( $item ) : false;
1699 function getName() {
1700 if ( $this->node
instanceof DOMNodeList
) {
1703 return $this->node
->nodeName
;
1708 * Split a "<part>" node into an associative array containing:
1709 * - name PPNode name
1710 * - index String index
1711 * - value PPNode value
1713 * @throws MWException
1716 function splitArg() {
1717 $xpath = $this->getXPath();
1718 $names = $xpath->query( 'name', $this->node
);
1719 $values = $xpath->query( 'value', $this->node
);
1720 if ( !$names->length ||
!$values->length
) {
1721 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1723 $name = $names->item( 0 );
1724 $index = $name->getAttribute( 'index' );
1726 'name' => new self( $name ),
1728 'value' => new self( $values->item( 0 ) ) );
1732 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1733 * All values in the resulting array are PPNodes. Inner and close are optional.
1735 * @throws MWException
1738 function splitExt() {
1739 $xpath = $this->getXPath();
1740 $names = $xpath->query( 'name', $this->node
);
1741 $attrs = $xpath->query( 'attr', $this->node
);
1742 $inners = $xpath->query( 'inner', $this->node
);
1743 $closes = $xpath->query( 'close', $this->node
);
1744 if ( !$names->length ||
!$attrs->length
) {
1745 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1748 'name' => new self( $names->item( 0 ) ),
1749 'attr' => new self( $attrs->item( 0 ) ) );
1750 if ( $inners->length
) {
1751 $parts['inner'] = new self( $inners->item( 0 ) );
1753 if ( $closes->length
) {
1754 $parts['close'] = new self( $closes->item( 0 ) );
1760 * Split a "<h>" node
1761 * @throws MWException
1764 function splitHeading() {
1765 if ( $this->getName() !== 'h' ) {
1766 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1769 'i' => $this->node
->getAttribute( 'i' ),
1770 'level' => $this->node
->getAttribute( 'level' ),
1771 'contents' => $this->getChildren()