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.
912 * @param bool|int $openingCount
915 function breakSyntax( $openingCount = false ) {
916 if ( $this->open
== "\n" ) {
917 $s = $this->parts
[0]->out
;
919 if ( $openingCount === false ) {
920 $openingCount = $this->count
;
922 $s = str_repeat( $this->open
, $openingCount );
924 foreach ( $this->parts
as $part ) {
944 // Optional member variables:
945 // eqpos Position of equals sign in output accumulator
946 // commentEnd Past-the-end input pointer for the last comment encountered
947 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
949 function __construct( $out = '' ) {
955 * An expansion frame, used as a context to expand the result of preprocessToObj()
958 class PPFrame_DOM
implements PPFrame
{
963 * @var array Hashtable listing templates which are disallowed for expansion
964 * in this frame, having been encountered previously in parent frames.
966 public $loopCheckHash;
969 * @var int Recursion depth of this frame, top = 0.
970 * Note that this is NOT the same as expansion depth in expand()
974 /** @var Preprocessor */
975 protected $preprocessor;
984 * Construct a new preprocessor frame.
985 * @param Preprocessor $preprocessor The parent preprocessor
987 function __construct( $preprocessor ) {
988 $this->preprocessor
= $preprocessor;
989 $this->parser
= $preprocessor->parser
;
990 $this->title
= $this->parser
->mTitle
;
991 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
992 $this->loopCheckHash
= array();
997 * Create a new child frame
998 * $args is optionally a multi-root PPNode or array containing the template arguments
1000 * @param bool|array $args
1001 * @param Title|bool $title
1002 * @param int $indexOffset
1003 * @return PPTemplateFrame_DOM
1005 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1006 $namedArgs = array();
1007 $numberedArgs = array();
1008 if ( $title === false ) {
1009 $title = $this->title
;
1011 if ( $args !== false ) {
1013 if ( $args instanceof PPNode
) {
1014 $args = $args->node
;
1016 foreach ( $args as $arg ) {
1017 if ( $arg instanceof PPNode
) {
1021 $xpath = new DOMXPath( $arg->ownerDocument
);
1024 $nameNodes = $xpath->query( 'name', $arg );
1025 $value = $xpath->query( 'value', $arg );
1026 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1027 // Numbered parameter
1028 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1029 $index = $index - $indexOffset;
1030 $numberedArgs[$index] = $value->item( 0 );
1031 unset( $namedArgs[$index] );
1034 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1035 $namedArgs[$name] = $value->item( 0 );
1036 unset( $numberedArgs[$name] );
1040 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1044 * @throws MWException
1045 * @param string|PPNode_DOM|DOMDocument $root
1049 function expand( $root, $flags = 0 ) {
1050 static $expansionDepth = 0;
1051 if ( is_string( $root ) ) {
1055 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1056 $this->parser
->limitationWarn( 'node-count-exceeded',
1057 $this->parser
->mPPNodeCount
,
1058 $this->parser
->mOptions
->getMaxPPNodeCount()
1060 return '<span class="error">Node-count limit exceeded</span>';
1063 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1064 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1066 $this->parser
->mOptions
->getMaxPPExpandDepth()
1068 return '<span class="error">Expansion depth limit exceeded</span>';
1070 wfProfileIn( __METHOD__
);
1072 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1073 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1076 if ( $root instanceof PPNode_DOM
) {
1077 $root = $root->node
;
1079 if ( $root instanceof DOMDocument
) {
1080 $root = $root->documentElement
;
1083 $outStack = array( '', '' );
1084 $iteratorStack = array( false, $root );
1085 $indexStack = array( 0, 0 );
1087 while ( count( $iteratorStack ) > 1 ) {
1088 $level = count( $outStack ) - 1;
1089 $iteratorNode =& $iteratorStack[$level];
1090 $out =& $outStack[$level];
1091 $index =& $indexStack[$level];
1093 if ( $iteratorNode instanceof PPNode_DOM
) {
1094 $iteratorNode = $iteratorNode->node
;
1097 if ( is_array( $iteratorNode ) ) {
1098 if ( $index >= count( $iteratorNode ) ) {
1099 // All done with this iterator
1100 $iteratorStack[$level] = false;
1101 $contextNode = false;
1103 $contextNode = $iteratorNode[$index];
1106 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1107 if ( $index >= $iteratorNode->length
) {
1108 // All done with this iterator
1109 $iteratorStack[$level] = false;
1110 $contextNode = false;
1112 $contextNode = $iteratorNode->item( $index );
1116 // Copy to $contextNode and then delete from iterator stack,
1117 // because this is not an iterator but we do have to execute it once
1118 $contextNode = $iteratorStack[$level];
1119 $iteratorStack[$level] = false;
1122 if ( $contextNode instanceof PPNode_DOM
) {
1123 $contextNode = $contextNode->node
;
1126 $newIterator = false;
1128 if ( $contextNode === false ) {
1130 } elseif ( is_string( $contextNode ) ) {
1131 $out .= $contextNode;
1132 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1133 $newIterator = $contextNode;
1134 } elseif ( $contextNode instanceof DOMNode
) {
1135 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1136 $out .= $contextNode->nodeValue
;
1137 } elseif ( $contextNode->nodeName
== 'template' ) {
1138 # Double-brace expansion
1139 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1140 $titles = $xpath->query( 'title', $contextNode );
1141 $title = $titles->item( 0 );
1142 $parts = $xpath->query( 'part', $contextNode );
1143 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1144 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1146 $lineStart = $contextNode->getAttribute( 'lineStart' );
1148 'title' => new PPNode_DOM( $title ),
1149 'parts' => new PPNode_DOM( $parts ),
1150 'lineStart' => $lineStart );
1151 $ret = $this->parser
->braceSubstitution( $params, $this );
1152 if ( isset( $ret['object'] ) ) {
1153 $newIterator = $ret['object'];
1155 $out .= $ret['text'];
1158 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1159 # Triple-brace expansion
1160 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1161 $titles = $xpath->query( 'title', $contextNode );
1162 $title = $titles->item( 0 );
1163 $parts = $xpath->query( 'part', $contextNode );
1164 if ( $flags & PPFrame
::NO_ARGS
) {
1165 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1168 'title' => new PPNode_DOM( $title ),
1169 'parts' => new PPNode_DOM( $parts ) );
1170 $ret = $this->parser
->argSubstitution( $params, $this );
1171 if ( isset( $ret['object'] ) ) {
1172 $newIterator = $ret['object'];
1174 $out .= $ret['text'];
1177 } elseif ( $contextNode->nodeName
== 'comment' ) {
1178 # HTML-style comment
1179 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1180 if ( $this->parser
->ot
['html']
1181 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1182 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1185 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1186 # Add a strip marker in PST mode so that pstPass2() can
1187 # run some old-fashioned regexes on the result.
1188 # Not in RECOVER_COMMENTS mode (extractSections) though.
1189 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1191 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1192 $out .= $contextNode->textContent
;
1194 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1195 # Output suppression used by <includeonly> etc.
1196 # OT_WIKI will only respect <ignore> in substed templates.
1197 # The other output types respect it unless NO_IGNORE is set.
1198 # extractSections() sets NO_IGNORE and so never respects it.
1199 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1200 ||
( $flags & PPFrame
::NO_IGNORE
)
1202 $out .= $contextNode->textContent
;
1206 } elseif ( $contextNode->nodeName
== 'ext' ) {
1208 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1209 $names = $xpath->query( 'name', $contextNode );
1210 $attrs = $xpath->query( 'attr', $contextNode );
1211 $inners = $xpath->query( 'inner', $contextNode );
1212 $closes = $xpath->query( 'close', $contextNode );
1214 'name' => new PPNode_DOM( $names->item( 0 ) ),
1215 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1216 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1217 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1219 $out .= $this->parser
->extensionSubstitution( $params, $this );
1220 } elseif ( $contextNode->nodeName
== 'h' ) {
1222 $s = $this->expand( $contextNode->childNodes
, $flags );
1224 # Insert a heading marker only for <h> children of <root>
1225 # This is to stop extractSections from going over multiple tree levels
1226 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1227 # Insert heading index marker
1228 $headingIndex = $contextNode->getAttribute( 'i' );
1229 $titleText = $this->title
->getPrefixedDBkey();
1230 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1231 $serial = count( $this->parser
->mHeadings
) - 1;
1232 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1233 $count = $contextNode->getAttribute( 'level' );
1234 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1235 $this->parser
->mStripState
->addGeneral( $marker, '' );
1239 # Generic recursive expansion
1240 $newIterator = $contextNode->childNodes
;
1243 wfProfileOut( __METHOD__
);
1244 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1247 if ( $newIterator !== false ) {
1248 if ( $newIterator instanceof PPNode_DOM
) {
1249 $newIterator = $newIterator->node
;
1252 $iteratorStack[] = $newIterator;
1254 } elseif ( $iteratorStack[$level] === false ) {
1255 // Return accumulated value to parent
1256 // With tail recursion
1257 while ( $iteratorStack[$level] === false && $level > 0 ) {
1258 $outStack[$level - 1] .= $out;
1259 array_pop( $outStack );
1260 array_pop( $iteratorStack );
1261 array_pop( $indexStack );
1267 wfProfileOut( __METHOD__
);
1268 return $outStack[0];
1272 * @param string $sep
1276 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1277 $args = array_slice( func_get_args(), 2 );
1281 foreach ( $args as $root ) {
1282 if ( $root instanceof PPNode_DOM
) {
1283 $root = $root->node
;
1285 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1286 $root = array( $root );
1288 foreach ( $root as $node ) {
1294 $s .= $this->expand( $node, $flags );
1301 * Implode with no flags specified
1302 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1304 * @param string $sep
1307 function implode( $sep /*, ... */ ) {
1308 $args = array_slice( func_get_args(), 1 );
1312 foreach ( $args as $root ) {
1313 if ( $root instanceof PPNode_DOM
) {
1314 $root = $root->node
;
1316 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1317 $root = array( $root );
1319 foreach ( $root as $node ) {
1325 $s .= $this->expand( $node );
1332 * Makes an object that, when expand()ed, will be the same as one obtained
1335 * @param string $sep
1338 function virtualImplode( $sep /*, ... */ ) {
1339 $args = array_slice( func_get_args(), 1 );
1343 foreach ( $args as $root ) {
1344 if ( $root instanceof PPNode_DOM
) {
1345 $root = $root->node
;
1347 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1348 $root = array( $root );
1350 foreach ( $root as $node ) {
1363 * Virtual implode with brackets
1364 * @param string $start
1365 * @param string $sep
1366 * @param string $end
1369 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1370 $args = array_slice( func_get_args(), 3 );
1371 $out = array( $start );
1374 foreach ( $args as $root ) {
1375 if ( $root instanceof PPNode_DOM
) {
1376 $root = $root->node
;
1378 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1379 $root = array( $root );
1381 foreach ( $root as $node ) {
1394 function __toString() {
1398 function getPDBK( $level = false ) {
1399 if ( $level === false ) {
1400 return $this->title
->getPrefixedDBkey();
1402 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1409 function getArguments() {
1416 function getNumberedArguments() {
1423 function getNamedArguments() {
1428 * Returns true if there are no arguments in this frame
1432 function isEmpty() {
1436 function getArgument( $name ) {
1441 * Returns true if the infinite loop check is OK, false if a loop is detected
1443 * @param Title $title
1446 function loopCheck( $title ) {
1447 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1451 * Return true if the frame is a template frame
1455 function isTemplate() {
1460 * Get a title of frame
1464 function getTitle() {
1465 return $this->title
;
1470 * Expansion frame with template arguments
1473 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1474 /** @var PPFrame_DOM */
1478 protected $numberedArgs;
1481 protected $namedArgs;
1484 protected $numberedExpansionCache;
1486 /** @var string[] */
1487 protected $namedExpansionCache;
1490 * @param Preprocessor $preprocessor
1491 * @param bool|PPFrame_DOM $parent
1492 * @param array $numberedArgs
1493 * @param array $namedArgs
1494 * @param bool|Title $title
1496 function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1497 $namedArgs = array(), $title = false
1499 parent
::__construct( $preprocessor );
1501 $this->parent
= $parent;
1502 $this->numberedArgs
= $numberedArgs;
1503 $this->namedArgs
= $namedArgs;
1504 $this->title
= $title;
1505 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1506 $this->titleCache
= $parent->titleCache
;
1507 $this->titleCache
[] = $pdbk;
1508 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1509 if ( $pdbk !== false ) {
1510 $this->loopCheckHash
[$pdbk] = true;
1512 $this->depth
= $parent->depth +
1;
1513 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1516 function __toString() {
1519 $args = $this->numberedArgs +
$this->namedArgs
;
1520 foreach ( $args as $name => $value ) {
1526 $s .= "\"$name\":\"" .
1527 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1534 * Returns true if there are no arguments in this frame
1538 function isEmpty() {
1539 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1542 function getArguments() {
1543 $arguments = array();
1544 foreach ( array_merge(
1545 array_keys( $this->numberedArgs
),
1546 array_keys( $this->namedArgs
) ) as $key ) {
1547 $arguments[$key] = $this->getArgument( $key );
1552 function getNumberedArguments() {
1553 $arguments = array();
1554 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1555 $arguments[$key] = $this->getArgument( $key );
1560 function getNamedArguments() {
1561 $arguments = array();
1562 foreach ( array_keys( $this->namedArgs
) as $key ) {
1563 $arguments[$key] = $this->getArgument( $key );
1568 function getNumberedArgument( $index ) {
1569 if ( !isset( $this->numberedArgs
[$index] ) ) {
1572 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1573 # No trimming for unnamed arguments
1574 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1575 $this->numberedArgs
[$index],
1576 PPFrame
::STRIP_COMMENTS
1579 return $this->numberedExpansionCache
[$index];
1582 function getNamedArgument( $name ) {
1583 if ( !isset( $this->namedArgs
[$name] ) ) {
1586 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1587 # Trim named arguments post-expand, for backwards compatibility
1588 $this->namedExpansionCache
[$name] = trim(
1589 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1591 return $this->namedExpansionCache
[$name];
1594 function getArgument( $name ) {
1595 $text = $this->getNumberedArgument( $name );
1596 if ( $text === false ) {
1597 $text = $this->getNamedArgument( $name );
1603 * Return true if the frame is a template frame
1607 function isTemplate() {
1613 * Expansion frame with custom arguments
1616 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1619 function __construct( $preprocessor, $args ) {
1620 parent
::__construct( $preprocessor );
1621 $this->args
= $args;
1624 function __toString() {
1627 foreach ( $this->args
as $name => $value ) {
1633 $s .= "\"$name\":\"" .
1634 str_replace( '"', '\\"', $value->__toString() ) . '"';
1643 function isEmpty() {
1644 return !count( $this->args
);
1647 function getArgument( $index ) {
1648 if ( !isset( $this->args
[$index] ) ) {
1651 return $this->args
[$index];
1654 function getArguments() {
1662 class PPNode_DOM
implements PPNode
{
1663 /** @var DOMElement */
1666 /** @var DOMXPath */
1669 function __construct( $node, $xpath = false ) {
1670 $this->node
= $node;
1676 function getXPath() {
1677 if ( $this->xpath
=== null ) {
1678 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1680 return $this->xpath
;
1683 function __toString() {
1684 if ( $this->node
instanceof DOMNodeList
) {
1686 foreach ( $this->node
as $node ) {
1687 $s .= $node->ownerDocument
->saveXML( $node );
1690 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1696 * @return bool|PPNode_DOM
1698 function getChildren() {
1699 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1703 * @return bool|PPNode_DOM
1705 function getFirstChild() {
1706 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1710 * @return bool|PPNode_DOM
1712 function getNextSibling() {
1713 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1717 * @param string $type
1719 * @return bool|PPNode_DOM
1721 function getChildrenOfType( $type ) {
1722 return new self( $this->getXPath()->query( $type, $this->node
) );
1728 function getLength() {
1729 if ( $this->node
instanceof DOMNodeList
) {
1730 return $this->node
->length
;
1738 * @return bool|PPNode_DOM
1740 function item( $i ) {
1741 $item = $this->node
->item( $i );
1742 return $item ?
new self( $item ) : false;
1748 function getName() {
1749 if ( $this->node
instanceof DOMNodeList
) {
1752 return $this->node
->nodeName
;
1757 * Split a "<part>" node into an associative array containing:
1758 * - name PPNode name
1759 * - index String index
1760 * - value PPNode value
1762 * @throws MWException
1765 function splitArg() {
1766 $xpath = $this->getXPath();
1767 $names = $xpath->query( 'name', $this->node
);
1768 $values = $xpath->query( 'value', $this->node
);
1769 if ( !$names->length ||
!$values->length
) {
1770 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1772 $name = $names->item( 0 );
1773 $index = $name->getAttribute( 'index' );
1775 'name' => new self( $name ),
1777 'value' => new self( $values->item( 0 ) ) );
1781 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1782 * All values in the resulting array are PPNodes. Inner and close are optional.
1784 * @throws MWException
1787 function splitExt() {
1788 $xpath = $this->getXPath();
1789 $names = $xpath->query( 'name', $this->node
);
1790 $attrs = $xpath->query( 'attr', $this->node
);
1791 $inners = $xpath->query( 'inner', $this->node
);
1792 $closes = $xpath->query( 'close', $this->node
);
1793 if ( !$names->length ||
!$attrs->length
) {
1794 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1797 'name' => new self( $names->item( 0 ) ),
1798 'attr' => new self( $attrs->item( 0 ) ) );
1799 if ( $inners->length
) {
1800 $parts['inner'] = new self( $inners->item( 0 ) );
1802 if ( $closes->length
) {
1803 $parts['close'] = new self( $closes->item( 0 ) );
1809 * Split a "<h>" node
1810 * @throws MWException
1813 function splitHeading() {
1814 if ( $this->getName() !== 'h' ) {
1815 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1818 'i' => $this->node
->getAttribute( 'i' ),
1819 'level' => $this->node
->getAttribute( 'level' ),
1820 'contents' => $this->getChildren()