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.
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 behaviour /={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 $names = $rules[$piece->open
]['names'];
663 $enclosingAccum =& $accum;
664 while ( $piece->count
) {
665 if ( array_key_exists( $piece->count
, $names ) ) {
666 $stack->push( $piece );
667 $accum =& $stack->getAccum();
673 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
675 $flags = $stack->getFlags();
678 # Add XML element to the enclosing accumulator
680 } elseif ( $found == 'pipe' ) {
681 $findEquals = true; // shortcut for getFlags()
683 $accum =& $stack->getAccum();
685 } elseif ( $found == 'equals' ) {
686 $findEquals = false; // shortcut for getFlags()
687 $stack->getCurrentPart()->eqpos
= strlen( $accum );
693 # Output any remaining unclosed brackets
694 foreach ( $stack->stack
as $piece ) {
695 $stack->rootAccum
.= $piece->breakSyntax();
697 $stack->rootAccum
.= '</root>';
698 $xml = $stack->rootAccum
;
700 wfProfileOut( __METHOD__
);
707 * Stack class to help Preprocessor::preprocessToObj()
711 var $stack, $rootAccum;
718 var $elementClass = 'PPDStackElement';
720 static $false = false;
722 function __construct() {
723 $this->stack
= array();
725 $this->rootAccum
= '';
726 $this->accum
=& $this->rootAccum
;
733 return count( $this->stack
);
736 function &getAccum() {
740 function getCurrentPart() {
741 if ( $this->top
=== false ) {
744 return $this->top
->getCurrentPart();
748 function push( $data ) {
749 if ( $data instanceof $this->elementClass
) {
750 $this->stack
[] = $data;
752 $class = $this->elementClass
;
753 $this->stack
[] = new $class( $data );
755 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
756 $this->accum
=& $this->top
->getAccum();
760 if ( !count( $this->stack
) ) {
761 throw new MWException( __METHOD__
.': no elements remaining' );
763 $temp = array_pop( $this->stack
);
765 if ( count( $this->stack
) ) {
766 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
767 $this->accum
=& $this->top
->getAccum();
769 $this->top
= self
::$false;
770 $this->accum
=& $this->rootAccum
;
775 function addPart( $s = '' ) {
776 $this->top
->addPart( $s );
777 $this->accum
=& $this->top
->getAccum();
783 function getFlags() {
784 if ( !count( $this->stack
) ) {
786 'findEquals' => false,
788 'inHeading' => false,
791 return $this->top
->getFlags();
799 class PPDStackElement
{
800 var $open, // Opening character (\n for heading)
801 $close, // Matching closing character
802 $count, // Number of opening characters found (number of "=" for heading)
803 $parts, // Array of PPDPart objects describing pipe-separated parts.
804 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
806 var $partClass = 'PPDPart';
808 function __construct( $data = array() ) {
809 $class = $this->partClass
;
810 $this->parts
= array( new $class );
812 foreach ( $data as $name => $value ) {
813 $this->$name = $value;
817 function &getAccum() {
818 return $this->parts
[count($this->parts
) - 1]->out
;
821 function addPart( $s = '' ) {
822 $class = $this->partClass
;
823 $this->parts
[] = new $class( $s );
826 function getCurrentPart() {
827 return $this->parts
[count($this->parts
) - 1];
833 function getFlags() {
834 $partCount = count( $this->parts
);
835 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
837 'findPipe' => $findPipe,
838 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
839 'inHeading' => $this->open
== "\n",
844 * Get the output string that would result if the close is not found.
848 function breakSyntax( $openingCount = false ) {
849 if ( $this->open
== "\n" ) {
850 $s = $this->parts
[0]->out
;
852 if ( $openingCount === false ) {
853 $openingCount = $this->count
;
855 $s = str_repeat( $this->open
, $openingCount );
857 foreach ( $this->parts
as $part ) {
874 var $out; // Output accumulator string
876 // Optional member variables:
877 // eqpos Position of equals sign in output accumulator
878 // commentEnd Past-the-end input pointer for the last comment encountered
879 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
881 function __construct( $out = '' ) {
887 * An expansion frame, used as a context to expand the result of preprocessToObj()
890 class PPFrame_DOM
implements PPFrame
{
909 * Hashtable listing templates which are disallowed for expansion in this frame,
910 * having been encountered previously in parent frames.
915 * Recursion depth of this frame, top = 0
916 * Note that this is NOT the same as expansion depth in expand()
922 * Construct a new preprocessor frame.
923 * @param $preprocessor Preprocessor The parent preprocessor
925 function __construct( $preprocessor ) {
926 $this->preprocessor
= $preprocessor;
927 $this->parser
= $preprocessor->parser
;
928 $this->title
= $this->parser
->mTitle
;
929 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
930 $this->loopCheckHash
= array();
935 * Create a new child frame
936 * $args is optionally a multi-root PPNode or array containing the template arguments
938 * @return PPTemplateFrame_DOM
940 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
941 $namedArgs = array();
942 $numberedArgs = array();
943 if ( $title === false ) {
944 $title = $this->title
;
946 if ( $args !== false ) {
948 if ( $args instanceof PPNode
) {
951 foreach ( $args as $arg ) {
952 if ( $arg instanceof PPNode
) {
956 $xpath = new DOMXPath( $arg->ownerDocument
);
959 $nameNodes = $xpath->query( 'name', $arg );
960 $value = $xpath->query( 'value', $arg );
961 if ( $nameNodes->item( 0 )->hasAttributes() ) {
962 // Numbered parameter
963 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
964 $index = $index - $indexOffset;
965 $numberedArgs[$index] = $value->item( 0 );
966 unset( $namedArgs[$index] );
969 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
970 $namedArgs[$name] = $value->item( 0 );
971 unset( $numberedArgs[$name] );
975 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
979 * @throws MWException
984 function expand( $root, $flags = 0 ) {
985 static $expansionDepth = 0;
986 if ( is_string( $root ) ) {
990 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
991 $this->parser
->limitationWarn( 'node-count-exceeded',
992 $this->parser
->mPPNodeCount
,
993 $this->parser
->mOptions
->getMaxPPNodeCount()
995 return '<span class="error">Node-count limit exceeded</span>';
998 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
999 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1001 $this->parser
->mOptions
->getMaxPPExpandDepth()
1003 return '<span class="error">Expansion depth limit exceeded</span>';
1005 wfProfileIn( __METHOD__
);
1007 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1008 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1011 if ( $root instanceof PPNode_DOM
) {
1012 $root = $root->node
;
1014 if ( $root instanceof DOMDocument
) {
1015 $root = $root->documentElement
;
1018 $outStack = array( '', '' );
1019 $iteratorStack = array( false, $root );
1020 $indexStack = array( 0, 0 );
1022 while ( count( $iteratorStack ) > 1 ) {
1023 $level = count( $outStack ) - 1;
1024 $iteratorNode =& $iteratorStack[ $level ];
1025 $out =& $outStack[$level];
1026 $index =& $indexStack[$level];
1028 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
1030 if ( is_array( $iteratorNode ) ) {
1031 if ( $index >= count( $iteratorNode ) ) {
1032 // All done with this iterator
1033 $iteratorStack[$level] = false;
1034 $contextNode = false;
1036 $contextNode = $iteratorNode[$index];
1039 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1040 if ( $index >= $iteratorNode->length
) {
1041 // All done with this iterator
1042 $iteratorStack[$level] = false;
1043 $contextNode = false;
1045 $contextNode = $iteratorNode->item( $index );
1049 // Copy to $contextNode and then delete from iterator stack,
1050 // because this is not an iterator but we do have to execute it once
1051 $contextNode = $iteratorStack[$level];
1052 $iteratorStack[$level] = false;
1055 if ( $contextNode instanceof PPNode_DOM
) {
1056 $contextNode = $contextNode->node
;
1059 $newIterator = false;
1061 if ( $contextNode === false ) {
1063 } elseif ( is_string( $contextNode ) ) {
1064 $out .= $contextNode;
1065 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1066 $newIterator = $contextNode;
1067 } elseif ( $contextNode instanceof DOMNode
) {
1068 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1069 $out .= $contextNode->nodeValue
;
1070 } elseif ( $contextNode->nodeName
== 'template' ) {
1071 # Double-brace expansion
1072 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1073 $titles = $xpath->query( 'title', $contextNode );
1074 $title = $titles->item( 0 );
1075 $parts = $xpath->query( 'part', $contextNode );
1076 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1077 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1079 $lineStart = $contextNode->getAttribute( 'lineStart' );
1081 'title' => new PPNode_DOM( $title ),
1082 'parts' => new PPNode_DOM( $parts ),
1083 'lineStart' => $lineStart );
1084 $ret = $this->parser
->braceSubstitution( $params, $this );
1085 if ( isset( $ret['object'] ) ) {
1086 $newIterator = $ret['object'];
1088 $out .= $ret['text'];
1091 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1092 # Triple-brace expansion
1093 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1094 $titles = $xpath->query( 'title', $contextNode );
1095 $title = $titles->item( 0 );
1096 $parts = $xpath->query( 'part', $contextNode );
1097 if ( $flags & PPFrame
::NO_ARGS
) {
1098 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1101 'title' => new PPNode_DOM( $title ),
1102 'parts' => new PPNode_DOM( $parts ) );
1103 $ret = $this->parser
->argSubstitution( $params, $this );
1104 if ( isset( $ret['object'] ) ) {
1105 $newIterator = $ret['object'];
1107 $out .= $ret['text'];
1110 } elseif ( $contextNode->nodeName
== 'comment' ) {
1111 # HTML-style comment
1112 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1113 if ( $this->parser
->ot
['html']
1114 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1115 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1119 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1120 # Not in RECOVER_COMMENTS mode (extractSections) though
1121 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1122 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1124 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1126 $out .= $contextNode->textContent
;
1128 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1129 # Output suppression used by <includeonly> etc.
1130 # OT_WIKI will only respect <ignore> in substed templates.
1131 # The other output types respect it unless NO_IGNORE is set.
1132 # extractSections() sets NO_IGNORE and so never respects it.
1133 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1134 $out .= $contextNode->textContent
;
1138 } elseif ( $contextNode->nodeName
== 'ext' ) {
1140 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1141 $names = $xpath->query( 'name', $contextNode );
1142 $attrs = $xpath->query( 'attr', $contextNode );
1143 $inners = $xpath->query( 'inner', $contextNode );
1144 $closes = $xpath->query( 'close', $contextNode );
1146 'name' => new PPNode_DOM( $names->item( 0 ) ),
1147 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1148 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1149 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1151 $out .= $this->parser
->extensionSubstitution( $params, $this );
1152 } elseif ( $contextNode->nodeName
== 'h' ) {
1154 $s = $this->expand( $contextNode->childNodes
, $flags );
1156 # Insert a heading marker only for <h> children of <root>
1157 # This is to stop extractSections from going over multiple tree levels
1158 if ( $contextNode->parentNode
->nodeName
== 'root'
1159 && $this->parser
->ot
['html'] )
1161 # Insert heading index marker
1162 $headingIndex = $contextNode->getAttribute( 'i' );
1163 $titleText = $this->title
->getPrefixedDBkey();
1164 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1165 $serial = count( $this->parser
->mHeadings
) - 1;
1166 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1167 $count = $contextNode->getAttribute( 'level' );
1168 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1169 $this->parser
->mStripState
->addGeneral( $marker, '' );
1173 # Generic recursive expansion
1174 $newIterator = $contextNode->childNodes
;
1177 wfProfileOut( __METHOD__
);
1178 throw new MWException( __METHOD__
.': Invalid parameter type' );
1181 if ( $newIterator !== false ) {
1182 if ( $newIterator instanceof PPNode_DOM
) {
1183 $newIterator = $newIterator->node
;
1186 $iteratorStack[] = $newIterator;
1188 } elseif ( $iteratorStack[$level] === false ) {
1189 // Return accumulated value to parent
1190 // With tail recursion
1191 while ( $iteratorStack[$level] === false && $level > 0 ) {
1192 $outStack[$level - 1] .= $out;
1193 array_pop( $outStack );
1194 array_pop( $iteratorStack );
1195 array_pop( $indexStack );
1201 wfProfileOut( __METHOD__
);
1202 return $outStack[0];
1210 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1211 $args = array_slice( func_get_args(), 2 );
1215 foreach ( $args as $root ) {
1216 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1217 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1218 $root = array( $root );
1220 foreach ( $root as $node ) {
1226 $s .= $this->expand( $node, $flags );
1233 * Implode with no flags specified
1234 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1238 function implode( $sep /*, ... */ ) {
1239 $args = array_slice( func_get_args(), 1 );
1243 foreach ( $args as $root ) {
1244 if ( $root instanceof PPNode_DOM
) {
1245 $root = $root->node
;
1247 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1248 $root = array( $root );
1250 foreach ( $root as $node ) {
1256 $s .= $this->expand( $node );
1263 * Makes an object that, when expand()ed, will be the same as one obtained
1268 function virtualImplode( $sep /*, ... */ ) {
1269 $args = array_slice( func_get_args(), 1 );
1273 foreach ( $args as $root ) {
1274 if ( $root instanceof PPNode_DOM
) {
1275 $root = $root->node
;
1277 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1278 $root = array( $root );
1280 foreach ( $root as $node ) {
1293 * Virtual implode with brackets
1296 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1297 $args = array_slice( func_get_args(), 3 );
1298 $out = array( $start );
1301 foreach ( $args as $root ) {
1302 if ( $root instanceof PPNode_DOM
) {
1303 $root = $root->node
;
1305 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1306 $root = array( $root );
1308 foreach ( $root as $node ) {
1321 function __toString() {
1325 function getPDBK( $level = false ) {
1326 if ( $level === false ) {
1327 return $this->title
->getPrefixedDBkey();
1329 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1336 function getArguments() {
1343 function getNumberedArguments() {
1350 function getNamedArguments() {
1355 * Returns true if there are no arguments in this frame
1359 function isEmpty() {
1363 function getArgument( $name ) {
1368 * Returns true if the infinite loop check is OK, false if a loop is detected
1372 function loopCheck( $title ) {
1373 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1377 * Return true if the frame is a template frame
1381 function isTemplate() {
1386 * Get a title of frame
1390 function getTitle() {
1391 return $this->title
;
1396 * Expansion frame with template arguments
1399 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1400 var $numberedArgs, $namedArgs;
1406 var $numberedExpansionCache, $namedExpansionCache;
1409 * @param $preprocessor
1410 * @param $parent PPFrame_DOM
1411 * @param $numberedArgs array
1412 * @param $namedArgs array
1413 * @param $title Title
1415 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1416 parent
::__construct( $preprocessor );
1418 $this->parent
= $parent;
1419 $this->numberedArgs
= $numberedArgs;
1420 $this->namedArgs
= $namedArgs;
1421 $this->title
= $title;
1422 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1423 $this->titleCache
= $parent->titleCache
;
1424 $this->titleCache
[] = $pdbk;
1425 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1426 if ( $pdbk !== false ) {
1427 $this->loopCheckHash
[$pdbk] = true;
1429 $this->depth
= $parent->depth +
1;
1430 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1433 function __toString() {
1436 $args = $this->numberedArgs +
$this->namedArgs
;
1437 foreach ( $args as $name => $value ) {
1443 $s .= "\"$name\":\"" .
1444 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1451 * Returns true if there are no arguments in this frame
1455 function isEmpty() {
1456 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1459 function getArguments() {
1460 $arguments = array();
1461 foreach ( array_merge(
1462 array_keys($this->numberedArgs
),
1463 array_keys($this->namedArgs
)) as $key ) {
1464 $arguments[$key] = $this->getArgument($key);
1469 function getNumberedArguments() {
1470 $arguments = array();
1471 foreach ( array_keys($this->numberedArgs
) as $key ) {
1472 $arguments[$key] = $this->getArgument($key);
1477 function getNamedArguments() {
1478 $arguments = array();
1479 foreach ( array_keys($this->namedArgs
) as $key ) {
1480 $arguments[$key] = $this->getArgument($key);
1485 function getNumberedArgument( $index ) {
1486 if ( !isset( $this->numberedArgs
[$index] ) ) {
1489 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1490 # No trimming for unnamed arguments
1491 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1493 return $this->numberedExpansionCache
[$index];
1496 function getNamedArgument( $name ) {
1497 if ( !isset( $this->namedArgs
[$name] ) ) {
1500 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1501 # Trim named arguments post-expand, for backwards compatibility
1502 $this->namedExpansionCache
[$name] = trim(
1503 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1505 return $this->namedExpansionCache
[$name];
1508 function getArgument( $name ) {
1509 $text = $this->getNumberedArgument( $name );
1510 if ( $text === false ) {
1511 $text = $this->getNamedArgument( $name );
1517 * Return true if the frame is a template frame
1521 function isTemplate() {
1527 * Expansion frame with custom arguments
1530 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1533 function __construct( $preprocessor, $args ) {
1534 parent
::__construct( $preprocessor );
1535 $this->args
= $args;
1538 function __toString() {
1541 foreach ( $this->args
as $name => $value ) {
1547 $s .= "\"$name\":\"" .
1548 str_replace( '"', '\\"', $value->__toString() ) . '"';
1557 function isEmpty() {
1558 return !count( $this->args
);
1561 function getArgument( $index ) {
1562 if ( !isset( $this->args
[$index] ) ) {
1565 return $this->args
[$index];
1568 function getArguments() {
1576 class PPNode_DOM
implements PPNode
{
1584 function __construct( $node, $xpath = false ) {
1585 $this->node
= $node;
1591 function getXPath() {
1592 if ( $this->xpath
=== null ) {
1593 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1595 return $this->xpath
;
1598 function __toString() {
1599 if ( $this->node
instanceof DOMNodeList
) {
1601 foreach ( $this->node
as $node ) {
1602 $s .= $node->ownerDocument
->saveXML( $node );
1605 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1611 * @return bool|PPNode_DOM
1613 function getChildren() {
1614 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1618 * @return bool|PPNode_DOM
1620 function getFirstChild() {
1621 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1625 * @return bool|PPNode_DOM
1627 function getNextSibling() {
1628 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1634 * @return bool|PPNode_DOM
1636 function getChildrenOfType( $type ) {
1637 return new self( $this->getXPath()->query( $type, $this->node
) );
1643 function getLength() {
1644 if ( $this->node
instanceof DOMNodeList
) {
1645 return $this->node
->length
;
1653 * @return bool|PPNode_DOM
1655 function item( $i ) {
1656 $item = $this->node
->item( $i );
1657 return $item ?
new self( $item ) : false;
1663 function getName() {
1664 if ( $this->node
instanceof DOMNodeList
) {
1667 return $this->node
->nodeName
;
1672 * Split a "<part>" node into an associative array containing:
1673 * - name PPNode name
1674 * - index String index
1675 * - value PPNode value
1677 * @throws MWException
1680 function splitArg() {
1681 $xpath = $this->getXPath();
1682 $names = $xpath->query( 'name', $this->node
);
1683 $values = $xpath->query( 'value', $this->node
);
1684 if ( !$names->length ||
!$values->length
) {
1685 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1687 $name = $names->item( 0 );
1688 $index = $name->getAttribute( 'index' );
1690 'name' => new self( $name ),
1692 'value' => new self( $values->item( 0 ) ) );
1696 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1697 * All values in the resulting array are PPNodes. Inner and close are optional.
1699 * @throws MWException
1702 function splitExt() {
1703 $xpath = $this->getXPath();
1704 $names = $xpath->query( 'name', $this->node
);
1705 $attrs = $xpath->query( 'attr', $this->node
);
1706 $inners = $xpath->query( 'inner', $this->node
);
1707 $closes = $xpath->query( 'close', $this->node
);
1708 if ( !$names->length ||
!$attrs->length
) {
1709 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1712 'name' => new self( $names->item( 0 ) ),
1713 'attr' => new self( $attrs->item( 0 ) ) );
1714 if ( $inners->length
) {
1715 $parts['inner'] = new self( $inners->item( 0 ) );
1717 if ( $closes->length
) {
1718 $parts['close'] = new self( $closes->item( 0 ) );
1724 * Split a "<h>" node
1725 * @throws MWException
1728 function splitHeading() {
1729 if ( $this->getName() !== 'h' ) {
1730 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1733 'i' => $this->node
->getAttribute( 'i' ),
1734 'level' => $this->node
->getAttribute( 'level' ),
1735 'contents' => $this->getChildren()