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] == '!--' ) {
364 // To avoid leaving blank lines, when a comment is both preceded
365 // and followed by a newline (ignoring spaces), trim leading and
366 // trailing spaces and one of the newlines.
369 $endPos = strpos( $text, '-->', $i +
4 );
370 if ( $endPos === false ) {
371 // Unclosed comment in input, runs to end
372 $inner = substr( $text, $i );
373 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
376 // Search backwards for leading whitespace
377 $wsStart = $i ?
( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
378 // Search forwards for trailing whitespace
379 // $wsEnd will be the position of the last space (or the '>' if there's none)
380 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
381 // Eat the line if possible
382 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
383 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
384 // it's a possible beneficial b/c break.
385 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
386 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
388 $startPos = $wsStart;
389 $endPos = $wsEnd +
1;
390 // Remove leading whitespace from the end of the accumulator
391 // Sanity check first though
392 $wsLength = $i - $wsStart;
393 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
394 $accum = substr( $accum, 0, -$wsLength );
396 // Do a line-start run next time to look for headings after the comment
397 $fakeLineStart = true;
399 // No line to eat, just take the comment itself
405 $part = $stack->top
->getCurrentPart();
406 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
407 $part->visualEnd
= $wsStart;
409 // Else comments abutting, no change in visual end
410 $part->commentEnd
= $endPos;
413 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
414 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
419 $lowerName = strtolower( $name );
420 $attrStart = $i +
strlen( $name ) +
1;
423 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
424 if ( $tagEndPos === false ) {
425 // Infinite backtrack
426 // Disable tag search to prevent worst-case O(N^2) performance
433 // Handle ignored tags
434 if ( in_array( $lowerName, $ignoredTags ) ) {
435 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
441 if ( $text[$tagEndPos - 1] == '/' ) {
442 $attrEnd = $tagEndPos - 1;
447 $attrEnd = $tagEndPos;
449 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
450 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
452 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
453 $i = $matches[0][1] +
strlen( $matches[0][0] );
454 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
456 // No end tag -- let it run out to the end of the text.
457 $inner = substr( $text, $tagEndPos +
1 );
462 // <includeonly> and <noinclude> just become <ignore> tags
463 if ( in_array( $lowerName, $ignoredElements ) ) {
464 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
470 if ( $attrEnd <= $attrStart ) {
473 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
475 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
476 // Note that the attr element contains the whitespace between name and attribute,
477 // this is necessary for precise reconstruction during pre-save transform.
478 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
479 if ( $inner !== null ) {
480 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
482 $accum .= $close . '</ext>';
483 } elseif ( $found == 'line-start' ) {
484 // Is this the start of a heading?
485 // Line break belongs before the heading element in any case
486 if ( $fakeLineStart ) {
487 $fakeLineStart = false;
493 $count = strspn( $text, '=', $i, 6 );
494 if ( $count == 1 && $findEquals ) {
495 // DWIM: This looks kind of like a name/value separator
496 // Let's let the equals handler have it and break the potential heading
497 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
498 } elseif ( $count > 0 ) {
502 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
505 $stack->push( $piece );
506 $accum =& $stack->getAccum();
507 $flags = $stack->getFlags();
511 } elseif ( $found == 'line-end' ) {
512 $piece = $stack->top
;
513 // A heading must be open, otherwise \n wouldn't have been in the search list
514 assert( '$piece->open == "\n"' );
515 $part = $piece->getCurrentPart();
516 // Search back through the input to see if it has a proper close
517 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
518 $wsLength = strspn( $revText, " \t", $lengthText - $i );
519 $searchStart = $i - $wsLength;
520 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
521 // Comment found at line end
522 // Search for equals signs before the comment
523 $searchStart = $part->visualEnd
;
524 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
526 $count = $piece->count
;
527 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
528 if ( $equalsLength > 0 ) {
529 if ( $searchStart - $equalsLength == $piece->startPos
) {
530 // This is just a single string of equals signs on its own line
531 // Replicate the doHeadings behavior /={count}(.+)={count}/
532 // First find out how many equals signs there really are (don't stop at 6)
533 $count = $equalsLength;
537 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
540 $count = min( $equalsLength, $count );
543 // Normal match, output <h>
544 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
547 // Single equals sign on its own line, count=0
551 // No match, no <h>, just pass down the inner text
556 $accum =& $stack->getAccum();
557 $flags = $stack->getFlags();
560 // Append the result to the enclosing accumulator
562 // Note that we do NOT increment the input pointer.
563 // This is because the closing linebreak could be the opening linebreak of
564 // another heading. Infinite loops are avoided because the next iteration MUST
565 // hit the heading open case above, which unconditionally increments the
567 } elseif ( $found == 'open' ) {
568 # count opening brace characters
569 $count = strspn( $text, $curChar, $i );
571 # we need to add to stack only if opening brace count is enough for one of the rules
572 if ( $count >= $rule['min'] ) {
573 # Add it to the stack
576 'close' => $rule['end'],
578 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
581 $stack->push( $piece );
582 $accum =& $stack->getAccum();
583 $flags = $stack->getFlags();
586 # Add literal brace(s)
587 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
590 } elseif ( $found == 'close' ) {
591 $piece = $stack->top
;
592 # lets check if there are enough characters for closing brace
593 $maxCount = $piece->count
;
594 $count = strspn( $text, $curChar, $i, $maxCount );
596 # check for maximum matching characters (if there are 5 closing
597 # characters, we will probably need only 3 - depending on the rules)
598 $rule = $rules[$piece->open
];
599 if ( $count > $rule['max'] ) {
600 # The specified maximum exists in the callback array, unless the caller
602 $matchingCount = $rule['max'];
604 # Count is less than the maximum
605 # Skip any gaps in the callback array to find the true largest match
606 # Need to use array_key_exists not isset because the callback can be null
607 $matchingCount = $count;
608 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
613 if ( $matchingCount <= 0 ) {
614 # No matching element found in callback array
615 # Output a literal closing brace and continue
616 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
620 $name = $rule['names'][$matchingCount];
621 if ( $name === null ) {
622 // No element, just literal text
623 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
626 # Note: $parts is already XML, does not need to be encoded further
627 $parts = $piece->parts
;
628 $title = $parts[0]->out
;
631 # The invocation is at the start of the line if lineStart is set in
632 # the stack, and all opening brackets are used up.
633 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
634 $attr = ' lineStart="1"';
639 $element = "<$name$attr>";
640 $element .= "<title>$title</title>";
642 foreach ( $parts as $part ) {
643 if ( isset( $part->eqpos
) ) {
644 $argName = substr( $part->out
, 0, $part->eqpos
);
645 $argValue = substr( $part->out
, $part->eqpos +
1 );
646 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
648 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
652 $element .= "</$name>";
655 # Advance input pointer
656 $i +
= $matchingCount;
660 $accum =& $stack->getAccum();
662 # Re-add the old stack element if it still has unmatched opening characters remaining
663 if ( $matchingCount < $piece->count
) {
664 $piece->parts
= array( new PPDPart
);
665 $piece->count
-= $matchingCount;
666 # do we still qualify for any callback with remaining count?
667 $min = $rules[$piece->open
]['min'];
668 if ( $piece->count
>= $min ) {
669 $stack->push( $piece );
670 $accum =& $stack->getAccum();
672 $accum .= str_repeat( $piece->open
, $piece->count
);
675 $flags = $stack->getFlags();
678 # Add XML element to the enclosing accumulator
680 } elseif ( $found == 'pipe' ) {
681 $findEquals = true; // shortcut for getFlags()
683 $accum =& $stack->getAccum();
685 } elseif ( $found == 'equals' ) {
686 $findEquals = false; // shortcut for getFlags()
687 $stack->getCurrentPart()->eqpos
= strlen( $accum );
693 # Output any remaining unclosed brackets
694 foreach ( $stack->stack
as $piece ) {
695 $stack->rootAccum
.= $piece->breakSyntax();
697 $stack->rootAccum
.= '</root>';
698 $xml = $stack->rootAccum
;
700 wfProfileOut( __METHOD__
);
707 * Stack class to help Preprocessor::preprocessToObj()
711 var $stack, $rootAccum;
718 var $elementClass = 'PPDStackElement';
720 static $false = false;
722 function __construct() {
723 $this->stack
= array();
725 $this->rootAccum
= '';
726 $this->accum
=& $this->rootAccum
;
733 return count( $this->stack
);
736 function &getAccum() {
740 function getCurrentPart() {
741 if ( $this->top
=== false ) {
744 return $this->top
->getCurrentPart();
748 function push( $data ) {
749 if ( $data instanceof $this->elementClass
) {
750 $this->stack
[] = $data;
752 $class = $this->elementClass
;
753 $this->stack
[] = new $class( $data );
755 $this->top
= $this->stack
[count( $this->stack
) - 1];
756 $this->accum
=& $this->top
->getAccum();
760 if ( !count( $this->stack
) ) {
761 throw new MWException( __METHOD__
. ': no elements remaining' );
763 $temp = array_pop( $this->stack
);
765 if ( count( $this->stack
) ) {
766 $this->top
= $this->stack
[count( $this->stack
) - 1];
767 $this->accum
=& $this->top
->getAccum();
769 $this->top
= self
::$false;
770 $this->accum
=& $this->rootAccum
;
775 function addPart( $s = '' ) {
776 $this->top
->addPart( $s );
777 $this->accum
=& $this->top
->getAccum();
783 function getFlags() {
784 if ( !count( $this->stack
) ) {
786 'findEquals' => false,
788 'inHeading' => false,
791 return $this->top
->getFlags();
799 class PPDStackElement
{
800 var $open, // Opening character (\n for heading)
801 $close, // Matching closing character
802 $count, // Number of opening characters found (number of "=" for heading)
803 $parts, // Array of PPDPart objects describing pipe-separated parts.
804 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
806 var $partClass = 'PPDPart';
808 function __construct( $data = array() ) {
809 $class = $this->partClass
;
810 $this->parts
= array( new $class );
812 foreach ( $data as $name => $value ) {
813 $this->$name = $value;
817 function &getAccum() {
818 return $this->parts
[count( $this->parts
) - 1]->out
;
821 function addPart( $s = '' ) {
822 $class = $this->partClass
;
823 $this->parts
[] = new $class( $s );
826 function getCurrentPart() {
827 return $this->parts
[count( $this->parts
) - 1];
833 function getFlags() {
834 $partCount = count( $this->parts
);
835 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
837 'findPipe' => $findPipe,
838 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
839 'inHeading' => $this->open
== "\n",
844 * Get the output string that would result if the close is not found.
848 function breakSyntax( $openingCount = false ) {
849 if ( $this->open
== "\n" ) {
850 $s = $this->parts
[0]->out
;
852 if ( $openingCount === false ) {
853 $openingCount = $this->count
;
855 $s = str_repeat( $this->open
, $openingCount );
857 foreach ( $this->parts
as $part ) {
874 var $out; // Output accumulator string
876 // Optional member variables:
877 // eqpos Position of equals sign in output accumulator
878 // commentEnd Past-the-end input pointer for the last comment encountered
879 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
881 function __construct( $out = '' ) {
887 * An expansion frame, used as a context to expand the result of preprocessToObj()
890 class PPFrame_DOM
implements PPFrame
{
909 * Hashtable listing templates which are disallowed for expansion in this frame,
910 * having been encountered previously in parent frames.
915 * Recursion depth of this frame, top = 0
916 * Note that this is NOT the same as expansion depth in expand()
921 * Construct a new preprocessor frame.
922 * @param $preprocessor Preprocessor The parent preprocessor
924 function __construct( $preprocessor ) {
925 $this->preprocessor
= $preprocessor;
926 $this->parser
= $preprocessor->parser
;
927 $this->title
= $this->parser
->mTitle
;
928 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
929 $this->loopCheckHash
= array();
934 * Create a new child frame
935 * $args is optionally a multi-root PPNode or array containing the template arguments
937 * @return PPTemplateFrame_DOM
939 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
940 $namedArgs = array();
941 $numberedArgs = array();
942 if ( $title === false ) {
943 $title = $this->title
;
945 if ( $args !== false ) {
947 if ( $args instanceof PPNode
) {
950 foreach ( $args as $arg ) {
951 if ( $arg instanceof PPNode
) {
955 $xpath = new DOMXPath( $arg->ownerDocument
);
958 $nameNodes = $xpath->query( 'name', $arg );
959 $value = $xpath->query( 'value', $arg );
960 if ( $nameNodes->item( 0 )->hasAttributes() ) {
961 // Numbered parameter
962 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
963 $index = $index - $indexOffset;
964 $numberedArgs[$index] = $value->item( 0 );
965 unset( $namedArgs[$index] );
968 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
969 $namedArgs[$name] = $value->item( 0 );
970 unset( $numberedArgs[$name] );
974 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
978 * @throws MWException
983 function expand( $root, $flags = 0 ) {
984 static $expansionDepth = 0;
985 if ( is_string( $root ) ) {
989 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
990 $this->parser
->limitationWarn( 'node-count-exceeded',
991 $this->parser
->mPPNodeCount
,
992 $this->parser
->mOptions
->getMaxPPNodeCount()
994 return '<span class="error">Node-count limit exceeded</span>';
997 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
998 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1000 $this->parser
->mOptions
->getMaxPPExpandDepth()
1002 return '<span class="error">Expansion depth limit exceeded</span>';
1004 wfProfileIn( __METHOD__
);
1006 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1007 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1010 if ( $root instanceof PPNode_DOM
) {
1011 $root = $root->node
;
1013 if ( $root instanceof DOMDocument
) {
1014 $root = $root->documentElement
;
1017 $outStack = array( '', '' );
1018 $iteratorStack = array( false, $root );
1019 $indexStack = array( 0, 0 );
1021 while ( count( $iteratorStack ) > 1 ) {
1022 $level = count( $outStack ) - 1;
1023 $iteratorNode =& $iteratorStack[$level];
1024 $out =& $outStack[$level];
1025 $index =& $indexStack[$level];
1027 if ( $iteratorNode instanceof PPNode_DOM
) {
1028 $iteratorNode = $iteratorNode->node
;
1031 if ( is_array( $iteratorNode ) ) {
1032 if ( $index >= count( $iteratorNode ) ) {
1033 // All done with this iterator
1034 $iteratorStack[$level] = false;
1035 $contextNode = false;
1037 $contextNode = $iteratorNode[$index];
1040 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1041 if ( $index >= $iteratorNode->length
) {
1042 // All done with this iterator
1043 $iteratorStack[$level] = false;
1044 $contextNode = false;
1046 $contextNode = $iteratorNode->item( $index );
1050 // Copy to $contextNode and then delete from iterator stack,
1051 // because this is not an iterator but we do have to execute it once
1052 $contextNode = $iteratorStack[$level];
1053 $iteratorStack[$level] = false;
1056 if ( $contextNode instanceof PPNode_DOM
) {
1057 $contextNode = $contextNode->node
;
1060 $newIterator = false;
1062 if ( $contextNode === false ) {
1064 } elseif ( is_string( $contextNode ) ) {
1065 $out .= $contextNode;
1066 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1067 $newIterator = $contextNode;
1068 } elseif ( $contextNode instanceof DOMNode
) {
1069 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1070 $out .= $contextNode->nodeValue
;
1071 } elseif ( $contextNode->nodeName
== 'template' ) {
1072 # Double-brace expansion
1073 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1074 $titles = $xpath->query( 'title', $contextNode );
1075 $title = $titles->item( 0 );
1076 $parts = $xpath->query( 'part', $contextNode );
1077 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1078 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1080 $lineStart = $contextNode->getAttribute( 'lineStart' );
1082 'title' => new PPNode_DOM( $title ),
1083 'parts' => new PPNode_DOM( $parts ),
1084 'lineStart' => $lineStart );
1085 $ret = $this->parser
->braceSubstitution( $params, $this );
1086 if ( isset( $ret['object'] ) ) {
1087 $newIterator = $ret['object'];
1089 $out .= $ret['text'];
1092 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1093 # Triple-brace expansion
1094 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1095 $titles = $xpath->query( 'title', $contextNode );
1096 $title = $titles->item( 0 );
1097 $parts = $xpath->query( 'part', $contextNode );
1098 if ( $flags & PPFrame
::NO_ARGS
) {
1099 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1102 'title' => new PPNode_DOM( $title ),
1103 'parts' => new PPNode_DOM( $parts ) );
1104 $ret = $this->parser
->argSubstitution( $params, $this );
1105 if ( isset( $ret['object'] ) ) {
1106 $newIterator = $ret['object'];
1108 $out .= $ret['text'];
1111 } elseif ( $contextNode->nodeName
== 'comment' ) {
1112 # HTML-style comment
1113 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1114 if ( $this->parser
->ot
['html']
1115 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1116 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1120 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1121 # Not in RECOVER_COMMENTS mode (extractSections) though
1122 elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1123 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1125 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1127 $out .= $contextNode->textContent
;
1129 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1130 # Output suppression used by <includeonly> etc.
1131 # OT_WIKI will only respect <ignore> in substed templates.
1132 # The other output types respect it unless NO_IGNORE is set.
1133 # extractSections() sets NO_IGNORE and so never respects it.
1134 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1135 $out .= $contextNode->textContent
;
1139 } elseif ( $contextNode->nodeName
== 'ext' ) {
1141 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1142 $names = $xpath->query( 'name', $contextNode );
1143 $attrs = $xpath->query( 'attr', $contextNode );
1144 $inners = $xpath->query( 'inner', $contextNode );
1145 $closes = $xpath->query( 'close', $contextNode );
1147 'name' => new PPNode_DOM( $names->item( 0 ) ),
1148 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1149 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1150 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1152 $out .= $this->parser
->extensionSubstitution( $params, $this );
1153 } elseif ( $contextNode->nodeName
== 'h' ) {
1155 $s = $this->expand( $contextNode->childNodes
, $flags );
1157 # Insert a heading marker only for <h> children of <root>
1158 # This is to stop extractSections from going over multiple tree levels
1159 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1160 # Insert heading index marker
1161 $headingIndex = $contextNode->getAttribute( 'i' );
1162 $titleText = $this->title
->getPrefixedDBkey();
1163 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1164 $serial = count( $this->parser
->mHeadings
) - 1;
1165 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1166 $count = $contextNode->getAttribute( 'level' );
1167 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1168 $this->parser
->mStripState
->addGeneral( $marker, '' );
1172 # Generic recursive expansion
1173 $newIterator = $contextNode->childNodes
;
1176 wfProfileOut( __METHOD__
);
1177 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1180 if ( $newIterator !== false ) {
1181 if ( $newIterator instanceof PPNode_DOM
) {
1182 $newIterator = $newIterator->node
;
1185 $iteratorStack[] = $newIterator;
1187 } elseif ( $iteratorStack[$level] === false ) {
1188 // Return accumulated value to parent
1189 // With tail recursion
1190 while ( $iteratorStack[$level] === false && $level > 0 ) {
1191 $outStack[$level - 1] .= $out;
1192 array_pop( $outStack );
1193 array_pop( $iteratorStack );
1194 array_pop( $indexStack );
1200 wfProfileOut( __METHOD__
);
1201 return $outStack[0];
1209 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1210 $args = array_slice( func_get_args(), 2 );
1214 foreach ( $args as $root ) {
1215 if ( $root instanceof PPNode_DOM
) {
1216 $root = $root->node
;
1218 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1219 $root = array( $root );
1221 foreach ( $root as $node ) {
1227 $s .= $this->expand( $node, $flags );
1234 * Implode with no flags specified
1235 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1239 function implode( $sep /*, ... */ ) {
1240 $args = array_slice( func_get_args(), 1 );
1244 foreach ( $args as $root ) {
1245 if ( $root instanceof PPNode_DOM
) {
1246 $root = $root->node
;
1248 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1249 $root = array( $root );
1251 foreach ( $root as $node ) {
1257 $s .= $this->expand( $node );
1264 * Makes an object that, when expand()ed, will be the same as one obtained
1269 function virtualImplode( $sep /*, ... */ ) {
1270 $args = array_slice( func_get_args(), 1 );
1274 foreach ( $args as $root ) {
1275 if ( $root instanceof PPNode_DOM
) {
1276 $root = $root->node
;
1278 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1279 $root = array( $root );
1281 foreach ( $root as $node ) {
1294 * Virtual implode with brackets
1297 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1298 $args = array_slice( func_get_args(), 3 );
1299 $out = array( $start );
1302 foreach ( $args as $root ) {
1303 if ( $root instanceof PPNode_DOM
) {
1304 $root = $root->node
;
1306 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1307 $root = array( $root );
1309 foreach ( $root as $node ) {
1322 function __toString() {
1326 function getPDBK( $level = false ) {
1327 if ( $level === false ) {
1328 return $this->title
->getPrefixedDBkey();
1330 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1337 function getArguments() {
1344 function getNumberedArguments() {
1351 function getNamedArguments() {
1356 * Returns true if there are no arguments in this frame
1360 function isEmpty() {
1364 function getArgument( $name ) {
1369 * Returns true if the infinite loop check is OK, false if a loop is detected
1373 function loopCheck( $title ) {
1374 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1378 * Return true if the frame is a template frame
1382 function isTemplate() {
1387 * Get a title of frame
1391 function getTitle() {
1392 return $this->title
;
1397 * Expansion frame with template arguments
1400 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1401 var $numberedArgs, $namedArgs;
1407 var $numberedExpansionCache, $namedExpansionCache;
1410 * @param $preprocessor
1411 * @param $parent PPFrame_DOM
1412 * @param $numberedArgs array
1413 * @param $namedArgs array
1414 * @param $title Title
1416 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1417 parent
::__construct( $preprocessor );
1419 $this->parent
= $parent;
1420 $this->numberedArgs
= $numberedArgs;
1421 $this->namedArgs
= $namedArgs;
1422 $this->title
= $title;
1423 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1424 $this->titleCache
= $parent->titleCache
;
1425 $this->titleCache
[] = $pdbk;
1426 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1427 if ( $pdbk !== false ) {
1428 $this->loopCheckHash
[$pdbk] = true;
1430 $this->depth
= $parent->depth +
1;
1431 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1434 function __toString() {
1437 $args = $this->numberedArgs +
$this->namedArgs
;
1438 foreach ( $args as $name => $value ) {
1444 $s .= "\"$name\":\"" .
1445 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1452 * Returns true if there are no arguments in this frame
1456 function isEmpty() {
1457 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1460 function getArguments() {
1461 $arguments = array();
1462 foreach ( array_merge(
1463 array_keys( $this->numberedArgs
),
1464 array_keys( $this->namedArgs
) ) as $key ) {
1465 $arguments[$key] = $this->getArgument( $key );
1470 function getNumberedArguments() {
1471 $arguments = array();
1472 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1473 $arguments[$key] = $this->getArgument( $key );
1478 function getNamedArguments() {
1479 $arguments = array();
1480 foreach ( array_keys( $this->namedArgs
) as $key ) {
1481 $arguments[$key] = $this->getArgument( $key );
1486 function getNumberedArgument( $index ) {
1487 if ( !isset( $this->numberedArgs
[$index] ) ) {
1490 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1491 # No trimming for unnamed arguments
1492 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1494 return $this->numberedExpansionCache
[$index];
1497 function getNamedArgument( $name ) {
1498 if ( !isset( $this->namedArgs
[$name] ) ) {
1501 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1502 # Trim named arguments post-expand, for backwards compatibility
1503 $this->namedExpansionCache
[$name] = trim(
1504 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1506 return $this->namedExpansionCache
[$name];
1509 function getArgument( $name ) {
1510 $text = $this->getNumberedArgument( $name );
1511 if ( $text === false ) {
1512 $text = $this->getNamedArgument( $name );
1518 * Return true if the frame is a template frame
1522 function isTemplate() {
1528 * Expansion frame with custom arguments
1531 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1534 function __construct( $preprocessor, $args ) {
1535 parent
::__construct( $preprocessor );
1536 $this->args
= $args;
1539 function __toString() {
1542 foreach ( $this->args
as $name => $value ) {
1548 $s .= "\"$name\":\"" .
1549 str_replace( '"', '\\"', $value->__toString() ) . '"';
1558 function isEmpty() {
1559 return !count( $this->args
);
1562 function getArgument( $index ) {
1563 if ( !isset( $this->args
[$index] ) ) {
1566 return $this->args
[$index];
1569 function getArguments() {
1577 class PPNode_DOM
implements PPNode
{
1585 function __construct( $node, $xpath = false ) {
1586 $this->node
= $node;
1592 function getXPath() {
1593 if ( $this->xpath
=== null ) {
1594 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1596 return $this->xpath
;
1599 function __toString() {
1600 if ( $this->node
instanceof DOMNodeList
) {
1602 foreach ( $this->node
as $node ) {
1603 $s .= $node->ownerDocument
->saveXML( $node );
1606 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1612 * @return bool|PPNode_DOM
1614 function getChildren() {
1615 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1619 * @return bool|PPNode_DOM
1621 function getFirstChild() {
1622 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1626 * @return bool|PPNode_DOM
1628 function getNextSibling() {
1629 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1635 * @return bool|PPNode_DOM
1637 function getChildrenOfType( $type ) {
1638 return new self( $this->getXPath()->query( $type, $this->node
) );
1644 function getLength() {
1645 if ( $this->node
instanceof DOMNodeList
) {
1646 return $this->node
->length
;
1654 * @return bool|PPNode_DOM
1656 function item( $i ) {
1657 $item = $this->node
->item( $i );
1658 return $item ?
new self( $item ) : false;
1664 function getName() {
1665 if ( $this->node
instanceof DOMNodeList
) {
1668 return $this->node
->nodeName
;
1673 * Split a "<part>" node into an associative array containing:
1674 * - name PPNode name
1675 * - index String index
1676 * - value PPNode value
1678 * @throws MWException
1681 function splitArg() {
1682 $xpath = $this->getXPath();
1683 $names = $xpath->query( 'name', $this->node
);
1684 $values = $xpath->query( 'value', $this->node
);
1685 if ( !$names->length ||
!$values->length
) {
1686 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1688 $name = $names->item( 0 );
1689 $index = $name->getAttribute( 'index' );
1691 'name' => new self( $name ),
1693 'value' => new self( $values->item( 0 ) ) );
1697 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1698 * All values in the resulting array are PPNodes. Inner and close are optional.
1700 * @throws MWException
1703 function splitExt() {
1704 $xpath = $this->getXPath();
1705 $names = $xpath->query( 'name', $this->node
);
1706 $attrs = $xpath->query( 'attr', $this->node
);
1707 $inners = $xpath->query( 'inner', $this->node
);
1708 $closes = $xpath->query( 'close', $this->node
);
1709 if ( !$names->length ||
!$attrs->length
) {
1710 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1713 'name' => new self( $names->item( 0 ) ),
1714 'attr' => new self( $attrs->item( 0 ) ) );
1715 if ( $inners->length
) {
1716 $parts['inner'] = new self( $inners->item( 0 ) );
1718 if ( $closes->length
) {
1719 $parts['close'] = new self( $closes->item( 0 ) );
1725 * Split a "<h>" node
1726 * @throws MWException
1729 function splitHeading() {
1730 if ( $this->getName() !== 'h' ) {
1731 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1734 'i' => $this->node
->getAttribute( 'i' ),
1735 'level' => $this->node
->getAttribute( 'level' ),
1736 'contents' => $this->getChildren()