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 string $text 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.
129 * @throws MWException
132 function preprocessToObj( $text, $flags = 0 ) {
133 wfProfileIn( __METHOD__
);
134 global $wgMemc, $wgPreprocessorCacheThreshold;
137 $cacheable = ( $wgPreprocessorCacheThreshold !== false
138 && strlen( $text ) > $wgPreprocessorCacheThreshold );
140 wfProfileIn( __METHOD__
. '-cacheable' );
142 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
143 $cacheValue = $wgMemc->get( $cacheKey );
145 $version = substr( $cacheValue, 0, 8 );
146 if ( intval( $version ) == self
::CACHE_VERSION
) {
147 $xml = substr( $cacheValue, 8 );
149 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
153 if ( $xml === false ) {
155 wfProfileIn( __METHOD__
. '-cache-miss' );
156 $xml = $this->preprocessToXml( $text, $flags );
157 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
158 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
159 wfProfileOut( __METHOD__
. '-cache-miss' );
160 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
162 $xml = $this->preprocessToXml( $text, $flags );
167 // Fail if the number of elements exceeds acceptable limits
168 // Do not attempt to generate the DOM
169 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
170 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
171 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
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 don't barf when the XML is >256 levels deep
184 $result = $dom->loadXML( $xml, 1 << 19 );
186 throw new MWException( __METHOD__
. ' generated invalid XML' );
189 $obj = new PPNode_DOM( $dom->documentElement
);
190 wfProfileOut( __METHOD__
. '-loadXML' );
192 wfProfileOut( __METHOD__
. '-cacheable' );
194 wfProfileOut( __METHOD__
);
199 * @param $text string
203 function preprocessToXml( $text, $flags = 0 ) {
204 wfProfileIn( __METHOD__
);
217 'names' => array( 2 => null ),
223 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
225 $xmlishElements = $this->parser
->getStripList();
226 $enableOnlyinclude = false;
227 if ( $forInclusion ) {
228 $ignoredTags = array( 'includeonly', '/includeonly' );
229 $ignoredElements = array( 'noinclude' );
230 $xmlishElements[] = 'noinclude';
231 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
232 $enableOnlyinclude = true;
235 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
236 $ignoredElements = array( 'includeonly' );
237 $xmlishElements[] = 'includeonly';
239 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
241 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
242 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
244 $stack = new PPDStack
;
246 $searchBase = "[{<\n"; #}
247 $revText = strrev( $text ); // For fast reverse searches
248 $lengthText = strlen( $text );
250 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
251 $accum =& $stack->getAccum(); # Current accumulator
253 $findEquals = false; # True to find equals signs in arguments
254 $findPipe = false; # True to take notice of pipe characters
256 $inHeading = false; # True if $i is inside a possible heading
257 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
258 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
259 $fakeLineStart = true; # Do a line-start run without outputting an LF character
264 if ( $findOnlyinclude ) {
265 // Ignore all input up to the next <onlyinclude>
266 $startPos = strpos( $text, '<onlyinclude>', $i );
267 if ( $startPos === false ) {
268 // Ignored section runs to the end
269 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
272 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
273 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
275 $findOnlyinclude = false;
278 if ( $fakeLineStart ) {
279 $found = 'line-start';
282 # Find next opening brace, closing brace or pipe
283 $search = $searchBase;
284 if ( $stack->top
=== false ) {
285 $currentClosing = '';
287 $currentClosing = $stack->top
->close
;
288 $search .= $currentClosing;
294 // First equals will be for the template
298 # Output literal section, advance input counter
299 $literalLength = strcspn( $text, $search, $i );
300 if ( $literalLength > 0 ) {
301 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
302 $i +
= $literalLength;
304 if ( $i >= $lengthText ) {
305 if ( $currentClosing == "\n" ) {
306 // Do a past-the-end run to finish off the heading
314 $curChar = $text[$i];
315 if ( $curChar == '|' ) {
317 } elseif ( $curChar == '=' ) {
319 } elseif ( $curChar == '<' ) {
321 } elseif ( $curChar == "\n" ) {
325 $found = 'line-start';
327 } elseif ( $curChar == $currentClosing ) {
329 } elseif ( isset( $rules[$curChar] ) ) {
331 $rule = $rules[$curChar];
333 # Some versions of PHP have a strcspn which stops on null characters
334 # Ignore and continue
341 if ( $found == 'angle' ) {
343 // Handle </onlyinclude>
344 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
345 $findOnlyinclude = true;
349 // Determine element name
350 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
351 // Element name missing or not listed
357 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
358 // To avoid leaving blank lines, when a comment is both preceded
359 // and followed by a newline (ignoring spaces), trim leading and
360 // trailing spaces and one of the newlines.
363 $endPos = strpos( $text, '-->', $i +
4 );
364 if ( $endPos === false ) {
365 // Unclosed comment in input, runs to end
366 $inner = substr( $text, $i );
367 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
370 // Search backwards for leading whitespace
371 $wsStart = $i ?
( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
372 // Search forwards for trailing whitespace
373 // $wsEnd will be the position of the last space (or the '>' if there's none)
374 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
375 // Eat the line if possible
376 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
377 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
378 // it's a possible beneficial b/c break.
379 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
380 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
382 $startPos = $wsStart;
383 $endPos = $wsEnd +
1;
384 // Remove leading whitespace from the end of the accumulator
385 // Sanity check first though
386 $wsLength = $i - $wsStart;
387 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
388 $accum = substr( $accum, 0, -$wsLength );
390 // Do a line-start run next time to look for headings after the comment
391 $fakeLineStart = true;
393 // No line to eat, just take the comment itself
399 $part = $stack->top
->getCurrentPart();
400 if ( !(isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
401 $part->visualEnd
= $wsStart;
403 // Else comments abutting, no change in visual end
404 $part->commentEnd
= $endPos;
407 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
408 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
413 $lowerName = strtolower( $name );
414 $attrStart = $i +
strlen( $name ) +
1;
417 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
418 if ( $tagEndPos === false ) {
419 // Infinite backtrack
420 // Disable tag search to prevent worst-case O(N^2) performance
427 // Handle ignored tags
428 if ( in_array( $lowerName, $ignoredTags ) ) {
429 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
435 if ( $text[$tagEndPos-1] == '/' ) {
436 $attrEnd = $tagEndPos - 1;
441 $attrEnd = $tagEndPos;
443 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
444 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
446 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
447 $i = $matches[0][1] +
strlen( $matches[0][0] );
448 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
450 // No end tag -- let it run out to the end of the text.
451 $inner = substr( $text, $tagEndPos +
1 );
456 // <includeonly> and <noinclude> just become <ignore> tags
457 if ( in_array( $lowerName, $ignoredElements ) ) {
458 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
464 if ( $attrEnd <= $attrStart ) {
467 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
469 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
470 // Note that the attr element contains the whitespace between name and attribute,
471 // this is necessary for precise reconstruction during pre-save transform.
472 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
473 if ( $inner !== null ) {
474 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
476 $accum .= $close . '</ext>';
477 } elseif ( $found == 'line-start' ) {
478 // Is this the start of a heading?
479 // Line break belongs before the heading element in any case
480 if ( $fakeLineStart ) {
481 $fakeLineStart = false;
487 $count = strspn( $text, '=', $i, 6 );
488 if ( $count == 1 && $findEquals ) {
489 // DWIM: This looks kind of like a name/value separator
490 // Let's let the equals handler have it and break the potential heading
491 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
492 } elseif ( $count > 0 ) {
496 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
499 $stack->push( $piece );
500 $accum =& $stack->getAccum();
501 $flags = $stack->getFlags();
505 } elseif ( $found == 'line-end' ) {
506 $piece = $stack->top
;
507 // A heading must be open, otherwise \n wouldn't have been in the search list
508 assert( '$piece->open == "\n"' );
509 $part = $piece->getCurrentPart();
510 // Search back through the input to see if it has a proper close
511 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
512 $wsLength = strspn( $revText, " \t", $lengthText - $i );
513 $searchStart = $i - $wsLength;
514 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
515 // Comment found at line end
516 // Search for equals signs before the comment
517 $searchStart = $part->visualEnd
;
518 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
520 $count = $piece->count
;
521 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
522 if ( $equalsLength > 0 ) {
523 if ( $searchStart - $equalsLength == $piece->startPos
) {
524 // This is just a single string of equals signs on its own line
525 // Replicate the doHeadings behavior /={count}(.+)={count}/
526 // First find out how many equals signs there really are (don't stop at 6)
527 $count = $equalsLength;
531 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
534 $count = min( $equalsLength, $count );
537 // Normal match, output <h>
538 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
541 // Single equals sign on its own line, count=0
545 // No match, no <h>, just pass down the inner text
550 $accum =& $stack->getAccum();
551 $flags = $stack->getFlags();
554 // Append the result to the enclosing accumulator
556 // Note that we do NOT increment the input pointer.
557 // This is because the closing linebreak could be the opening linebreak of
558 // another heading. Infinite loops are avoided because the next iteration MUST
559 // hit the heading open case above, which unconditionally increments the
561 } elseif ( $found == 'open' ) {
562 # count opening brace characters
563 $count = strspn( $text, $curChar, $i );
565 # we need to add to stack only if opening brace count is enough for one of the rules
566 if ( $count >= $rule['min'] ) {
567 # Add it to the stack
570 'close' => $rule['end'],
572 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
575 $stack->push( $piece );
576 $accum =& $stack->getAccum();
577 $flags = $stack->getFlags();
580 # Add literal brace(s)
581 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
584 } elseif ( $found == 'close' ) {
585 $piece = $stack->top
;
586 # lets check if there are enough characters for closing brace
587 $maxCount = $piece->count
;
588 $count = strspn( $text, $curChar, $i, $maxCount );
590 # check for maximum matching characters (if there are 5 closing
591 # characters, we will probably need only 3 - depending on the rules)
592 $rule = $rules[$piece->open
];
593 if ( $count > $rule['max'] ) {
594 # The specified maximum exists in the callback array, unless the caller
596 $matchingCount = $rule['max'];
598 # Count is less than the maximum
599 # Skip any gaps in the callback array to find the true largest match
600 # Need to use array_key_exists not isset because the callback can be null
601 $matchingCount = $count;
602 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
607 if ( $matchingCount <= 0 ) {
608 # No matching element found in callback array
609 # Output a literal closing brace and continue
610 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
614 $name = $rule['names'][$matchingCount];
615 if ( $name === null ) {
616 // No element, just literal text
617 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
620 # Note: $parts is already XML, does not need to be encoded further
621 $parts = $piece->parts
;
622 $title = $parts[0]->out
;
625 # The invocation is at the start of the line if lineStart is set in
626 # the stack, and all opening brackets are used up.
627 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
628 $attr = ' lineStart="1"';
633 $element = "<$name$attr>";
634 $element .= "<title>$title</title>";
636 foreach ( $parts as $part ) {
637 if ( isset( $part->eqpos
) ) {
638 $argName = substr( $part->out
, 0, $part->eqpos
);
639 $argValue = substr( $part->out
, $part->eqpos +
1 );
640 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
642 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
646 $element .= "</$name>";
649 # Advance input pointer
650 $i +
= $matchingCount;
654 $accum =& $stack->getAccum();
656 # Re-add the old stack element if it still has unmatched opening characters remaining
657 if ( $matchingCount < $piece->count
) {
658 $piece->parts
= array( new PPDPart
);
659 $piece->count
-= $matchingCount;
660 # do we still qualify for any callback with remaining count?
661 $min = $rules[$piece->open
]['min'];
662 if ( $piece->count
>= $min ) {
663 $stack->push( $piece );
664 $accum =& $stack->getAccum();
666 $accum .= str_repeat( $piece->open
, $piece->count
);
669 $flags = $stack->getFlags();
672 # Add XML element to the enclosing accumulator
674 } elseif ( $found == 'pipe' ) {
675 $findEquals = true; // shortcut for getFlags()
677 $accum =& $stack->getAccum();
679 } elseif ( $found == 'equals' ) {
680 $findEquals = false; // shortcut for getFlags()
681 $stack->getCurrentPart()->eqpos
= strlen( $accum );
687 # Output any remaining unclosed brackets
688 foreach ( $stack->stack
as $piece ) {
689 $stack->rootAccum
.= $piece->breakSyntax();
691 $stack->rootAccum
.= '</root>';
692 $xml = $stack->rootAccum
;
694 wfProfileOut( __METHOD__
);
701 * Stack class to help Preprocessor::preprocessToObj()
705 var $stack, $rootAccum;
712 var $elementClass = 'PPDStackElement';
714 static $false = false;
716 function __construct() {
717 $this->stack
= array();
719 $this->rootAccum
= '';
720 $this->accum
=& $this->rootAccum
;
727 return count( $this->stack
);
730 function &getAccum() {
734 function getCurrentPart() {
735 if ( $this->top
=== false ) {
738 return $this->top
->getCurrentPart();
742 function push( $data ) {
743 if ( $data instanceof $this->elementClass
) {
744 $this->stack
[] = $data;
746 $class = $this->elementClass
;
747 $this->stack
[] = new $class( $data );
749 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
750 $this->accum
=& $this->top
->getAccum();
754 if ( !count( $this->stack
) ) {
755 throw new MWException( __METHOD__
. ': no elements remaining' );
757 $temp = array_pop( $this->stack
);
759 if ( count( $this->stack
) ) {
760 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
761 $this->accum
=& $this->top
->getAccum();
763 $this->top
= self
::$false;
764 $this->accum
=& $this->rootAccum
;
769 function addPart( $s = '' ) {
770 $this->top
->addPart( $s );
771 $this->accum
=& $this->top
->getAccum();
777 function getFlags() {
778 if ( !count( $this->stack
) ) {
780 'findEquals' => false,
782 'inHeading' => false,
785 return $this->top
->getFlags();
793 class PPDStackElement
{
794 var $open, // Opening character (\n for heading)
795 $close, // Matching closing character
796 $count, // Number of opening characters found (number of "=" for heading)
797 $parts, // Array of PPDPart objects describing pipe-separated parts.
798 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
800 var $partClass = 'PPDPart';
802 function __construct( $data = array() ) {
803 $class = $this->partClass
;
804 $this->parts
= array( new $class );
806 foreach ( $data as $name => $value ) {
807 $this->$name = $value;
811 function &getAccum() {
812 return $this->parts
[count( $this->parts
) - 1]->out
;
815 function addPart( $s = '' ) {
816 $class = $this->partClass
;
817 $this->parts
[] = new $class( $s );
820 function getCurrentPart() {
821 return $this->parts
[count( $this->parts
) - 1];
827 function getFlags() {
828 $partCount = count( $this->parts
);
829 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
831 'findPipe' => $findPipe,
832 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
833 'inHeading' => $this->open
== "\n",
838 * Get the output string that would result if the close is not found.
842 function breakSyntax( $openingCount = false ) {
843 if ( $this->open
== "\n" ) {
844 $s = $this->parts
[0]->out
;
846 if ( $openingCount === false ) {
847 $openingCount = $this->count
;
849 $s = str_repeat( $this->open
, $openingCount );
851 foreach ( $this->parts
as $part ) {
868 var $out; // Output accumulator string
870 // Optional member variables:
871 // eqpos Position of equals sign in output accumulator
872 // commentEnd Past-the-end input pointer for the last comment encountered
873 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
875 function __construct( $out = '' ) {
881 * An expansion frame, used as a context to expand the result of preprocessToObj()
884 class PPFrame_DOM
implements PPFrame
{
903 * Hashtable listing templates which are disallowed for expansion in this frame,
904 * having been encountered previously in parent frames.
909 * Recursion depth of this frame, top = 0
910 * Note that this is NOT the same as expansion depth in expand()
915 * Construct a new preprocessor frame.
916 * @param $preprocessor Preprocessor The parent preprocessor
918 function __construct( $preprocessor ) {
919 $this->preprocessor
= $preprocessor;
920 $this->parser
= $preprocessor->parser
;
921 $this->title
= $this->parser
->mTitle
;
922 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
923 $this->loopCheckHash
= array();
928 * Create a new child frame
929 * $args is optionally a multi-root PPNode or array containing the template arguments
931 * @return PPTemplateFrame_DOM
933 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
934 $namedArgs = array();
935 $numberedArgs = array();
936 if ( $title === false ) {
937 $title = $this->title
;
939 if ( $args !== false ) {
941 if ( $args instanceof PPNode
) {
944 foreach ( $args as $arg ) {
945 if ( $arg instanceof PPNode
) {
949 $xpath = new DOMXPath( $arg->ownerDocument
);
952 $nameNodes = $xpath->query( 'name', $arg );
953 $value = $xpath->query( 'value', $arg );
954 if ( $nameNodes->item( 0 )->hasAttributes() ) {
955 // Numbered parameter
956 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
957 $index = $index - $indexOffset;
958 $numberedArgs[$index] = $value->item( 0 );
959 unset( $namedArgs[$index] );
962 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
963 $namedArgs[$name] = $value->item( 0 );
964 unset( $numberedArgs[$name] );
968 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
972 * @throws MWException
977 function expand( $root, $flags = 0 ) {
978 static $expansionDepth = 0;
979 if ( is_string( $root ) ) {
983 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
984 $this->parser
->limitationWarn( 'node-count-exceeded',
985 $this->parser
->mPPNodeCount
,
986 $this->parser
->mOptions
->getMaxPPNodeCount()
988 return '<span class="error">Node-count limit exceeded</span>';
991 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
992 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
994 $this->parser
->mOptions
->getMaxPPExpandDepth()
996 return '<span class="error">Expansion depth limit exceeded</span>';
998 wfProfileIn( __METHOD__
);
1000 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1001 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1004 if ( $root instanceof PPNode_DOM
) {
1005 $root = $root->node
;
1007 if ( $root instanceof DOMDocument
) {
1008 $root = $root->documentElement
;
1011 $outStack = array( '', '' );
1012 $iteratorStack = array( false, $root );
1013 $indexStack = array( 0, 0 );
1015 while ( count( $iteratorStack ) > 1 ) {
1016 $level = count( $outStack ) - 1;
1017 $iteratorNode =& $iteratorStack[ $level ];
1018 $out =& $outStack[$level];
1019 $index =& $indexStack[$level];
1021 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
1023 if ( is_array( $iteratorNode ) ) {
1024 if ( $index >= count( $iteratorNode ) ) {
1025 // All done with this iterator
1026 $iteratorStack[$level] = false;
1027 $contextNode = false;
1029 $contextNode = $iteratorNode[$index];
1032 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1033 if ( $index >= $iteratorNode->length
) {
1034 // All done with this iterator
1035 $iteratorStack[$level] = false;
1036 $contextNode = false;
1038 $contextNode = $iteratorNode->item( $index );
1042 // Copy to $contextNode and then delete from iterator stack,
1043 // because this is not an iterator but we do have to execute it once
1044 $contextNode = $iteratorStack[$level];
1045 $iteratorStack[$level] = false;
1048 if ( $contextNode instanceof PPNode_DOM
) {
1049 $contextNode = $contextNode->node
;
1052 $newIterator = false;
1054 if ( $contextNode === false ) {
1056 } elseif ( is_string( $contextNode ) ) {
1057 $out .= $contextNode;
1058 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1059 $newIterator = $contextNode;
1060 } elseif ( $contextNode instanceof DOMNode
) {
1061 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1062 $out .= $contextNode->nodeValue
;
1063 } elseif ( $contextNode->nodeName
== 'template' ) {
1064 # Double-brace expansion
1065 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1066 $titles = $xpath->query( 'title', $contextNode );
1067 $title = $titles->item( 0 );
1068 $parts = $xpath->query( 'part', $contextNode );
1069 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1070 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1072 $lineStart = $contextNode->getAttribute( 'lineStart' );
1074 'title' => new PPNode_DOM( $title ),
1075 'parts' => new PPNode_DOM( $parts ),
1076 'lineStart' => $lineStart );
1077 $ret = $this->parser
->braceSubstitution( $params, $this );
1078 if ( isset( $ret['object'] ) ) {
1079 $newIterator = $ret['object'];
1081 $out .= $ret['text'];
1084 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1085 # Triple-brace expansion
1086 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1087 $titles = $xpath->query( 'title', $contextNode );
1088 $title = $titles->item( 0 );
1089 $parts = $xpath->query( 'part', $contextNode );
1090 if ( $flags & PPFrame
::NO_ARGS
) {
1091 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1094 'title' => new PPNode_DOM( $title ),
1095 'parts' => new PPNode_DOM( $parts ) );
1096 $ret = $this->parser
->argSubstitution( $params, $this );
1097 if ( isset( $ret['object'] ) ) {
1098 $newIterator = $ret['object'];
1100 $out .= $ret['text'];
1103 } elseif ( $contextNode->nodeName
== 'comment' ) {
1104 # HTML-style comment
1105 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1106 if ( $this->parser
->ot
['html']
1107 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1108 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1112 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1113 # Not in RECOVER_COMMENTS mode (extractSections) though
1114 elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1115 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1117 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1119 $out .= $contextNode->textContent
;
1121 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1122 # Output suppression used by <includeonly> etc.
1123 # OT_WIKI will only respect <ignore> in substed templates.
1124 # The other output types respect it unless NO_IGNORE is set.
1125 # extractSections() sets NO_IGNORE and so never respects it.
1126 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1127 $out .= $contextNode->textContent
;
1131 } elseif ( $contextNode->nodeName
== 'ext' ) {
1133 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1134 $names = $xpath->query( 'name', $contextNode );
1135 $attrs = $xpath->query( 'attr', $contextNode );
1136 $inners = $xpath->query( 'inner', $contextNode );
1137 $closes = $xpath->query( 'close', $contextNode );
1139 'name' => new PPNode_DOM( $names->item( 0 ) ),
1140 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1141 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1142 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1144 $out .= $this->parser
->extensionSubstitution( $params, $this );
1145 } elseif ( $contextNode->nodeName
== 'h' ) {
1147 $s = $this->expand( $contextNode->childNodes
, $flags );
1149 # Insert a heading marker only for <h> children of <root>
1150 # This is to stop extractSections from going over multiple tree levels
1151 if ( $contextNode->parentNode
->nodeName
== 'root'
1152 && $this->parser
->ot
['html'] )
1154 # Insert heading index marker
1155 $headingIndex = $contextNode->getAttribute( 'i' );
1156 $titleText = $this->title
->getPrefixedDBkey();
1157 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1158 $serial = count( $this->parser
->mHeadings
) - 1;
1159 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1160 $count = $contextNode->getAttribute( 'level' );
1161 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1162 $this->parser
->mStripState
->addGeneral( $marker, '' );
1166 # Generic recursive expansion
1167 $newIterator = $contextNode->childNodes
;
1170 wfProfileOut( __METHOD__
);
1171 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1174 if ( $newIterator !== false ) {
1175 if ( $newIterator instanceof PPNode_DOM
) {
1176 $newIterator = $newIterator->node
;
1179 $iteratorStack[] = $newIterator;
1181 } elseif ( $iteratorStack[$level] === false ) {
1182 // Return accumulated value to parent
1183 // With tail recursion
1184 while ( $iteratorStack[$level] === false && $level > 0 ) {
1185 $outStack[$level - 1] .= $out;
1186 array_pop( $outStack );
1187 array_pop( $iteratorStack );
1188 array_pop( $indexStack );
1194 wfProfileOut( __METHOD__
);
1195 return $outStack[0];
1203 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1204 $args = array_slice( func_get_args(), 2 );
1208 foreach ( $args as $root ) {
1209 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1210 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1211 $root = array( $root );
1213 foreach ( $root as $node ) {
1219 $s .= $this->expand( $node, $flags );
1226 * Implode with no flags specified
1227 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1231 function implode( $sep /*, ... */ ) {
1232 $args = array_slice( func_get_args(), 1 );
1236 foreach ( $args as $root ) {
1237 if ( $root instanceof PPNode_DOM
) {
1238 $root = $root->node
;
1240 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1241 $root = array( $root );
1243 foreach ( $root as $node ) {
1249 $s .= $this->expand( $node );
1256 * Makes an object that, when expand()ed, will be the same as one obtained
1261 function virtualImplode( $sep /*, ... */ ) {
1262 $args = array_slice( func_get_args(), 1 );
1266 foreach ( $args as $root ) {
1267 if ( $root instanceof PPNode_DOM
) {
1268 $root = $root->node
;
1270 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1271 $root = array( $root );
1273 foreach ( $root as $node ) {
1286 * Virtual implode with brackets
1289 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1290 $args = array_slice( func_get_args(), 3 );
1291 $out = array( $start );
1294 foreach ( $args as $root ) {
1295 if ( $root instanceof PPNode_DOM
) {
1296 $root = $root->node
;
1298 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1299 $root = array( $root );
1301 foreach ( $root as $node ) {
1314 function __toString() {
1318 function getPDBK( $level = false ) {
1319 if ( $level === false ) {
1320 return $this->title
->getPrefixedDBkey();
1322 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1329 function getArguments() {
1336 function getNumberedArguments() {
1343 function getNamedArguments() {
1348 * Returns true if there are no arguments in this frame
1352 function isEmpty() {
1356 function getArgument( $name ) {
1361 * Returns true if the infinite loop check is OK, false if a loop is detected
1365 function loopCheck( $title ) {
1366 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1370 * Return true if the frame is a template frame
1374 function isTemplate() {
1379 * Get a title of frame
1383 function getTitle() {
1384 return $this->title
;
1389 * Expansion frame with template arguments
1392 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1393 var $numberedArgs, $namedArgs;
1399 var $numberedExpansionCache, $namedExpansionCache;
1402 * @param $preprocessor
1403 * @param $parent PPFrame_DOM
1404 * @param $numberedArgs array
1405 * @param $namedArgs array
1406 * @param $title Title
1408 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1409 parent
::__construct( $preprocessor );
1411 $this->parent
= $parent;
1412 $this->numberedArgs
= $numberedArgs;
1413 $this->namedArgs
= $namedArgs;
1414 $this->title
= $title;
1415 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1416 $this->titleCache
= $parent->titleCache
;
1417 $this->titleCache
[] = $pdbk;
1418 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1419 if ( $pdbk !== false ) {
1420 $this->loopCheckHash
[$pdbk] = true;
1422 $this->depth
= $parent->depth +
1;
1423 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1426 function __toString() {
1429 $args = $this->numberedArgs +
$this->namedArgs
;
1430 foreach ( $args as $name => $value ) {
1436 $s .= "\"$name\":\"" .
1437 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1444 * Returns true if there are no arguments in this frame
1448 function isEmpty() {
1449 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1452 function getArguments() {
1453 $arguments = array();
1454 foreach ( array_merge(
1455 array_keys( $this->numberedArgs
),
1456 array_keys( $this->namedArgs
) ) as $key ) {
1457 $arguments[$key] = $this->getArgument( $key );
1462 function getNumberedArguments() {
1463 $arguments = array();
1464 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1465 $arguments[$key] = $this->getArgument( $key );
1470 function getNamedArguments() {
1471 $arguments = array();
1472 foreach ( array_keys( $this->namedArgs
) as $key ) {
1473 $arguments[$key] = $this->getArgument( $key );
1478 function getNumberedArgument( $index ) {
1479 if ( !isset( $this->numberedArgs
[$index] ) ) {
1482 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1483 # No trimming for unnamed arguments
1484 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1486 return $this->numberedExpansionCache
[$index];
1489 function getNamedArgument( $name ) {
1490 if ( !isset( $this->namedArgs
[$name] ) ) {
1493 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1494 # Trim named arguments post-expand, for backwards compatibility
1495 $this->namedExpansionCache
[$name] = trim(
1496 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1498 return $this->namedExpansionCache
[$name];
1501 function getArgument( $name ) {
1502 $text = $this->getNumberedArgument( $name );
1503 if ( $text === false ) {
1504 $text = $this->getNamedArgument( $name );
1510 * Return true if the frame is a template frame
1514 function isTemplate() {
1520 * Expansion frame with custom arguments
1523 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1526 function __construct( $preprocessor, $args ) {
1527 parent
::__construct( $preprocessor );
1528 $this->args
= $args;
1531 function __toString() {
1534 foreach ( $this->args
as $name => $value ) {
1540 $s .= "\"$name\":\"" .
1541 str_replace( '"', '\\"', $value->__toString() ) . '"';
1550 function isEmpty() {
1551 return !count( $this->args
);
1554 function getArgument( $index ) {
1555 if ( !isset( $this->args
[$index] ) ) {
1558 return $this->args
[$index];
1561 function getArguments() {
1569 class PPNode_DOM
implements PPNode
{
1577 function __construct( $node, $xpath = false ) {
1578 $this->node
= $node;
1584 function getXPath() {
1585 if ( $this->xpath
=== null ) {
1586 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1588 return $this->xpath
;
1591 function __toString() {
1592 if ( $this->node
instanceof DOMNodeList
) {
1594 foreach ( $this->node
as $node ) {
1595 $s .= $node->ownerDocument
->saveXML( $node );
1598 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1604 * @return bool|PPNode_DOM
1606 function getChildren() {
1607 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1611 * @return bool|PPNode_DOM
1613 function getFirstChild() {
1614 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1618 * @return bool|PPNode_DOM
1620 function getNextSibling() {
1621 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1627 * @return bool|PPNode_DOM
1629 function getChildrenOfType( $type ) {
1630 return new self( $this->getXPath()->query( $type, $this->node
) );
1636 function getLength() {
1637 if ( $this->node
instanceof DOMNodeList
) {
1638 return $this->node
->length
;
1646 * @return bool|PPNode_DOM
1648 function item( $i ) {
1649 $item = $this->node
->item( $i );
1650 return $item ?
new self( $item ) : false;
1656 function getName() {
1657 if ( $this->node
instanceof DOMNodeList
) {
1660 return $this->node
->nodeName
;
1665 * Split a "<part>" node into an associative array containing:
1666 * - name PPNode name
1667 * - index String index
1668 * - value PPNode value
1670 * @throws MWException
1673 function splitArg() {
1674 $xpath = $this->getXPath();
1675 $names = $xpath->query( 'name', $this->node
);
1676 $values = $xpath->query( 'value', $this->node
);
1677 if ( !$names->length ||
!$values->length
) {
1678 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1680 $name = $names->item( 0 );
1681 $index = $name->getAttribute( 'index' );
1683 'name' => new self( $name ),
1685 'value' => new self( $values->item( 0 ) ) );
1689 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1690 * All values in the resulting array are PPNodes. Inner and close are optional.
1692 * @throws MWException
1695 function splitExt() {
1696 $xpath = $this->getXPath();
1697 $names = $xpath->query( 'name', $this->node
);
1698 $attrs = $xpath->query( 'attr', $this->node
);
1699 $inners = $xpath->query( 'inner', $this->node
);
1700 $closes = $xpath->query( 'close', $this->node
);
1701 if ( !$names->length ||
!$attrs->length
) {
1702 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1705 'name' => new self( $names->item( 0 ) ),
1706 'attr' => new self( $attrs->item( 0 ) ) );
1707 if ( $inners->length
) {
1708 $parts['inner'] = new self( $inners->item( 0 ) );
1710 if ( $closes->length
) {
1711 $parts['close'] = new self( $closes->item( 0 ) );
1717 * Split a "<h>" node
1718 * @throws MWException
1721 function splitHeading() {
1722 if ( $this->getName() !== 'h' ) {
1723 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1726 'i' => $this->node
->getAttribute( 'i' ),
1727 'level' => $this->node
->getAttribute( 'level' ),
1728 'contents' => $this->getChildren()