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
{
31 protected $memoryLimit;
33 const CACHE_VERSION
= 1;
35 function __construct( $parser ) {
36 $this->parser
= $parser;
37 $mem = ini_get( 'memory_limit' );
38 $this->memoryLimit
= false;
39 if ( strval( $mem ) !== '' && $mem != -1 ) {
40 if ( preg_match( '/^\d+$/', $mem ) ) {
41 $this->memoryLimit
= $mem;
42 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
43 $this->memoryLimit
= $m[1] * 1048576;
52 return new PPFrame_DOM( $this );
57 * @return PPCustomFrame_DOM
59 function newCustomFrame( $args ) {
60 return new PPCustomFrame_DOM( $this, $args );
64 * @param array $values
67 function newPartNodeArray( $values ) {
68 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
71 foreach ( $values as $k => $val ) {
73 $xml .= "<part><name index=\"$k\"/><value>"
74 . htmlspecialchars( $val ) . "</value></part>";
76 $xml .= "<part><name>" . htmlspecialchars( $k )
77 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
83 wfProfileIn( __METHOD__
. '-loadXML' );
84 $dom = new DOMDocument();
86 $result = $dom->loadXML( $xml );
89 // Try running the XML through UtfNormal to get rid of invalid characters
90 $xml = UtfNormal
::cleanUp( $xml );
91 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
92 $result = $dom->loadXML( $xml, 1 << 19 );
94 wfProfileOut( __METHOD__
. '-loadXML' );
97 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
100 $root = $dom->documentElement
;
101 $node = new PPNode_DOM( $root->childNodes
);
106 * @throws MWException
109 function memCheck() {
110 if ( $this->memoryLimit
=== false ) {
113 $usage = memory_get_usage();
114 if ( $usage > $this->memoryLimit
* 0.9 ) {
115 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
116 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
118 return $usage <= $this->memoryLimit
* 0.8;
122 * Preprocess some wikitext and return the document tree.
123 * This is the ghost of Parser::replace_variables().
125 * @param string $text The text to parse
126 * @param int $flags Bitwise combination of:
127 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
128 * as if the text is being included. Default
129 * is to assume a direct page view.
131 * The generated DOM tree must depend only on the input text and the flags.
132 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
134 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
135 * change in the DOM tree for a given text, must be passed through the section identifier
136 * in the section edit link and thus back to extractSections().
138 * The output of this function is currently only cached in process memory, but a persistent
139 * cache may be implemented at a later date which takes further advantage of these strict
140 * dependency requirements.
142 * @throws MWException
145 function preprocessToObj( $text, $flags = 0 ) {
146 wfProfileIn( __METHOD__
);
147 global $wgMemc, $wgPreprocessorCacheThreshold;
150 $cacheable = ( $wgPreprocessorCacheThreshold !== false
151 && strlen( $text ) > $wgPreprocessorCacheThreshold );
153 wfProfileIn( __METHOD__
. '-cacheable' );
155 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
156 $cacheValue = $wgMemc->get( $cacheKey );
158 $version = substr( $cacheValue, 0, 8 );
159 if ( intval( $version ) == self
::CACHE_VERSION
) {
160 $xml = substr( $cacheValue, 8 );
162 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
165 if ( $xml === false ) {
166 wfProfileIn( __METHOD__
. '-cache-miss' );
167 $xml = $this->preprocessToXml( $text, $flags );
168 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
169 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
170 wfProfileOut( __METHOD__
. '-cache-miss' );
171 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
174 $xml = $this->preprocessToXml( $text, $flags );
177 // Fail if the number of elements exceeds acceptable limits
178 // Do not attempt to generate the DOM
179 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
180 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
181 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
183 wfProfileOut( __METHOD__
. '-cacheable' );
185 wfProfileOut( __METHOD__
);
186 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
189 wfProfileIn( __METHOD__
. '-loadXML' );
190 $dom = new DOMDocument
;
191 wfSuppressWarnings();
192 $result = $dom->loadXML( $xml );
195 // Try running the XML through UtfNormal to get rid of invalid characters
196 $xml = UtfNormal
::cleanUp( $xml );
197 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
198 // don't barf when the XML is >256 levels deep.
199 $result = $dom->loadXML( $xml, 1 << 19 );
202 $obj = new PPNode_DOM( $dom->documentElement
);
204 wfProfileOut( __METHOD__
. '-loadXML' );
207 wfProfileOut( __METHOD__
. '-cacheable' );
210 wfProfileOut( __METHOD__
);
213 throw new MWException( __METHOD__
. ' generated invalid XML' );
219 * @param string $text
223 function preprocessToXml( $text, $flags = 0 ) {
224 wfProfileIn( __METHOD__
);
237 'names' => array( 2 => null ),
243 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
245 $xmlishElements = $this->parser
->getStripList();
246 $enableOnlyinclude = false;
247 if ( $forInclusion ) {
248 $ignoredTags = array( 'includeonly', '/includeonly' );
249 $ignoredElements = array( 'noinclude' );
250 $xmlishElements[] = 'noinclude';
251 if ( strpos( $text, '<onlyinclude>' ) !== false
252 && strpos( $text, '</onlyinclude>' ) !== false
254 $enableOnlyinclude = true;
257 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
258 $ignoredElements = array( 'includeonly' );
259 $xmlishElements[] = 'includeonly';
261 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
263 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
264 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
266 $stack = new PPDStack
;
268 $searchBase = "[{<\n"; #}
269 // For fast reverse searches
270 $revText = strrev( $text );
271 $lengthText = strlen( $text );
273 // Input pointer, starts out pointing to a pseudo-newline before the start
275 // Current accumulator
276 $accum =& $stack->getAccum();
278 // True to find equals signs in arguments
280 // True to take notice of pipe characters
283 // True if $i is inside a possible heading
285 // True if there are no more greater-than (>) signs right of $i
287 // True to ignore all input up to the next <onlyinclude>
288 $findOnlyinclude = $enableOnlyinclude;
289 // Do a line-start run without outputting an LF character
290 $fakeLineStart = true;
295 if ( $findOnlyinclude ) {
296 // Ignore all input up to the next <onlyinclude>
297 $startPos = strpos( $text, '<onlyinclude>', $i );
298 if ( $startPos === false ) {
299 // Ignored section runs to the end
300 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
303 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
304 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
306 $findOnlyinclude = false;
309 if ( $fakeLineStart ) {
310 $found = 'line-start';
313 # Find next opening brace, closing brace or pipe
314 $search = $searchBase;
315 if ( $stack->top
=== false ) {
316 $currentClosing = '';
318 $currentClosing = $stack->top
->close
;
319 $search .= $currentClosing;
325 // First equals will be for the template
329 # Output literal section, advance input counter
330 $literalLength = strcspn( $text, $search, $i );
331 if ( $literalLength > 0 ) {
332 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
333 $i +
= $literalLength;
335 if ( $i >= $lengthText ) {
336 if ( $currentClosing == "\n" ) {
337 // Do a past-the-end run to finish off the heading
345 $curChar = $text[$i];
346 if ( $curChar == '|' ) {
348 } elseif ( $curChar == '=' ) {
350 } elseif ( $curChar == '<' ) {
352 } elseif ( $curChar == "\n" ) {
356 $found = 'line-start';
358 } elseif ( $curChar == $currentClosing ) {
360 } elseif ( isset( $rules[$curChar] ) ) {
362 $rule = $rules[$curChar];
364 # Some versions of PHP have a strcspn which stops on null characters
365 # Ignore and continue
372 if ( $found == 'angle' ) {
374 // Handle </onlyinclude>
375 if ( $enableOnlyinclude
376 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
378 $findOnlyinclude = true;
382 // Determine element name
383 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
384 // Element name missing or not listed
390 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
392 // To avoid leaving blank lines, when a sequence of
393 // space-separated comments is both preceded and followed by
394 // a newline (ignoring spaces), then
395 // trim leading and trailing spaces and the trailing newline.
398 $endPos = strpos( $text, '-->', $i +
4 );
399 if ( $endPos === false ) {
400 // Unclosed comment in input, runs to end
401 $inner = substr( $text, $i );
402 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
405 // Search backwards for leading whitespace
406 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
408 // Search forwards for trailing whitespace
409 // $wsEnd will be the position of the last space (or the '>' if there's none)
410 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
412 // Keep looking forward as long as we're finding more
414 $comments = array( array( $wsStart, $wsEnd ) );
415 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
416 $c = strpos( $text, '-->', $wsEnd +
4 );
417 if ( $c === false ) {
420 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
421 $comments[] = array( $wsEnd +
1, $c );
425 // Eat the line if possible
426 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
427 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
428 // it's a possible beneficial b/c break.
429 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
430 && substr( $text, $wsEnd +
1, 1 ) == "\n"
432 // Remove leading whitespace from the end of the accumulator
433 // Sanity check first though
434 $wsLength = $i - $wsStart;
436 && strspn( $accum, " \t", -$wsLength ) === $wsLength
438 $accum = substr( $accum, 0, -$wsLength );
441 // Dump all but the last comment to the accumulator
442 foreach ( $comments as $j => $com ) {
444 $endPos = $com[1] +
1;
445 if ( $j == ( count( $comments ) - 1 ) ) {
448 $inner = substr( $text, $startPos, $endPos - $startPos );
449 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
452 // Do a line-start run next time to look for headings after the comment
453 $fakeLineStart = true;
455 // No line to eat, just take the comment itself
461 $part = $stack->top
->getCurrentPart();
462 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
463 $part->visualEnd
= $wsStart;
465 // Else comments abutting, no change in visual end
466 $part->commentEnd
= $endPos;
469 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
470 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
475 $lowerName = strtolower( $name );
476 $attrStart = $i +
strlen( $name ) +
1;
479 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
480 if ( $tagEndPos === false ) {
481 // Infinite backtrack
482 // Disable tag search to prevent worst-case O(N^2) performance
489 // Handle ignored tags
490 if ( in_array( $lowerName, $ignoredTags ) ) {
492 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
499 if ( $text[$tagEndPos - 1] == '/' ) {
500 $attrEnd = $tagEndPos - 1;
505 $attrEnd = $tagEndPos;
507 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
508 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
510 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
511 $i = $matches[0][1] +
strlen( $matches[0][0] );
512 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
514 // No end tag -- let it run out to the end of the text.
515 $inner = substr( $text, $tagEndPos +
1 );
520 // <includeonly> and <noinclude> just become <ignore> tags
521 if ( in_array( $lowerName, $ignoredElements ) ) {
522 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
528 if ( $attrEnd <= $attrStart ) {
531 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
533 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
534 // Note that the attr element contains the whitespace between name and attribute,
535 // this is necessary for precise reconstruction during pre-save transform.
536 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
537 if ( $inner !== null ) {
538 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
540 $accum .= $close . '</ext>';
541 } elseif ( $found == 'line-start' ) {
542 // Is this the start of a heading?
543 // Line break belongs before the heading element in any case
544 if ( $fakeLineStart ) {
545 $fakeLineStart = false;
551 $count = strspn( $text, '=', $i, 6 );
552 if ( $count == 1 && $findEquals ) {
553 // DWIM: This looks kind of like a name/value separator.
554 // Let's let the equals handler have it and break the
555 // potential heading. This is heuristic, but AFAICT the
556 // methods for completely correct disambiguation are very
558 } elseif ( $count > 0 ) {
562 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
565 $stack->push( $piece );
566 $accum =& $stack->getAccum();
567 $flags = $stack->getFlags();
571 } elseif ( $found == 'line-end' ) {
572 $piece = $stack->top
;
573 // A heading must be open, otherwise \n wouldn't have been in the search list
574 assert( '$piece->open == "\n"' );
575 $part = $piece->getCurrentPart();
576 // Search back through the input to see if it has a proper close.
577 // Do this using the reversed string since the other solutions
578 // (end anchor, etc.) are inefficient.
579 $wsLength = strspn( $revText, " \t", $lengthText - $i );
580 $searchStart = $i - $wsLength;
581 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
582 // Comment found at line end
583 // Search for equals signs before the comment
584 $searchStart = $part->visualEnd
;
585 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
587 $count = $piece->count
;
588 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
589 if ( $equalsLength > 0 ) {
590 if ( $searchStart - $equalsLength == $piece->startPos
) {
591 // This is just a single string of equals signs on its own line
592 // Replicate the doHeadings behavior /={count}(.+)={count}/
593 // First find out how many equals signs there really are (don't stop at 6)
594 $count = $equalsLength;
598 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
601 $count = min( $equalsLength, $count );
604 // Normal match, output <h>
605 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
608 // Single equals sign on its own line, count=0
612 // No match, no <h>, just pass down the inner text
617 $accum =& $stack->getAccum();
618 $flags = $stack->getFlags();
621 // Append the result to the enclosing accumulator
623 // Note that we do NOT increment the input pointer.
624 // This is because the closing linebreak could be the opening linebreak of
625 // another heading. Infinite loops are avoided because the next iteration MUST
626 // hit the heading open case above, which unconditionally increments the
628 } elseif ( $found == 'open' ) {
629 # count opening brace characters
630 $count = strspn( $text, $curChar, $i );
632 # we need to add to stack only if opening brace count is enough for one of the rules
633 if ( $count >= $rule['min'] ) {
634 # Add it to the stack
637 'close' => $rule['end'],
639 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
642 $stack->push( $piece );
643 $accum =& $stack->getAccum();
644 $flags = $stack->getFlags();
647 # Add literal brace(s)
648 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
651 } elseif ( $found == 'close' ) {
652 $piece = $stack->top
;
653 # lets check if there are enough characters for closing brace
654 $maxCount = $piece->count
;
655 $count = strspn( $text, $curChar, $i, $maxCount );
657 # check for maximum matching characters (if there are 5 closing
658 # characters, we will probably need only 3 - depending on the rules)
659 $rule = $rules[$piece->open
];
660 if ( $count > $rule['max'] ) {
661 # The specified maximum exists in the callback array, unless the caller
663 $matchingCount = $rule['max'];
665 # Count is less than the maximum
666 # Skip any gaps in the callback array to find the true largest match
667 # Need to use array_key_exists not isset because the callback can be null
668 $matchingCount = $count;
669 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
674 if ( $matchingCount <= 0 ) {
675 # No matching element found in callback array
676 # Output a literal closing brace and continue
677 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
681 $name = $rule['names'][$matchingCount];
682 if ( $name === null ) {
683 // No element, just literal text
684 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
687 # Note: $parts is already XML, does not need to be encoded further
688 $parts = $piece->parts
;
689 $title = $parts[0]->out
;
692 # The invocation is at the start of the line if lineStart is set in
693 # the stack, and all opening brackets are used up.
694 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
695 $attr = ' lineStart="1"';
700 $element = "<$name$attr>";
701 $element .= "<title>$title</title>";
703 foreach ( $parts as $part ) {
704 if ( isset( $part->eqpos
) ) {
705 $argName = substr( $part->out
, 0, $part->eqpos
);
706 $argValue = substr( $part->out
, $part->eqpos +
1 );
707 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
709 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
713 $element .= "</$name>";
716 # Advance input pointer
717 $i +
= $matchingCount;
721 $accum =& $stack->getAccum();
723 # Re-add the old stack element if it still has unmatched opening characters remaining
724 if ( $matchingCount < $piece->count
) {
725 $piece->parts
= array( new PPDPart
);
726 $piece->count
-= $matchingCount;
727 # do we still qualify for any callback with remaining count?
728 $min = $rules[$piece->open
]['min'];
729 if ( $piece->count
>= $min ) {
730 $stack->push( $piece );
731 $accum =& $stack->getAccum();
733 $accum .= str_repeat( $piece->open
, $piece->count
);
736 $flags = $stack->getFlags();
739 # Add XML element to the enclosing accumulator
741 } elseif ( $found == 'pipe' ) {
742 $findEquals = true; // shortcut for getFlags()
744 $accum =& $stack->getAccum();
746 } elseif ( $found == 'equals' ) {
747 $findEquals = false; // shortcut for getFlags()
748 $stack->getCurrentPart()->eqpos
= strlen( $accum );
754 # Output any remaining unclosed brackets
755 foreach ( $stack->stack
as $piece ) {
756 $stack->rootAccum
.= $piece->breakSyntax();
758 $stack->rootAccum
.= '</root>';
759 $xml = $stack->rootAccum
;
761 wfProfileOut( __METHOD__
);
768 * Stack class to help Preprocessor::preprocessToObj()
778 /** @var bool|PPDStack */
785 protected $elementClass = 'PPDStackElement';
787 protected static $false = false;
789 function __construct() {
790 $this->stack
= array();
792 $this->rootAccum
= '';
793 $this->accum
=& $this->rootAccum
;
800 return count( $this->stack
);
803 function &getAccum() {
807 function getCurrentPart() {
808 if ( $this->top
=== false ) {
811 return $this->top
->getCurrentPart();
815 function push( $data ) {
816 if ( $data instanceof $this->elementClass
) {
817 $this->stack
[] = $data;
819 $class = $this->elementClass
;
820 $this->stack
[] = new $class( $data );
822 $this->top
= $this->stack
[count( $this->stack
) - 1];
823 $this->accum
=& $this->top
->getAccum();
827 if ( !count( $this->stack
) ) {
828 throw new MWException( __METHOD__
. ': no elements remaining' );
830 $temp = array_pop( $this->stack
);
832 if ( count( $this->stack
) ) {
833 $this->top
= $this->stack
[count( $this->stack
) - 1];
834 $this->accum
=& $this->top
->getAccum();
836 $this->top
= self
::$false;
837 $this->accum
=& $this->rootAccum
;
842 function addPart( $s = '' ) {
843 $this->top
->addPart( $s );
844 $this->accum
=& $this->top
->getAccum();
850 function getFlags() {
851 if ( !count( $this->stack
) ) {
853 'findEquals' => false,
855 'inHeading' => false,
858 return $this->top
->getFlags();
866 class PPDStackElement
{
867 /** @var string Opening character (\n for heading) */
870 /** @var string Matching closing character */
873 /** @var int Number of opening characters found (number of "=" for heading) */
876 /** @var array PPDPart objects describing pipe-separated parts. */
880 * @var bool True if the open char appeared at the start of the input line.
881 * Not set for headings.
886 protected $partClass = 'PPDPart';
888 function __construct( $data = array() ) {
889 $class = $this->partClass
;
890 $this->parts
= array( new $class );
892 foreach ( $data as $name => $value ) {
893 $this->$name = $value;
897 function &getAccum() {
898 return $this->parts
[count( $this->parts
) - 1]->out
;
901 function addPart( $s = '' ) {
902 $class = $this->partClass
;
903 $this->parts
[] = new $class( $s );
906 function getCurrentPart() {
907 return $this->parts
[count( $this->parts
) - 1];
913 function getFlags() {
914 $partCount = count( $this->parts
);
915 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
917 'findPipe' => $findPipe,
918 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
919 'inHeading' => $this->open
== "\n",
924 * Get the output string that would result if the close is not found.
926 * @param bool|int $openingCount
929 function breakSyntax( $openingCount = false ) {
930 if ( $this->open
== "\n" ) {
931 $s = $this->parts
[0]->out
;
933 if ( $openingCount === false ) {
934 $openingCount = $this->count
;
936 $s = str_repeat( $this->open
, $openingCount );
938 foreach ( $this->parts
as $part ) {
958 // Optional member variables:
959 // eqpos Position of equals sign in output accumulator
960 // commentEnd Past-the-end input pointer for the last comment encountered
961 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
963 function __construct( $out = '' ) {
969 * An expansion frame, used as a context to expand the result of preprocessToObj()
972 class PPFrame_DOM
implements PPFrame
{
977 * @var array Hashtable listing templates which are disallowed for expansion
978 * in this frame, having been encountered previously in parent frames.
980 public $loopCheckHash;
983 * @var int Recursion depth of this frame, top = 0.
984 * Note that this is NOT the same as expansion depth in expand()
988 /** @var Preprocessor */
989 protected $preprocessor;
998 * Construct a new preprocessor frame.
999 * @param Preprocessor $preprocessor The parent preprocessor
1001 function __construct( $preprocessor ) {
1002 $this->preprocessor
= $preprocessor;
1003 $this->parser
= $preprocessor->parser
;
1004 $this->title
= $this->parser
->mTitle
;
1005 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
1006 $this->loopCheckHash
= array();
1011 * Create a new child frame
1012 * $args is optionally a multi-root PPNode or array containing the template arguments
1014 * @param bool|array $args
1015 * @param Title|bool $title
1016 * @param int $indexOffset
1017 * @return PPTemplateFrame_DOM
1019 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1020 $namedArgs = array();
1021 $numberedArgs = array();
1022 if ( $title === false ) {
1023 $title = $this->title
;
1025 if ( $args !== false ) {
1027 if ( $args instanceof PPNode
) {
1028 $args = $args->node
;
1030 foreach ( $args as $arg ) {
1031 if ( $arg instanceof PPNode
) {
1035 $xpath = new DOMXPath( $arg->ownerDocument
);
1038 $nameNodes = $xpath->query( 'name', $arg );
1039 $value = $xpath->query( 'value', $arg );
1040 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1041 // Numbered parameter
1042 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1043 $index = $index - $indexOffset;
1044 $numberedArgs[$index] = $value->item( 0 );
1045 unset( $namedArgs[$index] );
1048 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1049 $namedArgs[$name] = $value->item( 0 );
1050 unset( $numberedArgs[$name] );
1054 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1058 * @throws MWException
1059 * @param string|PPNode_DOM|DOMDocument $root
1063 function expand( $root, $flags = 0 ) {
1064 static $expansionDepth = 0;
1065 if ( is_string( $root ) ) {
1069 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1070 $this->parser
->limitationWarn( 'node-count-exceeded',
1071 $this->parser
->mPPNodeCount
,
1072 $this->parser
->mOptions
->getMaxPPNodeCount()
1074 return '<span class="error">Node-count limit exceeded</span>';
1077 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1078 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1080 $this->parser
->mOptions
->getMaxPPExpandDepth()
1082 return '<span class="error">Expansion depth limit exceeded</span>';
1084 wfProfileIn( __METHOD__
);
1086 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1087 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1090 if ( $root instanceof PPNode_DOM
) {
1091 $root = $root->node
;
1093 if ( $root instanceof DOMDocument
) {
1094 $root = $root->documentElement
;
1097 $outStack = array( '', '' );
1098 $iteratorStack = array( false, $root );
1099 $indexStack = array( 0, 0 );
1101 while ( count( $iteratorStack ) > 1 ) {
1102 $level = count( $outStack ) - 1;
1103 $iteratorNode =& $iteratorStack[$level];
1104 $out =& $outStack[$level];
1105 $index =& $indexStack[$level];
1107 if ( $iteratorNode instanceof PPNode_DOM
) {
1108 $iteratorNode = $iteratorNode->node
;
1111 if ( is_array( $iteratorNode ) ) {
1112 if ( $index >= count( $iteratorNode ) ) {
1113 // All done with this iterator
1114 $iteratorStack[$level] = false;
1115 $contextNode = false;
1117 $contextNode = $iteratorNode[$index];
1120 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1121 if ( $index >= $iteratorNode->length
) {
1122 // All done with this iterator
1123 $iteratorStack[$level] = false;
1124 $contextNode = false;
1126 $contextNode = $iteratorNode->item( $index );
1130 // Copy to $contextNode and then delete from iterator stack,
1131 // because this is not an iterator but we do have to execute it once
1132 $contextNode = $iteratorStack[$level];
1133 $iteratorStack[$level] = false;
1136 if ( $contextNode instanceof PPNode_DOM
) {
1137 $contextNode = $contextNode->node
;
1140 $newIterator = false;
1142 if ( $contextNode === false ) {
1144 } elseif ( is_string( $contextNode ) ) {
1145 $out .= $contextNode;
1146 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1147 $newIterator = $contextNode;
1148 } elseif ( $contextNode instanceof DOMNode
) {
1149 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1150 $out .= $contextNode->nodeValue
;
1151 } elseif ( $contextNode->nodeName
== 'template' ) {
1152 # Double-brace expansion
1153 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1154 $titles = $xpath->query( 'title', $contextNode );
1155 $title = $titles->item( 0 );
1156 $parts = $xpath->query( 'part', $contextNode );
1157 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1158 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1160 $lineStart = $contextNode->getAttribute( 'lineStart' );
1162 'title' => new PPNode_DOM( $title ),
1163 'parts' => new PPNode_DOM( $parts ),
1164 'lineStart' => $lineStart );
1165 $ret = $this->parser
->braceSubstitution( $params, $this );
1166 if ( isset( $ret['object'] ) ) {
1167 $newIterator = $ret['object'];
1169 $out .= $ret['text'];
1172 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1173 # Triple-brace expansion
1174 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1175 $titles = $xpath->query( 'title', $contextNode );
1176 $title = $titles->item( 0 );
1177 $parts = $xpath->query( 'part', $contextNode );
1178 if ( $flags & PPFrame
::NO_ARGS
) {
1179 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1182 'title' => new PPNode_DOM( $title ),
1183 'parts' => new PPNode_DOM( $parts ) );
1184 $ret = $this->parser
->argSubstitution( $params, $this );
1185 if ( isset( $ret['object'] ) ) {
1186 $newIterator = $ret['object'];
1188 $out .= $ret['text'];
1191 } elseif ( $contextNode->nodeName
== 'comment' ) {
1192 # HTML-style comment
1193 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1194 if ( $this->parser
->ot
['html']
1195 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1196 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1199 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1200 # Add a strip marker in PST mode so that pstPass2() can
1201 # run some old-fashioned regexes on the result.
1202 # Not in RECOVER_COMMENTS mode (extractSections) though.
1203 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1205 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1206 $out .= $contextNode->textContent
;
1208 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1209 # Output suppression used by <includeonly> etc.
1210 # OT_WIKI will only respect <ignore> in substed templates.
1211 # The other output types respect it unless NO_IGNORE is set.
1212 # extractSections() sets NO_IGNORE and so never respects it.
1213 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1214 ||
( $flags & PPFrame
::NO_IGNORE
)
1216 $out .= $contextNode->textContent
;
1220 } elseif ( $contextNode->nodeName
== 'ext' ) {
1222 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1223 $names = $xpath->query( 'name', $contextNode );
1224 $attrs = $xpath->query( 'attr', $contextNode );
1225 $inners = $xpath->query( 'inner', $contextNode );
1226 $closes = $xpath->query( 'close', $contextNode );
1228 'name' => new PPNode_DOM( $names->item( 0 ) ),
1229 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1230 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1231 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1233 $out .= $this->parser
->extensionSubstitution( $params, $this );
1234 } elseif ( $contextNode->nodeName
== 'h' ) {
1236 $s = $this->expand( $contextNode->childNodes
, $flags );
1238 # Insert a heading marker only for <h> children of <root>
1239 # This is to stop extractSections from going over multiple tree levels
1240 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1241 # Insert heading index marker
1242 $headingIndex = $contextNode->getAttribute( 'i' );
1243 $titleText = $this->title
->getPrefixedDBkey();
1244 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1245 $serial = count( $this->parser
->mHeadings
) - 1;
1246 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1247 $count = $contextNode->getAttribute( 'level' );
1248 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1249 $this->parser
->mStripState
->addGeneral( $marker, '' );
1253 # Generic recursive expansion
1254 $newIterator = $contextNode->childNodes
;
1257 wfProfileOut( __METHOD__
);
1258 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1261 if ( $newIterator !== false ) {
1262 if ( $newIterator instanceof PPNode_DOM
) {
1263 $newIterator = $newIterator->node
;
1266 $iteratorStack[] = $newIterator;
1268 } elseif ( $iteratorStack[$level] === false ) {
1269 // Return accumulated value to parent
1270 // With tail recursion
1271 while ( $iteratorStack[$level] === false && $level > 0 ) {
1272 $outStack[$level - 1] .= $out;
1273 array_pop( $outStack );
1274 array_pop( $iteratorStack );
1275 array_pop( $indexStack );
1281 wfProfileOut( __METHOD__
);
1282 return $outStack[0];
1286 * @param string $sep
1290 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1291 $args = array_slice( func_get_args(), 2 );
1295 foreach ( $args as $root ) {
1296 if ( $root instanceof PPNode_DOM
) {
1297 $root = $root->node
;
1299 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1300 $root = array( $root );
1302 foreach ( $root as $node ) {
1308 $s .= $this->expand( $node, $flags );
1315 * Implode with no flags specified
1316 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1318 * @param string $sep
1321 function implode( $sep /*, ... */ ) {
1322 $args = array_slice( func_get_args(), 1 );
1326 foreach ( $args as $root ) {
1327 if ( $root instanceof PPNode_DOM
) {
1328 $root = $root->node
;
1330 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1331 $root = array( $root );
1333 foreach ( $root as $node ) {
1339 $s .= $this->expand( $node );
1346 * Makes an object that, when expand()ed, will be the same as one obtained
1349 * @param string $sep
1352 function virtualImplode( $sep /*, ... */ ) {
1353 $args = array_slice( func_get_args(), 1 );
1357 foreach ( $args as $root ) {
1358 if ( $root instanceof PPNode_DOM
) {
1359 $root = $root->node
;
1361 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1362 $root = array( $root );
1364 foreach ( $root as $node ) {
1377 * Virtual implode with brackets
1378 * @param string $start
1379 * @param string $sep
1380 * @param string $end
1383 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1384 $args = array_slice( func_get_args(), 3 );
1385 $out = array( $start );
1388 foreach ( $args as $root ) {
1389 if ( $root instanceof PPNode_DOM
) {
1390 $root = $root->node
;
1392 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1393 $root = array( $root );
1395 foreach ( $root as $node ) {
1408 function __toString() {
1412 function getPDBK( $level = false ) {
1413 if ( $level === false ) {
1414 return $this->title
->getPrefixedDBkey();
1416 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1423 function getArguments() {
1430 function getNumberedArguments() {
1437 function getNamedArguments() {
1442 * Returns true if there are no arguments in this frame
1446 function isEmpty() {
1450 function getArgument( $name ) {
1455 * Returns true if the infinite loop check is OK, false if a loop is detected
1457 * @param Title $title
1460 function loopCheck( $title ) {
1461 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1465 * Return true if the frame is a template frame
1469 function isTemplate() {
1474 * Get a title of frame
1478 function getTitle() {
1479 return $this->title
;
1484 * Expansion frame with template arguments
1487 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1488 /** @var PPFrame_DOM */
1492 protected $numberedArgs;
1495 protected $namedArgs;
1498 protected $numberedExpansionCache;
1500 /** @var string[] */
1501 protected $namedExpansionCache;
1504 * @param Preprocessor $preprocessor
1505 * @param bool|PPFrame_DOM $parent
1506 * @param array $numberedArgs
1507 * @param array $namedArgs
1508 * @param bool|Title $title
1510 function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1511 $namedArgs = array(), $title = false
1513 parent
::__construct( $preprocessor );
1515 $this->parent
= $parent;
1516 $this->numberedArgs
= $numberedArgs;
1517 $this->namedArgs
= $namedArgs;
1518 $this->title
= $title;
1519 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1520 $this->titleCache
= $parent->titleCache
;
1521 $this->titleCache
[] = $pdbk;
1522 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1523 if ( $pdbk !== false ) {
1524 $this->loopCheckHash
[$pdbk] = true;
1526 $this->depth
= $parent->depth +
1;
1527 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1530 function __toString() {
1533 $args = $this->numberedArgs +
$this->namedArgs
;
1534 foreach ( $args as $name => $value ) {
1540 $s .= "\"$name\":\"" .
1541 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1548 * Returns true if there are no arguments in this frame
1552 function isEmpty() {
1553 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1556 function getArguments() {
1557 $arguments = array();
1558 foreach ( array_merge(
1559 array_keys( $this->numberedArgs
),
1560 array_keys( $this->namedArgs
) ) as $key ) {
1561 $arguments[$key] = $this->getArgument( $key );
1566 function getNumberedArguments() {
1567 $arguments = array();
1568 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1569 $arguments[$key] = $this->getArgument( $key );
1574 function getNamedArguments() {
1575 $arguments = array();
1576 foreach ( array_keys( $this->namedArgs
) as $key ) {
1577 $arguments[$key] = $this->getArgument( $key );
1582 function getNumberedArgument( $index ) {
1583 if ( !isset( $this->numberedArgs
[$index] ) ) {
1586 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1587 # No trimming for unnamed arguments
1588 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1589 $this->numberedArgs
[$index],
1590 PPFrame
::STRIP_COMMENTS
1593 return $this->numberedExpansionCache
[$index];
1596 function getNamedArgument( $name ) {
1597 if ( !isset( $this->namedArgs
[$name] ) ) {
1600 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1601 # Trim named arguments post-expand, for backwards compatibility
1602 $this->namedExpansionCache
[$name] = trim(
1603 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1605 return $this->namedExpansionCache
[$name];
1608 function getArgument( $name ) {
1609 $text = $this->getNumberedArgument( $name );
1610 if ( $text === false ) {
1611 $text = $this->getNamedArgument( $name );
1617 * Return true if the frame is a template frame
1621 function isTemplate() {
1627 * Expansion frame with custom arguments
1630 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1633 function __construct( $preprocessor, $args ) {
1634 parent
::__construct( $preprocessor );
1635 $this->args
= $args;
1638 function __toString() {
1641 foreach ( $this->args
as $name => $value ) {
1647 $s .= "\"$name\":\"" .
1648 str_replace( '"', '\\"', $value->__toString() ) . '"';
1657 function isEmpty() {
1658 return !count( $this->args
);
1661 function getArgument( $index ) {
1662 if ( !isset( $this->args
[$index] ) ) {
1665 return $this->args
[$index];
1668 function getArguments() {
1676 class PPNode_DOM
implements PPNode
{
1677 /** @var DOMElement */
1680 /** @var DOMXPath */
1683 function __construct( $node, $xpath = false ) {
1684 $this->node
= $node;
1690 function getXPath() {
1691 if ( $this->xpath
=== null ) {
1692 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1694 return $this->xpath
;
1697 function __toString() {
1698 if ( $this->node
instanceof DOMNodeList
) {
1700 foreach ( $this->node
as $node ) {
1701 $s .= $node->ownerDocument
->saveXML( $node );
1704 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1710 * @return bool|PPNode_DOM
1712 function getChildren() {
1713 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1717 * @return bool|PPNode_DOM
1719 function getFirstChild() {
1720 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1724 * @return bool|PPNode_DOM
1726 function getNextSibling() {
1727 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1731 * @param string $type
1733 * @return bool|PPNode_DOM
1735 function getChildrenOfType( $type ) {
1736 return new self( $this->getXPath()->query( $type, $this->node
) );
1742 function getLength() {
1743 if ( $this->node
instanceof DOMNodeList
) {
1744 return $this->node
->length
;
1752 * @return bool|PPNode_DOM
1754 function item( $i ) {
1755 $item = $this->node
->item( $i );
1756 return $item ?
new self( $item ) : false;
1762 function getName() {
1763 if ( $this->node
instanceof DOMNodeList
) {
1766 return $this->node
->nodeName
;
1771 * Split a "<part>" node into an associative array containing:
1772 * - name PPNode name
1773 * - index String index
1774 * - value PPNode value
1776 * @throws MWException
1779 function splitArg() {
1780 $xpath = $this->getXPath();
1781 $names = $xpath->query( 'name', $this->node
);
1782 $values = $xpath->query( 'value', $this->node
);
1783 if ( !$names->length ||
!$values->length
) {
1784 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1786 $name = $names->item( 0 );
1787 $index = $name->getAttribute( 'index' );
1789 'name' => new self( $name ),
1791 'value' => new self( $values->item( 0 ) ) );
1795 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1796 * All values in the resulting array are PPNodes. Inner and close are optional.
1798 * @throws MWException
1801 function splitExt() {
1802 $xpath = $this->getXPath();
1803 $names = $xpath->query( 'name', $this->node
);
1804 $attrs = $xpath->query( 'attr', $this->node
);
1805 $inners = $xpath->query( 'inner', $this->node
);
1806 $closes = $xpath->query( 'close', $this->node
);
1807 if ( !$names->length ||
!$attrs->length
) {
1808 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1811 'name' => new self( $names->item( 0 ) ),
1812 'attr' => new self( $attrs->item( 0 ) ) );
1813 if ( $inners->length
) {
1814 $parts['inner'] = new self( $inners->item( 0 ) );
1816 if ( $closes->length
) {
1817 $parts['close'] = new self( $closes->item( 0 ) );
1823 * Split a "<h>" node
1824 * @throws MWException
1827 function splitHeading() {
1828 if ( $this->getName() !== 'h' ) {
1829 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1832 'i' => $this->node
->getAttribute( 'i' ),
1833 'level' => $this->node
->getAttribute( 'level' ),
1834 'contents' => $this->getChildren()