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 );
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 $flags Integer: 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 );
164 // Fail if the number of elements exceeds acceptable limits
165 // Do not attempt to generate the DOM
166 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
167 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
168 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
170 wfProfileOut( __METHOD__
. '-cacheable' );
172 wfProfileOut( __METHOD__
);
173 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
176 wfProfileIn( __METHOD__
. '-loadXML' );
177 $dom = new DOMDocument
;
178 wfSuppressWarnings();
179 $result = $dom->loadXML( $xml );
182 // Try running the XML through UtfNormal to get rid of invalid characters
183 $xml = UtfNormal
::cleanUp( $xml );
184 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
185 $result = $dom->loadXML( $xml, 1 << 19 );
187 wfProfileOut( __METHOD__
. '-loadXML' );
189 wfProfileOut( __METHOD__
. '-cacheable' );
191 wfProfileOut( __METHOD__
);
192 throw new MWException( __METHOD__
. ' generated invalid XML' );
195 $obj = new PPNode_DOM( $dom->documentElement
);
196 wfProfileOut( __METHOD__
. '-loadXML' );
198 wfProfileOut( __METHOD__
. '-cacheable' );
200 wfProfileOut( __METHOD__
);
205 * @param $text string
209 function preprocessToXml( $text, $flags = 0 ) {
210 wfProfileIn( __METHOD__
);
223 'names' => array( 2 => null ),
229 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
231 $xmlishElements = $this->parser
->getStripList();
232 $enableOnlyinclude = false;
233 if ( $forInclusion ) {
234 $ignoredTags = array( 'includeonly', '/includeonly' );
235 $ignoredElements = array( 'noinclude' );
236 $xmlishElements[] = 'noinclude';
237 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
238 $enableOnlyinclude = true;
241 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
242 $ignoredElements = array( 'includeonly' );
243 $xmlishElements[] = 'includeonly';
245 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
247 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
248 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
250 $stack = new PPDStack
;
252 $searchBase = "[{<\n"; #}
253 $revText = strrev( $text ); // For fast reverse searches
254 $lengthText = strlen( $text );
256 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
257 $accum =& $stack->getAccum(); # Current accumulator
259 $findEquals = false; # True to find equals signs in arguments
260 $findPipe = false; # True to take notice of pipe characters
262 $inHeading = false; # True if $i is inside a possible heading
263 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
264 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
265 $fakeLineStart = true; # Do a line-start run without outputting an LF character
270 if ( $findOnlyinclude ) {
271 // Ignore all input up to the next <onlyinclude>
272 $startPos = strpos( $text, '<onlyinclude>', $i );
273 if ( $startPos === false ) {
274 // Ignored section runs to the end
275 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
278 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
279 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
281 $findOnlyinclude = false;
284 if ( $fakeLineStart ) {
285 $found = 'line-start';
288 # Find next opening brace, closing brace or pipe
289 $search = $searchBase;
290 if ( $stack->top
=== false ) {
291 $currentClosing = '';
293 $currentClosing = $stack->top
->close
;
294 $search .= $currentClosing;
300 // First equals will be for the template
304 # Output literal section, advance input counter
305 $literalLength = strcspn( $text, $search, $i );
306 if ( $literalLength > 0 ) {
307 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
308 $i +
= $literalLength;
310 if ( $i >= $lengthText ) {
311 if ( $currentClosing == "\n" ) {
312 // Do a past-the-end run to finish off the heading
320 $curChar = $text[$i];
321 if ( $curChar == '|' ) {
323 } elseif ( $curChar == '=' ) {
325 } elseif ( $curChar == '<' ) {
327 } elseif ( $curChar == "\n" ) {
331 $found = 'line-start';
333 } elseif ( $curChar == $currentClosing ) {
335 } elseif ( isset( $rules[$curChar] ) ) {
337 $rule = $rules[$curChar];
339 # Some versions of PHP have a strcspn which stops on null characters
340 # Ignore and continue
347 if ( $found == 'angle' ) {
349 // Handle </onlyinclude>
350 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
351 $findOnlyinclude = true;
355 // Determine element name
356 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
357 // Element name missing or not listed
363 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
365 // To avoid leaving blank lines, when a sequence of
366 // space-separated comments is both preceded and followed by
367 // a newline (ignoring spaces), then
368 // trim leading and trailing spaces and the trailing newline.
371 $endPos = strpos( $text, '-->', $i +
4 );
372 if ( $endPos === false ) {
373 // Unclosed comment in input, runs to end
374 $inner = substr( $text, $i );
375 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
378 // Search backwards for leading whitespace
379 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
381 // Search forwards for trailing whitespace
382 // $wsEnd will be the position of the last space (or the '>' if there's none)
383 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
385 // Keep looking forward as long as we're finding more
387 $comments = array( array( $wsStart, $wsEnd ) );
388 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
389 $c = strpos( $text, '-->', $wsEnd +
4 );
390 if ( $c === false ) {
393 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
394 $comments[] = array( $wsEnd +
1, $c );
398 // Eat the line if possible
399 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
400 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
401 // it's a possible beneficial b/c break.
402 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
403 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
405 // Remove leading whitespace from the end of the accumulator
406 // Sanity check first though
407 $wsLength = $i - $wsStart;
409 && strspn( $accum, " \t", -$wsLength ) === $wsLength )
411 $accum = substr( $accum, 0, -$wsLength );
414 // Dump all but the last comment to the accumulator
415 foreach ( $comments as $j => $com ) {
417 $endPos = $com[1] +
1;
418 if ( $j == ( count( $comments ) - 1) ) {
421 $inner = substr( $text, $startPos, $endPos - $startPos);
422 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
425 // Do a line-start run next time to look for headings after the comment
426 $fakeLineStart = true;
428 // No line to eat, just take the comment itself
434 $part = $stack->top
->getCurrentPart();
435 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
436 $part->visualEnd
= $wsStart;
438 // Else comments abutting, no change in visual end
439 $part->commentEnd
= $endPos;
442 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
443 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
448 $lowerName = strtolower( $name );
449 $attrStart = $i +
strlen( $name ) +
1;
452 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
453 if ( $tagEndPos === false ) {
454 // Infinite backtrack
455 // Disable tag search to prevent worst-case O(N^2) performance
462 // Handle ignored tags
463 if ( in_array( $lowerName, $ignoredTags ) ) {
464 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
470 if ( $text[$tagEndPos - 1] == '/' ) {
471 $attrEnd = $tagEndPos - 1;
476 $attrEnd = $tagEndPos;
478 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
479 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
481 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
482 $i = $matches[0][1] +
strlen( $matches[0][0] );
483 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
485 // No end tag -- let it run out to the end of the text.
486 $inner = substr( $text, $tagEndPos +
1 );
491 // <includeonly> and <noinclude> just become <ignore> tags
492 if ( in_array( $lowerName, $ignoredElements ) ) {
493 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
499 if ( $attrEnd <= $attrStart ) {
502 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
504 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
505 // Note that the attr element contains the whitespace between name and attribute,
506 // this is necessary for precise reconstruction during pre-save transform.
507 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
508 if ( $inner !== null ) {
509 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
511 $accum .= $close . '</ext>';
512 } elseif ( $found == 'line-start' ) {
513 // Is this the start of a heading?
514 // Line break belongs before the heading element in any case
515 if ( $fakeLineStart ) {
516 $fakeLineStart = false;
522 $count = strspn( $text, '=', $i, 6 );
523 if ( $count == 1 && $findEquals ) {
524 // DWIM: This looks kind of like a name/value separator
525 // Let's let the equals handler have it and break the potential heading
526 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
527 } elseif ( $count > 0 ) {
531 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
534 $stack->push( $piece );
535 $accum =& $stack->getAccum();
536 $flags = $stack->getFlags();
540 } elseif ( $found == 'line-end' ) {
541 $piece = $stack->top
;
542 // A heading must be open, otherwise \n wouldn't have been in the search list
543 assert( '$piece->open == "\n"' );
544 $part = $piece->getCurrentPart();
545 // Search back through the input to see if it has a proper close
546 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
547 $wsLength = strspn( $revText, " \t", $lengthText - $i );
548 $searchStart = $i - $wsLength;
549 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
550 // Comment found at line end
551 // Search for equals signs before the comment
552 $searchStart = $part->visualEnd
;
553 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
555 $count = $piece->count
;
556 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
557 if ( $equalsLength > 0 ) {
558 if ( $searchStart - $equalsLength == $piece->startPos
) {
559 // This is just a single string of equals signs on its own line
560 // Replicate the doHeadings behavior /={count}(.+)={count}/
561 // First find out how many equals signs there really are (don't stop at 6)
562 $count = $equalsLength;
566 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
569 $count = min( $equalsLength, $count );
572 // Normal match, output <h>
573 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
576 // Single equals sign on its own line, count=0
580 // No match, no <h>, just pass down the inner text
585 $accum =& $stack->getAccum();
586 $flags = $stack->getFlags();
589 // Append the result to the enclosing accumulator
591 // Note that we do NOT increment the input pointer.
592 // This is because the closing linebreak could be the opening linebreak of
593 // another heading. Infinite loops are avoided because the next iteration MUST
594 // hit the heading open case above, which unconditionally increments the
596 } elseif ( $found == 'open' ) {
597 # count opening brace characters
598 $count = strspn( $text, $curChar, $i );
600 # we need to add to stack only if opening brace count is enough for one of the rules
601 if ( $count >= $rule['min'] ) {
602 # Add it to the stack
605 'close' => $rule['end'],
607 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
610 $stack->push( $piece );
611 $accum =& $stack->getAccum();
612 $flags = $stack->getFlags();
615 # Add literal brace(s)
616 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
619 } elseif ( $found == 'close' ) {
620 $piece = $stack->top
;
621 # lets check if there are enough characters for closing brace
622 $maxCount = $piece->count
;
623 $count = strspn( $text, $curChar, $i, $maxCount );
625 # check for maximum matching characters (if there are 5 closing
626 # characters, we will probably need only 3 - depending on the rules)
627 $rule = $rules[$piece->open
];
628 if ( $count > $rule['max'] ) {
629 # The specified maximum exists in the callback array, unless the caller
631 $matchingCount = $rule['max'];
633 # Count is less than the maximum
634 # Skip any gaps in the callback array to find the true largest match
635 # Need to use array_key_exists not isset because the callback can be null
636 $matchingCount = $count;
637 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
642 if ( $matchingCount <= 0 ) {
643 # No matching element found in callback array
644 # Output a literal closing brace and continue
645 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
649 $name = $rule['names'][$matchingCount];
650 if ( $name === null ) {
651 // No element, just literal text
652 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
655 # Note: $parts is already XML, does not need to be encoded further
656 $parts = $piece->parts
;
657 $title = $parts[0]->out
;
660 # The invocation is at the start of the line if lineStart is set in
661 # the stack, and all opening brackets are used up.
662 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
663 $attr = ' lineStart="1"';
668 $element = "<$name$attr>";
669 $element .= "<title>$title</title>";
671 foreach ( $parts as $part ) {
672 if ( isset( $part->eqpos
) ) {
673 $argName = substr( $part->out
, 0, $part->eqpos
);
674 $argValue = substr( $part->out
, $part->eqpos +
1 );
675 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
677 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
681 $element .= "</$name>";
684 # Advance input pointer
685 $i +
= $matchingCount;
689 $accum =& $stack->getAccum();
691 # Re-add the old stack element if it still has unmatched opening characters remaining
692 if ( $matchingCount < $piece->count
) {
693 $piece->parts
= array( new PPDPart
);
694 $piece->count
-= $matchingCount;
695 # do we still qualify for any callback with remaining count?
696 $min = $rules[$piece->open
]['min'];
697 if ( $piece->count
>= $min ) {
698 $stack->push( $piece );
699 $accum =& $stack->getAccum();
701 $accum .= str_repeat( $piece->open
, $piece->count
);
704 $flags = $stack->getFlags();
707 # Add XML element to the enclosing accumulator
709 } elseif ( $found == 'pipe' ) {
710 $findEquals = true; // shortcut for getFlags()
712 $accum =& $stack->getAccum();
714 } elseif ( $found == 'equals' ) {
715 $findEquals = false; // shortcut for getFlags()
716 $stack->getCurrentPart()->eqpos
= strlen( $accum );
722 # Output any remaining unclosed brackets
723 foreach ( $stack->stack
as $piece ) {
724 $stack->rootAccum
.= $piece->breakSyntax();
726 $stack->rootAccum
.= '</root>';
727 $xml = $stack->rootAccum
;
729 wfProfileOut( __METHOD__
);
736 * Stack class to help Preprocessor::preprocessToObj()
740 var $stack, $rootAccum;
747 var $elementClass = 'PPDStackElement';
749 static $false = false;
751 function __construct() {
752 $this->stack
= array();
754 $this->rootAccum
= '';
755 $this->accum
=& $this->rootAccum
;
762 return count( $this->stack
);
765 function &getAccum() {
769 function getCurrentPart() {
770 if ( $this->top
=== false ) {
773 return $this->top
->getCurrentPart();
777 function push( $data ) {
778 if ( $data instanceof $this->elementClass
) {
779 $this->stack
[] = $data;
781 $class = $this->elementClass
;
782 $this->stack
[] = new $class( $data );
784 $this->top
= $this->stack
[count( $this->stack
) - 1];
785 $this->accum
=& $this->top
->getAccum();
789 if ( !count( $this->stack
) ) {
790 throw new MWException( __METHOD__
. ': no elements remaining' );
792 $temp = array_pop( $this->stack
);
794 if ( count( $this->stack
) ) {
795 $this->top
= $this->stack
[count( $this->stack
) - 1];
796 $this->accum
=& $this->top
->getAccum();
798 $this->top
= self
::$false;
799 $this->accum
=& $this->rootAccum
;
804 function addPart( $s = '' ) {
805 $this->top
->addPart( $s );
806 $this->accum
=& $this->top
->getAccum();
812 function getFlags() {
813 if ( !count( $this->stack
) ) {
815 'findEquals' => false,
817 'inHeading' => false,
820 return $this->top
->getFlags();
828 class PPDStackElement
{
829 var $open, // Opening character (\n for heading)
830 $close, // Matching closing character
831 $count, // Number of opening characters found (number of "=" for heading)
832 $parts, // Array of PPDPart objects describing pipe-separated parts.
833 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
835 var $partClass = 'PPDPart';
837 function __construct( $data = array() ) {
838 $class = $this->partClass
;
839 $this->parts
= array( new $class );
841 foreach ( $data as $name => $value ) {
842 $this->$name = $value;
846 function &getAccum() {
847 return $this->parts
[count( $this->parts
) - 1]->out
;
850 function addPart( $s = '' ) {
851 $class = $this->partClass
;
852 $this->parts
[] = new $class( $s );
855 function getCurrentPart() {
856 return $this->parts
[count( $this->parts
) - 1];
862 function getFlags() {
863 $partCount = count( $this->parts
);
864 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
866 'findPipe' => $findPipe,
867 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
868 'inHeading' => $this->open
== "\n",
873 * Get the output string that would result if the close is not found.
877 function breakSyntax( $openingCount = false ) {
878 if ( $this->open
== "\n" ) {
879 $s = $this->parts
[0]->out
;
881 if ( $openingCount === false ) {
882 $openingCount = $this->count
;
884 $s = str_repeat( $this->open
, $openingCount );
886 foreach ( $this->parts
as $part ) {
903 var $out; // Output accumulator string
905 // Optional member variables:
906 // eqpos Position of equals sign in output accumulator
907 // commentEnd Past-the-end input pointer for the last comment encountered
908 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
910 function __construct( $out = '' ) {
916 * An expansion frame, used as a context to expand the result of preprocessToObj()
919 class PPFrame_DOM
implements PPFrame
{
938 * Hashtable listing templates which are disallowed for expansion in this frame,
939 * having been encountered previously in parent frames.
944 * Recursion depth of this frame, top = 0
945 * Note that this is NOT the same as expansion depth in expand()
950 * Construct a new preprocessor frame.
951 * @param $preprocessor Preprocessor The parent preprocessor
953 function __construct( $preprocessor ) {
954 $this->preprocessor
= $preprocessor;
955 $this->parser
= $preprocessor->parser
;
956 $this->title
= $this->parser
->mTitle
;
957 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
958 $this->loopCheckHash
= array();
963 * Create a new child frame
964 * $args is optionally a multi-root PPNode or array containing the template arguments
966 * @return PPTemplateFrame_DOM
968 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
969 $namedArgs = array();
970 $numberedArgs = array();
971 if ( $title === false ) {
972 $title = $this->title
;
974 if ( $args !== false ) {
976 if ( $args instanceof PPNode
) {
979 foreach ( $args as $arg ) {
980 if ( $arg instanceof PPNode
) {
984 $xpath = new DOMXPath( $arg->ownerDocument
);
987 $nameNodes = $xpath->query( 'name', $arg );
988 $value = $xpath->query( 'value', $arg );
989 if ( $nameNodes->item( 0 )->hasAttributes() ) {
990 // Numbered parameter
991 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
992 $index = $index - $indexOffset;
993 $numberedArgs[$index] = $value->item( 0 );
994 unset( $namedArgs[$index] );
997 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
998 $namedArgs[$name] = $value->item( 0 );
999 unset( $numberedArgs[$name] );
1003 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1007 * @throws MWException
1012 function expand( $root, $flags = 0 ) {
1013 static $expansionDepth = 0;
1014 if ( is_string( $root ) ) {
1018 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1019 $this->parser
->limitationWarn( 'node-count-exceeded',
1020 $this->parser
->mPPNodeCount
,
1021 $this->parser
->mOptions
->getMaxPPNodeCount()
1023 return '<span class="error">Node-count limit exceeded</span>';
1026 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1027 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1029 $this->parser
->mOptions
->getMaxPPExpandDepth()
1031 return '<span class="error">Expansion depth limit exceeded</span>';
1033 wfProfileIn( __METHOD__
);
1035 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1036 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1039 if ( $root instanceof PPNode_DOM
) {
1040 $root = $root->node
;
1042 if ( $root instanceof DOMDocument
) {
1043 $root = $root->documentElement
;
1046 $outStack = array( '', '' );
1047 $iteratorStack = array( false, $root );
1048 $indexStack = array( 0, 0 );
1050 while ( count( $iteratorStack ) > 1 ) {
1051 $level = count( $outStack ) - 1;
1052 $iteratorNode =& $iteratorStack[$level];
1053 $out =& $outStack[$level];
1054 $index =& $indexStack[$level];
1056 if ( $iteratorNode instanceof PPNode_DOM
) {
1057 $iteratorNode = $iteratorNode->node
;
1060 if ( is_array( $iteratorNode ) ) {
1061 if ( $index >= count( $iteratorNode ) ) {
1062 // All done with this iterator
1063 $iteratorStack[$level] = false;
1064 $contextNode = false;
1066 $contextNode = $iteratorNode[$index];
1069 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1070 if ( $index >= $iteratorNode->length
) {
1071 // All done with this iterator
1072 $iteratorStack[$level] = false;
1073 $contextNode = false;
1075 $contextNode = $iteratorNode->item( $index );
1079 // Copy to $contextNode and then delete from iterator stack,
1080 // because this is not an iterator but we do have to execute it once
1081 $contextNode = $iteratorStack[$level];
1082 $iteratorStack[$level] = false;
1085 if ( $contextNode instanceof PPNode_DOM
) {
1086 $contextNode = $contextNode->node
;
1089 $newIterator = false;
1091 if ( $contextNode === false ) {
1093 } elseif ( is_string( $contextNode ) ) {
1094 $out .= $contextNode;
1095 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1096 $newIterator = $contextNode;
1097 } elseif ( $contextNode instanceof DOMNode
) {
1098 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1099 $out .= $contextNode->nodeValue
;
1100 } elseif ( $contextNode->nodeName
== 'template' ) {
1101 # Double-brace expansion
1102 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1103 $titles = $xpath->query( 'title', $contextNode );
1104 $title = $titles->item( 0 );
1105 $parts = $xpath->query( 'part', $contextNode );
1106 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1107 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1109 $lineStart = $contextNode->getAttribute( 'lineStart' );
1111 'title' => new PPNode_DOM( $title ),
1112 'parts' => new PPNode_DOM( $parts ),
1113 'lineStart' => $lineStart );
1114 $ret = $this->parser
->braceSubstitution( $params, $this );
1115 if ( isset( $ret['object'] ) ) {
1116 $newIterator = $ret['object'];
1118 $out .= $ret['text'];
1121 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1122 # Triple-brace expansion
1123 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1124 $titles = $xpath->query( 'title', $contextNode );
1125 $title = $titles->item( 0 );
1126 $parts = $xpath->query( 'part', $contextNode );
1127 if ( $flags & PPFrame
::NO_ARGS
) {
1128 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1131 'title' => new PPNode_DOM( $title ),
1132 'parts' => new PPNode_DOM( $parts ) );
1133 $ret = $this->parser
->argSubstitution( $params, $this );
1134 if ( isset( $ret['object'] ) ) {
1135 $newIterator = $ret['object'];
1137 $out .= $ret['text'];
1140 } elseif ( $contextNode->nodeName
== 'comment' ) {
1141 # HTML-style comment
1142 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1143 if ( $this->parser
->ot
['html']
1144 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1145 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1149 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1150 # Not in RECOVER_COMMENTS mode (extractSections) though
1151 elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1152 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1154 # 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];
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
1268 function implode( $sep /*, ... */ ) {
1269 $args = array_slice( func_get_args(), 1 );
1273 foreach ( $args as $root ) {
1274 if ( $root instanceof PPNode_DOM
) {
1275 $root = $root->node
;
1277 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1278 $root = array( $root );
1280 foreach ( $root as $node ) {
1286 $s .= $this->expand( $node );
1293 * Makes an object that, when expand()ed, will be the same as one obtained
1298 function virtualImplode( $sep /*, ... */ ) {
1299 $args = array_slice( func_get_args(), 1 );
1303 foreach ( $args as $root ) {
1304 if ( $root instanceof PPNode_DOM
) {
1305 $root = $root->node
;
1307 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1308 $root = array( $root );
1310 foreach ( $root as $node ) {
1323 * Virtual implode with brackets
1326 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1327 $args = array_slice( func_get_args(), 3 );
1328 $out = array( $start );
1331 foreach ( $args as $root ) {
1332 if ( $root instanceof PPNode_DOM
) {
1333 $root = $root->node
;
1335 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1336 $root = array( $root );
1338 foreach ( $root as $node ) {
1351 function __toString() {
1355 function getPDBK( $level = false ) {
1356 if ( $level === false ) {
1357 return $this->title
->getPrefixedDBkey();
1359 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1366 function getArguments() {
1373 function getNumberedArguments() {
1380 function getNamedArguments() {
1385 * Returns true if there are no arguments in this frame
1389 function isEmpty() {
1393 function getArgument( $name ) {
1398 * Returns true if the infinite loop check is OK, false if a loop is detected
1402 function loopCheck( $title ) {
1403 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1407 * Return true if the frame is a template frame
1411 function isTemplate() {
1416 * Get a title of frame
1420 function getTitle() {
1421 return $this->title
;
1426 * Expansion frame with template arguments
1429 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1430 var $numberedArgs, $namedArgs;
1436 var $numberedExpansionCache, $namedExpansionCache;
1439 * @param $preprocessor
1440 * @param $parent PPFrame_DOM
1441 * @param $numberedArgs array
1442 * @param $namedArgs array
1443 * @param $title Title
1445 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1446 parent
::__construct( $preprocessor );
1448 $this->parent
= $parent;
1449 $this->numberedArgs
= $numberedArgs;
1450 $this->namedArgs
= $namedArgs;
1451 $this->title
= $title;
1452 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1453 $this->titleCache
= $parent->titleCache
;
1454 $this->titleCache
[] = $pdbk;
1455 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1456 if ( $pdbk !== false ) {
1457 $this->loopCheckHash
[$pdbk] = true;
1459 $this->depth
= $parent->depth +
1;
1460 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1463 function __toString() {
1466 $args = $this->numberedArgs +
$this->namedArgs
;
1467 foreach ( $args as $name => $value ) {
1473 $s .= "\"$name\":\"" .
1474 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1481 * Returns true if there are no arguments in this frame
1485 function isEmpty() {
1486 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1489 function getArguments() {
1490 $arguments = array();
1491 foreach ( array_merge(
1492 array_keys( $this->numberedArgs
),
1493 array_keys( $this->namedArgs
) ) as $key ) {
1494 $arguments[$key] = $this->getArgument( $key );
1499 function getNumberedArguments() {
1500 $arguments = array();
1501 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1502 $arguments[$key] = $this->getArgument( $key );
1507 function getNamedArguments() {
1508 $arguments = array();
1509 foreach ( array_keys( $this->namedArgs
) as $key ) {
1510 $arguments[$key] = $this->getArgument( $key );
1515 function getNumberedArgument( $index ) {
1516 if ( !isset( $this->numberedArgs
[$index] ) ) {
1519 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1520 # No trimming for unnamed arguments
1521 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1523 return $this->numberedExpansionCache
[$index];
1526 function getNamedArgument( $name ) {
1527 if ( !isset( $this->namedArgs
[$name] ) ) {
1530 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1531 # Trim named arguments post-expand, for backwards compatibility
1532 $this->namedExpansionCache
[$name] = trim(
1533 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1535 return $this->namedExpansionCache
[$name];
1538 function getArgument( $name ) {
1539 $text = $this->getNumberedArgument( $name );
1540 if ( $text === false ) {
1541 $text = $this->getNamedArgument( $name );
1547 * Return true if the frame is a template frame
1551 function isTemplate() {
1557 * Expansion frame with custom arguments
1560 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1563 function __construct( $preprocessor, $args ) {
1564 parent
::__construct( $preprocessor );
1565 $this->args
= $args;
1568 function __toString() {
1571 foreach ( $this->args
as $name => $value ) {
1577 $s .= "\"$name\":\"" .
1578 str_replace( '"', '\\"', $value->__toString() ) . '"';
1587 function isEmpty() {
1588 return !count( $this->args
);
1591 function getArgument( $index ) {
1592 if ( !isset( $this->args
[$index] ) ) {
1595 return $this->args
[$index];
1598 function getArguments() {
1606 class PPNode_DOM
implements PPNode
{
1614 function __construct( $node, $xpath = false ) {
1615 $this->node
= $node;
1621 function getXPath() {
1622 if ( $this->xpath
=== null ) {
1623 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1625 return $this->xpath
;
1628 function __toString() {
1629 if ( $this->node
instanceof DOMNodeList
) {
1631 foreach ( $this->node
as $node ) {
1632 $s .= $node->ownerDocument
->saveXML( $node );
1635 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1641 * @return bool|PPNode_DOM
1643 function getChildren() {
1644 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1648 * @return bool|PPNode_DOM
1650 function getFirstChild() {
1651 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1655 * @return bool|PPNode_DOM
1657 function getNextSibling() {
1658 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1664 * @return bool|PPNode_DOM
1666 function getChildrenOfType( $type ) {
1667 return new self( $this->getXPath()->query( $type, $this->node
) );
1673 function getLength() {
1674 if ( $this->node
instanceof DOMNodeList
) {
1675 return $this->node
->length
;
1683 * @return bool|PPNode_DOM
1685 function item( $i ) {
1686 $item = $this->node
->item( $i );
1687 return $item ?
new self( $item ) : false;
1693 function getName() {
1694 if ( $this->node
instanceof DOMNodeList
) {
1697 return $this->node
->nodeName
;
1702 * Split a "<part>" node into an associative array containing:
1703 * - name PPNode name
1704 * - index String index
1705 * - value PPNode value
1707 * @throws MWException
1710 function splitArg() {
1711 $xpath = $this->getXPath();
1712 $names = $xpath->query( 'name', $this->node
);
1713 $values = $xpath->query( 'value', $this->node
);
1714 if ( !$names->length ||
!$values->length
) {
1715 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1717 $name = $names->item( 0 );
1718 $index = $name->getAttribute( 'index' );
1720 'name' => new self( $name ),
1722 'value' => new self( $values->item( 0 ) ) );
1726 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1727 * All values in the resulting array are PPNodes. Inner and close are optional.
1729 * @throws MWException
1732 function splitExt() {
1733 $xpath = $this->getXPath();
1734 $names = $xpath->query( 'name', $this->node
);
1735 $attrs = $xpath->query( 'attr', $this->node
);
1736 $inners = $xpath->query( 'inner', $this->node
);
1737 $closes = $xpath->query( 'close', $this->node
);
1738 if ( !$names->length ||
!$attrs->length
) {
1739 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1742 'name' => new self( $names->item( 0 ) ),
1743 'attr' => new self( $attrs->item( 0 ) ) );
1744 if ( $inners->length
) {
1745 $parts['inner'] = new self( $inners->item( 0 ) );
1747 if ( $closes->length
) {
1748 $parts['close'] = new self( $closes->item( 0 ) );
1754 * Split a "<h>" node
1755 * @throws MWException
1758 function splitHeading() {
1759 if ( $this->getName() !== 'h' ) {
1760 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1763 'i' => $this->node
->getAttribute( 'i' ),
1764 'level' => $this->node
->getAttribute( 'level' ),
1765 'contents' => $this->getChildren()