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>/<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 );
165 wfProfileIn( __METHOD__
.'-loadXML' );
166 $dom = new DOMDocument
;
167 wfSuppressWarnings();
168 $result = $dom->loadXML( $xml );
171 // Try running the XML through UtfNormal to get rid of invalid characters
172 $xml = UtfNormal
::cleanUp( $xml );
173 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
174 $result = $dom->loadXML( $xml, 1 << 19 );
176 throw new MWException( __METHOD__
.' generated invalid XML' );
179 $obj = new PPNode_DOM( $dom->documentElement
);
180 wfProfileOut( __METHOD__
.'-loadXML' );
182 wfProfileOut( __METHOD__
.'-cacheable' );
184 wfProfileOut( __METHOD__
);
189 * @param $text string
193 function preprocessToXml( $text, $flags = 0 ) {
194 wfProfileIn( __METHOD__
);
207 'names' => array( 2 => null ),
213 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
215 $xmlishElements = $this->parser
->getStripList();
216 $enableOnlyinclude = false;
217 if ( $forInclusion ) {
218 $ignoredTags = array( 'includeonly', '/includeonly' );
219 $ignoredElements = array( 'noinclude' );
220 $xmlishElements[] = 'noinclude';
221 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
222 $enableOnlyinclude = true;
225 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
226 $ignoredElements = array( 'includeonly' );
227 $xmlishElements[] = 'includeonly';
229 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
231 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
232 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
234 $stack = new PPDStack
;
236 $searchBase = "[{<\n"; #}
237 $revText = strrev( $text ); // For fast reverse searches
239 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
240 $accum =& $stack->getAccum(); # Current accumulator
242 $findEquals = false; # True to find equals signs in arguments
243 $findPipe = false; # True to take notice of pipe characters
245 $inHeading = false; # True if $i is inside a possible heading
246 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
247 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
248 $fakeLineStart = true; # Do a line-start run without outputting an LF character
253 if ( $findOnlyinclude ) {
254 // Ignore all input up to the next <onlyinclude>
255 $startPos = strpos( $text, '<onlyinclude>', $i );
256 if ( $startPos === false ) {
257 // Ignored section runs to the end
258 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
261 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
262 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
264 $findOnlyinclude = false;
267 if ( $fakeLineStart ) {
268 $found = 'line-start';
271 # Find next opening brace, closing brace or pipe
272 $search = $searchBase;
273 if ( $stack->top
=== false ) {
274 $currentClosing = '';
276 $currentClosing = $stack->top
->close
;
277 $search .= $currentClosing;
283 // First equals will be for the template
287 # Output literal section, advance input counter
288 $literalLength = strcspn( $text, $search, $i );
289 if ( $literalLength > 0 ) {
290 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
291 $i +
= $literalLength;
293 if ( $i >= strlen( $text ) ) {
294 if ( $currentClosing == "\n" ) {
295 // Do a past-the-end run to finish off the heading
303 $curChar = $text[$i];
304 if ( $curChar == '|' ) {
306 } elseif ( $curChar == '=' ) {
308 } elseif ( $curChar == '<' ) {
310 } elseif ( $curChar == "\n" ) {
314 $found = 'line-start';
316 } elseif ( $curChar == $currentClosing ) {
318 } elseif ( isset( $rules[$curChar] ) ) {
320 $rule = $rules[$curChar];
322 # Some versions of PHP have a strcspn which stops on null characters
323 # Ignore and continue
330 if ( $found == 'angle' ) {
332 // Handle </onlyinclude>
333 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
334 $findOnlyinclude = true;
338 // Determine element name
339 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
340 // Element name missing or not listed
346 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
347 // To avoid leaving blank lines, when a comment is both preceded
348 // and followed by a newline (ignoring spaces), trim leading and
349 // trailing spaces and one of the newlines.
352 $endPos = strpos( $text, '-->', $i +
4 );
353 if ( $endPos === false ) {
354 // Unclosed comment in input, runs to end
355 $inner = substr( $text, $i );
356 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
357 $i = strlen( $text );
359 // Search backwards for leading whitespace
360 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
361 // Search forwards for trailing whitespace
362 // $wsEnd will be the position of the last space (or the '>' if there's none)
363 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
364 // Eat the line if possible
365 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
366 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
367 // it's a possible beneficial b/c break.
368 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
369 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
371 $startPos = $wsStart;
372 $endPos = $wsEnd +
1;
373 // Remove leading whitespace from the end of the accumulator
374 // Sanity check first though
375 $wsLength = $i - $wsStart;
376 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
377 $accum = substr( $accum, 0, -$wsLength );
379 // Do a line-start run next time to look for headings after the comment
380 $fakeLineStart = true;
382 // No line to eat, just take the comment itself
388 $part = $stack->top
->getCurrentPart();
389 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
390 $part->visualEnd
= $wsStart;
392 // Else comments abutting, no change in visual end
393 $part->commentEnd
= $endPos;
396 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
397 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
402 $lowerName = strtolower( $name );
403 $attrStart = $i +
strlen( $name ) +
1;
406 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
407 if ( $tagEndPos === false ) {
408 // Infinite backtrack
409 // Disable tag search to prevent worst-case O(N^2) performance
416 // Handle ignored tags
417 if ( in_array( $lowerName, $ignoredTags ) ) {
418 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
424 if ( $text[$tagEndPos-1] == '/' ) {
425 $attrEnd = $tagEndPos - 1;
430 $attrEnd = $tagEndPos;
432 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
433 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
435 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
436 $i = $matches[0][1] +
strlen( $matches[0][0] );
437 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
439 // No end tag -- let it run out to the end of the text.
440 $inner = substr( $text, $tagEndPos +
1 );
441 $i = strlen( $text );
445 // <includeonly> and <noinclude> just become <ignore> tags
446 if ( in_array( $lowerName, $ignoredElements ) ) {
447 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
453 if ( $attrEnd <= $attrStart ) {
456 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
458 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
459 // Note that the attr element contains the whitespace between name and attribute,
460 // this is necessary for precise reconstruction during pre-save transform.
461 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
462 if ( $inner !== null ) {
463 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
465 $accum .= $close . '</ext>';
466 } elseif ( $found == 'line-start' ) {
467 // Is this the start of a heading?
468 // Line break belongs before the heading element in any case
469 if ( $fakeLineStart ) {
470 $fakeLineStart = false;
476 $count = strspn( $text, '=', $i, 6 );
477 if ( $count == 1 && $findEquals ) {
478 // DWIM: This looks kind of like a name/value separator
479 // Let's let the equals handler have it and break the potential heading
480 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
481 } elseif ( $count > 0 ) {
485 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
488 $stack->push( $piece );
489 $accum =& $stack->getAccum();
490 $flags = $stack->getFlags();
494 } elseif ( $found == 'line-end' ) {
495 $piece = $stack->top
;
496 // A heading must be open, otherwise \n wouldn't have been in the search list
497 assert( '$piece->open == "\n"' );
498 $part = $piece->getCurrentPart();
499 // Search back through the input to see if it has a proper close
500 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
501 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
502 $searchStart = $i - $wsLength;
503 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
504 // Comment found at line end
505 // Search for equals signs before the comment
506 $searchStart = $part->visualEnd
;
507 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
509 $count = $piece->count
;
510 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
511 if ( $equalsLength > 0 ) {
512 if ( $searchStart - $equalsLength == $piece->startPos
) {
513 // This is just a single string of equals signs on its own line
514 // Replicate the doHeadings behaviour /={count}(.+)={count}/
515 // First find out how many equals signs there really are (don't stop at 6)
516 $count = $equalsLength;
520 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
523 $count = min( $equalsLength, $count );
526 // Normal match, output <h>
527 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
530 // Single equals sign on its own line, count=0
534 // No match, no <h>, just pass down the inner text
539 $accum =& $stack->getAccum();
540 $flags = $stack->getFlags();
543 // Append the result to the enclosing accumulator
545 // Note that we do NOT increment the input pointer.
546 // This is because the closing linebreak could be the opening linebreak of
547 // another heading. Infinite loops are avoided because the next iteration MUST
548 // hit the heading open case above, which unconditionally increments the
550 } elseif ( $found == 'open' ) {
551 # count opening brace characters
552 $count = strspn( $text, $curChar, $i );
554 # we need to add to stack only if opening brace count is enough for one of the rules
555 if ( $count >= $rule['min'] ) {
556 # Add it to the stack
559 'close' => $rule['end'],
561 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
564 $stack->push( $piece );
565 $accum =& $stack->getAccum();
566 $flags = $stack->getFlags();
569 # Add literal brace(s)
570 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
573 } elseif ( $found == 'close' ) {
574 $piece = $stack->top
;
575 # lets check if there are enough characters for closing brace
576 $maxCount = $piece->count
;
577 $count = strspn( $text, $curChar, $i, $maxCount );
579 # check for maximum matching characters (if there are 5 closing
580 # characters, we will probably need only 3 - depending on the rules)
581 $rule = $rules[$piece->open
];
582 if ( $count > $rule['max'] ) {
583 # The specified maximum exists in the callback array, unless the caller
585 $matchingCount = $rule['max'];
587 # Count is less than the maximum
588 # Skip any gaps in the callback array to find the true largest match
589 # Need to use array_key_exists not isset because the callback can be null
590 $matchingCount = $count;
591 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
596 if ( $matchingCount <= 0 ) {
597 # No matching element found in callback array
598 # Output a literal closing brace and continue
599 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
603 $name = $rule['names'][$matchingCount];
604 if ( $name === null ) {
605 // No element, just literal text
606 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
609 # Note: $parts is already XML, does not need to be encoded further
610 $parts = $piece->parts
;
611 $title = $parts[0]->out
;
614 # The invocation is at the start of the line if lineStart is set in
615 # the stack, and all opening brackets are used up.
616 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
617 $attr = ' lineStart="1"';
622 $element = "<$name$attr>";
623 $element .= "<title>$title</title>";
625 foreach ( $parts as $part ) {
626 if ( isset( $part->eqpos
) ) {
627 $argName = substr( $part->out
, 0, $part->eqpos
);
628 $argValue = substr( $part->out
, $part->eqpos +
1 );
629 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
631 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
635 $element .= "</$name>";
638 # Advance input pointer
639 $i +
= $matchingCount;
643 $accum =& $stack->getAccum();
645 # Re-add the old stack element if it still has unmatched opening characters remaining
646 if ( $matchingCount < $piece->count
) {
647 $piece->parts
= array( new PPDPart
);
648 $piece->count
-= $matchingCount;
649 # do we still qualify for any callback with remaining count?
650 $names = $rules[$piece->open
]['names'];
652 $enclosingAccum =& $accum;
653 while ( $piece->count
) {
654 if ( array_key_exists( $piece->count
, $names ) ) {
655 $stack->push( $piece );
656 $accum =& $stack->getAccum();
662 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
664 $flags = $stack->getFlags();
667 # Add XML element to the enclosing accumulator
669 } elseif ( $found == 'pipe' ) {
670 $findEquals = true; // shortcut for getFlags()
672 $accum =& $stack->getAccum();
674 } elseif ( $found == 'equals' ) {
675 $findEquals = false; // shortcut for getFlags()
676 $stack->getCurrentPart()->eqpos
= strlen( $accum );
682 # Output any remaining unclosed brackets
683 foreach ( $stack->stack
as $piece ) {
684 $stack->rootAccum
.= $piece->breakSyntax();
686 $stack->rootAccum
.= '</root>';
687 $xml = $stack->rootAccum
;
689 wfProfileOut( __METHOD__
);
696 * Stack class to help Preprocessor::preprocessToObj()
700 var $stack, $rootAccum;
707 var $elementClass = 'PPDStackElement';
709 static $false = false;
711 function __construct() {
712 $this->stack
= array();
714 $this->rootAccum
= '';
715 $this->accum
=& $this->rootAccum
;
722 return count( $this->stack
);
725 function &getAccum() {
729 function getCurrentPart() {
730 if ( $this->top
=== false ) {
733 return $this->top
->getCurrentPart();
737 function push( $data ) {
738 if ( $data instanceof $this->elementClass
) {
739 $this->stack
[] = $data;
741 $class = $this->elementClass
;
742 $this->stack
[] = new $class( $data );
744 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
745 $this->accum
=& $this->top
->getAccum();
749 if ( !count( $this->stack
) ) {
750 throw new MWException( __METHOD__
.': no elements remaining' );
752 $temp = array_pop( $this->stack
);
754 if ( count( $this->stack
) ) {
755 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
756 $this->accum
=& $this->top
->getAccum();
758 $this->top
= self
::$false;
759 $this->accum
=& $this->rootAccum
;
764 function addPart( $s = '' ) {
765 $this->top
->addPart( $s );
766 $this->accum
=& $this->top
->getAccum();
772 function getFlags() {
773 if ( !count( $this->stack
) ) {
775 'findEquals' => false,
777 'inHeading' => false,
780 return $this->top
->getFlags();
788 class PPDStackElement
{
789 var $open, // Opening character (\n for heading)
790 $close, // Matching closing character
791 $count, // Number of opening characters found (number of "=" for heading)
792 $parts, // Array of PPDPart objects describing pipe-separated parts.
793 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
795 var $partClass = 'PPDPart';
797 function __construct( $data = array() ) {
798 $class = $this->partClass
;
799 $this->parts
= array( new $class );
801 foreach ( $data as $name => $value ) {
802 $this->$name = $value;
806 function &getAccum() {
807 return $this->parts
[count($this->parts
) - 1]->out
;
810 function addPart( $s = '' ) {
811 $class = $this->partClass
;
812 $this->parts
[] = new $class( $s );
815 function getCurrentPart() {
816 return $this->parts
[count($this->parts
) - 1];
822 function getFlags() {
823 $partCount = count( $this->parts
);
824 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
826 'findPipe' => $findPipe,
827 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
828 'inHeading' => $this->open
== "\n",
833 * Get the output string that would result if the close is not found.
837 function breakSyntax( $openingCount = false ) {
838 if ( $this->open
== "\n" ) {
839 $s = $this->parts
[0]->out
;
841 if ( $openingCount === false ) {
842 $openingCount = $this->count
;
844 $s = str_repeat( $this->open
, $openingCount );
846 foreach ( $this->parts
as $part ) {
863 var $out; // Output accumulator string
865 // Optional member variables:
866 // eqpos Position of equals sign in output accumulator
867 // commentEnd Past-the-end input pointer for the last comment encountered
868 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
870 function __construct( $out = '' ) {
876 * An expansion frame, used as a context to expand the result of preprocessToObj()
879 class PPFrame_DOM
implements PPFrame
{
898 * Hashtable listing templates which are disallowed for expansion in this frame,
899 * having been encountered previously in parent frames.
904 * Recursion depth of this frame, top = 0
905 * Note that this is NOT the same as expansion depth in expand()
911 * Construct a new preprocessor frame.
912 * @param $preprocessor Preprocessor The parent preprocessor
914 function __construct( $preprocessor ) {
915 $this->preprocessor
= $preprocessor;
916 $this->parser
= $preprocessor->parser
;
917 $this->title
= $this->parser
->mTitle
;
918 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
919 $this->loopCheckHash
= array();
924 * Create a new child frame
925 * $args is optionally a multi-root PPNode or array containing the template arguments
927 * @return PPTemplateFrame_DOM
929 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
930 $namedArgs = array();
931 $numberedArgs = array();
932 if ( $title === false ) {
933 $title = $this->title
;
935 if ( $args !== false ) {
937 if ( $args instanceof PPNode
) {
940 foreach ( $args as $arg ) {
941 if ( $arg instanceof PPNode
) {
945 $xpath = new DOMXPath( $arg->ownerDocument
);
948 $nameNodes = $xpath->query( 'name', $arg );
949 $value = $xpath->query( 'value', $arg );
950 if ( $nameNodes->item( 0 )->hasAttributes() ) {
951 // Numbered parameter
952 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
953 $index = $index - $indexOffset;
954 $numberedArgs[$index] = $value->item( 0 );
955 unset( $namedArgs[$index] );
958 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
959 $namedArgs[$name] = $value->item( 0 );
960 unset( $numberedArgs[$name] );
964 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
968 * @throws MWException
973 function expand( $root, $flags = 0 ) {
974 static $expansionDepth = 0;
975 if ( is_string( $root ) ) {
979 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
980 $this->parser
->limitationWarn( 'node-count-exceeded',
981 $this->parser
->mPPNodeCount
,
982 $this->parser
->mOptions
->getMaxPPNodeCount()
984 return '<span class="error">Node-count limit exceeded</span>';
987 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
988 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
990 $this->parser
->mOptions
->getMaxPPExpandDepth()
992 return '<span class="error">Expansion depth limit exceeded</span>';
994 wfProfileIn( __METHOD__
);
996 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
997 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1000 if ( $root instanceof PPNode_DOM
) {
1001 $root = $root->node
;
1003 if ( $root instanceof DOMDocument
) {
1004 $root = $root->documentElement
;
1007 $outStack = array( '', '' );
1008 $iteratorStack = array( false, $root );
1009 $indexStack = array( 0, 0 );
1011 while ( count( $iteratorStack ) > 1 ) {
1012 $level = count( $outStack ) - 1;
1013 $iteratorNode =& $iteratorStack[ $level ];
1014 $out =& $outStack[$level];
1015 $index =& $indexStack[$level];
1017 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
1019 if ( is_array( $iteratorNode ) ) {
1020 if ( $index >= count( $iteratorNode ) ) {
1021 // All done with this iterator
1022 $iteratorStack[$level] = false;
1023 $contextNode = false;
1025 $contextNode = $iteratorNode[$index];
1028 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1029 if ( $index >= $iteratorNode->length
) {
1030 // All done with this iterator
1031 $iteratorStack[$level] = false;
1032 $contextNode = false;
1034 $contextNode = $iteratorNode->item( $index );
1038 // Copy to $contextNode and then delete from iterator stack,
1039 // because this is not an iterator but we do have to execute it once
1040 $contextNode = $iteratorStack[$level];
1041 $iteratorStack[$level] = false;
1044 if ( $contextNode instanceof PPNode_DOM
) {
1045 $contextNode = $contextNode->node
;
1048 $newIterator = false;
1050 if ( $contextNode === false ) {
1052 } elseif ( is_string( $contextNode ) ) {
1053 $out .= $contextNode;
1054 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1055 $newIterator = $contextNode;
1056 } elseif ( $contextNode instanceof DOMNode
) {
1057 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1058 $out .= $contextNode->nodeValue
;
1059 } elseif ( $contextNode->nodeName
== 'template' ) {
1060 # Double-brace expansion
1061 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1062 $titles = $xpath->query( 'title', $contextNode );
1063 $title = $titles->item( 0 );
1064 $parts = $xpath->query( 'part', $contextNode );
1065 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1066 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1068 $lineStart = $contextNode->getAttribute( 'lineStart' );
1070 'title' => new PPNode_DOM( $title ),
1071 'parts' => new PPNode_DOM( $parts ),
1072 'lineStart' => $lineStart );
1073 $ret = $this->parser
->braceSubstitution( $params, $this );
1074 if ( isset( $ret['object'] ) ) {
1075 $newIterator = $ret['object'];
1077 $out .= $ret['text'];
1080 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1081 # Triple-brace expansion
1082 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1083 $titles = $xpath->query( 'title', $contextNode );
1084 $title = $titles->item( 0 );
1085 $parts = $xpath->query( 'part', $contextNode );
1086 if ( $flags & PPFrame
::NO_ARGS
) {
1087 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1090 'title' => new PPNode_DOM( $title ),
1091 'parts' => new PPNode_DOM( $parts ) );
1092 $ret = $this->parser
->argSubstitution( $params, $this );
1093 if ( isset( $ret['object'] ) ) {
1094 $newIterator = $ret['object'];
1096 $out .= $ret['text'];
1099 } elseif ( $contextNode->nodeName
== 'comment' ) {
1100 # HTML-style comment
1101 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1102 if ( $this->parser
->ot
['html']
1103 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1104 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1108 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1109 # Not in RECOVER_COMMENTS mode (extractSections) though
1110 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1111 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1113 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1115 $out .= $contextNode->textContent
;
1117 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1118 # Output suppression used by <includeonly> etc.
1119 # OT_WIKI will only respect <ignore> in substed templates.
1120 # The other output types respect it unless NO_IGNORE is set.
1121 # extractSections() sets NO_IGNORE and so never respects it.
1122 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1123 $out .= $contextNode->textContent
;
1127 } elseif ( $contextNode->nodeName
== 'ext' ) {
1129 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1130 $names = $xpath->query( 'name', $contextNode );
1131 $attrs = $xpath->query( 'attr', $contextNode );
1132 $inners = $xpath->query( 'inner', $contextNode );
1133 $closes = $xpath->query( 'close', $contextNode );
1135 'name' => new PPNode_DOM( $names->item( 0 ) ),
1136 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1137 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1138 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1140 $out .= $this->parser
->extensionSubstitution( $params, $this );
1141 } elseif ( $contextNode->nodeName
== 'h' ) {
1143 $s = $this->expand( $contextNode->childNodes
, $flags );
1145 # Insert a heading marker only for <h> children of <root>
1146 # This is to stop extractSections from going over multiple tree levels
1147 if ( $contextNode->parentNode
->nodeName
== 'root'
1148 && $this->parser
->ot
['html'] )
1150 # Insert heading index marker
1151 $headingIndex = $contextNode->getAttribute( 'i' );
1152 $titleText = $this->title
->getPrefixedDBkey();
1153 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1154 $serial = count( $this->parser
->mHeadings
) - 1;
1155 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1156 $count = $contextNode->getAttribute( 'level' );
1157 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1158 $this->parser
->mStripState
->addGeneral( $marker, '' );
1162 # Generic recursive expansion
1163 $newIterator = $contextNode->childNodes
;
1166 wfProfileOut( __METHOD__
);
1167 throw new MWException( __METHOD__
.': Invalid parameter type' );
1170 if ( $newIterator !== false ) {
1171 if ( $newIterator instanceof PPNode_DOM
) {
1172 $newIterator = $newIterator->node
;
1175 $iteratorStack[] = $newIterator;
1177 } elseif ( $iteratorStack[$level] === false ) {
1178 // Return accumulated value to parent
1179 // With tail recursion
1180 while ( $iteratorStack[$level] === false && $level > 0 ) {
1181 $outStack[$level - 1] .= $out;
1182 array_pop( $outStack );
1183 array_pop( $iteratorStack );
1184 array_pop( $indexStack );
1190 wfProfileOut( __METHOD__
);
1191 return $outStack[0];
1199 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1200 $args = array_slice( func_get_args(), 2 );
1204 foreach ( $args as $root ) {
1205 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1206 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1207 $root = array( $root );
1209 foreach ( $root as $node ) {
1215 $s .= $this->expand( $node, $flags );
1222 * Implode with no flags specified
1223 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1227 function implode( $sep /*, ... */ ) {
1228 $args = array_slice( func_get_args(), 1 );
1232 foreach ( $args as $root ) {
1233 if ( $root instanceof PPNode_DOM
) {
1234 $root = $root->node
;
1236 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1237 $root = array( $root );
1239 foreach ( $root as $node ) {
1245 $s .= $this->expand( $node );
1252 * Makes an object that, when expand()ed, will be the same as one obtained
1257 function virtualImplode( $sep /*, ... */ ) {
1258 $args = array_slice( func_get_args(), 1 );
1262 foreach ( $args as $root ) {
1263 if ( $root instanceof PPNode_DOM
) {
1264 $root = $root->node
;
1266 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1267 $root = array( $root );
1269 foreach ( $root as $node ) {
1282 * Virtual implode with brackets
1285 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1286 $args = array_slice( func_get_args(), 3 );
1287 $out = array( $start );
1290 foreach ( $args as $root ) {
1291 if ( $root instanceof PPNode_DOM
) {
1292 $root = $root->node
;
1294 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1295 $root = array( $root );
1297 foreach ( $root as $node ) {
1310 function __toString() {
1314 function getPDBK( $level = false ) {
1315 if ( $level === false ) {
1316 return $this->title
->getPrefixedDBkey();
1318 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1325 function getArguments() {
1332 function getNumberedArguments() {
1339 function getNamedArguments() {
1344 * Returns true if there are no arguments in this frame
1348 function isEmpty() {
1352 function getArgument( $name ) {
1357 * Returns true if the infinite loop check is OK, false if a loop is detected
1361 function loopCheck( $title ) {
1362 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1366 * Return true if the frame is a template frame
1370 function isTemplate() {
1375 * Get a title of frame
1379 function getTitle() {
1380 return $this->title
;
1385 * Expansion frame with template arguments
1388 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1389 var $numberedArgs, $namedArgs;
1395 var $numberedExpansionCache, $namedExpansionCache;
1398 * @param $preprocessor
1399 * @param $parent PPFrame_DOM
1400 * @param $numberedArgs array
1401 * @param $namedArgs array
1402 * @param $title Title
1404 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1405 parent
::__construct( $preprocessor );
1407 $this->parent
= $parent;
1408 $this->numberedArgs
= $numberedArgs;
1409 $this->namedArgs
= $namedArgs;
1410 $this->title
= $title;
1411 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1412 $this->titleCache
= $parent->titleCache
;
1413 $this->titleCache
[] = $pdbk;
1414 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1415 if ( $pdbk !== false ) {
1416 $this->loopCheckHash
[$pdbk] = true;
1418 $this->depth
= $parent->depth +
1;
1419 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1422 function __toString() {
1425 $args = $this->numberedArgs +
$this->namedArgs
;
1426 foreach ( $args as $name => $value ) {
1432 $s .= "\"$name\":\"" .
1433 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1440 * Returns true if there are no arguments in this frame
1444 function isEmpty() {
1445 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1448 function getArguments() {
1449 $arguments = array();
1450 foreach ( array_merge(
1451 array_keys($this->numberedArgs
),
1452 array_keys($this->namedArgs
)) as $key ) {
1453 $arguments[$key] = $this->getArgument($key);
1458 function getNumberedArguments() {
1459 $arguments = array();
1460 foreach ( array_keys($this->numberedArgs
) as $key ) {
1461 $arguments[$key] = $this->getArgument($key);
1466 function getNamedArguments() {
1467 $arguments = array();
1468 foreach ( array_keys($this->namedArgs
) as $key ) {
1469 $arguments[$key] = $this->getArgument($key);
1474 function getNumberedArgument( $index ) {
1475 if ( !isset( $this->numberedArgs
[$index] ) ) {
1478 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1479 # No trimming for unnamed arguments
1480 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1482 return $this->numberedExpansionCache
[$index];
1485 function getNamedArgument( $name ) {
1486 if ( !isset( $this->namedArgs
[$name] ) ) {
1489 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1490 # Trim named arguments post-expand, for backwards compatibility
1491 $this->namedExpansionCache
[$name] = trim(
1492 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1494 return $this->namedExpansionCache
[$name];
1497 function getArgument( $name ) {
1498 $text = $this->getNumberedArgument( $name );
1499 if ( $text === false ) {
1500 $text = $this->getNamedArgument( $name );
1506 * Return true if the frame is a template frame
1510 function isTemplate() {
1516 * Expansion frame with custom arguments
1519 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1522 function __construct( $preprocessor, $args ) {
1523 parent
::__construct( $preprocessor );
1524 $this->args
= $args;
1527 function __toString() {
1530 foreach ( $this->args
as $name => $value ) {
1536 $s .= "\"$name\":\"" .
1537 str_replace( '"', '\\"', $value->__toString() ) . '"';
1546 function isEmpty() {
1547 return !count( $this->args
);
1550 function getArgument( $index ) {
1551 if ( !isset( $this->args
[$index] ) ) {
1554 return $this->args
[$index];
1557 function getArguments() {
1565 class PPNode_DOM
implements PPNode
{
1573 function __construct( $node, $xpath = false ) {
1574 $this->node
= $node;
1580 function getXPath() {
1581 if ( $this->xpath
=== null ) {
1582 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1584 return $this->xpath
;
1587 function __toString() {
1588 if ( $this->node
instanceof DOMNodeList
) {
1590 foreach ( $this->node
as $node ) {
1591 $s .= $node->ownerDocument
->saveXML( $node );
1594 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1600 * @return bool|PPNode_DOM
1602 function getChildren() {
1603 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1607 * @return bool|PPNode_DOM
1609 function getFirstChild() {
1610 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1614 * @return bool|PPNode_DOM
1616 function getNextSibling() {
1617 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1623 * @return bool|PPNode_DOM
1625 function getChildrenOfType( $type ) {
1626 return new self( $this->getXPath()->query( $type, $this->node
) );
1632 function getLength() {
1633 if ( $this->node
instanceof DOMNodeList
) {
1634 return $this->node
->length
;
1642 * @return bool|PPNode_DOM
1644 function item( $i ) {
1645 $item = $this->node
->item( $i );
1646 return $item ?
new self( $item ) : false;
1652 function getName() {
1653 if ( $this->node
instanceof DOMNodeList
) {
1656 return $this->node
->nodeName
;
1661 * Split a <part> node into an associative array containing:
1663 * index String index
1664 * value PPNode value
1668 function splitArg() {
1669 $xpath = $this->getXPath();
1670 $names = $xpath->query( 'name', $this->node
);
1671 $values = $xpath->query( 'value', $this->node
);
1672 if ( !$names->length ||
!$values->length
) {
1673 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1675 $name = $names->item( 0 );
1676 $index = $name->getAttribute( 'index' );
1678 'name' => new self( $name ),
1680 'value' => new self( $values->item( 0 ) ) );
1684 * Split an <ext> node into an associative array containing name, attr, inner and close
1685 * All values in the resulting array are PPNodes. Inner and close are optional.
1689 function splitExt() {
1690 $xpath = $this->getXPath();
1691 $names = $xpath->query( 'name', $this->node
);
1692 $attrs = $xpath->query( 'attr', $this->node
);
1693 $inners = $xpath->query( 'inner', $this->node
);
1694 $closes = $xpath->query( 'close', $this->node
);
1695 if ( !$names->length ||
!$attrs->length
) {
1696 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1699 'name' => new self( $names->item( 0 ) ),
1700 'attr' => new self( $attrs->item( 0 ) ) );
1701 if ( $inners->length
) {
1702 $parts['inner'] = new self( $inners->item( 0 ) );
1704 if ( $closes->length
) {
1705 $parts['close'] = new self( $closes->item( 0 ) );
1714 function splitHeading() {
1715 if ( $this->getName() !== 'h' ) {
1716 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1719 'i' => $this->node
->getAttribute( 'i' ),
1720 'level' => $this->node
->getAttribute( 'level' ),
1721 'contents' => $this->getChildren()