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, ' ', $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, ' ', $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, ' ', $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;
408 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
409 $accum = substr( $accum, 0, -$wsLength );
412 // Dump all but the last comment to the accumulator
413 foreach ( $comments as $j => $com ) {
415 $endPos = $com[1] +
1;
416 if ( $j == ( count( $comments ) - 1) ) {
419 $inner = substr( $text, $startPos, $endPos - $startPos);
420 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
423 // Do a line-start run next time to look for headings after the comment
424 $fakeLineStart = true;
426 // No line to eat, just take the comment itself
432 $part = $stack->top
->getCurrentPart();
433 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
434 $part->visualEnd
= $wsStart;
436 // Else comments abutting, no change in visual end
437 $part->commentEnd
= $endPos;
440 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
441 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
446 $lowerName = strtolower( $name );
447 $attrStart = $i +
strlen( $name ) +
1;
450 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
451 if ( $tagEndPos === false ) {
452 // Infinite backtrack
453 // Disable tag search to prevent worst-case O(N^2) performance
460 // Handle ignored tags
461 if ( in_array( $lowerName, $ignoredTags ) ) {
462 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
468 if ( $text[$tagEndPos - 1] == '/' ) {
469 $attrEnd = $tagEndPos - 1;
474 $attrEnd = $tagEndPos;
476 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
477 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
479 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
480 $i = $matches[0][1] +
strlen( $matches[0][0] );
481 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
483 // No end tag -- let it run out to the end of the text.
484 $inner = substr( $text, $tagEndPos +
1 );
489 // <includeonly> and <noinclude> just become <ignore> tags
490 if ( in_array( $lowerName, $ignoredElements ) ) {
491 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
497 if ( $attrEnd <= $attrStart ) {
500 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
502 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
503 // Note that the attr element contains the whitespace between name and attribute,
504 // this is necessary for precise reconstruction during pre-save transform.
505 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
506 if ( $inner !== null ) {
507 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
509 $accum .= $close . '</ext>';
510 } elseif ( $found == 'line-start' ) {
511 // Is this the start of a heading?
512 // Line break belongs before the heading element in any case
513 if ( $fakeLineStart ) {
514 $fakeLineStart = false;
520 $count = strspn( $text, '=', $i, 6 );
521 if ( $count == 1 && $findEquals ) {
522 // DWIM: This looks kind of like a name/value separator
523 // Let's let the equals handler have it and break the potential heading
524 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
525 } elseif ( $count > 0 ) {
529 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
532 $stack->push( $piece );
533 $accum =& $stack->getAccum();
534 $flags = $stack->getFlags();
538 } elseif ( $found == 'line-end' ) {
539 $piece = $stack->top
;
540 // A heading must be open, otherwise \n wouldn't have been in the search list
541 assert( '$piece->open == "\n"' );
542 $part = $piece->getCurrentPart();
543 // Search back through the input to see if it has a proper close
544 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
545 $wsLength = strspn( $revText, " \t", $lengthText - $i );
546 $searchStart = $i - $wsLength;
547 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
548 // Comment found at line end
549 // Search for equals signs before the comment
550 $searchStart = $part->visualEnd
;
551 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
553 $count = $piece->count
;
554 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
555 if ( $equalsLength > 0 ) {
556 if ( $searchStart - $equalsLength == $piece->startPos
) {
557 // This is just a single string of equals signs on its own line
558 // Replicate the doHeadings behavior /={count}(.+)={count}/
559 // First find out how many equals signs there really are (don't stop at 6)
560 $count = $equalsLength;
564 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
567 $count = min( $equalsLength, $count );
570 // Normal match, output <h>
571 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
574 // Single equals sign on its own line, count=0
578 // No match, no <h>, just pass down the inner text
583 $accum =& $stack->getAccum();
584 $flags = $stack->getFlags();
587 // Append the result to the enclosing accumulator
589 // Note that we do NOT increment the input pointer.
590 // This is because the closing linebreak could be the opening linebreak of
591 // another heading. Infinite loops are avoided because the next iteration MUST
592 // hit the heading open case above, which unconditionally increments the
594 } elseif ( $found == 'open' ) {
595 # count opening brace characters
596 $count = strspn( $text, $curChar, $i );
598 # we need to add to stack only if opening brace count is enough for one of the rules
599 if ( $count >= $rule['min'] ) {
600 # Add it to the stack
603 'close' => $rule['end'],
605 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
608 $stack->push( $piece );
609 $accum =& $stack->getAccum();
610 $flags = $stack->getFlags();
613 # Add literal brace(s)
614 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
617 } elseif ( $found == 'close' ) {
618 $piece = $stack->top
;
619 # lets check if there are enough characters for closing brace
620 $maxCount = $piece->count
;
621 $count = strspn( $text, $curChar, $i, $maxCount );
623 # check for maximum matching characters (if there are 5 closing
624 # characters, we will probably need only 3 - depending on the rules)
625 $rule = $rules[$piece->open
];
626 if ( $count > $rule['max'] ) {
627 # The specified maximum exists in the callback array, unless the caller
629 $matchingCount = $rule['max'];
631 # Count is less than the maximum
632 # Skip any gaps in the callback array to find the true largest match
633 # Need to use array_key_exists not isset because the callback can be null
634 $matchingCount = $count;
635 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
640 if ( $matchingCount <= 0 ) {
641 # No matching element found in callback array
642 # Output a literal closing brace and continue
643 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
647 $name = $rule['names'][$matchingCount];
648 if ( $name === null ) {
649 // No element, just literal text
650 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
653 # Note: $parts is already XML, does not need to be encoded further
654 $parts = $piece->parts
;
655 $title = $parts[0]->out
;
658 # The invocation is at the start of the line if lineStart is set in
659 # the stack, and all opening brackets are used up.
660 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
661 $attr = ' lineStart="1"';
666 $element = "<$name$attr>";
667 $element .= "<title>$title</title>";
669 foreach ( $parts as $part ) {
670 if ( isset( $part->eqpos
) ) {
671 $argName = substr( $part->out
, 0, $part->eqpos
);
672 $argValue = substr( $part->out
, $part->eqpos +
1 );
673 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
675 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
679 $element .= "</$name>";
682 # Advance input pointer
683 $i +
= $matchingCount;
687 $accum =& $stack->getAccum();
689 # Re-add the old stack element if it still has unmatched opening characters remaining
690 if ( $matchingCount < $piece->count
) {
691 $piece->parts
= array( new PPDPart
);
692 $piece->count
-= $matchingCount;
693 # do we still qualify for any callback with remaining count?
694 $min = $rules[$piece->open
]['min'];
695 if ( $piece->count
>= $min ) {
696 $stack->push( $piece );
697 $accum =& $stack->getAccum();
699 $accum .= str_repeat( $piece->open
, $piece->count
);
702 $flags = $stack->getFlags();
705 # Add XML element to the enclosing accumulator
707 } elseif ( $found == 'pipe' ) {
708 $findEquals = true; // shortcut for getFlags()
710 $accum =& $stack->getAccum();
712 } elseif ( $found == 'equals' ) {
713 $findEquals = false; // shortcut for getFlags()
714 $stack->getCurrentPart()->eqpos
= strlen( $accum );
720 # Output any remaining unclosed brackets
721 foreach ( $stack->stack
as $piece ) {
722 $stack->rootAccum
.= $piece->breakSyntax();
724 $stack->rootAccum
.= '</root>';
725 $xml = $stack->rootAccum
;
727 wfProfileOut( __METHOD__
);
734 * Stack class to help Preprocessor::preprocessToObj()
738 var $stack, $rootAccum;
745 var $elementClass = 'PPDStackElement';
747 static $false = false;
749 function __construct() {
750 $this->stack
= array();
752 $this->rootAccum
= '';
753 $this->accum
=& $this->rootAccum
;
760 return count( $this->stack
);
763 function &getAccum() {
767 function getCurrentPart() {
768 if ( $this->top
=== false ) {
771 return $this->top
->getCurrentPart();
775 function push( $data ) {
776 if ( $data instanceof $this->elementClass
) {
777 $this->stack
[] = $data;
779 $class = $this->elementClass
;
780 $this->stack
[] = new $class( $data );
782 $this->top
= $this->stack
[count( $this->stack
) - 1];
783 $this->accum
=& $this->top
->getAccum();
787 if ( !count( $this->stack
) ) {
788 throw new MWException( __METHOD__
. ': no elements remaining' );
790 $temp = array_pop( $this->stack
);
792 if ( count( $this->stack
) ) {
793 $this->top
= $this->stack
[count( $this->stack
) - 1];
794 $this->accum
=& $this->top
->getAccum();
796 $this->top
= self
::$false;
797 $this->accum
=& $this->rootAccum
;
802 function addPart( $s = '' ) {
803 $this->top
->addPart( $s );
804 $this->accum
=& $this->top
->getAccum();
810 function getFlags() {
811 if ( !count( $this->stack
) ) {
813 'findEquals' => false,
815 'inHeading' => false,
818 return $this->top
->getFlags();
826 class PPDStackElement
{
827 var $open, // Opening character (\n for heading)
828 $close, // Matching closing character
829 $count, // Number of opening characters found (number of "=" for heading)
830 $parts, // Array of PPDPart objects describing pipe-separated parts.
831 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
833 var $partClass = 'PPDPart';
835 function __construct( $data = array() ) {
836 $class = $this->partClass
;
837 $this->parts
= array( new $class );
839 foreach ( $data as $name => $value ) {
840 $this->$name = $value;
844 function &getAccum() {
845 return $this->parts
[count( $this->parts
) - 1]->out
;
848 function addPart( $s = '' ) {
849 $class = $this->partClass
;
850 $this->parts
[] = new $class( $s );
853 function getCurrentPart() {
854 return $this->parts
[count( $this->parts
) - 1];
860 function getFlags() {
861 $partCount = count( $this->parts
);
862 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
864 'findPipe' => $findPipe,
865 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
866 'inHeading' => $this->open
== "\n",
871 * Get the output string that would result if the close is not found.
875 function breakSyntax( $openingCount = false ) {
876 if ( $this->open
== "\n" ) {
877 $s = $this->parts
[0]->out
;
879 if ( $openingCount === false ) {
880 $openingCount = $this->count
;
882 $s = str_repeat( $this->open
, $openingCount );
884 foreach ( $this->parts
as $part ) {
901 var $out; // Output accumulator string
903 // Optional member variables:
904 // eqpos Position of equals sign in output accumulator
905 // commentEnd Past-the-end input pointer for the last comment encountered
906 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
908 function __construct( $out = '' ) {
914 * An expansion frame, used as a context to expand the result of preprocessToObj()
917 class PPFrame_DOM
implements PPFrame
{
936 * Hashtable listing templates which are disallowed for expansion in this frame,
937 * having been encountered previously in parent frames.
942 * Recursion depth of this frame, top = 0
943 * Note that this is NOT the same as expansion depth in expand()
948 * Construct a new preprocessor frame.
949 * @param $preprocessor Preprocessor The parent preprocessor
951 function __construct( $preprocessor ) {
952 $this->preprocessor
= $preprocessor;
953 $this->parser
= $preprocessor->parser
;
954 $this->title
= $this->parser
->mTitle
;
955 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
956 $this->loopCheckHash
= array();
961 * Create a new child frame
962 * $args is optionally a multi-root PPNode or array containing the template arguments
964 * @return PPTemplateFrame_DOM
966 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
967 $namedArgs = array();
968 $numberedArgs = array();
969 if ( $title === false ) {
970 $title = $this->title
;
972 if ( $args !== false ) {
974 if ( $args instanceof PPNode
) {
977 foreach ( $args as $arg ) {
978 if ( $arg instanceof PPNode
) {
982 $xpath = new DOMXPath( $arg->ownerDocument
);
985 $nameNodes = $xpath->query( 'name', $arg );
986 $value = $xpath->query( 'value', $arg );
987 if ( $nameNodes->item( 0 )->hasAttributes() ) {
988 // Numbered parameter
989 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
990 $index = $index - $indexOffset;
991 $numberedArgs[$index] = $value->item( 0 );
992 unset( $namedArgs[$index] );
995 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
996 $namedArgs[$name] = $value->item( 0 );
997 unset( $numberedArgs[$name] );
1001 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1005 * @throws MWException
1010 function expand( $root, $flags = 0 ) {
1011 static $expansionDepth = 0;
1012 if ( is_string( $root ) ) {
1016 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1017 $this->parser
->limitationWarn( 'node-count-exceeded',
1018 $this->parser
->mPPNodeCount
,
1019 $this->parser
->mOptions
->getMaxPPNodeCount()
1021 return '<span class="error">Node-count limit exceeded</span>';
1024 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1025 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1027 $this->parser
->mOptions
->getMaxPPExpandDepth()
1029 return '<span class="error">Expansion depth limit exceeded</span>';
1031 wfProfileIn( __METHOD__
);
1033 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1034 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1037 if ( $root instanceof PPNode_DOM
) {
1038 $root = $root->node
;
1040 if ( $root instanceof DOMDocument
) {
1041 $root = $root->documentElement
;
1044 $outStack = array( '', '' );
1045 $iteratorStack = array( false, $root );
1046 $indexStack = array( 0, 0 );
1048 while ( count( $iteratorStack ) > 1 ) {
1049 $level = count( $outStack ) - 1;
1050 $iteratorNode =& $iteratorStack[$level];
1051 $out =& $outStack[$level];
1052 $index =& $indexStack[$level];
1054 if ( $iteratorNode instanceof PPNode_DOM
) {
1055 $iteratorNode = $iteratorNode->node
;
1058 if ( is_array( $iteratorNode ) ) {
1059 if ( $index >= count( $iteratorNode ) ) {
1060 // All done with this iterator
1061 $iteratorStack[$level] = false;
1062 $contextNode = false;
1064 $contextNode = $iteratorNode[$index];
1067 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1068 if ( $index >= $iteratorNode->length
) {
1069 // All done with this iterator
1070 $iteratorStack[$level] = false;
1071 $contextNode = false;
1073 $contextNode = $iteratorNode->item( $index );
1077 // Copy to $contextNode and then delete from iterator stack,
1078 // because this is not an iterator but we do have to execute it once
1079 $contextNode = $iteratorStack[$level];
1080 $iteratorStack[$level] = false;
1083 if ( $contextNode instanceof PPNode_DOM
) {
1084 $contextNode = $contextNode->node
;
1087 $newIterator = false;
1089 if ( $contextNode === false ) {
1091 } elseif ( is_string( $contextNode ) ) {
1092 $out .= $contextNode;
1093 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1094 $newIterator = $contextNode;
1095 } elseif ( $contextNode instanceof DOMNode
) {
1096 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1097 $out .= $contextNode->nodeValue
;
1098 } elseif ( $contextNode->nodeName
== 'template' ) {
1099 # Double-brace expansion
1100 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1101 $titles = $xpath->query( 'title', $contextNode );
1102 $title = $titles->item( 0 );
1103 $parts = $xpath->query( 'part', $contextNode );
1104 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1105 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1107 $lineStart = $contextNode->getAttribute( 'lineStart' );
1109 'title' => new PPNode_DOM( $title ),
1110 'parts' => new PPNode_DOM( $parts ),
1111 'lineStart' => $lineStart );
1112 $ret = $this->parser
->braceSubstitution( $params, $this );
1113 if ( isset( $ret['object'] ) ) {
1114 $newIterator = $ret['object'];
1116 $out .= $ret['text'];
1119 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1120 # Triple-brace expansion
1121 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1122 $titles = $xpath->query( 'title', $contextNode );
1123 $title = $titles->item( 0 );
1124 $parts = $xpath->query( 'part', $contextNode );
1125 if ( $flags & PPFrame
::NO_ARGS
) {
1126 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1129 'title' => new PPNode_DOM( $title ),
1130 'parts' => new PPNode_DOM( $parts ) );
1131 $ret = $this->parser
->argSubstitution( $params, $this );
1132 if ( isset( $ret['object'] ) ) {
1133 $newIterator = $ret['object'];
1135 $out .= $ret['text'];
1138 } elseif ( $contextNode->nodeName
== 'comment' ) {
1139 # HTML-style comment
1140 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1141 if ( $this->parser
->ot
['html']
1142 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1143 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1147 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1148 # Not in RECOVER_COMMENTS mode (extractSections) though
1149 elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1150 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1152 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1154 $out .= $contextNode->textContent
;
1156 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1157 # Output suppression used by <includeonly> etc.
1158 # OT_WIKI will only respect <ignore> in substed templates.
1159 # The other output types respect it unless NO_IGNORE is set.
1160 # extractSections() sets NO_IGNORE and so never respects it.
1161 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1162 $out .= $contextNode->textContent
;
1166 } elseif ( $contextNode->nodeName
== 'ext' ) {
1168 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1169 $names = $xpath->query( 'name', $contextNode );
1170 $attrs = $xpath->query( 'attr', $contextNode );
1171 $inners = $xpath->query( 'inner', $contextNode );
1172 $closes = $xpath->query( 'close', $contextNode );
1174 'name' => new PPNode_DOM( $names->item( 0 ) ),
1175 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1176 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1177 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1179 $out .= $this->parser
->extensionSubstitution( $params, $this );
1180 } elseif ( $contextNode->nodeName
== 'h' ) {
1182 $s = $this->expand( $contextNode->childNodes
, $flags );
1184 # Insert a heading marker only for <h> children of <root>
1185 # This is to stop extractSections from going over multiple tree levels
1186 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1187 # Insert heading index marker
1188 $headingIndex = $contextNode->getAttribute( 'i' );
1189 $titleText = $this->title
->getPrefixedDBkey();
1190 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1191 $serial = count( $this->parser
->mHeadings
) - 1;
1192 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1193 $count = $contextNode->getAttribute( 'level' );
1194 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1195 $this->parser
->mStripState
->addGeneral( $marker, '' );
1199 # Generic recursive expansion
1200 $newIterator = $contextNode->childNodes
;
1203 wfProfileOut( __METHOD__
);
1204 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1207 if ( $newIterator !== false ) {
1208 if ( $newIterator instanceof PPNode_DOM
) {
1209 $newIterator = $newIterator->node
;
1212 $iteratorStack[] = $newIterator;
1214 } elseif ( $iteratorStack[$level] === false ) {
1215 // Return accumulated value to parent
1216 // With tail recursion
1217 while ( $iteratorStack[$level] === false && $level > 0 ) {
1218 $outStack[$level - 1] .= $out;
1219 array_pop( $outStack );
1220 array_pop( $iteratorStack );
1221 array_pop( $indexStack );
1227 wfProfileOut( __METHOD__
);
1228 return $outStack[0];
1236 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1237 $args = array_slice( func_get_args(), 2 );
1241 foreach ( $args as $root ) {
1242 if ( $root instanceof PPNode_DOM
) {
1243 $root = $root->node
;
1245 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1246 $root = array( $root );
1248 foreach ( $root as $node ) {
1254 $s .= $this->expand( $node, $flags );
1261 * Implode with no flags specified
1262 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1266 function implode( $sep /*, ... */ ) {
1267 $args = array_slice( func_get_args(), 1 );
1271 foreach ( $args as $root ) {
1272 if ( $root instanceof PPNode_DOM
) {
1273 $root = $root->node
;
1275 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1276 $root = array( $root );
1278 foreach ( $root as $node ) {
1284 $s .= $this->expand( $node );
1291 * Makes an object that, when expand()ed, will be the same as one obtained
1296 function virtualImplode( $sep /*, ... */ ) {
1297 $args = array_slice( func_get_args(), 1 );
1301 foreach ( $args as $root ) {
1302 if ( $root instanceof PPNode_DOM
) {
1303 $root = $root->node
;
1305 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1306 $root = array( $root );
1308 foreach ( $root as $node ) {
1321 * Virtual implode with brackets
1324 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1325 $args = array_slice( func_get_args(), 3 );
1326 $out = array( $start );
1329 foreach ( $args as $root ) {
1330 if ( $root instanceof PPNode_DOM
) {
1331 $root = $root->node
;
1333 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1334 $root = array( $root );
1336 foreach ( $root as $node ) {
1349 function __toString() {
1353 function getPDBK( $level = false ) {
1354 if ( $level === false ) {
1355 return $this->title
->getPrefixedDBkey();
1357 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1364 function getArguments() {
1371 function getNumberedArguments() {
1378 function getNamedArguments() {
1383 * Returns true if there are no arguments in this frame
1387 function isEmpty() {
1391 function getArgument( $name ) {
1396 * Returns true if the infinite loop check is OK, false if a loop is detected
1400 function loopCheck( $title ) {
1401 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1405 * Return true if the frame is a template frame
1409 function isTemplate() {
1414 * Get a title of frame
1418 function getTitle() {
1419 return $this->title
;
1424 * Expansion frame with template arguments
1427 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1428 var $numberedArgs, $namedArgs;
1434 var $numberedExpansionCache, $namedExpansionCache;
1437 * @param $preprocessor
1438 * @param $parent PPFrame_DOM
1439 * @param $numberedArgs array
1440 * @param $namedArgs array
1441 * @param $title Title
1443 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1444 parent
::__construct( $preprocessor );
1446 $this->parent
= $parent;
1447 $this->numberedArgs
= $numberedArgs;
1448 $this->namedArgs
= $namedArgs;
1449 $this->title
= $title;
1450 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1451 $this->titleCache
= $parent->titleCache
;
1452 $this->titleCache
[] = $pdbk;
1453 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1454 if ( $pdbk !== false ) {
1455 $this->loopCheckHash
[$pdbk] = true;
1457 $this->depth
= $parent->depth +
1;
1458 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1461 function __toString() {
1464 $args = $this->numberedArgs +
$this->namedArgs
;
1465 foreach ( $args as $name => $value ) {
1471 $s .= "\"$name\":\"" .
1472 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1479 * Returns true if there are no arguments in this frame
1483 function isEmpty() {
1484 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1487 function getArguments() {
1488 $arguments = array();
1489 foreach ( array_merge(
1490 array_keys( $this->numberedArgs
),
1491 array_keys( $this->namedArgs
) ) as $key ) {
1492 $arguments[$key] = $this->getArgument( $key );
1497 function getNumberedArguments() {
1498 $arguments = array();
1499 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1500 $arguments[$key] = $this->getArgument( $key );
1505 function getNamedArguments() {
1506 $arguments = array();
1507 foreach ( array_keys( $this->namedArgs
) as $key ) {
1508 $arguments[$key] = $this->getArgument( $key );
1513 function getNumberedArgument( $index ) {
1514 if ( !isset( $this->numberedArgs
[$index] ) ) {
1517 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1518 # No trimming for unnamed arguments
1519 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1521 return $this->numberedExpansionCache
[$index];
1524 function getNamedArgument( $name ) {
1525 if ( !isset( $this->namedArgs
[$name] ) ) {
1528 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1529 # Trim named arguments post-expand, for backwards compatibility
1530 $this->namedExpansionCache
[$name] = trim(
1531 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1533 return $this->namedExpansionCache
[$name];
1536 function getArgument( $name ) {
1537 $text = $this->getNumberedArgument( $name );
1538 if ( $text === false ) {
1539 $text = $this->getNamedArgument( $name );
1545 * Return true if the frame is a template frame
1549 function isTemplate() {
1555 * Expansion frame with custom arguments
1558 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1561 function __construct( $preprocessor, $args ) {
1562 parent
::__construct( $preprocessor );
1563 $this->args
= $args;
1566 function __toString() {
1569 foreach ( $this->args
as $name => $value ) {
1575 $s .= "\"$name\":\"" .
1576 str_replace( '"', '\\"', $value->__toString() ) . '"';
1585 function isEmpty() {
1586 return !count( $this->args
);
1589 function getArgument( $index ) {
1590 if ( !isset( $this->args
[$index] ) ) {
1593 return $this->args
[$index];
1596 function getArguments() {
1604 class PPNode_DOM
implements PPNode
{
1612 function __construct( $node, $xpath = false ) {
1613 $this->node
= $node;
1619 function getXPath() {
1620 if ( $this->xpath
=== null ) {
1621 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1623 return $this->xpath
;
1626 function __toString() {
1627 if ( $this->node
instanceof DOMNodeList
) {
1629 foreach ( $this->node
as $node ) {
1630 $s .= $node->ownerDocument
->saveXML( $node );
1633 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1639 * @return bool|PPNode_DOM
1641 function getChildren() {
1642 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1646 * @return bool|PPNode_DOM
1648 function getFirstChild() {
1649 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1653 * @return bool|PPNode_DOM
1655 function getNextSibling() {
1656 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1662 * @return bool|PPNode_DOM
1664 function getChildrenOfType( $type ) {
1665 return new self( $this->getXPath()->query( $type, $this->node
) );
1671 function getLength() {
1672 if ( $this->node
instanceof DOMNodeList
) {
1673 return $this->node
->length
;
1681 * @return bool|PPNode_DOM
1683 function item( $i ) {
1684 $item = $this->node
->item( $i );
1685 return $item ?
new self( $item ) : false;
1691 function getName() {
1692 if ( $this->node
instanceof DOMNodeList
) {
1695 return $this->node
->nodeName
;
1700 * Split a "<part>" node into an associative array containing:
1701 * - name PPNode name
1702 * - index String index
1703 * - value PPNode value
1705 * @throws MWException
1708 function splitArg() {
1709 $xpath = $this->getXPath();
1710 $names = $xpath->query( 'name', $this->node
);
1711 $values = $xpath->query( 'value', $this->node
);
1712 if ( !$names->length ||
!$values->length
) {
1713 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1715 $name = $names->item( 0 );
1716 $index = $name->getAttribute( 'index' );
1718 'name' => new self( $name ),
1720 'value' => new self( $values->item( 0 ) ) );
1724 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1725 * All values in the resulting array are PPNodes. Inner and close are optional.
1727 * @throws MWException
1730 function splitExt() {
1731 $xpath = $this->getXPath();
1732 $names = $xpath->query( 'name', $this->node
);
1733 $attrs = $xpath->query( 'attr', $this->node
);
1734 $inners = $xpath->query( 'inner', $this->node
);
1735 $closes = $xpath->query( 'close', $this->node
);
1736 if ( !$names->length ||
!$attrs->length
) {
1737 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1740 'name' => new self( $names->item( 0 ) ),
1741 'attr' => new self( $attrs->item( 0 ) ) );
1742 if ( $inners->length
) {
1743 $parts['inner'] = new self( $inners->item( 0 ) );
1745 if ( $closes->length
) {
1746 $parts['close'] = new self( $closes->item( 0 ) );
1752 * Split a "<h>" node
1753 * @throws MWException
1756 function splitHeading() {
1757 if ( $this->getName() !== 'h' ) {
1758 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1761 'i' => $this->node
->getAttribute( 'i' ),
1762 'level' => $this->node
->getAttribute( 'level' ),
1763 'contents' => $this->getChildren()