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)" );
152 if ( $xml === false ) {
154 wfProfileIn( __METHOD__
. '-cache-miss' );
155 $xml = $this->preprocessToXml( $text, $flags );
156 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
157 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
158 wfProfileOut( __METHOD__
. '-cache-miss' );
159 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
161 $xml = $this->preprocessToXml( $text, $flags );
166 // Fail if the number of elements exceeds acceptable limits
167 // Do not attempt to generate the DOM
168 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
169 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
170 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
172 wfProfileOut( __METHOD__
. '-cacheable' );
174 wfProfileOut( __METHOD__
);
175 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
178 wfProfileIn( __METHOD__
. '-loadXML' );
179 $dom = new DOMDocument
;
180 wfSuppressWarnings();
181 $result = $dom->loadXML( $xml );
184 // Try running the XML through UtfNormal to get rid of invalid characters
185 $xml = UtfNormal
::cleanUp( $xml );
186 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
187 $result = $dom->loadXML( $xml, 1 << 19 );
189 wfProfileOut( __METHOD__
. '-loadXML' );
191 wfProfileOut( __METHOD__
. '-cacheable' );
193 wfProfileOut( __METHOD__
);
194 throw new MWException( __METHOD__
. ' generated invalid XML' );
197 $obj = new PPNode_DOM( $dom->documentElement
);
198 wfProfileOut( __METHOD__
. '-loadXML' );
200 wfProfileOut( __METHOD__
. '-cacheable' );
202 wfProfileOut( __METHOD__
);
207 * @param $text string
211 function preprocessToXml( $text, $flags = 0 ) {
212 wfProfileIn( __METHOD__
);
225 'names' => array( 2 => null ),
231 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
233 $xmlishElements = $this->parser
->getStripList();
234 $enableOnlyinclude = false;
235 if ( $forInclusion ) {
236 $ignoredTags = array( 'includeonly', '/includeonly' );
237 $ignoredElements = array( 'noinclude' );
238 $xmlishElements[] = 'noinclude';
239 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
240 $enableOnlyinclude = true;
243 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
244 $ignoredElements = array( 'includeonly' );
245 $xmlishElements[] = 'includeonly';
247 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
249 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
250 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
252 $stack = new PPDStack
;
254 $searchBase = "[{<\n"; #}
255 $revText = strrev( $text ); // For fast reverse searches
256 $lengthText = strlen( $text );
258 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
259 $accum =& $stack->getAccum(); # Current accumulator
261 $findEquals = false; # True to find equals signs in arguments
262 $findPipe = false; # True to take notice of pipe characters
264 $inHeading = false; # True if $i is inside a possible heading
265 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
266 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
267 $fakeLineStart = true; # Do a line-start run without outputting an LF character
272 if ( $findOnlyinclude ) {
273 // Ignore all input up to the next <onlyinclude>
274 $startPos = strpos( $text, '<onlyinclude>', $i );
275 if ( $startPos === false ) {
276 // Ignored section runs to the end
277 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
280 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
281 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
283 $findOnlyinclude = false;
286 if ( $fakeLineStart ) {
287 $found = 'line-start';
290 # Find next opening brace, closing brace or pipe
291 $search = $searchBase;
292 if ( $stack->top
=== false ) {
293 $currentClosing = '';
295 $currentClosing = $stack->top
->close
;
296 $search .= $currentClosing;
302 // First equals will be for the template
306 # Output literal section, advance input counter
307 $literalLength = strcspn( $text, $search, $i );
308 if ( $literalLength > 0 ) {
309 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
310 $i +
= $literalLength;
312 if ( $i >= $lengthText ) {
313 if ( $currentClosing == "\n" ) {
314 // Do a past-the-end run to finish off the heading
322 $curChar = $text[$i];
323 if ( $curChar == '|' ) {
325 } elseif ( $curChar == '=' ) {
327 } elseif ( $curChar == '<' ) {
329 } elseif ( $curChar == "\n" ) {
333 $found = 'line-start';
335 } elseif ( $curChar == $currentClosing ) {
337 } elseif ( isset( $rules[$curChar] ) ) {
339 $rule = $rules[$curChar];
341 # Some versions of PHP have a strcspn which stops on null characters
342 # Ignore and continue
349 if ( $found == 'angle' ) {
351 // Handle </onlyinclude>
352 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
353 $findOnlyinclude = true;
357 // Determine element name
358 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
359 // Element name missing or not listed
365 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
366 // To avoid leaving blank lines, when a comment is both preceded
367 // and followed by a newline (ignoring spaces), trim leading and
368 // trailing spaces and one of the newlines.
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;
380 // Search forwards for trailing whitespace
381 // $wsEnd will be the position of the last space (or the '>' if there's none)
382 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
383 // Eat the line if possible
384 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
385 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
386 // it's a possible beneficial b/c break.
387 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
388 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
390 $startPos = $wsStart;
391 $endPos = $wsEnd +
1;
392 // Remove leading whitespace from the end of the accumulator
393 // Sanity check first though
394 $wsLength = $i - $wsStart;
395 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
396 $accum = substr( $accum, 0, -$wsLength );
398 // Do a line-start run next time to look for headings after the comment
399 $fakeLineStart = true;
401 // No line to eat, just take the comment itself
407 $part = $stack->top
->getCurrentPart();
408 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
409 $part->visualEnd
= $wsStart;
411 // Else comments abutting, no change in visual end
412 $part->commentEnd
= $endPos;
415 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
416 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
421 $lowerName = strtolower( $name );
422 $attrStart = $i +
strlen( $name ) +
1;
425 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
426 if ( $tagEndPos === false ) {
427 // Infinite backtrack
428 // Disable tag search to prevent worst-case O(N^2) performance
435 // Handle ignored tags
436 if ( in_array( $lowerName, $ignoredTags ) ) {
437 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
443 if ( $text[$tagEndPos - 1] == '/' ) {
444 $attrEnd = $tagEndPos - 1;
449 $attrEnd = $tagEndPos;
451 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
452 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
454 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
455 $i = $matches[0][1] +
strlen( $matches[0][0] );
456 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
458 // No end tag -- let it run out to the end of the text.
459 $inner = substr( $text, $tagEndPos +
1 );
464 // <includeonly> and <noinclude> just become <ignore> tags
465 if ( in_array( $lowerName, $ignoredElements ) ) {
466 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
472 if ( $attrEnd <= $attrStart ) {
475 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
477 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
478 // Note that the attr element contains the whitespace between name and attribute,
479 // this is necessary for precise reconstruction during pre-save transform.
480 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
481 if ( $inner !== null ) {
482 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
484 $accum .= $close . '</ext>';
485 } elseif ( $found == 'line-start' ) {
486 // Is this the start of a heading?
487 // Line break belongs before the heading element in any case
488 if ( $fakeLineStart ) {
489 $fakeLineStart = false;
495 $count = strspn( $text, '=', $i, 6 );
496 if ( $count == 1 && $findEquals ) {
497 // DWIM: This looks kind of like a name/value separator
498 // Let's let the equals handler have it and break the potential heading
499 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
500 } elseif ( $count > 0 ) {
504 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
507 $stack->push( $piece );
508 $accum =& $stack->getAccum();
509 $flags = $stack->getFlags();
513 } elseif ( $found == 'line-end' ) {
514 $piece = $stack->top
;
515 // A heading must be open, otherwise \n wouldn't have been in the search list
516 assert( '$piece->open == "\n"' );
517 $part = $piece->getCurrentPart();
518 // Search back through the input to see if it has a proper close
519 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
520 $wsLength = strspn( $revText, " \t", $lengthText - $i );
521 $searchStart = $i - $wsLength;
522 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
523 // Comment found at line end
524 // Search for equals signs before the comment
525 $searchStart = $part->visualEnd
;
526 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
528 $count = $piece->count
;
529 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
530 if ( $equalsLength > 0 ) {
531 if ( $searchStart - $equalsLength == $piece->startPos
) {
532 // This is just a single string of equals signs on its own line
533 // Replicate the doHeadings behavior /={count}(.+)={count}/
534 // First find out how many equals signs there really are (don't stop at 6)
535 $count = $equalsLength;
539 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
542 $count = min( $equalsLength, $count );
545 // Normal match, output <h>
546 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
549 // Single equals sign on its own line, count=0
553 // No match, no <h>, just pass down the inner text
558 $accum =& $stack->getAccum();
559 $flags = $stack->getFlags();
562 // Append the result to the enclosing accumulator
564 // Note that we do NOT increment the input pointer.
565 // This is because the closing linebreak could be the opening linebreak of
566 // another heading. Infinite loops are avoided because the next iteration MUST
567 // hit the heading open case above, which unconditionally increments the
569 } elseif ( $found == 'open' ) {
570 # count opening brace characters
571 $count = strspn( $text, $curChar, $i );
573 # we need to add to stack only if opening brace count is enough for one of the rules
574 if ( $count >= $rule['min'] ) {
575 # Add it to the stack
578 'close' => $rule['end'],
580 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
583 $stack->push( $piece );
584 $accum =& $stack->getAccum();
585 $flags = $stack->getFlags();
588 # Add literal brace(s)
589 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
592 } elseif ( $found == 'close' ) {
593 $piece = $stack->top
;
594 # lets check if there are enough characters for closing brace
595 $maxCount = $piece->count
;
596 $count = strspn( $text, $curChar, $i, $maxCount );
598 # check for maximum matching characters (if there are 5 closing
599 # characters, we will probably need only 3 - depending on the rules)
600 $rule = $rules[$piece->open
];
601 if ( $count > $rule['max'] ) {
602 # The specified maximum exists in the callback array, unless the caller
604 $matchingCount = $rule['max'];
606 # Count is less than the maximum
607 # Skip any gaps in the callback array to find the true largest match
608 # Need to use array_key_exists not isset because the callback can be null
609 $matchingCount = $count;
610 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
615 if ( $matchingCount <= 0 ) {
616 # No matching element found in callback array
617 # Output a literal closing brace and continue
618 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
622 $name = $rule['names'][$matchingCount];
623 if ( $name === null ) {
624 // No element, just literal text
625 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
628 # Note: $parts is already XML, does not need to be encoded further
629 $parts = $piece->parts
;
630 $title = $parts[0]->out
;
633 # The invocation is at the start of the line if lineStart is set in
634 # the stack, and all opening brackets are used up.
635 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
636 $attr = ' lineStart="1"';
641 $element = "<$name$attr>";
642 $element .= "<title>$title</title>";
644 foreach ( $parts as $part ) {
645 if ( isset( $part->eqpos
) ) {
646 $argName = substr( $part->out
, 0, $part->eqpos
);
647 $argValue = substr( $part->out
, $part->eqpos +
1 );
648 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
650 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
654 $element .= "</$name>";
657 # Advance input pointer
658 $i +
= $matchingCount;
662 $accum =& $stack->getAccum();
664 # Re-add the old stack element if it still has unmatched opening characters remaining
665 if ( $matchingCount < $piece->count
) {
666 $piece->parts
= array( new PPDPart
);
667 $piece->count
-= $matchingCount;
668 # do we still qualify for any callback with remaining count?
669 $min = $rules[$piece->open
]['min'];
670 if ( $piece->count
>= $min ) {
671 $stack->push( $piece );
672 $accum =& $stack->getAccum();
674 $accum .= str_repeat( $piece->open
, $piece->count
);
677 $flags = $stack->getFlags();
680 # Add XML element to the enclosing accumulator
682 } elseif ( $found == 'pipe' ) {
683 $findEquals = true; // shortcut for getFlags()
685 $accum =& $stack->getAccum();
687 } elseif ( $found == 'equals' ) {
688 $findEquals = false; // shortcut for getFlags()
689 $stack->getCurrentPart()->eqpos
= strlen( $accum );
695 # Output any remaining unclosed brackets
696 foreach ( $stack->stack
as $piece ) {
697 $stack->rootAccum
.= $piece->breakSyntax();
699 $stack->rootAccum
.= '</root>';
700 $xml = $stack->rootAccum
;
702 wfProfileOut( __METHOD__
);
709 * Stack class to help Preprocessor::preprocessToObj()
713 var $stack, $rootAccum;
720 var $elementClass = 'PPDStackElement';
722 static $false = false;
724 function __construct() {
725 $this->stack
= array();
727 $this->rootAccum
= '';
728 $this->accum
=& $this->rootAccum
;
735 return count( $this->stack
);
738 function &getAccum() {
742 function getCurrentPart() {
743 if ( $this->top
=== false ) {
746 return $this->top
->getCurrentPart();
750 function push( $data ) {
751 if ( $data instanceof $this->elementClass
) {
752 $this->stack
[] = $data;
754 $class = $this->elementClass
;
755 $this->stack
[] = new $class( $data );
757 $this->top
= $this->stack
[count( $this->stack
) - 1];
758 $this->accum
=& $this->top
->getAccum();
762 if ( !count( $this->stack
) ) {
763 throw new MWException( __METHOD__
. ': no elements remaining' );
765 $temp = array_pop( $this->stack
);
767 if ( count( $this->stack
) ) {
768 $this->top
= $this->stack
[count( $this->stack
) - 1];
769 $this->accum
=& $this->top
->getAccum();
771 $this->top
= self
::$false;
772 $this->accum
=& $this->rootAccum
;
777 function addPart( $s = '' ) {
778 $this->top
->addPart( $s );
779 $this->accum
=& $this->top
->getAccum();
785 function getFlags() {
786 if ( !count( $this->stack
) ) {
788 'findEquals' => false,
790 'inHeading' => false,
793 return $this->top
->getFlags();
801 class PPDStackElement
{
802 var $open, // Opening character (\n for heading)
803 $close, // Matching closing character
804 $count, // Number of opening characters found (number of "=" for heading)
805 $parts, // Array of PPDPart objects describing pipe-separated parts.
806 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
808 var $partClass = 'PPDPart';
810 function __construct( $data = array() ) {
811 $class = $this->partClass
;
812 $this->parts
= array( new $class );
814 foreach ( $data as $name => $value ) {
815 $this->$name = $value;
819 function &getAccum() {
820 return $this->parts
[count( $this->parts
) - 1]->out
;
823 function addPart( $s = '' ) {
824 $class = $this->partClass
;
825 $this->parts
[] = new $class( $s );
828 function getCurrentPart() {
829 return $this->parts
[count( $this->parts
) - 1];
835 function getFlags() {
836 $partCount = count( $this->parts
);
837 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
839 'findPipe' => $findPipe,
840 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
841 'inHeading' => $this->open
== "\n",
846 * Get the output string that would result if the close is not found.
850 function breakSyntax( $openingCount = false ) {
851 if ( $this->open
== "\n" ) {
852 $s = $this->parts
[0]->out
;
854 if ( $openingCount === false ) {
855 $openingCount = $this->count
;
857 $s = str_repeat( $this->open
, $openingCount );
859 foreach ( $this->parts
as $part ) {
876 var $out; // Output accumulator string
878 // Optional member variables:
879 // eqpos Position of equals sign in output accumulator
880 // commentEnd Past-the-end input pointer for the last comment encountered
881 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
883 function __construct( $out = '' ) {
889 * An expansion frame, used as a context to expand the result of preprocessToObj()
892 class PPFrame_DOM
implements PPFrame
{
911 * Hashtable listing templates which are disallowed for expansion in this frame,
912 * having been encountered previously in parent frames.
917 * Recursion depth of this frame, top = 0
918 * Note that this is NOT the same as expansion depth in expand()
923 * Construct a new preprocessor frame.
924 * @param $preprocessor Preprocessor The parent preprocessor
926 function __construct( $preprocessor ) {
927 $this->preprocessor
= $preprocessor;
928 $this->parser
= $preprocessor->parser
;
929 $this->title
= $this->parser
->mTitle
;
930 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
931 $this->loopCheckHash
= array();
936 * Create a new child frame
937 * $args is optionally a multi-root PPNode or array containing the template arguments
939 * @return PPTemplateFrame_DOM
941 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
942 $namedArgs = array();
943 $numberedArgs = array();
944 if ( $title === false ) {
945 $title = $this->title
;
947 if ( $args !== false ) {
949 if ( $args instanceof PPNode
) {
952 foreach ( $args as $arg ) {
953 if ( $arg instanceof PPNode
) {
957 $xpath = new DOMXPath( $arg->ownerDocument
);
960 $nameNodes = $xpath->query( 'name', $arg );
961 $value = $xpath->query( 'value', $arg );
962 if ( $nameNodes->item( 0 )->hasAttributes() ) {
963 // Numbered parameter
964 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
965 $index = $index - $indexOffset;
966 $numberedArgs[$index] = $value->item( 0 );
967 unset( $namedArgs[$index] );
970 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
971 $namedArgs[$name] = $value->item( 0 );
972 unset( $numberedArgs[$name] );
976 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
980 * @throws MWException
985 function expand( $root, $flags = 0 ) {
986 static $expansionDepth = 0;
987 if ( is_string( $root ) ) {
991 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
992 $this->parser
->limitationWarn( 'node-count-exceeded',
993 $this->parser
->mPPNodeCount
,
994 $this->parser
->mOptions
->getMaxPPNodeCount()
996 return '<span class="error">Node-count limit exceeded</span>';
999 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1000 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1002 $this->parser
->mOptions
->getMaxPPExpandDepth()
1004 return '<span class="error">Expansion depth limit exceeded</span>';
1006 wfProfileIn( __METHOD__
);
1008 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1009 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1012 if ( $root instanceof PPNode_DOM
) {
1013 $root = $root->node
;
1015 if ( $root instanceof DOMDocument
) {
1016 $root = $root->documentElement
;
1019 $outStack = array( '', '' );
1020 $iteratorStack = array( false, $root );
1021 $indexStack = array( 0, 0 );
1023 while ( count( $iteratorStack ) > 1 ) {
1024 $level = count( $outStack ) - 1;
1025 $iteratorNode =& $iteratorStack[$level];
1026 $out =& $outStack[$level];
1027 $index =& $indexStack[$level];
1029 if ( $iteratorNode instanceof PPNode_DOM
) {
1030 $iteratorNode = $iteratorNode->node
;
1033 if ( is_array( $iteratorNode ) ) {
1034 if ( $index >= count( $iteratorNode ) ) {
1035 // All done with this iterator
1036 $iteratorStack[$level] = false;
1037 $contextNode = false;
1039 $contextNode = $iteratorNode[$index];
1042 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1043 if ( $index >= $iteratorNode->length
) {
1044 // All done with this iterator
1045 $iteratorStack[$level] = false;
1046 $contextNode = false;
1048 $contextNode = $iteratorNode->item( $index );
1052 // Copy to $contextNode and then delete from iterator stack,
1053 // because this is not an iterator but we do have to execute it once
1054 $contextNode = $iteratorStack[$level];
1055 $iteratorStack[$level] = false;
1058 if ( $contextNode instanceof PPNode_DOM
) {
1059 $contextNode = $contextNode->node
;
1062 $newIterator = false;
1064 if ( $contextNode === false ) {
1066 } elseif ( is_string( $contextNode ) ) {
1067 $out .= $contextNode;
1068 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1069 $newIterator = $contextNode;
1070 } elseif ( $contextNode instanceof DOMNode
) {
1071 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1072 $out .= $contextNode->nodeValue
;
1073 } elseif ( $contextNode->nodeName
== 'template' ) {
1074 # Double-brace expansion
1075 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1076 $titles = $xpath->query( 'title', $contextNode );
1077 $title = $titles->item( 0 );
1078 $parts = $xpath->query( 'part', $contextNode );
1079 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1080 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1082 $lineStart = $contextNode->getAttribute( 'lineStart' );
1084 'title' => new PPNode_DOM( $title ),
1085 'parts' => new PPNode_DOM( $parts ),
1086 'lineStart' => $lineStart );
1087 $ret = $this->parser
->braceSubstitution( $params, $this );
1088 if ( isset( $ret['object'] ) ) {
1089 $newIterator = $ret['object'];
1091 $out .= $ret['text'];
1094 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1095 # Triple-brace expansion
1096 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1097 $titles = $xpath->query( 'title', $contextNode );
1098 $title = $titles->item( 0 );
1099 $parts = $xpath->query( 'part', $contextNode );
1100 if ( $flags & PPFrame
::NO_ARGS
) {
1101 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1104 'title' => new PPNode_DOM( $title ),
1105 'parts' => new PPNode_DOM( $parts ) );
1106 $ret = $this->parser
->argSubstitution( $params, $this );
1107 if ( isset( $ret['object'] ) ) {
1108 $newIterator = $ret['object'];
1110 $out .= $ret['text'];
1113 } elseif ( $contextNode->nodeName
== 'comment' ) {
1114 # HTML-style comment
1115 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1116 if ( $this->parser
->ot
['html']
1117 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1118 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1122 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1123 # Not in RECOVER_COMMENTS mode (extractSections) though
1124 elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1125 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1127 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1129 $out .= $contextNode->textContent
;
1131 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1132 # Output suppression used by <includeonly> etc.
1133 # OT_WIKI will only respect <ignore> in substed templates.
1134 # The other output types respect it unless NO_IGNORE is set.
1135 # extractSections() sets NO_IGNORE and so never respects it.
1136 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1137 $out .= $contextNode->textContent
;
1141 } elseif ( $contextNode->nodeName
== 'ext' ) {
1143 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1144 $names = $xpath->query( 'name', $contextNode );
1145 $attrs = $xpath->query( 'attr', $contextNode );
1146 $inners = $xpath->query( 'inner', $contextNode );
1147 $closes = $xpath->query( 'close', $contextNode );
1149 'name' => new PPNode_DOM( $names->item( 0 ) ),
1150 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1151 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1152 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1154 $out .= $this->parser
->extensionSubstitution( $params, $this );
1155 } elseif ( $contextNode->nodeName
== 'h' ) {
1157 $s = $this->expand( $contextNode->childNodes
, $flags );
1159 # Insert a heading marker only for <h> children of <root>
1160 # This is to stop extractSections from going over multiple tree levels
1161 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1162 # Insert heading index marker
1163 $headingIndex = $contextNode->getAttribute( 'i' );
1164 $titleText = $this->title
->getPrefixedDBkey();
1165 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1166 $serial = count( $this->parser
->mHeadings
) - 1;
1167 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1168 $count = $contextNode->getAttribute( 'level' );
1169 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1170 $this->parser
->mStripState
->addGeneral( $marker, '' );
1174 # Generic recursive expansion
1175 $newIterator = $contextNode->childNodes
;
1178 wfProfileOut( __METHOD__
);
1179 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1182 if ( $newIterator !== false ) {
1183 if ( $newIterator instanceof PPNode_DOM
) {
1184 $newIterator = $newIterator->node
;
1187 $iteratorStack[] = $newIterator;
1189 } elseif ( $iteratorStack[$level] === false ) {
1190 // Return accumulated value to parent
1191 // With tail recursion
1192 while ( $iteratorStack[$level] === false && $level > 0 ) {
1193 $outStack[$level - 1] .= $out;
1194 array_pop( $outStack );
1195 array_pop( $iteratorStack );
1196 array_pop( $indexStack );
1202 wfProfileOut( __METHOD__
);
1203 return $outStack[0];
1211 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1212 $args = array_slice( func_get_args(), 2 );
1216 foreach ( $args as $root ) {
1217 if ( $root instanceof PPNode_DOM
) {
1218 $root = $root->node
;
1220 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1221 $root = array( $root );
1223 foreach ( $root as $node ) {
1229 $s .= $this->expand( $node, $flags );
1236 * Implode with no flags specified
1237 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1241 function implode( $sep /*, ... */ ) {
1242 $args = array_slice( func_get_args(), 1 );
1246 foreach ( $args as $root ) {
1247 if ( $root instanceof PPNode_DOM
) {
1248 $root = $root->node
;
1250 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1251 $root = array( $root );
1253 foreach ( $root as $node ) {
1259 $s .= $this->expand( $node );
1266 * Makes an object that, when expand()ed, will be the same as one obtained
1271 function virtualImplode( $sep /*, ... */ ) {
1272 $args = array_slice( func_get_args(), 1 );
1276 foreach ( $args as $root ) {
1277 if ( $root instanceof PPNode_DOM
) {
1278 $root = $root->node
;
1280 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1281 $root = array( $root );
1283 foreach ( $root as $node ) {
1296 * Virtual implode with brackets
1299 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1300 $args = array_slice( func_get_args(), 3 );
1301 $out = array( $start );
1304 foreach ( $args as $root ) {
1305 if ( $root instanceof PPNode_DOM
) {
1306 $root = $root->node
;
1308 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1309 $root = array( $root );
1311 foreach ( $root as $node ) {
1324 function __toString() {
1328 function getPDBK( $level = false ) {
1329 if ( $level === false ) {
1330 return $this->title
->getPrefixedDBkey();
1332 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1339 function getArguments() {
1346 function getNumberedArguments() {
1353 function getNamedArguments() {
1358 * Returns true if there are no arguments in this frame
1362 function isEmpty() {
1366 function getArgument( $name ) {
1371 * Returns true if the infinite loop check is OK, false if a loop is detected
1375 function loopCheck( $title ) {
1376 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1380 * Return true if the frame is a template frame
1384 function isTemplate() {
1389 * Get a title of frame
1393 function getTitle() {
1394 return $this->title
;
1399 * Expansion frame with template arguments
1402 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1403 var $numberedArgs, $namedArgs;
1409 var $numberedExpansionCache, $namedExpansionCache;
1412 * @param $preprocessor
1413 * @param $parent PPFrame_DOM
1414 * @param $numberedArgs array
1415 * @param $namedArgs array
1416 * @param $title Title
1418 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1419 parent
::__construct( $preprocessor );
1421 $this->parent
= $parent;
1422 $this->numberedArgs
= $numberedArgs;
1423 $this->namedArgs
= $namedArgs;
1424 $this->title
= $title;
1425 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1426 $this->titleCache
= $parent->titleCache
;
1427 $this->titleCache
[] = $pdbk;
1428 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1429 if ( $pdbk !== false ) {
1430 $this->loopCheckHash
[$pdbk] = true;
1432 $this->depth
= $parent->depth +
1;
1433 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1436 function __toString() {
1439 $args = $this->numberedArgs +
$this->namedArgs
;
1440 foreach ( $args as $name => $value ) {
1446 $s .= "\"$name\":\"" .
1447 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1454 * Returns true if there are no arguments in this frame
1458 function isEmpty() {
1459 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1462 function getArguments() {
1463 $arguments = array();
1464 foreach ( array_merge(
1465 array_keys( $this->numberedArgs
),
1466 array_keys( $this->namedArgs
) ) as $key ) {
1467 $arguments[$key] = $this->getArgument( $key );
1472 function getNumberedArguments() {
1473 $arguments = array();
1474 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1475 $arguments[$key] = $this->getArgument( $key );
1480 function getNamedArguments() {
1481 $arguments = array();
1482 foreach ( array_keys( $this->namedArgs
) as $key ) {
1483 $arguments[$key] = $this->getArgument( $key );
1488 function getNumberedArgument( $index ) {
1489 if ( !isset( $this->numberedArgs
[$index] ) ) {
1492 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1493 # No trimming for unnamed arguments
1494 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1496 return $this->numberedExpansionCache
[$index];
1499 function getNamedArgument( $name ) {
1500 if ( !isset( $this->namedArgs
[$name] ) ) {
1503 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1504 # Trim named arguments post-expand, for backwards compatibility
1505 $this->namedExpansionCache
[$name] = trim(
1506 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1508 return $this->namedExpansionCache
[$name];
1511 function getArgument( $name ) {
1512 $text = $this->getNumberedArgument( $name );
1513 if ( $text === false ) {
1514 $text = $this->getNamedArgument( $name );
1520 * Return true if the frame is a template frame
1524 function isTemplate() {
1530 * Expansion frame with custom arguments
1533 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1536 function __construct( $preprocessor, $args ) {
1537 parent
::__construct( $preprocessor );
1538 $this->args
= $args;
1541 function __toString() {
1544 foreach ( $this->args
as $name => $value ) {
1550 $s .= "\"$name\":\"" .
1551 str_replace( '"', '\\"', $value->__toString() ) . '"';
1560 function isEmpty() {
1561 return !count( $this->args
);
1564 function getArgument( $index ) {
1565 if ( !isset( $this->args
[$index] ) ) {
1568 return $this->args
[$index];
1571 function getArguments() {
1579 class PPNode_DOM
implements PPNode
{
1587 function __construct( $node, $xpath = false ) {
1588 $this->node
= $node;
1594 function getXPath() {
1595 if ( $this->xpath
=== null ) {
1596 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1598 return $this->xpath
;
1601 function __toString() {
1602 if ( $this->node
instanceof DOMNodeList
) {
1604 foreach ( $this->node
as $node ) {
1605 $s .= $node->ownerDocument
->saveXML( $node );
1608 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1614 * @return bool|PPNode_DOM
1616 function getChildren() {
1617 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1621 * @return bool|PPNode_DOM
1623 function getFirstChild() {
1624 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1628 * @return bool|PPNode_DOM
1630 function getNextSibling() {
1631 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1637 * @return bool|PPNode_DOM
1639 function getChildrenOfType( $type ) {
1640 return new self( $this->getXPath()->query( $type, $this->node
) );
1646 function getLength() {
1647 if ( $this->node
instanceof DOMNodeList
) {
1648 return $this->node
->length
;
1656 * @return bool|PPNode_DOM
1658 function item( $i ) {
1659 $item = $this->node
->item( $i );
1660 return $item ?
new self( $item ) : false;
1666 function getName() {
1667 if ( $this->node
instanceof DOMNodeList
) {
1670 return $this->node
->nodeName
;
1675 * Split a "<part>" node into an associative array containing:
1676 * - name PPNode name
1677 * - index String index
1678 * - value PPNode value
1680 * @throws MWException
1683 function splitArg() {
1684 $xpath = $this->getXPath();
1685 $names = $xpath->query( 'name', $this->node
);
1686 $values = $xpath->query( 'value', $this->node
);
1687 if ( !$names->length ||
!$values->length
) {
1688 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1690 $name = $names->item( 0 );
1691 $index = $name->getAttribute( 'index' );
1693 'name' => new self( $name ),
1695 'value' => new self( $values->item( 0 ) ) );
1699 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1700 * All values in the resulting array are PPNodes. Inner and close are optional.
1702 * @throws MWException
1705 function splitExt() {
1706 $xpath = $this->getXPath();
1707 $names = $xpath->query( 'name', $this->node
);
1708 $attrs = $xpath->query( 'attr', $this->node
);
1709 $inners = $xpath->query( 'inner', $this->node
);
1710 $closes = $xpath->query( 'close', $this->node
);
1711 if ( !$names->length ||
!$attrs->length
) {
1712 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1715 'name' => new self( $names->item( 0 ) ),
1716 'attr' => new self( $attrs->item( 0 ) ) );
1717 if ( $inners->length
) {
1718 $parts['inner'] = new self( $inners->item( 0 ) );
1720 if ( $closes->length
) {
1721 $parts['close'] = new self( $closes->item( 0 ) );
1727 * Split a "<h>" node
1728 * @throws MWException
1731 function splitHeading() {
1732 if ( $this->getName() !== 'h' ) {
1733 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1736 'i' => $this->node
->getAttribute( 'i' ),
1737 'level' => $this->node
->getAttribute( 'level' ),
1738 'contents' => $this->getChildren()