3 * Preprocessor using PHP's dom extension
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
27 class Preprocessor_DOM
implements Preprocessor
{
36 const CACHE_VERSION
= 1;
38 function __construct( $parser ) {
39 $this->parser
= $parser;
40 $mem = ini_get( 'memory_limit' );
41 $this->memoryLimit
= false;
42 if ( strval( $mem ) !== '' && $mem != -1 ) {
43 if ( preg_match( '/^\d+$/', $mem ) ) {
44 $this->memoryLimit
= $mem;
45 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
46 $this->memoryLimit
= $m[1] * 1048576;
55 return new PPFrame_DOM( $this );
60 * @return PPCustomFrame_DOM
62 function newCustomFrame( $args ) {
63 return new PPCustomFrame_DOM( $this, $args );
70 function newPartNodeArray( $values ) {
71 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
74 foreach ( $values as $k => $val ) {
77 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
79 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
85 $dom = new DOMDocument();
86 $dom->loadXML( $xml );
87 $root = $dom->documentElement
;
89 $node = new PPNode_DOM( $root->childNodes
);
98 if ( $this->memoryLimit
=== false ) {
101 $usage = memory_get_usage();
102 if ( $usage > $this->memoryLimit
* 0.9 ) {
103 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
104 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
106 return $usage <= $this->memoryLimit
* 0.8;
110 * Preprocess some wikitext and return the document tree.
111 * This is the ghost of Parser::replace_variables().
113 * @param $text String: the text to parse
114 * @param $flags Integer: bitwise combination of:
115 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
116 * included. Default is to assume a direct page view.
118 * The generated DOM tree must depend only on the input text and the flags.
119 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
121 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
122 * change in the DOM tree for a given text, must be passed through the section identifier
123 * in the section edit link and thus back to extractSections().
125 * The output of this function is currently only cached in process memory, but a persistent
126 * cache may be implemented at a later date which takes further advantage of these strict
127 * dependency requirements.
131 function preprocessToObj( $text, $flags = 0 ) {
132 wfProfileIn( __METHOD__
);
133 global $wgMemc, $wgPreprocessorCacheThreshold;
136 $cacheable = ( $wgPreprocessorCacheThreshold !== false
137 && strlen( $text ) > $wgPreprocessorCacheThreshold );
139 wfProfileIn( __METHOD__
.'-cacheable' );
141 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
142 $cacheValue = $wgMemc->get( $cacheKey );
144 $version = substr( $cacheValue, 0, 8 );
145 if ( intval( $version ) == self
::CACHE_VERSION
) {
146 $xml = substr( $cacheValue, 8 );
148 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
152 if ( $xml === false ) {
154 wfProfileIn( __METHOD__
.'-cache-miss' );
155 $xml = $this->preprocessToXml( $text, $flags );
156 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
157 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
158 wfProfileOut( __METHOD__
.'-cache-miss' );
159 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
161 $xml = $this->preprocessToXml( $text, $flags );
166 // Fail if the number of elements exceeds acceptable limits
167 // Do not attempt to generate the DOM
168 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
169 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
170 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
171 throw new MWException( __METHOD__
.': generated node count limit exceeded' );
174 wfProfileIn( __METHOD__
.'-loadXML' );
175 $dom = new DOMDocument
;
176 wfSuppressWarnings();
177 $result = $dom->loadXML( $xml );
180 // Try running the XML through UtfNormal to get rid of invalid characters
181 $xml = UtfNormal
::cleanUp( $xml );
182 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
183 $result = $dom->loadXML( $xml, 1 << 19 );
185 throw new MWException( __METHOD__
.' generated invalid XML' );
188 $obj = new PPNode_DOM( $dom->documentElement
);
189 wfProfileOut( __METHOD__
.'-loadXML' );
191 wfProfileOut( __METHOD__
.'-cacheable' );
193 wfProfileOut( __METHOD__
);
198 * @param $text string
202 function preprocessToXml( $text, $flags = 0 ) {
203 wfProfileIn( __METHOD__
);
216 'names' => array( 2 => null ),
222 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
224 $xmlishElements = $this->parser
->getStripList();
225 $enableOnlyinclude = false;
226 if ( $forInclusion ) {
227 $ignoredTags = array( 'includeonly', '/includeonly' );
228 $ignoredElements = array( 'noinclude' );
229 $xmlishElements[] = 'noinclude';
230 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
231 $enableOnlyinclude = true;
234 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
235 $ignoredElements = array( 'includeonly' );
236 $xmlishElements[] = 'includeonly';
238 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
240 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
241 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
243 $stack = new PPDStack
;
245 $searchBase = "[{<\n"; #}
246 $revText = strrev( $text ); // For fast reverse searches
247 $lengthText = strlen( $text );
249 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
250 $accum =& $stack->getAccum(); # Current accumulator
252 $findEquals = false; # True to find equals signs in arguments
253 $findPipe = false; # True to take notice of pipe characters
255 $inHeading = false; # True if $i is inside a possible heading
256 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
257 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
258 $fakeLineStart = true; # Do a line-start run without outputting an LF character
263 if ( $findOnlyinclude ) {
264 // Ignore all input up to the next <onlyinclude>
265 $startPos = strpos( $text, '<onlyinclude>', $i );
266 if ( $startPos === false ) {
267 // Ignored section runs to the end
268 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
271 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
272 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
274 $findOnlyinclude = false;
277 if ( $fakeLineStart ) {
278 $found = 'line-start';
281 # Find next opening brace, closing brace or pipe
282 $search = $searchBase;
283 if ( $stack->top
=== false ) {
284 $currentClosing = '';
286 $currentClosing = $stack->top
->close
;
287 $search .= $currentClosing;
293 // First equals will be for the template
297 # Output literal section, advance input counter
298 $literalLength = strcspn( $text, $search, $i );
299 if ( $literalLength > 0 ) {
300 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
301 $i +
= $literalLength;
303 if ( $i >= $lengthText ) {
304 if ( $currentClosing == "\n" ) {
305 // Do a past-the-end run to finish off the heading
313 $curChar = $text[$i];
314 if ( $curChar == '|' ) {
316 } elseif ( $curChar == '=' ) {
318 } elseif ( $curChar == '<' ) {
320 } elseif ( $curChar == "\n" ) {
324 $found = 'line-start';
326 } elseif ( $curChar == $currentClosing ) {
328 } elseif ( isset( $rules[$curChar] ) ) {
330 $rule = $rules[$curChar];
332 # Some versions of PHP have a strcspn which stops on null characters
333 # Ignore and continue
340 if ( $found == 'angle' ) {
342 // Handle </onlyinclude>
343 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
344 $findOnlyinclude = true;
348 // Determine element name
349 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
350 // Element name missing or not listed
356 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
357 // To avoid leaving blank lines, when a comment is both preceded
358 // and followed by a newline (ignoring spaces), trim leading and
359 // trailing spaces and one of the newlines.
362 $endPos = strpos( $text, '-->', $i +
4 );
363 if ( $endPos === false ) {
364 // Unclosed comment in input, runs to end
365 $inner = substr( $text, $i );
366 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
369 // Search backwards for leading whitespace
370 $wsStart = $i ?
( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
371 // Search forwards for trailing whitespace
372 // $wsEnd will be the position of the last space (or the '>' if there's none)
373 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
374 // Eat the line if possible
375 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
376 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
377 // it's a possible beneficial b/c break.
378 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
379 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
381 $startPos = $wsStart;
382 $endPos = $wsEnd +
1;
383 // Remove leading whitespace from the end of the accumulator
384 // Sanity check first though
385 $wsLength = $i - $wsStart;
386 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
387 $accum = substr( $accum, 0, -$wsLength );
389 // Do a line-start run next time to look for headings after the comment
390 $fakeLineStart = true;
392 // No line to eat, just take the comment itself
398 $part = $stack->top
->getCurrentPart();
399 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
400 $part->visualEnd
= $wsStart;
402 // Else comments abutting, no change in visual end
403 $part->commentEnd
= $endPos;
406 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
407 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
412 $lowerName = strtolower( $name );
413 $attrStart = $i +
strlen( $name ) +
1;
416 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
417 if ( $tagEndPos === false ) {
418 // Infinite backtrack
419 // Disable tag search to prevent worst-case O(N^2) performance
426 // Handle ignored tags
427 if ( in_array( $lowerName, $ignoredTags ) ) {
428 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
434 if ( $text[$tagEndPos-1] == '/' ) {
435 $attrEnd = $tagEndPos - 1;
440 $attrEnd = $tagEndPos;
442 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
443 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
445 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
446 $i = $matches[0][1] +
strlen( $matches[0][0] );
447 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
449 // No end tag -- let it run out to the end of the text.
450 $inner = substr( $text, $tagEndPos +
1 );
455 // <includeonly> and <noinclude> just become <ignore> tags
456 if ( in_array( $lowerName, $ignoredElements ) ) {
457 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
463 if ( $attrEnd <= $attrStart ) {
466 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
468 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
469 // Note that the attr element contains the whitespace between name and attribute,
470 // this is necessary for precise reconstruction during pre-save transform.
471 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
472 if ( $inner !== null ) {
473 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
475 $accum .= $close . '</ext>';
476 } elseif ( $found == 'line-start' ) {
477 // Is this the start of a heading?
478 // Line break belongs before the heading element in any case
479 if ( $fakeLineStart ) {
480 $fakeLineStart = false;
486 $count = strspn( $text, '=', $i, 6 );
487 if ( $count == 1 && $findEquals ) {
488 // DWIM: This looks kind of like a name/value separator
489 // Let's let the equals handler have it and break the potential heading
490 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
491 } elseif ( $count > 0 ) {
495 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
498 $stack->push( $piece );
499 $accum =& $stack->getAccum();
500 $flags = $stack->getFlags();
504 } elseif ( $found == 'line-end' ) {
505 $piece = $stack->top
;
506 // A heading must be open, otherwise \n wouldn't have been in the search list
507 assert( '$piece->open == "\n"' );
508 $part = $piece->getCurrentPart();
509 // Search back through the input to see if it has a proper close
510 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
511 $wsLength = strspn( $revText, " \t", $lengthText - $i );
512 $searchStart = $i - $wsLength;
513 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
514 // Comment found at line end
515 // Search for equals signs before the comment
516 $searchStart = $part->visualEnd
;
517 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
519 $count = $piece->count
;
520 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
521 if ( $equalsLength > 0 ) {
522 if ( $searchStart - $equalsLength == $piece->startPos
) {
523 // This is just a single string of equals signs on its own line
524 // Replicate the doHeadings behaviour /={count}(.+)={count}/
525 // First find out how many equals signs there really are (don't stop at 6)
526 $count = $equalsLength;
530 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
533 $count = min( $equalsLength, $count );
536 // Normal match, output <h>
537 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
540 // Single equals sign on its own line, count=0
544 // No match, no <h>, just pass down the inner text
549 $accum =& $stack->getAccum();
550 $flags = $stack->getFlags();
553 // Append the result to the enclosing accumulator
555 // Note that we do NOT increment the input pointer.
556 // This is because the closing linebreak could be the opening linebreak of
557 // another heading. Infinite loops are avoided because the next iteration MUST
558 // hit the heading open case above, which unconditionally increments the
560 } elseif ( $found == 'open' ) {
561 # count opening brace characters
562 $count = strspn( $text, $curChar, $i );
564 # we need to add to stack only if opening brace count is enough for one of the rules
565 if ( $count >= $rule['min'] ) {
566 # Add it to the stack
569 'close' => $rule['end'],
571 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
574 $stack->push( $piece );
575 $accum =& $stack->getAccum();
576 $flags = $stack->getFlags();
579 # Add literal brace(s)
580 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
583 } elseif ( $found == 'close' ) {
584 $piece = $stack->top
;
585 # lets check if there are enough characters for closing brace
586 $maxCount = $piece->count
;
587 $count = strspn( $text, $curChar, $i, $maxCount );
589 # check for maximum matching characters (if there are 5 closing
590 # characters, we will probably need only 3 - depending on the rules)
591 $rule = $rules[$piece->open
];
592 if ( $count > $rule['max'] ) {
593 # The specified maximum exists in the callback array, unless the caller
595 $matchingCount = $rule['max'];
597 # Count is less than the maximum
598 # Skip any gaps in the callback array to find the true largest match
599 # Need to use array_key_exists not isset because the callback can be null
600 $matchingCount = $count;
601 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
606 if ( $matchingCount <= 0 ) {
607 # No matching element found in callback array
608 # Output a literal closing brace and continue
609 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
613 $name = $rule['names'][$matchingCount];
614 if ( $name === null ) {
615 // No element, just literal text
616 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
619 # Note: $parts is already XML, does not need to be encoded further
620 $parts = $piece->parts
;
621 $title = $parts[0]->out
;
624 # The invocation is at the start of the line if lineStart is set in
625 # the stack, and all opening brackets are used up.
626 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
627 $attr = ' lineStart="1"';
632 $element = "<$name$attr>";
633 $element .= "<title>$title</title>";
635 foreach ( $parts as $part ) {
636 if ( isset( $part->eqpos
) ) {
637 $argName = substr( $part->out
, 0, $part->eqpos
);
638 $argValue = substr( $part->out
, $part->eqpos +
1 );
639 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
641 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
645 $element .= "</$name>";
648 # Advance input pointer
649 $i +
= $matchingCount;
653 $accum =& $stack->getAccum();
655 # Re-add the old stack element if it still has unmatched opening characters remaining
656 if ( $matchingCount < $piece->count
) {
657 $piece->parts
= array( new PPDPart
);
658 $piece->count
-= $matchingCount;
659 # do we still qualify for any callback with remaining count?
660 $names = $rules[$piece->open
]['names'];
662 $enclosingAccum =& $accum;
663 while ( $piece->count
) {
664 if ( array_key_exists( $piece->count
, $names ) ) {
665 $stack->push( $piece );
666 $accum =& $stack->getAccum();
672 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
674 $flags = $stack->getFlags();
677 # Add XML element to the enclosing accumulator
679 } elseif ( $found == 'pipe' ) {
680 $findEquals = true; // shortcut for getFlags()
682 $accum =& $stack->getAccum();
684 } elseif ( $found == 'equals' ) {
685 $findEquals = false; // shortcut for getFlags()
686 $stack->getCurrentPart()->eqpos
= strlen( $accum );
692 # Output any remaining unclosed brackets
693 foreach ( $stack->stack
as $piece ) {
694 $stack->rootAccum
.= $piece->breakSyntax();
696 $stack->rootAccum
.= '</root>';
697 $xml = $stack->rootAccum
;
699 wfProfileOut( __METHOD__
);
706 * Stack class to help Preprocessor::preprocessToObj()
710 var $stack, $rootAccum;
717 var $elementClass = 'PPDStackElement';
719 static $false = false;
721 function __construct() {
722 $this->stack
= array();
724 $this->rootAccum
= '';
725 $this->accum
=& $this->rootAccum
;
732 return count( $this->stack
);
735 function &getAccum() {
739 function getCurrentPart() {
740 if ( $this->top
=== false ) {
743 return $this->top
->getCurrentPart();
747 function push( $data ) {
748 if ( $data instanceof $this->elementClass
) {
749 $this->stack
[] = $data;
751 $class = $this->elementClass
;
752 $this->stack
[] = new $class( $data );
754 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
755 $this->accum
=& $this->top
->getAccum();
759 if ( !count( $this->stack
) ) {
760 throw new MWException( __METHOD__
.': no elements remaining' );
762 $temp = array_pop( $this->stack
);
764 if ( count( $this->stack
) ) {
765 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
766 $this->accum
=& $this->top
->getAccum();
768 $this->top
= self
::$false;
769 $this->accum
=& $this->rootAccum
;
774 function addPart( $s = '' ) {
775 $this->top
->addPart( $s );
776 $this->accum
=& $this->top
->getAccum();
782 function getFlags() {
783 if ( !count( $this->stack
) ) {
785 'findEquals' => false,
787 'inHeading' => false,
790 return $this->top
->getFlags();
798 class PPDStackElement
{
799 var $open, // Opening character (\n for heading)
800 $close, // Matching closing character
801 $count, // Number of opening characters found (number of "=" for heading)
802 $parts, // Array of PPDPart objects describing pipe-separated parts.
803 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
805 var $partClass = 'PPDPart';
807 function __construct( $data = array() ) {
808 $class = $this->partClass
;
809 $this->parts
= array( new $class );
811 foreach ( $data as $name => $value ) {
812 $this->$name = $value;
816 function &getAccum() {
817 return $this->parts
[count($this->parts
) - 1]->out
;
820 function addPart( $s = '' ) {
821 $class = $this->partClass
;
822 $this->parts
[] = new $class( $s );
825 function getCurrentPart() {
826 return $this->parts
[count($this->parts
) - 1];
832 function getFlags() {
833 $partCount = count( $this->parts
);
834 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
836 'findPipe' => $findPipe,
837 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
838 'inHeading' => $this->open
== "\n",
843 * Get the output string that would result if the close is not found.
847 function breakSyntax( $openingCount = false ) {
848 if ( $this->open
== "\n" ) {
849 $s = $this->parts
[0]->out
;
851 if ( $openingCount === false ) {
852 $openingCount = $this->count
;
854 $s = str_repeat( $this->open
, $openingCount );
856 foreach ( $this->parts
as $part ) {
873 var $out; // Output accumulator string
875 // Optional member variables:
876 // eqpos Position of equals sign in output accumulator
877 // commentEnd Past-the-end input pointer for the last comment encountered
878 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
880 function __construct( $out = '' ) {
886 * An expansion frame, used as a context to expand the result of preprocessToObj()
889 class PPFrame_DOM
implements PPFrame
{
908 * Hashtable listing templates which are disallowed for expansion in this frame,
909 * having been encountered previously in parent frames.
914 * Recursion depth of this frame, top = 0
915 * Note that this is NOT the same as expansion depth in expand()
921 * Construct a new preprocessor frame.
922 * @param $preprocessor Preprocessor The parent preprocessor
924 function __construct( $preprocessor ) {
925 $this->preprocessor
= $preprocessor;
926 $this->parser
= $preprocessor->parser
;
927 $this->title
= $this->parser
->mTitle
;
928 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
929 $this->loopCheckHash
= array();
934 * Create a new child frame
935 * $args is optionally a multi-root PPNode or array containing the template arguments
937 * @return PPTemplateFrame_DOM
939 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
940 $namedArgs = array();
941 $numberedArgs = array();
942 if ( $title === false ) {
943 $title = $this->title
;
945 if ( $args !== false ) {
947 if ( $args instanceof PPNode
) {
950 foreach ( $args as $arg ) {
951 if ( $arg instanceof PPNode
) {
955 $xpath = new DOMXPath( $arg->ownerDocument
);
958 $nameNodes = $xpath->query( 'name', $arg );
959 $value = $xpath->query( 'value', $arg );
960 if ( $nameNodes->item( 0 )->hasAttributes() ) {
961 // Numbered parameter
962 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
963 $index = $index - $indexOffset;
964 $numberedArgs[$index] = $value->item( 0 );
965 unset( $namedArgs[$index] );
968 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
969 $namedArgs[$name] = $value->item( 0 );
970 unset( $numberedArgs[$name] );
974 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
978 * @throws MWException
983 function expand( $root, $flags = 0 ) {
984 static $expansionDepth = 0;
985 if ( is_string( $root ) ) {
989 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
990 $this->parser
->limitationWarn( 'node-count-exceeded',
991 $this->parser
->mPPNodeCount
,
992 $this->parser
->mOptions
->getMaxPPNodeCount()
994 return '<span class="error">Node-count limit exceeded</span>';
997 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
998 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1000 $this->parser
->mOptions
->getMaxPPExpandDepth()
1002 return '<span class="error">Expansion depth limit exceeded</span>';
1004 wfProfileIn( __METHOD__
);
1006 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1007 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1010 if ( $root instanceof PPNode_DOM
) {
1011 $root = $root->node
;
1013 if ( $root instanceof DOMDocument
) {
1014 $root = $root->documentElement
;
1017 $outStack = array( '', '' );
1018 $iteratorStack = array( false, $root );
1019 $indexStack = array( 0, 0 );
1021 while ( count( $iteratorStack ) > 1 ) {
1022 $level = count( $outStack ) - 1;
1023 $iteratorNode =& $iteratorStack[ $level ];
1024 $out =& $outStack[$level];
1025 $index =& $indexStack[$level];
1027 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
1029 if ( is_array( $iteratorNode ) ) {
1030 if ( $index >= count( $iteratorNode ) ) {
1031 // All done with this iterator
1032 $iteratorStack[$level] = false;
1033 $contextNode = false;
1035 $contextNode = $iteratorNode[$index];
1038 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1039 if ( $index >= $iteratorNode->length
) {
1040 // All done with this iterator
1041 $iteratorStack[$level] = false;
1042 $contextNode = false;
1044 $contextNode = $iteratorNode->item( $index );
1048 // Copy to $contextNode and then delete from iterator stack,
1049 // because this is not an iterator but we do have to execute it once
1050 $contextNode = $iteratorStack[$level];
1051 $iteratorStack[$level] = false;
1054 if ( $contextNode instanceof PPNode_DOM
) {
1055 $contextNode = $contextNode->node
;
1058 $newIterator = false;
1060 if ( $contextNode === false ) {
1062 } elseif ( is_string( $contextNode ) ) {
1063 $out .= $contextNode;
1064 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1065 $newIterator = $contextNode;
1066 } elseif ( $contextNode instanceof DOMNode
) {
1067 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1068 $out .= $contextNode->nodeValue
;
1069 } elseif ( $contextNode->nodeName
== 'template' ) {
1070 # Double-brace expansion
1071 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1072 $titles = $xpath->query( 'title', $contextNode );
1073 $title = $titles->item( 0 );
1074 $parts = $xpath->query( 'part', $contextNode );
1075 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1076 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1078 $lineStart = $contextNode->getAttribute( 'lineStart' );
1080 'title' => new PPNode_DOM( $title ),
1081 'parts' => new PPNode_DOM( $parts ),
1082 'lineStart' => $lineStart );
1083 $ret = $this->parser
->braceSubstitution( $params, $this );
1084 if ( isset( $ret['object'] ) ) {
1085 $newIterator = $ret['object'];
1087 $out .= $ret['text'];
1090 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1091 # Triple-brace expansion
1092 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1093 $titles = $xpath->query( 'title', $contextNode );
1094 $title = $titles->item( 0 );
1095 $parts = $xpath->query( 'part', $contextNode );
1096 if ( $flags & PPFrame
::NO_ARGS
) {
1097 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1100 'title' => new PPNode_DOM( $title ),
1101 'parts' => new PPNode_DOM( $parts ) );
1102 $ret = $this->parser
->argSubstitution( $params, $this );
1103 if ( isset( $ret['object'] ) ) {
1104 $newIterator = $ret['object'];
1106 $out .= $ret['text'];
1109 } elseif ( $contextNode->nodeName
== 'comment' ) {
1110 # HTML-style comment
1111 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1112 if ( $this->parser
->ot
['html']
1113 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1114 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1118 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1119 # Not in RECOVER_COMMENTS mode (extractSections) though
1120 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1121 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1123 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1125 $out .= $contextNode->textContent
;
1127 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1128 # Output suppression used by <includeonly> etc.
1129 # OT_WIKI will only respect <ignore> in substed templates.
1130 # The other output types respect it unless NO_IGNORE is set.
1131 # extractSections() sets NO_IGNORE and so never respects it.
1132 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1133 $out .= $contextNode->textContent
;
1137 } elseif ( $contextNode->nodeName
== 'ext' ) {
1139 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1140 $names = $xpath->query( 'name', $contextNode );
1141 $attrs = $xpath->query( 'attr', $contextNode );
1142 $inners = $xpath->query( 'inner', $contextNode );
1143 $closes = $xpath->query( 'close', $contextNode );
1145 'name' => new PPNode_DOM( $names->item( 0 ) ),
1146 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1147 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1148 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1150 $out .= $this->parser
->extensionSubstitution( $params, $this );
1151 } elseif ( $contextNode->nodeName
== 'h' ) {
1153 $s = $this->expand( $contextNode->childNodes
, $flags );
1155 # Insert a heading marker only for <h> children of <root>
1156 # This is to stop extractSections from going over multiple tree levels
1157 if ( $contextNode->parentNode
->nodeName
== 'root'
1158 && $this->parser
->ot
['html'] )
1160 # Insert heading index marker
1161 $headingIndex = $contextNode->getAttribute( 'i' );
1162 $titleText = $this->title
->getPrefixedDBkey();
1163 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1164 $serial = count( $this->parser
->mHeadings
) - 1;
1165 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1166 $count = $contextNode->getAttribute( 'level' );
1167 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1168 $this->parser
->mStripState
->addGeneral( $marker, '' );
1172 # Generic recursive expansion
1173 $newIterator = $contextNode->childNodes
;
1176 wfProfileOut( __METHOD__
);
1177 throw new MWException( __METHOD__
.': Invalid parameter type' );
1180 if ( $newIterator !== false ) {
1181 if ( $newIterator instanceof PPNode_DOM
) {
1182 $newIterator = $newIterator->node
;
1185 $iteratorStack[] = $newIterator;
1187 } elseif ( $iteratorStack[$level] === false ) {
1188 // Return accumulated value to parent
1189 // With tail recursion
1190 while ( $iteratorStack[$level] === false && $level > 0 ) {
1191 $outStack[$level - 1] .= $out;
1192 array_pop( $outStack );
1193 array_pop( $iteratorStack );
1194 array_pop( $indexStack );
1200 wfProfileOut( __METHOD__
);
1201 return $outStack[0];
1209 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1210 $args = array_slice( func_get_args(), 2 );
1214 foreach ( $args as $root ) {
1215 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1216 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1217 $root = array( $root );
1219 foreach ( $root as $node ) {
1225 $s .= $this->expand( $node, $flags );
1232 * Implode with no flags specified
1233 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1237 function implode( $sep /*, ... */ ) {
1238 $args = array_slice( func_get_args(), 1 );
1242 foreach ( $args as $root ) {
1243 if ( $root instanceof PPNode_DOM
) {
1244 $root = $root->node
;
1246 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1247 $root = array( $root );
1249 foreach ( $root as $node ) {
1255 $s .= $this->expand( $node );
1262 * Makes an object that, when expand()ed, will be the same as one obtained
1267 function virtualImplode( $sep /*, ... */ ) {
1268 $args = array_slice( func_get_args(), 1 );
1272 foreach ( $args as $root ) {
1273 if ( $root instanceof PPNode_DOM
) {
1274 $root = $root->node
;
1276 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1277 $root = array( $root );
1279 foreach ( $root as $node ) {
1292 * Virtual implode with brackets
1295 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1296 $args = array_slice( func_get_args(), 3 );
1297 $out = array( $start );
1300 foreach ( $args as $root ) {
1301 if ( $root instanceof PPNode_DOM
) {
1302 $root = $root->node
;
1304 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1305 $root = array( $root );
1307 foreach ( $root as $node ) {
1320 function __toString() {
1324 function getPDBK( $level = false ) {
1325 if ( $level === false ) {
1326 return $this->title
->getPrefixedDBkey();
1328 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1335 function getArguments() {
1342 function getNumberedArguments() {
1349 function getNamedArguments() {
1354 * Returns true if there are no arguments in this frame
1358 function isEmpty() {
1362 function getArgument( $name ) {
1367 * Returns true if the infinite loop check is OK, false if a loop is detected
1371 function loopCheck( $title ) {
1372 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1376 * Return true if the frame is a template frame
1380 function isTemplate() {
1385 * Get a title of frame
1389 function getTitle() {
1390 return $this->title
;
1395 * Expansion frame with template arguments
1398 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1399 var $numberedArgs, $namedArgs;
1405 var $numberedExpansionCache, $namedExpansionCache;
1408 * @param $preprocessor
1409 * @param $parent PPFrame_DOM
1410 * @param $numberedArgs array
1411 * @param $namedArgs array
1412 * @param $title Title
1414 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1415 parent
::__construct( $preprocessor );
1417 $this->parent
= $parent;
1418 $this->numberedArgs
= $numberedArgs;
1419 $this->namedArgs
= $namedArgs;
1420 $this->title
= $title;
1421 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1422 $this->titleCache
= $parent->titleCache
;
1423 $this->titleCache
[] = $pdbk;
1424 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1425 if ( $pdbk !== false ) {
1426 $this->loopCheckHash
[$pdbk] = true;
1428 $this->depth
= $parent->depth +
1;
1429 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1432 function __toString() {
1435 $args = $this->numberedArgs +
$this->namedArgs
;
1436 foreach ( $args as $name => $value ) {
1442 $s .= "\"$name\":\"" .
1443 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1450 * Returns true if there are no arguments in this frame
1454 function isEmpty() {
1455 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1458 function getArguments() {
1459 $arguments = array();
1460 foreach ( array_merge(
1461 array_keys($this->numberedArgs
),
1462 array_keys($this->namedArgs
)) as $key ) {
1463 $arguments[$key] = $this->getArgument($key);
1468 function getNumberedArguments() {
1469 $arguments = array();
1470 foreach ( array_keys($this->numberedArgs
) as $key ) {
1471 $arguments[$key] = $this->getArgument($key);
1476 function getNamedArguments() {
1477 $arguments = array();
1478 foreach ( array_keys($this->namedArgs
) as $key ) {
1479 $arguments[$key] = $this->getArgument($key);
1484 function getNumberedArgument( $index ) {
1485 if ( !isset( $this->numberedArgs
[$index] ) ) {
1488 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1489 # No trimming for unnamed arguments
1490 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1492 return $this->numberedExpansionCache
[$index];
1495 function getNamedArgument( $name ) {
1496 if ( !isset( $this->namedArgs
[$name] ) ) {
1499 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1500 # Trim named arguments post-expand, for backwards compatibility
1501 $this->namedExpansionCache
[$name] = trim(
1502 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1504 return $this->namedExpansionCache
[$name];
1507 function getArgument( $name ) {
1508 $text = $this->getNumberedArgument( $name );
1509 if ( $text === false ) {
1510 $text = $this->getNamedArgument( $name );
1516 * Return true if the frame is a template frame
1520 function isTemplate() {
1526 * Expansion frame with custom arguments
1529 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1532 function __construct( $preprocessor, $args ) {
1533 parent
::__construct( $preprocessor );
1534 $this->args
= $args;
1537 function __toString() {
1540 foreach ( $this->args
as $name => $value ) {
1546 $s .= "\"$name\":\"" .
1547 str_replace( '"', '\\"', $value->__toString() ) . '"';
1556 function isEmpty() {
1557 return !count( $this->args
);
1560 function getArgument( $index ) {
1561 if ( !isset( $this->args
[$index] ) ) {
1564 return $this->args
[$index];
1567 function getArguments() {
1575 class PPNode_DOM
implements PPNode
{
1583 function __construct( $node, $xpath = false ) {
1584 $this->node
= $node;
1590 function getXPath() {
1591 if ( $this->xpath
=== null ) {
1592 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1594 return $this->xpath
;
1597 function __toString() {
1598 if ( $this->node
instanceof DOMNodeList
) {
1600 foreach ( $this->node
as $node ) {
1601 $s .= $node->ownerDocument
->saveXML( $node );
1604 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1610 * @return bool|PPNode_DOM
1612 function getChildren() {
1613 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1617 * @return bool|PPNode_DOM
1619 function getFirstChild() {
1620 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1624 * @return bool|PPNode_DOM
1626 function getNextSibling() {
1627 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1633 * @return bool|PPNode_DOM
1635 function getChildrenOfType( $type ) {
1636 return new self( $this->getXPath()->query( $type, $this->node
) );
1642 function getLength() {
1643 if ( $this->node
instanceof DOMNodeList
) {
1644 return $this->node
->length
;
1652 * @return bool|PPNode_DOM
1654 function item( $i ) {
1655 $item = $this->node
->item( $i );
1656 return $item ?
new self( $item ) : false;
1662 function getName() {
1663 if ( $this->node
instanceof DOMNodeList
) {
1666 return $this->node
->nodeName
;
1671 * Split a "<part>" node into an associative array containing:
1672 * - name PPNode name
1673 * - index String index
1674 * - value PPNode value
1678 function splitArg() {
1679 $xpath = $this->getXPath();
1680 $names = $xpath->query( 'name', $this->node
);
1681 $values = $xpath->query( 'value', $this->node
);
1682 if ( !$names->length ||
!$values->length
) {
1683 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1685 $name = $names->item( 0 );
1686 $index = $name->getAttribute( 'index' );
1688 'name' => new self( $name ),
1690 'value' => new self( $values->item( 0 ) ) );
1694 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1695 * All values in the resulting array are PPNodes. Inner and close are optional.
1699 function splitExt() {
1700 $xpath = $this->getXPath();
1701 $names = $xpath->query( 'name', $this->node
);
1702 $attrs = $xpath->query( 'attr', $this->node
);
1703 $inners = $xpath->query( 'inner', $this->node
);
1704 $closes = $xpath->query( 'close', $this->node
);
1705 if ( !$names->length ||
!$attrs->length
) {
1706 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1709 'name' => new self( $names->item( 0 ) ),
1710 'attr' => new self( $attrs->item( 0 ) ) );
1711 if ( $inners->length
) {
1712 $parts['inner'] = new self( $inners->item( 0 ) );
1714 if ( $closes->length
) {
1715 $parts['close'] = new self( $closes->item( 0 ) );
1721 * Split a "<h>" node
1724 function splitHeading() {
1725 if ( $this->getName() !== 'h' ) {
1726 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1729 'i' => $this->node
->getAttribute( 'i' ),
1730 'level' => $this->node
->getAttribute( 'level' ),
1731 'contents' => $this->getChildren()