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 ) {
77 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
79 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
85 $dom = new DOMDocument();
86 $dom->loadXML( $xml );
87 $root = $dom->documentElement
;
89 $node = new PPNode_DOM( $root->childNodes
);
98 if ( $this->memoryLimit
=== false ) {
101 $usage = memory_get_usage();
102 if ( $usage > $this->memoryLimit
* 0.9 ) {
103 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
104 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
106 return $usage <= $this->memoryLimit
* 0.8;
110 * Preprocess some wikitext and return the document tree.
111 * This is the ghost of Parser::replace_variables().
113 * @param string $text the text to parse
114 * @param $flags Integer: bitwise combination of:
115 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
116 * included. Default is to assume a direct page view.
118 * The generated DOM tree must depend only on the input text and the flags.
119 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
121 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
122 * change in the DOM tree for a given text, must be passed through the section identifier
123 * in the section edit link and thus back to extractSections().
125 * The output of this function is currently only cached in process memory, but a persistent
126 * cache may be implemented at a later date which takes further advantage of these strict
127 * dependency requirements.
129 * @throws MWException
132 function preprocessToObj( $text, $flags = 0 ) {
133 wfProfileIn( __METHOD__
);
134 global $wgMemc, $wgPreprocessorCacheThreshold;
137 $cacheable = ( $wgPreprocessorCacheThreshold !== false
138 && strlen( $text ) > $wgPreprocessorCacheThreshold );
140 wfProfileIn( __METHOD__
. '-cacheable' );
142 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
143 $cacheValue = $wgMemc->get( $cacheKey );
145 $version = substr( $cacheValue, 0, 8 );
146 if ( intval( $version ) == self
::CACHE_VERSION
) {
147 $xml = substr( $cacheValue, 8 );
149 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
153 if ( $xml === false ) {
155 wfProfileIn( __METHOD__
. '-cache-miss' );
156 $xml = $this->preprocessToXml( $text, $flags );
157 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
158 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
159 wfProfileOut( __METHOD__
. '-cache-miss' );
160 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
162 $xml = $this->preprocessToXml( $text, $flags );
167 // Fail if the number of elements exceeds acceptable limits
168 // Do not attempt to generate the DOM
169 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
170 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
171 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
173 wfProfileOut( __METHOD__
. '-cacheable' );
175 wfProfileOut( __METHOD__
);
176 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
179 wfProfileIn( __METHOD__
. '-loadXML' );
180 $dom = new DOMDocument
;
181 wfSuppressWarnings();
182 $result = $dom->loadXML( $xml );
185 // Try running the XML through UtfNormal to get rid of invalid characters
186 $xml = UtfNormal
::cleanUp( $xml );
187 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
188 $result = $dom->loadXML( $xml, 1 << 19 );
190 wfProfileOut( __METHOD__
. '-loadXML' );
192 wfProfileOut( __METHOD__
. '-cacheable' );
194 wfProfileOut( __METHOD__
);
195 throw new MWException( __METHOD__
. ' generated invalid XML' );
198 $obj = new PPNode_DOM( $dom->documentElement
);
199 wfProfileOut( __METHOD__
. '-loadXML' );
201 wfProfileOut( __METHOD__
. '-cacheable' );
203 wfProfileOut( __METHOD__
);
208 * @param $text string
212 function preprocessToXml( $text, $flags = 0 ) {
213 wfProfileIn( __METHOD__
);
226 'names' => array( 2 => null ),
232 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
234 $xmlishElements = $this->parser
->getStripList();
235 $enableOnlyinclude = false;
236 if ( $forInclusion ) {
237 $ignoredTags = array( 'includeonly', '/includeonly' );
238 $ignoredElements = array( 'noinclude' );
239 $xmlishElements[] = 'noinclude';
240 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
241 $enableOnlyinclude = true;
244 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
245 $ignoredElements = array( 'includeonly' );
246 $xmlishElements[] = 'includeonly';
248 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
250 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
251 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
253 $stack = new PPDStack
;
255 $searchBase = "[{<\n"; #}
256 $revText = strrev( $text ); // For fast reverse searches
257 $lengthText = strlen( $text );
259 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
260 $accum =& $stack->getAccum(); # Current accumulator
262 $findEquals = false; # True to find equals signs in arguments
263 $findPipe = false; # True to take notice of pipe characters
265 $inHeading = false; # True if $i is inside a possible heading
266 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
267 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
268 $fakeLineStart = true; # Do a line-start run without outputting an LF character
273 if ( $findOnlyinclude ) {
274 // Ignore all input up to the next <onlyinclude>
275 $startPos = strpos( $text, '<onlyinclude>', $i );
276 if ( $startPos === false ) {
277 // Ignored section runs to the end
278 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
281 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
282 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
284 $findOnlyinclude = false;
287 if ( $fakeLineStart ) {
288 $found = 'line-start';
291 # Find next opening brace, closing brace or pipe
292 $search = $searchBase;
293 if ( $stack->top
=== false ) {
294 $currentClosing = '';
296 $currentClosing = $stack->top
->close
;
297 $search .= $currentClosing;
303 // First equals will be for the template
307 # Output literal section, advance input counter
308 $literalLength = strcspn( $text, $search, $i );
309 if ( $literalLength > 0 ) {
310 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
311 $i +
= $literalLength;
313 if ( $i >= $lengthText ) {
314 if ( $currentClosing == "\n" ) {
315 // Do a past-the-end run to finish off the heading
323 $curChar = $text[$i];
324 if ( $curChar == '|' ) {
326 } elseif ( $curChar == '=' ) {
328 } elseif ( $curChar == '<' ) {
330 } elseif ( $curChar == "\n" ) {
334 $found = 'line-start';
336 } elseif ( $curChar == $currentClosing ) {
338 } elseif ( isset( $rules[$curChar] ) ) {
340 $rule = $rules[$curChar];
342 # Some versions of PHP have a strcspn which stops on null characters
343 # Ignore and continue
350 if ( $found == 'angle' ) {
352 // Handle </onlyinclude>
353 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
354 $findOnlyinclude = true;
358 // Determine element name
359 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
360 // Element name missing or not listed
366 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
367 // To avoid leaving blank lines, when a comment is both preceded
368 // and followed by a newline (ignoring spaces), trim leading and
369 // trailing spaces and one of the newlines.
372 $endPos = strpos( $text, '-->', $i +
4 );
373 if ( $endPos === false ) {
374 // Unclosed comment in input, runs to end
375 $inner = substr( $text, $i );
376 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
379 // Search backwards for leading whitespace
380 $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 );
384 // Eat the line if possible
385 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
386 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
387 // it's a possible beneficial b/c break.
388 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
389 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
391 $startPos = $wsStart;
392 $endPos = $wsEnd +
1;
393 // Remove leading whitespace from the end of the accumulator
394 // Sanity check first though
395 $wsLength = $i - $wsStart;
396 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
397 $accum = substr( $accum, 0, -$wsLength );
399 // Do a line-start run next time to look for headings after the comment
400 $fakeLineStart = true;
402 // No line to eat, just take the comment itself
408 $part = $stack->top
->getCurrentPart();
409 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
410 $part->visualEnd
= $wsStart;
412 // Else comments abutting, no change in visual end
413 $part->commentEnd
= $endPos;
416 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
417 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
422 $lowerName = strtolower( $name );
423 $attrStart = $i +
strlen( $name ) +
1;
426 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
427 if ( $tagEndPos === false ) {
428 // Infinite backtrack
429 // Disable tag search to prevent worst-case O(N^2) performance
436 // Handle ignored tags
437 if ( in_array( $lowerName, $ignoredTags ) ) {
438 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
444 if ( $text[$tagEndPos-1] == '/' ) {
445 $attrEnd = $tagEndPos - 1;
450 $attrEnd = $tagEndPos;
452 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
453 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
455 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
456 $i = $matches[0][1] +
strlen( $matches[0][0] );
457 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
459 // No end tag -- let it run out to the end of the text.
460 $inner = substr( $text, $tagEndPos +
1 );
465 // <includeonly> and <noinclude> just become <ignore> tags
466 if ( in_array( $lowerName, $ignoredElements ) ) {
467 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
473 if ( $attrEnd <= $attrStart ) {
476 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
478 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
479 // Note that the attr element contains the whitespace between name and attribute,
480 // this is necessary for precise reconstruction during pre-save transform.
481 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
482 if ( $inner !== null ) {
483 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
485 $accum .= $close . '</ext>';
486 } elseif ( $found == 'line-start' ) {
487 // Is this the start of a heading?
488 // Line break belongs before the heading element in any case
489 if ( $fakeLineStart ) {
490 $fakeLineStart = false;
496 $count = strspn( $text, '=', $i, 6 );
497 if ( $count == 1 && $findEquals ) {
498 // DWIM: This looks kind of like a name/value separator
499 // Let's let the equals handler have it and break the potential heading
500 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
501 } elseif ( $count > 0 ) {
505 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
508 $stack->push( $piece );
509 $accum =& $stack->getAccum();
510 $flags = $stack->getFlags();
514 } elseif ( $found == 'line-end' ) {
515 $piece = $stack->top
;
516 // A heading must be open, otherwise \n wouldn't have been in the search list
517 assert( '$piece->open == "\n"' );
518 $part = $piece->getCurrentPart();
519 // Search back through the input to see if it has a proper close
520 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
521 $wsLength = strspn( $revText, " \t", $lengthText - $i );
522 $searchStart = $i - $wsLength;
523 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
524 // Comment found at line end
525 // Search for equals signs before the comment
526 $searchStart = $part->visualEnd
;
527 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
529 $count = $piece->count
;
530 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
531 if ( $equalsLength > 0 ) {
532 if ( $searchStart - $equalsLength == $piece->startPos
) {
533 // This is just a single string of equals signs on its own line
534 // Replicate the doHeadings behavior /={count}(.+)={count}/
535 // First find out how many equals signs there really are (don't stop at 6)
536 $count = $equalsLength;
540 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
543 $count = min( $equalsLength, $count );
546 // Normal match, output <h>
547 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
550 // Single equals sign on its own line, count=0
554 // No match, no <h>, just pass down the inner text
559 $accum =& $stack->getAccum();
560 $flags = $stack->getFlags();
563 // Append the result to the enclosing accumulator
565 // Note that we do NOT increment the input pointer.
566 // This is because the closing linebreak could be the opening linebreak of
567 // another heading. Infinite loops are avoided because the next iteration MUST
568 // hit the heading open case above, which unconditionally increments the
570 } elseif ( $found == 'open' ) {
571 # count opening brace characters
572 $count = strspn( $text, $curChar, $i );
574 # we need to add to stack only if opening brace count is enough for one of the rules
575 if ( $count >= $rule['min'] ) {
576 # Add it to the stack
579 'close' => $rule['end'],
581 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
584 $stack->push( $piece );
585 $accum =& $stack->getAccum();
586 $flags = $stack->getFlags();
589 # Add literal brace(s)
590 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
593 } elseif ( $found == 'close' ) {
594 $piece = $stack->top
;
595 # lets check if there are enough characters for closing brace
596 $maxCount = $piece->count
;
597 $count = strspn( $text, $curChar, $i, $maxCount );
599 # check for maximum matching characters (if there are 5 closing
600 # characters, we will probably need only 3 - depending on the rules)
601 $rule = $rules[$piece->open
];
602 if ( $count > $rule['max'] ) {
603 # The specified maximum exists in the callback array, unless the caller
605 $matchingCount = $rule['max'];
607 # Count is less than the maximum
608 # Skip any gaps in the callback array to find the true largest match
609 # Need to use array_key_exists not isset because the callback can be null
610 $matchingCount = $count;
611 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
616 if ( $matchingCount <= 0 ) {
617 # No matching element found in callback array
618 # Output a literal closing brace and continue
619 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
623 $name = $rule['names'][$matchingCount];
624 if ( $name === null ) {
625 // No element, just literal text
626 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
629 # Note: $parts is already XML, does not need to be encoded further
630 $parts = $piece->parts
;
631 $title = $parts[0]->out
;
634 # The invocation is at the start of the line if lineStart is set in
635 # the stack, and all opening brackets are used up.
636 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
637 $attr = ' lineStart="1"';
642 $element = "<$name$attr>";
643 $element .= "<title>$title</title>";
645 foreach ( $parts as $part ) {
646 if ( isset( $part->eqpos
) ) {
647 $argName = substr( $part->out
, 0, $part->eqpos
);
648 $argValue = substr( $part->out
, $part->eqpos +
1 );
649 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
651 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
655 $element .= "</$name>";
658 # Advance input pointer
659 $i +
= $matchingCount;
663 $accum =& $stack->getAccum();
665 # Re-add the old stack element if it still has unmatched opening characters remaining
666 if ( $matchingCount < $piece->count
) {
667 $piece->parts
= array( new PPDPart
);
668 $piece->count
-= $matchingCount;
669 # do we still qualify for any callback with remaining count?
670 $min = $rules[$piece->open
]['min'];
671 if ( $piece->count
>= $min ) {
672 $stack->push( $piece );
673 $accum =& $stack->getAccum();
675 $accum .= str_repeat( $piece->open
, $piece->count
);
678 $flags = $stack->getFlags();
681 # Add XML element to the enclosing accumulator
683 } elseif ( $found == 'pipe' ) {
684 $findEquals = true; // shortcut for getFlags()
686 $accum =& $stack->getAccum();
688 } elseif ( $found == 'equals' ) {
689 $findEquals = false; // shortcut for getFlags()
690 $stack->getCurrentPart()->eqpos
= strlen( $accum );
696 # Output any remaining unclosed brackets
697 foreach ( $stack->stack
as $piece ) {
698 $stack->rootAccum
.= $piece->breakSyntax();
700 $stack->rootAccum
.= '</root>';
701 $xml = $stack->rootAccum
;
703 wfProfileOut( __METHOD__
);
710 * Stack class to help Preprocessor::preprocessToObj()
714 var $stack, $rootAccum;
721 var $elementClass = 'PPDStackElement';
723 static $false = false;
725 function __construct() {
726 $this->stack
= array();
728 $this->rootAccum
= '';
729 $this->accum
=& $this->rootAccum
;
736 return count( $this->stack
);
739 function &getAccum() {
743 function getCurrentPart() {
744 if ( $this->top
=== false ) {
747 return $this->top
->getCurrentPart();
751 function push( $data ) {
752 if ( $data instanceof $this->elementClass
) {
753 $this->stack
[] = $data;
755 $class = $this->elementClass
;
756 $this->stack
[] = new $class( $data );
758 $this->top
= $this->stack
[count( $this->stack
) - 1];
759 $this->accum
=& $this->top
->getAccum();
763 if ( !count( $this->stack
) ) {
764 throw new MWException( __METHOD__
. ': no elements remaining' );
766 $temp = array_pop( $this->stack
);
768 if ( count( $this->stack
) ) {
769 $this->top
= $this->stack
[count( $this->stack
) - 1];
770 $this->accum
=& $this->top
->getAccum();
772 $this->top
= self
::$false;
773 $this->accum
=& $this->rootAccum
;
778 function addPart( $s = '' ) {
779 $this->top
->addPart( $s );
780 $this->accum
=& $this->top
->getAccum();
786 function getFlags() {
787 if ( !count( $this->stack
) ) {
789 'findEquals' => false,
791 'inHeading' => false,
794 return $this->top
->getFlags();
802 class PPDStackElement
{
803 var $open, // Opening character (\n for heading)
804 $close, // Matching closing character
805 $count, // Number of opening characters found (number of "=" for heading)
806 $parts, // Array of PPDPart objects describing pipe-separated parts.
807 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
809 var $partClass = 'PPDPart';
811 function __construct( $data = array() ) {
812 $class = $this->partClass
;
813 $this->parts
= array( new $class );
815 foreach ( $data as $name => $value ) {
816 $this->$name = $value;
820 function &getAccum() {
821 return $this->parts
[count( $this->parts
) - 1]->out
;
824 function addPart( $s = '' ) {
825 $class = $this->partClass
;
826 $this->parts
[] = new $class( $s );
829 function getCurrentPart() {
830 return $this->parts
[count( $this->parts
) - 1];
836 function getFlags() {
837 $partCount = count( $this->parts
);
838 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
840 'findPipe' => $findPipe,
841 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
842 'inHeading' => $this->open
== "\n",
847 * Get the output string that would result if the close is not found.
851 function breakSyntax( $openingCount = false ) {
852 if ( $this->open
== "\n" ) {
853 $s = $this->parts
[0]->out
;
855 if ( $openingCount === false ) {
856 $openingCount = $this->count
;
858 $s = str_repeat( $this->open
, $openingCount );
860 foreach ( $this->parts
as $part ) {
877 var $out; // Output accumulator string
879 // Optional member variables:
880 // eqpos Position of equals sign in output accumulator
881 // commentEnd Past-the-end input pointer for the last comment encountered
882 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
884 function __construct( $out = '' ) {
890 * An expansion frame, used as a context to expand the result of preprocessToObj()
893 class PPFrame_DOM
implements PPFrame
{
912 * Hashtable listing templates which are disallowed for expansion in this frame,
913 * having been encountered previously in parent frames.
918 * Recursion depth of this frame, top = 0
919 * Note that this is NOT the same as expansion depth in expand()
924 * Construct a new preprocessor frame.
925 * @param $preprocessor Preprocessor The parent preprocessor
927 function __construct( $preprocessor ) {
928 $this->preprocessor
= $preprocessor;
929 $this->parser
= $preprocessor->parser
;
930 $this->title
= $this->parser
->mTitle
;
931 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
932 $this->loopCheckHash
= array();
937 * Create a new child frame
938 * $args is optionally a multi-root PPNode or array containing the template arguments
940 * @return PPTemplateFrame_DOM
942 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
943 $namedArgs = array();
944 $numberedArgs = array();
945 if ( $title === false ) {
946 $title = $this->title
;
948 if ( $args !== false ) {
950 if ( $args instanceof PPNode
) {
953 foreach ( $args as $arg ) {
954 if ( $arg instanceof PPNode
) {
958 $xpath = new DOMXPath( $arg->ownerDocument
);
961 $nameNodes = $xpath->query( 'name', $arg );
962 $value = $xpath->query( 'value', $arg );
963 if ( $nameNodes->item( 0 )->hasAttributes() ) {
964 // Numbered parameter
965 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
966 $index = $index - $indexOffset;
967 $numberedArgs[$index] = $value->item( 0 );
968 unset( $namedArgs[$index] );
971 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
972 $namedArgs[$name] = $value->item( 0 );
973 unset( $numberedArgs[$name] );
977 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
981 * @throws MWException
986 function expand( $root, $flags = 0 ) {
987 static $expansionDepth = 0;
988 if ( is_string( $root ) ) {
992 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
993 $this->parser
->limitationWarn( 'node-count-exceeded',
994 $this->parser
->mPPNodeCount
,
995 $this->parser
->mOptions
->getMaxPPNodeCount()
997 return '<span class="error">Node-count limit exceeded</span>';
1000 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1001 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1003 $this->parser
->mOptions
->getMaxPPExpandDepth()
1005 return '<span class="error">Expansion depth limit exceeded</span>';
1007 wfProfileIn( __METHOD__
);
1009 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1010 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1013 if ( $root instanceof PPNode_DOM
) {
1014 $root = $root->node
;
1016 if ( $root instanceof DOMDocument
) {
1017 $root = $root->documentElement
;
1020 $outStack = array( '', '' );
1021 $iteratorStack = array( false, $root );
1022 $indexStack = array( 0, 0 );
1024 while ( count( $iteratorStack ) > 1 ) {
1025 $level = count( $outStack ) - 1;
1026 $iteratorNode =& $iteratorStack[$level];
1027 $out =& $outStack[$level];
1028 $index =& $indexStack[$level];
1030 if ( $iteratorNode instanceof PPNode_DOM
) {
1031 $iteratorNode = $iteratorNode->node
;
1034 if ( is_array( $iteratorNode ) ) {
1035 if ( $index >= count( $iteratorNode ) ) {
1036 // All done with this iterator
1037 $iteratorStack[$level] = false;
1038 $contextNode = false;
1040 $contextNode = $iteratorNode[$index];
1043 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1044 if ( $index >= $iteratorNode->length
) {
1045 // All done with this iterator
1046 $iteratorStack[$level] = false;
1047 $contextNode = false;
1049 $contextNode = $iteratorNode->item( $index );
1053 // Copy to $contextNode and then delete from iterator stack,
1054 // because this is not an iterator but we do have to execute it once
1055 $contextNode = $iteratorStack[$level];
1056 $iteratorStack[$level] = false;
1059 if ( $contextNode instanceof PPNode_DOM
) {
1060 $contextNode = $contextNode->node
;
1063 $newIterator = false;
1065 if ( $contextNode === false ) {
1067 } elseif ( is_string( $contextNode ) ) {
1068 $out .= $contextNode;
1069 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1070 $newIterator = $contextNode;
1071 } elseif ( $contextNode instanceof DOMNode
) {
1072 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1073 $out .= $contextNode->nodeValue
;
1074 } elseif ( $contextNode->nodeName
== 'template' ) {
1075 # Double-brace expansion
1076 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1077 $titles = $xpath->query( 'title', $contextNode );
1078 $title = $titles->item( 0 );
1079 $parts = $xpath->query( 'part', $contextNode );
1080 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1081 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1083 $lineStart = $contextNode->getAttribute( 'lineStart' );
1085 'title' => new PPNode_DOM( $title ),
1086 'parts' => new PPNode_DOM( $parts ),
1087 'lineStart' => $lineStart );
1088 $ret = $this->parser
->braceSubstitution( $params, $this );
1089 if ( isset( $ret['object'] ) ) {
1090 $newIterator = $ret['object'];
1092 $out .= $ret['text'];
1095 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1096 # Triple-brace expansion
1097 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1098 $titles = $xpath->query( 'title', $contextNode );
1099 $title = $titles->item( 0 );
1100 $parts = $xpath->query( 'part', $contextNode );
1101 if ( $flags & PPFrame
::NO_ARGS
) {
1102 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1105 'title' => new PPNode_DOM( $title ),
1106 'parts' => new PPNode_DOM( $parts ) );
1107 $ret = $this->parser
->argSubstitution( $params, $this );
1108 if ( isset( $ret['object'] ) ) {
1109 $newIterator = $ret['object'];
1111 $out .= $ret['text'];
1114 } elseif ( $contextNode->nodeName
== 'comment' ) {
1115 # HTML-style comment
1116 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1117 if ( $this->parser
->ot
['html']
1118 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1119 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1123 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1124 # Not in RECOVER_COMMENTS mode (extractSections) though
1125 elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1126 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1128 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1130 $out .= $contextNode->textContent
;
1132 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1133 # Output suppression used by <includeonly> etc.
1134 # OT_WIKI will only respect <ignore> in substed templates.
1135 # The other output types respect it unless NO_IGNORE is set.
1136 # extractSections() sets NO_IGNORE and so never respects it.
1137 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1138 $out .= $contextNode->textContent
;
1142 } elseif ( $contextNode->nodeName
== 'ext' ) {
1144 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1145 $names = $xpath->query( 'name', $contextNode );
1146 $attrs = $xpath->query( 'attr', $contextNode );
1147 $inners = $xpath->query( 'inner', $contextNode );
1148 $closes = $xpath->query( 'close', $contextNode );
1150 'name' => new PPNode_DOM( $names->item( 0 ) ),
1151 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1152 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1153 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1155 $out .= $this->parser
->extensionSubstitution( $params, $this );
1156 } elseif ( $contextNode->nodeName
== 'h' ) {
1158 $s = $this->expand( $contextNode->childNodes
, $flags );
1160 # Insert a heading marker only for <h> children of <root>
1161 # This is to stop extractSections from going over multiple tree levels
1162 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1163 # Insert heading index marker
1164 $headingIndex = $contextNode->getAttribute( 'i' );
1165 $titleText = $this->title
->getPrefixedDBkey();
1166 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1167 $serial = count( $this->parser
->mHeadings
) - 1;
1168 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1169 $count = $contextNode->getAttribute( 'level' );
1170 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1171 $this->parser
->mStripState
->addGeneral( $marker, '' );
1175 # Generic recursive expansion
1176 $newIterator = $contextNode->childNodes
;
1179 wfProfileOut( __METHOD__
);
1180 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1183 if ( $newIterator !== false ) {
1184 if ( $newIterator instanceof PPNode_DOM
) {
1185 $newIterator = $newIterator->node
;
1188 $iteratorStack[] = $newIterator;
1190 } elseif ( $iteratorStack[$level] === false ) {
1191 // Return accumulated value to parent
1192 // With tail recursion
1193 while ( $iteratorStack[$level] === false && $level > 0 ) {
1194 $outStack[$level - 1] .= $out;
1195 array_pop( $outStack );
1196 array_pop( $iteratorStack );
1197 array_pop( $indexStack );
1203 wfProfileOut( __METHOD__
);
1204 return $outStack[0];
1212 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1213 $args = array_slice( func_get_args(), 2 );
1217 foreach ( $args as $root ) {
1218 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1219 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1220 $root = array( $root );
1222 foreach ( $root as $node ) {
1228 $s .= $this->expand( $node, $flags );
1235 * Implode with no flags specified
1236 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1240 function implode( $sep /*, ... */ ) {
1241 $args = array_slice( func_get_args(), 1 );
1245 foreach ( $args as $root ) {
1246 if ( $root instanceof PPNode_DOM
) {
1247 $root = $root->node
;
1249 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1250 $root = array( $root );
1252 foreach ( $root as $node ) {
1258 $s .= $this->expand( $node );
1265 * Makes an object that, when expand()ed, will be the same as one obtained
1270 function virtualImplode( $sep /*, ... */ ) {
1271 $args = array_slice( func_get_args(), 1 );
1275 foreach ( $args as $root ) {
1276 if ( $root instanceof PPNode_DOM
) {
1277 $root = $root->node
;
1279 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1280 $root = array( $root );
1282 foreach ( $root as $node ) {
1295 * Virtual implode with brackets
1298 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1299 $args = array_slice( func_get_args(), 3 );
1300 $out = array( $start );
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 function __toString() {
1327 function getPDBK( $level = false ) {
1328 if ( $level === false ) {
1329 return $this->title
->getPrefixedDBkey();
1331 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1338 function getArguments() {
1345 function getNumberedArguments() {
1352 function getNamedArguments() {
1357 * Returns true if there are no arguments in this frame
1361 function isEmpty() {
1365 function getArgument( $name ) {
1370 * Returns true if the infinite loop check is OK, false if a loop is detected
1374 function loopCheck( $title ) {
1375 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1379 * Return true if the frame is a template frame
1383 function isTemplate() {
1388 * Get a title of frame
1392 function getTitle() {
1393 return $this->title
;
1398 * Expansion frame with template arguments
1401 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1402 var $numberedArgs, $namedArgs;
1408 var $numberedExpansionCache, $namedExpansionCache;
1411 * @param $preprocessor
1412 * @param $parent PPFrame_DOM
1413 * @param $numberedArgs array
1414 * @param $namedArgs array
1415 * @param $title Title
1417 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1418 parent
::__construct( $preprocessor );
1420 $this->parent
= $parent;
1421 $this->numberedArgs
= $numberedArgs;
1422 $this->namedArgs
= $namedArgs;
1423 $this->title
= $title;
1424 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1425 $this->titleCache
= $parent->titleCache
;
1426 $this->titleCache
[] = $pdbk;
1427 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1428 if ( $pdbk !== false ) {
1429 $this->loopCheckHash
[$pdbk] = true;
1431 $this->depth
= $parent->depth +
1;
1432 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1435 function __toString() {
1438 $args = $this->numberedArgs +
$this->namedArgs
;
1439 foreach ( $args as $name => $value ) {
1445 $s .= "\"$name\":\"" .
1446 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1453 * Returns true if there are no arguments in this frame
1457 function isEmpty() {
1458 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1461 function getArguments() {
1462 $arguments = array();
1463 foreach ( array_merge(
1464 array_keys( $this->numberedArgs
),
1465 array_keys( $this->namedArgs
) ) as $key ) {
1466 $arguments[$key] = $this->getArgument( $key );
1471 function getNumberedArguments() {
1472 $arguments = array();
1473 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1474 $arguments[$key] = $this->getArgument( $key );
1479 function getNamedArguments() {
1480 $arguments = array();
1481 foreach ( array_keys( $this->namedArgs
) as $key ) {
1482 $arguments[$key] = $this->getArgument( $key );
1487 function getNumberedArgument( $index ) {
1488 if ( !isset( $this->numberedArgs
[$index] ) ) {
1491 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1492 # No trimming for unnamed arguments
1493 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1495 return $this->numberedExpansionCache
[$index];
1498 function getNamedArgument( $name ) {
1499 if ( !isset( $this->namedArgs
[$name] ) ) {
1502 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1503 # Trim named arguments post-expand, for backwards compatibility
1504 $this->namedExpansionCache
[$name] = trim(
1505 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1507 return $this->namedExpansionCache
[$name];
1510 function getArgument( $name ) {
1511 $text = $this->getNumberedArgument( $name );
1512 if ( $text === false ) {
1513 $text = $this->getNamedArgument( $name );
1519 * Return true if the frame is a template frame
1523 function isTemplate() {
1529 * Expansion frame with custom arguments
1532 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1535 function __construct( $preprocessor, $args ) {
1536 parent
::__construct( $preprocessor );
1537 $this->args
= $args;
1540 function __toString() {
1543 foreach ( $this->args
as $name => $value ) {
1549 $s .= "\"$name\":\"" .
1550 str_replace( '"', '\\"', $value->__toString() ) . '"';
1559 function isEmpty() {
1560 return !count( $this->args
);
1563 function getArgument( $index ) {
1564 if ( !isset( $this->args
[$index] ) ) {
1567 return $this->args
[$index];
1570 function getArguments() {
1578 class PPNode_DOM
implements PPNode
{
1586 function __construct( $node, $xpath = false ) {
1587 $this->node
= $node;
1593 function getXPath() {
1594 if ( $this->xpath
=== null ) {
1595 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1597 return $this->xpath
;
1600 function __toString() {
1601 if ( $this->node
instanceof DOMNodeList
) {
1603 foreach ( $this->node
as $node ) {
1604 $s .= $node->ownerDocument
->saveXML( $node );
1607 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1613 * @return bool|PPNode_DOM
1615 function getChildren() {
1616 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1620 * @return bool|PPNode_DOM
1622 function getFirstChild() {
1623 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1627 * @return bool|PPNode_DOM
1629 function getNextSibling() {
1630 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1636 * @return bool|PPNode_DOM
1638 function getChildrenOfType( $type ) {
1639 return new self( $this->getXPath()->query( $type, $this->node
) );
1645 function getLength() {
1646 if ( $this->node
instanceof DOMNodeList
) {
1647 return $this->node
->length
;
1655 * @return bool|PPNode_DOM
1657 function item( $i ) {
1658 $item = $this->node
->item( $i );
1659 return $item ?
new self( $item ) : false;
1665 function getName() {
1666 if ( $this->node
instanceof DOMNodeList
) {
1669 return $this->node
->nodeName
;
1674 * Split a "<part>" node into an associative array containing:
1675 * - name PPNode name
1676 * - index String index
1677 * - value PPNode value
1679 * @throws MWException
1682 function splitArg() {
1683 $xpath = $this->getXPath();
1684 $names = $xpath->query( 'name', $this->node
);
1685 $values = $xpath->query( 'value', $this->node
);
1686 if ( !$names->length ||
!$values->length
) {
1687 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1689 $name = $names->item( 0 );
1690 $index = $name->getAttribute( 'index' );
1692 'name' => new self( $name ),
1694 'value' => new self( $values->item( 0 ) ) );
1698 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1699 * All values in the resulting array are PPNodes. Inner and close are optional.
1701 * @throws MWException
1704 function splitExt() {
1705 $xpath = $this->getXPath();
1706 $names = $xpath->query( 'name', $this->node
);
1707 $attrs = $xpath->query( 'attr', $this->node
);
1708 $inners = $xpath->query( 'inner', $this->node
);
1709 $closes = $xpath->query( 'close', $this->node
);
1710 if ( !$names->length ||
!$attrs->length
) {
1711 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1714 'name' => new self( $names->item( 0 ) ),
1715 'attr' => new self( $attrs->item( 0 ) ) );
1716 if ( $inners->length
) {
1717 $parts['inner'] = new self( $inners->item( 0 ) );
1719 if ( $closes->length
) {
1720 $parts['close'] = new self( $closes->item( 0 ) );
1726 * Split a "<h>" node
1727 * @throws MWException
1730 function splitHeading() {
1731 if ( $this->getName() !== 'h' ) {
1732 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1735 'i' => $this->node
->getAttribute( 'i' ),
1736 'level' => $this->node
->getAttribute( 'level' ),
1737 'contents' => $this->getChildren()