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 $dom = new DOMDocument();
84 $dom->loadXML( $xml );
85 $root = $dom->documentElement
;
87 $node = new PPNode_DOM( $root->childNodes
);
96 if ( $this->memoryLimit
=== false ) {
99 $usage = memory_get_usage();
100 if ( $usage > $this->memoryLimit
* 0.9 ) {
101 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
102 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
104 return $usage <= $this->memoryLimit
* 0.8;
108 * Preprocess some wikitext and return the document tree.
109 * This is the ghost of Parser::replace_variables().
111 * @param string $text The text to parse
112 * @param int $flags Bitwise combination of:
113 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
114 * as if the text is being included. Default
115 * 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 );
163 // Fail if the number of elements exceeds acceptable limits
164 // Do not attempt to generate the DOM
165 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
166 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
167 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
169 wfProfileOut( __METHOD__
. '-cacheable' );
171 wfProfileOut( __METHOD__
);
172 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
175 wfProfileIn( __METHOD__
. '-loadXML' );
176 $dom = new DOMDocument
;
177 wfSuppressWarnings();
178 $result = $dom->loadXML( $xml );
181 // Try running the XML through UtfNormal to get rid of invalid characters
182 $xml = UtfNormal
::cleanUp( $xml );
183 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
184 // don't barf when the XML is >256 levels deep.
185 $result = $dom->loadXML( $xml, 1 << 19 );
188 $obj = new PPNode_DOM( $dom->documentElement
);
190 wfProfileOut( __METHOD__
. '-loadXML' );
193 wfProfileOut( __METHOD__
. '-cacheable' );
196 wfProfileOut( __METHOD__
);
199 throw new MWException( __METHOD__
. ' generated invalid XML' );
205 * @param string $text
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
238 && 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 // For fast reverse searches
256 $revText = strrev( $text );
257 $lengthText = strlen( $text );
259 // Input pointer, starts out pointing to a pseudo-newline before the start
261 // Current accumulator
262 $accum =& $stack->getAccum();
264 // True to find equals signs in arguments
266 // True to take notice of pipe characters
269 // True if $i is inside a possible heading
271 // True if there are no more greater-than (>) signs right of $i
273 // True to ignore all input up to the next <onlyinclude>
274 $findOnlyinclude = $enableOnlyinclude;
275 // Do a line-start run without outputting an LF character
276 $fakeLineStart = true;
281 if ( $findOnlyinclude ) {
282 // Ignore all input up to the next <onlyinclude>
283 $startPos = strpos( $text, '<onlyinclude>', $i );
284 if ( $startPos === false ) {
285 // Ignored section runs to the end
286 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
289 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
290 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
292 $findOnlyinclude = false;
295 if ( $fakeLineStart ) {
296 $found = 'line-start';
299 # Find next opening brace, closing brace or pipe
300 $search = $searchBase;
301 if ( $stack->top
=== false ) {
302 $currentClosing = '';
304 $currentClosing = $stack->top
->close
;
305 $search .= $currentClosing;
311 // First equals will be for the template
315 # Output literal section, advance input counter
316 $literalLength = strcspn( $text, $search, $i );
317 if ( $literalLength > 0 ) {
318 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
319 $i +
= $literalLength;
321 if ( $i >= $lengthText ) {
322 if ( $currentClosing == "\n" ) {
323 // Do a past-the-end run to finish off the heading
331 $curChar = $text[$i];
332 if ( $curChar == '|' ) {
334 } elseif ( $curChar == '=' ) {
336 } elseif ( $curChar == '<' ) {
338 } elseif ( $curChar == "\n" ) {
342 $found = 'line-start';
344 } elseif ( $curChar == $currentClosing ) {
346 } elseif ( isset( $rules[$curChar] ) ) {
348 $rule = $rules[$curChar];
350 # Some versions of PHP have a strcspn which stops on null characters
351 # Ignore and continue
358 if ( $found == 'angle' ) {
360 // Handle </onlyinclude>
361 if ( $enableOnlyinclude
362 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
364 $findOnlyinclude = true;
368 // Determine element name
369 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
370 // Element name missing or not listed
376 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
378 // To avoid leaving blank lines, when a sequence of
379 // space-separated comments is both preceded and followed by
380 // a newline (ignoring spaces), then
381 // trim leading and trailing spaces and the trailing newline.
384 $endPos = strpos( $text, '-->', $i +
4 );
385 if ( $endPos === false ) {
386 // Unclosed comment in input, runs to end
387 $inner = substr( $text, $i );
388 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
391 // Search backwards for leading whitespace
392 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
394 // Search forwards for trailing whitespace
395 // $wsEnd will be the position of the last space (or the '>' if there's none)
396 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
398 // Keep looking forward as long as we're finding more
400 $comments = array( array( $wsStart, $wsEnd ) );
401 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
402 $c = strpos( $text, '-->', $wsEnd +
4 );
403 if ( $c === false ) {
406 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
407 $comments[] = array( $wsEnd +
1, $c );
411 // Eat the line if possible
412 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
413 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
414 // it's a possible beneficial b/c break.
415 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
416 && substr( $text, $wsEnd +
1, 1 ) == "\n"
418 // Remove leading whitespace from the end of the accumulator
419 // Sanity check first though
420 $wsLength = $i - $wsStart;
422 && strspn( $accum, " \t", -$wsLength ) === $wsLength
424 $accum = substr( $accum, 0, -$wsLength );
427 // Dump all but the last comment to the accumulator
428 foreach ( $comments as $j => $com ) {
430 $endPos = $com[1] +
1;
431 if ( $j == ( count( $comments ) - 1 ) ) {
434 $inner = substr( $text, $startPos, $endPos - $startPos );
435 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
438 // Do a line-start run next time to look for headings after the comment
439 $fakeLineStart = true;
441 // No line to eat, just take the comment itself
447 $part = $stack->top
->getCurrentPart();
448 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
449 $part->visualEnd
= $wsStart;
451 // Else comments abutting, no change in visual end
452 $part->commentEnd
= $endPos;
455 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
456 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
461 $lowerName = strtolower( $name );
462 $attrStart = $i +
strlen( $name ) +
1;
465 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
466 if ( $tagEndPos === false ) {
467 // Infinite backtrack
468 // Disable tag search to prevent worst-case O(N^2) performance
475 // Handle ignored tags
476 if ( in_array( $lowerName, $ignoredTags ) ) {
478 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
485 if ( $text[$tagEndPos - 1] == '/' ) {
486 $attrEnd = $tagEndPos - 1;
491 $attrEnd = $tagEndPos;
493 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
494 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
496 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
497 $i = $matches[0][1] +
strlen( $matches[0][0] );
498 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
500 // No end tag -- let it run out to the end of the text.
501 $inner = substr( $text, $tagEndPos +
1 );
506 // <includeonly> and <noinclude> just become <ignore> tags
507 if ( in_array( $lowerName, $ignoredElements ) ) {
508 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
514 if ( $attrEnd <= $attrStart ) {
517 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
519 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
520 // Note that the attr element contains the whitespace between name and attribute,
521 // this is necessary for precise reconstruction during pre-save transform.
522 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
523 if ( $inner !== null ) {
524 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
526 $accum .= $close . '</ext>';
527 } elseif ( $found == 'line-start' ) {
528 // Is this the start of a heading?
529 // Line break belongs before the heading element in any case
530 if ( $fakeLineStart ) {
531 $fakeLineStart = false;
537 $count = strspn( $text, '=', $i, 6 );
538 if ( $count == 1 && $findEquals ) {
539 // DWIM: This looks kind of like a name/value separator.
540 // Let's let the equals handler have it and break the
541 // potential heading. This is heuristic, but AFAICT the
542 // methods for completely correct disambiguation are very
544 } elseif ( $count > 0 ) {
548 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
551 $stack->push( $piece );
552 $accum =& $stack->getAccum();
553 $flags = $stack->getFlags();
557 } elseif ( $found == 'line-end' ) {
558 $piece = $stack->top
;
559 // A heading must be open, otherwise \n wouldn't have been in the search list
560 assert( '$piece->open == "\n"' );
561 $part = $piece->getCurrentPart();
562 // Search back through the input to see if it has a proper close.
563 // Do this using the reversed string since the other solutions
564 // (end anchor, etc.) are inefficient.
565 $wsLength = strspn( $revText, " \t", $lengthText - $i );
566 $searchStart = $i - $wsLength;
567 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
568 // Comment found at line end
569 // Search for equals signs before the comment
570 $searchStart = $part->visualEnd
;
571 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
573 $count = $piece->count
;
574 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
575 if ( $equalsLength > 0 ) {
576 if ( $searchStart - $equalsLength == $piece->startPos
) {
577 // This is just a single string of equals signs on its own line
578 // Replicate the doHeadings behavior /={count}(.+)={count}/
579 // First find out how many equals signs there really are (don't stop at 6)
580 $count = $equalsLength;
584 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
587 $count = min( $equalsLength, $count );
590 // Normal match, output <h>
591 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
594 // Single equals sign on its own line, count=0
598 // No match, no <h>, just pass down the inner text
603 $accum =& $stack->getAccum();
604 $flags = $stack->getFlags();
607 // Append the result to the enclosing accumulator
609 // Note that we do NOT increment the input pointer.
610 // This is because the closing linebreak could be the opening linebreak of
611 // another heading. Infinite loops are avoided because the next iteration MUST
612 // hit the heading open case above, which unconditionally increments the
614 } elseif ( $found == 'open' ) {
615 # count opening brace characters
616 $count = strspn( $text, $curChar, $i );
618 # we need to add to stack only if opening brace count is enough for one of the rules
619 if ( $count >= $rule['min'] ) {
620 # Add it to the stack
623 'close' => $rule['end'],
625 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
628 $stack->push( $piece );
629 $accum =& $stack->getAccum();
630 $flags = $stack->getFlags();
633 # Add literal brace(s)
634 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
637 } elseif ( $found == 'close' ) {
638 $piece = $stack->top
;
639 # lets check if there are enough characters for closing brace
640 $maxCount = $piece->count
;
641 $count = strspn( $text, $curChar, $i, $maxCount );
643 # check for maximum matching characters (if there are 5 closing
644 # characters, we will probably need only 3 - depending on the rules)
645 $rule = $rules[$piece->open
];
646 if ( $count > $rule['max'] ) {
647 # The specified maximum exists in the callback array, unless the caller
649 $matchingCount = $rule['max'];
651 # Count is less than the maximum
652 # Skip any gaps in the callback array to find the true largest match
653 # Need to use array_key_exists not isset because the callback can be null
654 $matchingCount = $count;
655 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
660 if ( $matchingCount <= 0 ) {
661 # No matching element found in callback array
662 # Output a literal closing brace and continue
663 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
667 $name = $rule['names'][$matchingCount];
668 if ( $name === null ) {
669 // No element, just literal text
670 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
673 # Note: $parts is already XML, does not need to be encoded further
674 $parts = $piece->parts
;
675 $title = $parts[0]->out
;
678 # The invocation is at the start of the line if lineStart is set in
679 # the stack, and all opening brackets are used up.
680 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
681 $attr = ' lineStart="1"';
686 $element = "<$name$attr>";
687 $element .= "<title>$title</title>";
689 foreach ( $parts as $part ) {
690 if ( isset( $part->eqpos
) ) {
691 $argName = substr( $part->out
, 0, $part->eqpos
);
692 $argValue = substr( $part->out
, $part->eqpos +
1 );
693 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
695 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
699 $element .= "</$name>";
702 # Advance input pointer
703 $i +
= $matchingCount;
707 $accum =& $stack->getAccum();
709 # Re-add the old stack element if it still has unmatched opening characters remaining
710 if ( $matchingCount < $piece->count
) {
711 $piece->parts
= array( new PPDPart
);
712 $piece->count
-= $matchingCount;
713 # do we still qualify for any callback with remaining count?
714 $min = $rules[$piece->open
]['min'];
715 if ( $piece->count
>= $min ) {
716 $stack->push( $piece );
717 $accum =& $stack->getAccum();
719 $accum .= str_repeat( $piece->open
, $piece->count
);
722 $flags = $stack->getFlags();
725 # Add XML element to the enclosing accumulator
727 } elseif ( $found == 'pipe' ) {
728 $findEquals = true; // shortcut for getFlags()
730 $accum =& $stack->getAccum();
732 } elseif ( $found == 'equals' ) {
733 $findEquals = false; // shortcut for getFlags()
734 $stack->getCurrentPart()->eqpos
= strlen( $accum );
740 # Output any remaining unclosed brackets
741 foreach ( $stack->stack
as $piece ) {
742 $stack->rootAccum
.= $piece->breakSyntax();
744 $stack->rootAccum
.= '</root>';
745 $xml = $stack->rootAccum
;
747 wfProfileOut( __METHOD__
);
754 * Stack class to help Preprocessor::preprocessToObj()
764 /** @var bool|PPDStack */
771 protected $elementClass = 'PPDStackElement';
773 protected static $false = false;
775 function __construct() {
776 $this->stack
= array();
778 $this->rootAccum
= '';
779 $this->accum
=& $this->rootAccum
;
786 return count( $this->stack
);
789 function &getAccum() {
793 function getCurrentPart() {
794 if ( $this->top
=== false ) {
797 return $this->top
->getCurrentPart();
801 function push( $data ) {
802 if ( $data instanceof $this->elementClass
) {
803 $this->stack
[] = $data;
805 $class = $this->elementClass
;
806 $this->stack
[] = new $class( $data );
808 $this->top
= $this->stack
[count( $this->stack
) - 1];
809 $this->accum
=& $this->top
->getAccum();
813 if ( !count( $this->stack
) ) {
814 throw new MWException( __METHOD__
. ': no elements remaining' );
816 $temp = array_pop( $this->stack
);
818 if ( count( $this->stack
) ) {
819 $this->top
= $this->stack
[count( $this->stack
) - 1];
820 $this->accum
=& $this->top
->getAccum();
822 $this->top
= self
::$false;
823 $this->accum
=& $this->rootAccum
;
828 function addPart( $s = '' ) {
829 $this->top
->addPart( $s );
830 $this->accum
=& $this->top
->getAccum();
836 function getFlags() {
837 if ( !count( $this->stack
) ) {
839 'findEquals' => false,
841 'inHeading' => false,
844 return $this->top
->getFlags();
852 class PPDStackElement
{
853 /** @var string Opening character (\n for heading) */
856 /** @var string Matching closing character */
859 /** @var int Number of opening characters found (number of "=" for heading) */
862 /** @var array PPDPart objects describing pipe-separated parts. */
866 * @var bool True if the open char appeared at the start of the input line.
867 * Not set for headings.
872 protected $partClass = 'PPDPart';
874 function __construct( $data = array() ) {
875 $class = $this->partClass
;
876 $this->parts
= array( new $class );
878 foreach ( $data as $name => $value ) {
879 $this->$name = $value;
883 function &getAccum() {
884 return $this->parts
[count( $this->parts
) - 1]->out
;
887 function addPart( $s = '' ) {
888 $class = $this->partClass
;
889 $this->parts
[] = new $class( $s );
892 function getCurrentPart() {
893 return $this->parts
[count( $this->parts
) - 1];
899 function getFlags() {
900 $partCount = count( $this->parts
);
901 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
903 'findPipe' => $findPipe,
904 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
905 'inHeading' => $this->open
== "\n",
910 * Get the output string that would result if the close is not found.
914 function breakSyntax( $openingCount = false ) {
915 if ( $this->open
== "\n" ) {
916 $s = $this->parts
[0]->out
;
918 if ( $openingCount === false ) {
919 $openingCount = $this->count
;
921 $s = str_repeat( $this->open
, $openingCount );
923 foreach ( $this->parts
as $part ) {
943 // Optional member variables:
944 // eqpos Position of equals sign in output accumulator
945 // commentEnd Past-the-end input pointer for the last comment encountered
946 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
948 function __construct( $out = '' ) {
954 * An expansion frame, used as a context to expand the result of preprocessToObj()
957 class PPFrame_DOM
implements PPFrame
{
962 * @var array Hashtable listing templates which are disallowed for expansion
963 * in this frame, having been encountered previously in parent frames.
965 public $loopCheckHash;
968 * @var int Recursion depth of this frame, top = 0.
969 * Note that this is NOT the same as expansion depth in expand()
973 /** @var Preprocessor */
974 protected $preprocessor;
983 * Construct a new preprocessor frame.
984 * @param Preprocessor $preprocessor The parent preprocessor
986 function __construct( $preprocessor ) {
987 $this->preprocessor
= $preprocessor;
988 $this->parser
= $preprocessor->parser
;
989 $this->title
= $this->parser
->mTitle
;
990 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
991 $this->loopCheckHash
= array();
996 * Create a new child frame
997 * $args is optionally a multi-root PPNode or array containing the template arguments
999 * @param bool|array $args
1000 * @param Title|bool $title
1001 * @param int $indexOffset
1002 * @return PPTemplateFrame_DOM
1004 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1005 $namedArgs = array();
1006 $numberedArgs = array();
1007 if ( $title === false ) {
1008 $title = $this->title
;
1010 if ( $args !== false ) {
1012 if ( $args instanceof PPNode
) {
1013 $args = $args->node
;
1015 foreach ( $args as $arg ) {
1016 if ( $arg instanceof PPNode
) {
1020 $xpath = new DOMXPath( $arg->ownerDocument
);
1023 $nameNodes = $xpath->query( 'name', $arg );
1024 $value = $xpath->query( 'value', $arg );
1025 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1026 // Numbered parameter
1027 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1028 $index = $index - $indexOffset;
1029 $numberedArgs[$index] = $value->item( 0 );
1030 unset( $namedArgs[$index] );
1033 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1034 $namedArgs[$name] = $value->item( 0 );
1035 unset( $numberedArgs[$name] );
1039 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1043 * @throws MWException
1044 * @param string|PPNode_DOM|DOMDocument $root
1048 function expand( $root, $flags = 0 ) {
1049 static $expansionDepth = 0;
1050 if ( is_string( $root ) ) {
1054 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1055 $this->parser
->limitationWarn( 'node-count-exceeded',
1056 $this->parser
->mPPNodeCount
,
1057 $this->parser
->mOptions
->getMaxPPNodeCount()
1059 return '<span class="error">Node-count limit exceeded</span>';
1062 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1063 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1065 $this->parser
->mOptions
->getMaxPPExpandDepth()
1067 return '<span class="error">Expansion depth limit exceeded</span>';
1069 wfProfileIn( __METHOD__
);
1071 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1072 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1075 if ( $root instanceof PPNode_DOM
) {
1076 $root = $root->node
;
1078 if ( $root instanceof DOMDocument
) {
1079 $root = $root->documentElement
;
1082 $outStack = array( '', '' );
1083 $iteratorStack = array( false, $root );
1084 $indexStack = array( 0, 0 );
1086 while ( count( $iteratorStack ) > 1 ) {
1087 $level = count( $outStack ) - 1;
1088 $iteratorNode =& $iteratorStack[$level];
1089 $out =& $outStack[$level];
1090 $index =& $indexStack[$level];
1092 if ( $iteratorNode instanceof PPNode_DOM
) {
1093 $iteratorNode = $iteratorNode->node
;
1096 if ( is_array( $iteratorNode ) ) {
1097 if ( $index >= count( $iteratorNode ) ) {
1098 // All done with this iterator
1099 $iteratorStack[$level] = false;
1100 $contextNode = false;
1102 $contextNode = $iteratorNode[$index];
1105 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1106 if ( $index >= $iteratorNode->length
) {
1107 // All done with this iterator
1108 $iteratorStack[$level] = false;
1109 $contextNode = false;
1111 $contextNode = $iteratorNode->item( $index );
1115 // Copy to $contextNode and then delete from iterator stack,
1116 // because this is not an iterator but we do have to execute it once
1117 $contextNode = $iteratorStack[$level];
1118 $iteratorStack[$level] = false;
1121 if ( $contextNode instanceof PPNode_DOM
) {
1122 $contextNode = $contextNode->node
;
1125 $newIterator = false;
1127 if ( $contextNode === false ) {
1129 } elseif ( is_string( $contextNode ) ) {
1130 $out .= $contextNode;
1131 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1132 $newIterator = $contextNode;
1133 } elseif ( $contextNode instanceof DOMNode
) {
1134 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1135 $out .= $contextNode->nodeValue
;
1136 } elseif ( $contextNode->nodeName
== 'template' ) {
1137 # Double-brace expansion
1138 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1139 $titles = $xpath->query( 'title', $contextNode );
1140 $title = $titles->item( 0 );
1141 $parts = $xpath->query( 'part', $contextNode );
1142 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1143 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1145 $lineStart = $contextNode->getAttribute( 'lineStart' );
1147 'title' => new PPNode_DOM( $title ),
1148 'parts' => new PPNode_DOM( $parts ),
1149 'lineStart' => $lineStart );
1150 $ret = $this->parser
->braceSubstitution( $params, $this );
1151 if ( isset( $ret['object'] ) ) {
1152 $newIterator = $ret['object'];
1154 $out .= $ret['text'];
1157 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1158 # Triple-brace expansion
1159 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1160 $titles = $xpath->query( 'title', $contextNode );
1161 $title = $titles->item( 0 );
1162 $parts = $xpath->query( 'part', $contextNode );
1163 if ( $flags & PPFrame
::NO_ARGS
) {
1164 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1167 'title' => new PPNode_DOM( $title ),
1168 'parts' => new PPNode_DOM( $parts ) );
1169 $ret = $this->parser
->argSubstitution( $params, $this );
1170 if ( isset( $ret['object'] ) ) {
1171 $newIterator = $ret['object'];
1173 $out .= $ret['text'];
1176 } elseif ( $contextNode->nodeName
== 'comment' ) {
1177 # HTML-style comment
1178 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1179 if ( $this->parser
->ot
['html']
1180 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1181 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1184 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1185 # Add a strip marker in PST mode so that pstPass2() can
1186 # run some old-fashioned regexes on the result.
1187 # Not in RECOVER_COMMENTS mode (extractSections) though.
1188 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1190 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1191 $out .= $contextNode->textContent
;
1193 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1194 # Output suppression used by <includeonly> etc.
1195 # OT_WIKI will only respect <ignore> in substed templates.
1196 # The other output types respect it unless NO_IGNORE is set.
1197 # extractSections() sets NO_IGNORE and so never respects it.
1198 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1199 ||
( $flags & PPFrame
::NO_IGNORE
)
1201 $out .= $contextNode->textContent
;
1205 } elseif ( $contextNode->nodeName
== 'ext' ) {
1207 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1208 $names = $xpath->query( 'name', $contextNode );
1209 $attrs = $xpath->query( 'attr', $contextNode );
1210 $inners = $xpath->query( 'inner', $contextNode );
1211 $closes = $xpath->query( 'close', $contextNode );
1213 'name' => new PPNode_DOM( $names->item( 0 ) ),
1214 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1215 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1216 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1218 $out .= $this->parser
->extensionSubstitution( $params, $this );
1219 } elseif ( $contextNode->nodeName
== 'h' ) {
1221 $s = $this->expand( $contextNode->childNodes
, $flags );
1223 # Insert a heading marker only for <h> children of <root>
1224 # This is to stop extractSections from going over multiple tree levels
1225 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1226 # Insert heading index marker
1227 $headingIndex = $contextNode->getAttribute( 'i' );
1228 $titleText = $this->title
->getPrefixedDBkey();
1229 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1230 $serial = count( $this->parser
->mHeadings
) - 1;
1231 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1232 $count = $contextNode->getAttribute( 'level' );
1233 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1234 $this->parser
->mStripState
->addGeneral( $marker, '' );
1238 # Generic recursive expansion
1239 $newIterator = $contextNode->childNodes
;
1242 wfProfileOut( __METHOD__
);
1243 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1246 if ( $newIterator !== false ) {
1247 if ( $newIterator instanceof PPNode_DOM
) {
1248 $newIterator = $newIterator->node
;
1251 $iteratorStack[] = $newIterator;
1253 } elseif ( $iteratorStack[$level] === false ) {
1254 // Return accumulated value to parent
1255 // With tail recursion
1256 while ( $iteratorStack[$level] === false && $level > 0 ) {
1257 $outStack[$level - 1] .= $out;
1258 array_pop( $outStack );
1259 array_pop( $iteratorStack );
1260 array_pop( $indexStack );
1266 wfProfileOut( __METHOD__
);
1267 return $outStack[0];
1271 * @param string $sep
1275 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1276 $args = array_slice( func_get_args(), 2 );
1280 foreach ( $args as $root ) {
1281 if ( $root instanceof PPNode_DOM
) {
1282 $root = $root->node
;
1284 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1285 $root = array( $root );
1287 foreach ( $root as $node ) {
1293 $s .= $this->expand( $node, $flags );
1300 * Implode with no flags specified
1301 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1303 * @param string $sep
1306 function implode( $sep /*, ... */ ) {
1307 $args = array_slice( func_get_args(), 1 );
1311 foreach ( $args as $root ) {
1312 if ( $root instanceof PPNode_DOM
) {
1313 $root = $root->node
;
1315 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1316 $root = array( $root );
1318 foreach ( $root as $node ) {
1324 $s .= $this->expand( $node );
1331 * Makes an object that, when expand()ed, will be the same as one obtained
1334 * @param string $sep
1337 function virtualImplode( $sep /*, ... */ ) {
1338 $args = array_slice( func_get_args(), 1 );
1342 foreach ( $args as $root ) {
1343 if ( $root instanceof PPNode_DOM
) {
1344 $root = $root->node
;
1346 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1347 $root = array( $root );
1349 foreach ( $root as $node ) {
1362 * Virtual implode with brackets
1363 * @param string $start
1364 * @param string $sep
1365 * @param string $end
1368 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1369 $args = array_slice( func_get_args(), 3 );
1370 $out = array( $start );
1373 foreach ( $args as $root ) {
1374 if ( $root instanceof PPNode_DOM
) {
1375 $root = $root->node
;
1377 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1378 $root = array( $root );
1380 foreach ( $root as $node ) {
1393 function __toString() {
1397 function getPDBK( $level = false ) {
1398 if ( $level === false ) {
1399 return $this->title
->getPrefixedDBkey();
1401 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1408 function getArguments() {
1415 function getNumberedArguments() {
1422 function getNamedArguments() {
1427 * Returns true if there are no arguments in this frame
1431 function isEmpty() {
1435 function getArgument( $name ) {
1440 * Returns true if the infinite loop check is OK, false if a loop is detected
1442 * @param Title $title
1445 function loopCheck( $title ) {
1446 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1450 * Return true if the frame is a template frame
1454 function isTemplate() {
1459 * Get a title of frame
1463 function getTitle() {
1464 return $this->title
;
1469 * Expansion frame with template arguments
1472 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1473 /** @var PPFrame_DOM */
1477 protected $numberedArgs;
1480 protected $namedArgs;
1483 protected $numberedExpansionCache;
1485 /** @var string[] */
1486 protected $namedExpansionCache;
1489 * @param Preprocessor $preprocessor
1490 * @param PPFrame_DOM $parent
1491 * @param array $numberedArgs
1492 * @param array $namedArgs
1493 * @param Title $title
1495 function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1496 $namedArgs = array(), $title = false
1498 parent
::__construct( $preprocessor );
1500 $this->parent
= $parent;
1501 $this->numberedArgs
= $numberedArgs;
1502 $this->namedArgs
= $namedArgs;
1503 $this->title
= $title;
1504 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1505 $this->titleCache
= $parent->titleCache
;
1506 $this->titleCache
[] = $pdbk;
1507 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1508 if ( $pdbk !== false ) {
1509 $this->loopCheckHash
[$pdbk] = true;
1511 $this->depth
= $parent->depth +
1;
1512 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1515 function __toString() {
1518 $args = $this->numberedArgs +
$this->namedArgs
;
1519 foreach ( $args as $name => $value ) {
1525 $s .= "\"$name\":\"" .
1526 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1533 * Returns true if there are no arguments in this frame
1537 function isEmpty() {
1538 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1541 function getArguments() {
1542 $arguments = array();
1543 foreach ( array_merge(
1544 array_keys( $this->numberedArgs
),
1545 array_keys( $this->namedArgs
) ) as $key ) {
1546 $arguments[$key] = $this->getArgument( $key );
1551 function getNumberedArguments() {
1552 $arguments = array();
1553 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1554 $arguments[$key] = $this->getArgument( $key );
1559 function getNamedArguments() {
1560 $arguments = array();
1561 foreach ( array_keys( $this->namedArgs
) as $key ) {
1562 $arguments[$key] = $this->getArgument( $key );
1567 function getNumberedArgument( $index ) {
1568 if ( !isset( $this->numberedArgs
[$index] ) ) {
1571 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1572 # No trimming for unnamed arguments
1573 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1574 $this->numberedArgs
[$index],
1575 PPFrame
::STRIP_COMMENTS
1578 return $this->numberedExpansionCache
[$index];
1581 function getNamedArgument( $name ) {
1582 if ( !isset( $this->namedArgs
[$name] ) ) {
1585 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1586 # Trim named arguments post-expand, for backwards compatibility
1587 $this->namedExpansionCache
[$name] = trim(
1588 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1590 return $this->namedExpansionCache
[$name];
1593 function getArgument( $name ) {
1594 $text = $this->getNumberedArgument( $name );
1595 if ( $text === false ) {
1596 $text = $this->getNamedArgument( $name );
1602 * Return true if the frame is a template frame
1606 function isTemplate() {
1612 * Expansion frame with custom arguments
1615 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1618 function __construct( $preprocessor, $args ) {
1619 parent
::__construct( $preprocessor );
1620 $this->args
= $args;
1623 function __toString() {
1626 foreach ( $this->args
as $name => $value ) {
1632 $s .= "\"$name\":\"" .
1633 str_replace( '"', '\\"', $value->__toString() ) . '"';
1642 function isEmpty() {
1643 return !count( $this->args
);
1646 function getArgument( $index ) {
1647 if ( !isset( $this->args
[$index] ) ) {
1650 return $this->args
[$index];
1653 function getArguments() {
1661 class PPNode_DOM
implements PPNode
{
1662 /** @var DOMElement */
1665 /** @var DOMXPath */
1668 function __construct( $node, $xpath = false ) {
1669 $this->node
= $node;
1675 function getXPath() {
1676 if ( $this->xpath
=== null ) {
1677 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1679 return $this->xpath
;
1682 function __toString() {
1683 if ( $this->node
instanceof DOMNodeList
) {
1685 foreach ( $this->node
as $node ) {
1686 $s .= $node->ownerDocument
->saveXML( $node );
1689 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1695 * @return bool|PPNode_DOM
1697 function getChildren() {
1698 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1702 * @return bool|PPNode_DOM
1704 function getFirstChild() {
1705 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1709 * @return bool|PPNode_DOM
1711 function getNextSibling() {
1712 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1716 * @param string $type
1718 * @return bool|PPNode_DOM
1720 function getChildrenOfType( $type ) {
1721 return new self( $this->getXPath()->query( $type, $this->node
) );
1727 function getLength() {
1728 if ( $this->node
instanceof DOMNodeList
) {
1729 return $this->node
->length
;
1737 * @return bool|PPNode_DOM
1739 function item( $i ) {
1740 $item = $this->node
->item( $i );
1741 return $item ?
new self( $item ) : false;
1747 function getName() {
1748 if ( $this->node
instanceof DOMNodeList
) {
1751 return $this->node
->nodeName
;
1756 * Split a "<part>" node into an associative array containing:
1757 * - name PPNode name
1758 * - index String index
1759 * - value PPNode value
1761 * @throws MWException
1764 function splitArg() {
1765 $xpath = $this->getXPath();
1766 $names = $xpath->query( 'name', $this->node
);
1767 $values = $xpath->query( 'value', $this->node
);
1768 if ( !$names->length ||
!$values->length
) {
1769 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1771 $name = $names->item( 0 );
1772 $index = $name->getAttribute( 'index' );
1774 'name' => new self( $name ),
1776 'value' => new self( $values->item( 0 ) ) );
1780 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1781 * All values in the resulting array are PPNodes. Inner and close are optional.
1783 * @throws MWException
1786 function splitExt() {
1787 $xpath = $this->getXPath();
1788 $names = $xpath->query( 'name', $this->node
);
1789 $attrs = $xpath->query( 'attr', $this->node
);
1790 $inners = $xpath->query( 'inner', $this->node
);
1791 $closes = $xpath->query( 'close', $this->node
);
1792 if ( !$names->length ||
!$attrs->length
) {
1793 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1796 'name' => new self( $names->item( 0 ) ),
1797 'attr' => new self( $attrs->item( 0 ) ) );
1798 if ( $inners->length
) {
1799 $parts['inner'] = new self( $inners->item( 0 ) );
1801 if ( $closes->length
) {
1802 $parts['close'] = new self( $closes->item( 0 ) );
1808 * Split a "<h>" node
1809 * @throws MWException
1812 function splitHeading() {
1813 if ( $this->getName() !== 'h' ) {
1814 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1817 'i' => $this->node
->getAttribute( 'i' ),
1818 'level' => $this->node
->getAttribute( 'level' ),
1819 'contents' => $this->getChildren()