3 * Preprocessor using PHP's dom extension
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
27 class Preprocessor_DOM
implements Preprocessor
{
36 const CACHE_VERSION
= 1;
38 function __construct( $parser ) {
39 $this->parser
= $parser;
40 $mem = ini_get( 'memory_limit' );
41 $this->memoryLimit
= false;
42 if ( strval( $mem ) !== '' && $mem != -1 ) {
43 if ( preg_match( '/^\d+$/', $mem ) ) {
44 $this->memoryLimit
= $mem;
45 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
46 $this->memoryLimit
= $m[1] * 1048576;
55 return new PPFrame_DOM( $this );
60 * @return PPCustomFrame_DOM
62 function newCustomFrame( $args ) {
63 return new PPCustomFrame_DOM( $this, $args );
70 function newPartNodeArray( $values ) {
71 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
74 foreach ( $values as $k => $val ) {
77 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
79 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
85 $dom = new DOMDocument();
86 $dom->loadXML( $xml );
87 $root = $dom->documentElement
;
89 $node = new PPNode_DOM( $root->childNodes
);
98 if ( $this->memoryLimit
=== false ) {
101 $usage = memory_get_usage();
102 if ( $usage > $this->memoryLimit
* 0.9 ) {
103 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
104 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
106 return $usage <= $this->memoryLimit
* 0.8;
110 * Preprocess some wikitext and return the document tree.
111 * This is the ghost of Parser::replace_variables().
113 * @param $text String: the text to parse
114 * @param $flags Integer: bitwise combination of:
115 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
116 * included. Default is to assume a direct page view.
118 * The generated DOM tree must depend only on the input text and the flags.
119 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
121 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
122 * change in the DOM tree for a given text, must be passed through the section identifier
123 * in the section edit link and thus back to extractSections().
125 * The output of this function is currently only cached in process memory, but a persistent
126 * cache may be implemented at a later date which takes further advantage of these strict
127 * dependency requirements.
131 function preprocessToObj( $text, $flags = 0 ) {
132 wfProfileIn( __METHOD__
);
133 global $wgMemc, $wgPreprocessorCacheThreshold;
136 $cacheable = ( $wgPreprocessorCacheThreshold !== false
137 && strlen( $text ) > $wgPreprocessorCacheThreshold );
139 wfProfileIn( __METHOD__
.'-cacheable' );
141 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
142 $cacheValue = $wgMemc->get( $cacheKey );
144 $version = substr( $cacheValue, 0, 8 );
145 if ( intval( $version ) == self
::CACHE_VERSION
) {
146 $xml = substr( $cacheValue, 8 );
148 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
152 if ( $xml === false ) {
154 wfProfileIn( __METHOD__
.'-cache-miss' );
155 $xml = $this->preprocessToXml( $text, $flags );
156 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
157 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
158 wfProfileOut( __METHOD__
.'-cache-miss' );
159 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
161 $xml = $this->preprocessToXml( $text, $flags );
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
238 $lengthText = strlen( $text );
240 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
241 $accum =& $stack->getAccum(); # Current accumulator
243 $findEquals = false; # True to find equals signs in arguments
244 $findPipe = false; # True to take notice of pipe characters
246 $inHeading = false; # True if $i is inside a possible heading
247 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
248 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
249 $fakeLineStart = true; # Do a line-start run without outputting an LF character
254 if ( $findOnlyinclude ) {
255 // Ignore all input up to the next <onlyinclude>
256 $startPos = strpos( $text, '<onlyinclude>', $i );
257 if ( $startPos === false ) {
258 // Ignored section runs to the end
259 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
262 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
263 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
265 $findOnlyinclude = false;
268 if ( $fakeLineStart ) {
269 $found = 'line-start';
272 # Find next opening brace, closing brace or pipe
273 $search = $searchBase;
274 if ( $stack->top
=== false ) {
275 $currentClosing = '';
277 $currentClosing = $stack->top
->close
;
278 $search .= $currentClosing;
284 // First equals will be for the template
288 # Output literal section, advance input counter
289 $literalLength = strcspn( $text, $search, $i );
290 if ( $literalLength > 0 ) {
291 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
292 $i +
= $literalLength;
294 if ( $i >= $lengthText ) {
295 if ( $currentClosing == "\n" ) {
296 // Do a past-the-end run to finish off the heading
304 $curChar = $text[$i];
305 if ( $curChar == '|' ) {
307 } elseif ( $curChar == '=' ) {
309 } elseif ( $curChar == '<' ) {
311 } elseif ( $curChar == "\n" ) {
315 $found = 'line-start';
317 } elseif ( $curChar == $currentClosing ) {
319 } elseif ( isset( $rules[$curChar] ) ) {
321 $rule = $rules[$curChar];
323 # Some versions of PHP have a strcspn which stops on null characters
324 # Ignore and continue
331 if ( $found == 'angle' ) {
333 // Handle </onlyinclude>
334 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
335 $findOnlyinclude = true;
339 // Determine element name
340 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
341 // Element name missing or not listed
347 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
348 // To avoid leaving blank lines, when a comment is both preceded
349 // and followed by a newline (ignoring spaces), trim leading and
350 // trailing spaces and one of the newlines.
353 $endPos = strpos( $text, '-->', $i +
4 );
354 if ( $endPos === false ) {
355 // Unclosed comment in input, runs to end
356 $inner = substr( $text, $i );
357 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
360 // Search backwards for leading whitespace
361 $wsStart = $i ?
( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
362 // Search forwards for trailing whitespace
363 // $wsEnd will be the position of the last space (or the '>' if there's none)
364 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
365 // Eat the line if possible
366 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
367 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
368 // it's a possible beneficial b/c break.
369 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
370 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
372 $startPos = $wsStart;
373 $endPos = $wsEnd +
1;
374 // Remove leading whitespace from the end of the accumulator
375 // Sanity check first though
376 $wsLength = $i - $wsStart;
377 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
378 $accum = substr( $accum, 0, -$wsLength );
380 // Do a line-start run next time to look for headings after the comment
381 $fakeLineStart = true;
383 // No line to eat, just take the comment itself
389 $part = $stack->top
->getCurrentPart();
390 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
391 $part->visualEnd
= $wsStart;
393 // Else comments abutting, no change in visual end
394 $part->commentEnd
= $endPos;
397 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
398 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
403 $lowerName = strtolower( $name );
404 $attrStart = $i +
strlen( $name ) +
1;
407 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
408 if ( $tagEndPos === false ) {
409 // Infinite backtrack
410 // Disable tag search to prevent worst-case O(N^2) performance
417 // Handle ignored tags
418 if ( in_array( $lowerName, $ignoredTags ) ) {
419 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
425 if ( $text[$tagEndPos-1] == '/' ) {
426 $attrEnd = $tagEndPos - 1;
431 $attrEnd = $tagEndPos;
433 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
434 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
436 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
437 $i = $matches[0][1] +
strlen( $matches[0][0] );
438 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
440 // No end tag -- let it run out to the end of the text.
441 $inner = substr( $text, $tagEndPos +
1 );
446 // <includeonly> and <noinclude> just become <ignore> tags
447 if ( in_array( $lowerName, $ignoredElements ) ) {
448 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
454 if ( $attrEnd <= $attrStart ) {
457 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
459 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
460 // Note that the attr element contains the whitespace between name and attribute,
461 // this is necessary for precise reconstruction during pre-save transform.
462 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
463 if ( $inner !== null ) {
464 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
466 $accum .= $close . '</ext>';
467 } elseif ( $found == 'line-start' ) {
468 // Is this the start of a heading?
469 // Line break belongs before the heading element in any case
470 if ( $fakeLineStart ) {
471 $fakeLineStart = false;
477 $count = strspn( $text, '=', $i, 6 );
478 if ( $count == 1 && $findEquals ) {
479 // DWIM: This looks kind of like a name/value separator
480 // Let's let the equals handler have it and break the potential heading
481 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
482 } elseif ( $count > 0 ) {
486 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
489 $stack->push( $piece );
490 $accum =& $stack->getAccum();
491 $flags = $stack->getFlags();
495 } elseif ( $found == 'line-end' ) {
496 $piece = $stack->top
;
497 // A heading must be open, otherwise \n wouldn't have been in the search list
498 assert( '$piece->open == "\n"' );
499 $part = $piece->getCurrentPart();
500 // Search back through the input to see if it has a proper close
501 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
502 $wsLength = strspn( $revText, " \t", $lengthText - $i );
503 $searchStart = $i - $wsLength;
504 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
505 // Comment found at line end
506 // Search for equals signs before the comment
507 $searchStart = $part->visualEnd
;
508 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
510 $count = $piece->count
;
511 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
512 if ( $equalsLength > 0 ) {
513 if ( $searchStart - $equalsLength == $piece->startPos
) {
514 // This is just a single string of equals signs on its own line
515 // Replicate the doHeadings behaviour /={count}(.+)={count}/
516 // First find out how many equals signs there really are (don't stop at 6)
517 $count = $equalsLength;
521 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
524 $count = min( $equalsLength, $count );
527 // Normal match, output <h>
528 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
531 // Single equals sign on its own line, count=0
535 // No match, no <h>, just pass down the inner text
540 $accum =& $stack->getAccum();
541 $flags = $stack->getFlags();
544 // Append the result to the enclosing accumulator
546 // Note that we do NOT increment the input pointer.
547 // This is because the closing linebreak could be the opening linebreak of
548 // another heading. Infinite loops are avoided because the next iteration MUST
549 // hit the heading open case above, which unconditionally increments the
551 } elseif ( $found == 'open' ) {
552 # count opening brace characters
553 $count = strspn( $text, $curChar, $i );
555 # we need to add to stack only if opening brace count is enough for one of the rules
556 if ( $count >= $rule['min'] ) {
557 # Add it to the stack
560 'close' => $rule['end'],
562 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
565 $stack->push( $piece );
566 $accum =& $stack->getAccum();
567 $flags = $stack->getFlags();
570 # Add literal brace(s)
571 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
574 } elseif ( $found == 'close' ) {
575 $piece = $stack->top
;
576 # lets check if there are enough characters for closing brace
577 $maxCount = $piece->count
;
578 $count = strspn( $text, $curChar, $i, $maxCount );
580 # check for maximum matching characters (if there are 5 closing
581 # characters, we will probably need only 3 - depending on the rules)
582 $rule = $rules[$piece->open
];
583 if ( $count > $rule['max'] ) {
584 # The specified maximum exists in the callback array, unless the caller
586 $matchingCount = $rule['max'];
588 # Count is less than the maximum
589 # Skip any gaps in the callback array to find the true largest match
590 # Need to use array_key_exists not isset because the callback can be null
591 $matchingCount = $count;
592 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
597 if ( $matchingCount <= 0 ) {
598 # No matching element found in callback array
599 # Output a literal closing brace and continue
600 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
604 $name = $rule['names'][$matchingCount];
605 if ( $name === null ) {
606 // No element, just literal text
607 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
610 # Note: $parts is already XML, does not need to be encoded further
611 $parts = $piece->parts
;
612 $title = $parts[0]->out
;
615 # The invocation is at the start of the line if lineStart is set in
616 # the stack, and all opening brackets are used up.
617 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
618 $attr = ' lineStart="1"';
623 $element = "<$name$attr>";
624 $element .= "<title>$title</title>";
626 foreach ( $parts as $part ) {
627 if ( isset( $part->eqpos
) ) {
628 $argName = substr( $part->out
, 0, $part->eqpos
);
629 $argValue = substr( $part->out
, $part->eqpos +
1 );
630 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
632 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
636 $element .= "</$name>";
639 # Advance input pointer
640 $i +
= $matchingCount;
644 $accum =& $stack->getAccum();
646 # Re-add the old stack element if it still has unmatched opening characters remaining
647 if ( $matchingCount < $piece->count
) {
648 $piece->parts
= array( new PPDPart
);
649 $piece->count
-= $matchingCount;
650 # do we still qualify for any callback with remaining count?
651 $names = $rules[$piece->open
]['names'];
653 $enclosingAccum =& $accum;
654 while ( $piece->count
) {
655 if ( array_key_exists( $piece->count
, $names ) ) {
656 $stack->push( $piece );
657 $accum =& $stack->getAccum();
663 $enclosingAccum .= str_repeat( $piece->open
, $skippedBraces );
665 $flags = $stack->getFlags();
668 # Add XML element to the enclosing accumulator
670 } elseif ( $found == 'pipe' ) {
671 $findEquals = true; // shortcut for getFlags()
673 $accum =& $stack->getAccum();
675 } elseif ( $found == 'equals' ) {
676 $findEquals = false; // shortcut for getFlags()
677 $stack->getCurrentPart()->eqpos
= strlen( $accum );
683 # Output any remaining unclosed brackets
684 foreach ( $stack->stack
as $piece ) {
685 $stack->rootAccum
.= $piece->breakSyntax();
687 $stack->rootAccum
.= '</root>';
688 $xml = $stack->rootAccum
;
690 wfProfileOut( __METHOD__
);
697 * Stack class to help Preprocessor::preprocessToObj()
701 var $stack, $rootAccum;
708 var $elementClass = 'PPDStackElement';
710 static $false = false;
712 function __construct() {
713 $this->stack
= array();
715 $this->rootAccum
= '';
716 $this->accum
=& $this->rootAccum
;
723 return count( $this->stack
);
726 function &getAccum() {
730 function getCurrentPart() {
731 if ( $this->top
=== false ) {
734 return $this->top
->getCurrentPart();
738 function push( $data ) {
739 if ( $data instanceof $this->elementClass
) {
740 $this->stack
[] = $data;
742 $class = $this->elementClass
;
743 $this->stack
[] = new $class( $data );
745 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
746 $this->accum
=& $this->top
->getAccum();
750 if ( !count( $this->stack
) ) {
751 throw new MWException( __METHOD__
.': no elements remaining' );
753 $temp = array_pop( $this->stack
);
755 if ( count( $this->stack
) ) {
756 $this->top
= $this->stack
[ count( $this->stack
) - 1 ];
757 $this->accum
=& $this->top
->getAccum();
759 $this->top
= self
::$false;
760 $this->accum
=& $this->rootAccum
;
765 function addPart( $s = '' ) {
766 $this->top
->addPart( $s );
767 $this->accum
=& $this->top
->getAccum();
773 function getFlags() {
774 if ( !count( $this->stack
) ) {
776 'findEquals' => false,
778 'inHeading' => false,
781 return $this->top
->getFlags();
789 class PPDStackElement
{
790 var $open, // Opening character (\n for heading)
791 $close, // Matching closing character
792 $count, // Number of opening characters found (number of "=" for heading)
793 $parts, // Array of PPDPart objects describing pipe-separated parts.
794 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
796 var $partClass = 'PPDPart';
798 function __construct( $data = array() ) {
799 $class = $this->partClass
;
800 $this->parts
= array( new $class );
802 foreach ( $data as $name => $value ) {
803 $this->$name = $value;
807 function &getAccum() {
808 return $this->parts
[count($this->parts
) - 1]->out
;
811 function addPart( $s = '' ) {
812 $class = $this->partClass
;
813 $this->parts
[] = new $class( $s );
816 function getCurrentPart() {
817 return $this->parts
[count($this->parts
) - 1];
823 function getFlags() {
824 $partCount = count( $this->parts
);
825 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
827 'findPipe' => $findPipe,
828 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
829 'inHeading' => $this->open
== "\n",
834 * Get the output string that would result if the close is not found.
838 function breakSyntax( $openingCount = false ) {
839 if ( $this->open
== "\n" ) {
840 $s = $this->parts
[0]->out
;
842 if ( $openingCount === false ) {
843 $openingCount = $this->count
;
845 $s = str_repeat( $this->open
, $openingCount );
847 foreach ( $this->parts
as $part ) {
864 var $out; // Output accumulator string
866 // Optional member variables:
867 // eqpos Position of equals sign in output accumulator
868 // commentEnd Past-the-end input pointer for the last comment encountered
869 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
871 function __construct( $out = '' ) {
877 * An expansion frame, used as a context to expand the result of preprocessToObj()
880 class PPFrame_DOM
implements PPFrame
{
899 * Hashtable listing templates which are disallowed for expansion in this frame,
900 * having been encountered previously in parent frames.
905 * Recursion depth of this frame, top = 0
906 * Note that this is NOT the same as expansion depth in expand()
912 * Construct a new preprocessor frame.
913 * @param $preprocessor Preprocessor The parent preprocessor
915 function __construct( $preprocessor ) {
916 $this->preprocessor
= $preprocessor;
917 $this->parser
= $preprocessor->parser
;
918 $this->title
= $this->parser
->mTitle
;
919 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
920 $this->loopCheckHash
= array();
925 * Create a new child frame
926 * $args is optionally a multi-root PPNode or array containing the template arguments
928 * @return PPTemplateFrame_DOM
930 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
931 $namedArgs = array();
932 $numberedArgs = array();
933 if ( $title === false ) {
934 $title = $this->title
;
936 if ( $args !== false ) {
938 if ( $args instanceof PPNode
) {
941 foreach ( $args as $arg ) {
942 if ( $arg instanceof PPNode
) {
946 $xpath = new DOMXPath( $arg->ownerDocument
);
949 $nameNodes = $xpath->query( 'name', $arg );
950 $value = $xpath->query( 'value', $arg );
951 if ( $nameNodes->item( 0 )->hasAttributes() ) {
952 // Numbered parameter
953 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
954 $index = $index - $indexOffset;
955 $numberedArgs[$index] = $value->item( 0 );
956 unset( $namedArgs[$index] );
959 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
960 $namedArgs[$name] = $value->item( 0 );
961 unset( $numberedArgs[$name] );
965 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
969 * @throws MWException
974 function expand( $root, $flags = 0 ) {
975 static $expansionDepth = 0;
976 if ( is_string( $root ) ) {
980 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
981 $this->parser
->limitationWarn( 'node-count-exceeded',
982 $this->parser
->mPPNodeCount
,
983 $this->parser
->mOptions
->getMaxPPNodeCount()
985 return '<span class="error">Node-count limit exceeded</span>';
988 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
989 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
991 $this->parser
->mOptions
->getMaxPPExpandDepth()
993 return '<span class="error">Expansion depth limit exceeded</span>';
995 wfProfileIn( __METHOD__
);
997 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
998 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1001 if ( $root instanceof PPNode_DOM
) {
1002 $root = $root->node
;
1004 if ( $root instanceof DOMDocument
) {
1005 $root = $root->documentElement
;
1008 $outStack = array( '', '' );
1009 $iteratorStack = array( false, $root );
1010 $indexStack = array( 0, 0 );
1012 while ( count( $iteratorStack ) > 1 ) {
1013 $level = count( $outStack ) - 1;
1014 $iteratorNode =& $iteratorStack[ $level ];
1015 $out =& $outStack[$level];
1016 $index =& $indexStack[$level];
1018 if ( $iteratorNode instanceof PPNode_DOM
) $iteratorNode = $iteratorNode->node
;
1020 if ( is_array( $iteratorNode ) ) {
1021 if ( $index >= count( $iteratorNode ) ) {
1022 // All done with this iterator
1023 $iteratorStack[$level] = false;
1024 $contextNode = false;
1026 $contextNode = $iteratorNode[$index];
1029 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1030 if ( $index >= $iteratorNode->length
) {
1031 // All done with this iterator
1032 $iteratorStack[$level] = false;
1033 $contextNode = false;
1035 $contextNode = $iteratorNode->item( $index );
1039 // Copy to $contextNode and then delete from iterator stack,
1040 // because this is not an iterator but we do have to execute it once
1041 $contextNode = $iteratorStack[$level];
1042 $iteratorStack[$level] = false;
1045 if ( $contextNode instanceof PPNode_DOM
) {
1046 $contextNode = $contextNode->node
;
1049 $newIterator = false;
1051 if ( $contextNode === false ) {
1053 } elseif ( is_string( $contextNode ) ) {
1054 $out .= $contextNode;
1055 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1056 $newIterator = $contextNode;
1057 } elseif ( $contextNode instanceof DOMNode
) {
1058 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1059 $out .= $contextNode->nodeValue
;
1060 } elseif ( $contextNode->nodeName
== 'template' ) {
1061 # Double-brace expansion
1062 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1063 $titles = $xpath->query( 'title', $contextNode );
1064 $title = $titles->item( 0 );
1065 $parts = $xpath->query( 'part', $contextNode );
1066 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1067 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1069 $lineStart = $contextNode->getAttribute( 'lineStart' );
1071 'title' => new PPNode_DOM( $title ),
1072 'parts' => new PPNode_DOM( $parts ),
1073 'lineStart' => $lineStart );
1074 $ret = $this->parser
->braceSubstitution( $params, $this );
1075 if ( isset( $ret['object'] ) ) {
1076 $newIterator = $ret['object'];
1078 $out .= $ret['text'];
1081 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1082 # Triple-brace expansion
1083 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1084 $titles = $xpath->query( 'title', $contextNode );
1085 $title = $titles->item( 0 );
1086 $parts = $xpath->query( 'part', $contextNode );
1087 if ( $flags & PPFrame
::NO_ARGS
) {
1088 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1091 'title' => new PPNode_DOM( $title ),
1092 'parts' => new PPNode_DOM( $parts ) );
1093 $ret = $this->parser
->argSubstitution( $params, $this );
1094 if ( isset( $ret['object'] ) ) {
1095 $newIterator = $ret['object'];
1097 $out .= $ret['text'];
1100 } elseif ( $contextNode->nodeName
== 'comment' ) {
1101 # HTML-style comment
1102 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1103 if ( $this->parser
->ot
['html']
1104 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1105 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1109 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1110 # Not in RECOVER_COMMENTS mode (extractSections) though
1111 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1112 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1114 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1116 $out .= $contextNode->textContent
;
1118 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1119 # Output suppression used by <includeonly> etc.
1120 # OT_WIKI will only respect <ignore> in substed templates.
1121 # The other output types respect it unless NO_IGNORE is set.
1122 # extractSections() sets NO_IGNORE and so never respects it.
1123 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1124 $out .= $contextNode->textContent
;
1128 } elseif ( $contextNode->nodeName
== 'ext' ) {
1130 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1131 $names = $xpath->query( 'name', $contextNode );
1132 $attrs = $xpath->query( 'attr', $contextNode );
1133 $inners = $xpath->query( 'inner', $contextNode );
1134 $closes = $xpath->query( 'close', $contextNode );
1136 'name' => new PPNode_DOM( $names->item( 0 ) ),
1137 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1138 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1139 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1141 $out .= $this->parser
->extensionSubstitution( $params, $this );
1142 } elseif ( $contextNode->nodeName
== 'h' ) {
1144 $s = $this->expand( $contextNode->childNodes
, $flags );
1146 # Insert a heading marker only for <h> children of <root>
1147 # This is to stop extractSections from going over multiple tree levels
1148 if ( $contextNode->parentNode
->nodeName
== 'root'
1149 && $this->parser
->ot
['html'] )
1151 # Insert heading index marker
1152 $headingIndex = $contextNode->getAttribute( 'i' );
1153 $titleText = $this->title
->getPrefixedDBkey();
1154 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1155 $serial = count( $this->parser
->mHeadings
) - 1;
1156 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1157 $count = $contextNode->getAttribute( 'level' );
1158 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1159 $this->parser
->mStripState
->addGeneral( $marker, '' );
1163 # Generic recursive expansion
1164 $newIterator = $contextNode->childNodes
;
1167 wfProfileOut( __METHOD__
);
1168 throw new MWException( __METHOD__
.': Invalid parameter type' );
1171 if ( $newIterator !== false ) {
1172 if ( $newIterator instanceof PPNode_DOM
) {
1173 $newIterator = $newIterator->node
;
1176 $iteratorStack[] = $newIterator;
1178 } elseif ( $iteratorStack[$level] === false ) {
1179 // Return accumulated value to parent
1180 // With tail recursion
1181 while ( $iteratorStack[$level] === false && $level > 0 ) {
1182 $outStack[$level - 1] .= $out;
1183 array_pop( $outStack );
1184 array_pop( $iteratorStack );
1185 array_pop( $indexStack );
1191 wfProfileOut( __METHOD__
);
1192 return $outStack[0];
1200 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1201 $args = array_slice( func_get_args(), 2 );
1205 foreach ( $args as $root ) {
1206 if ( $root instanceof PPNode_DOM
) $root = $root->node
;
1207 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1208 $root = array( $root );
1210 foreach ( $root as $node ) {
1216 $s .= $this->expand( $node, $flags );
1223 * Implode with no flags specified
1224 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1228 function implode( $sep /*, ... */ ) {
1229 $args = array_slice( func_get_args(), 1 );
1233 foreach ( $args as $root ) {
1234 if ( $root instanceof PPNode_DOM
) {
1235 $root = $root->node
;
1237 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1238 $root = array( $root );
1240 foreach ( $root as $node ) {
1246 $s .= $this->expand( $node );
1253 * Makes an object that, when expand()ed, will be the same as one obtained
1258 function virtualImplode( $sep /*, ... */ ) {
1259 $args = array_slice( func_get_args(), 1 );
1263 foreach ( $args as $root ) {
1264 if ( $root instanceof PPNode_DOM
) {
1265 $root = $root->node
;
1267 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1268 $root = array( $root );
1270 foreach ( $root as $node ) {
1283 * Virtual implode with brackets
1286 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1287 $args = array_slice( func_get_args(), 3 );
1288 $out = array( $start );
1291 foreach ( $args as $root ) {
1292 if ( $root instanceof PPNode_DOM
) {
1293 $root = $root->node
;
1295 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1296 $root = array( $root );
1298 foreach ( $root as $node ) {
1311 function __toString() {
1315 function getPDBK( $level = false ) {
1316 if ( $level === false ) {
1317 return $this->title
->getPrefixedDBkey();
1319 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1326 function getArguments() {
1333 function getNumberedArguments() {
1340 function getNamedArguments() {
1345 * Returns true if there are no arguments in this frame
1349 function isEmpty() {
1353 function getArgument( $name ) {
1358 * Returns true if the infinite loop check is OK, false if a loop is detected
1362 function loopCheck( $title ) {
1363 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1367 * Return true if the frame is a template frame
1371 function isTemplate() {
1376 * Get a title of frame
1380 function getTitle() {
1381 return $this->title
;
1386 * Expansion frame with template arguments
1389 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1390 var $numberedArgs, $namedArgs;
1396 var $numberedExpansionCache, $namedExpansionCache;
1399 * @param $preprocessor
1400 * @param $parent PPFrame_DOM
1401 * @param $numberedArgs array
1402 * @param $namedArgs array
1403 * @param $title Title
1405 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1406 parent
::__construct( $preprocessor );
1408 $this->parent
= $parent;
1409 $this->numberedArgs
= $numberedArgs;
1410 $this->namedArgs
= $namedArgs;
1411 $this->title
= $title;
1412 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1413 $this->titleCache
= $parent->titleCache
;
1414 $this->titleCache
[] = $pdbk;
1415 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1416 if ( $pdbk !== false ) {
1417 $this->loopCheckHash
[$pdbk] = true;
1419 $this->depth
= $parent->depth +
1;
1420 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1423 function __toString() {
1426 $args = $this->numberedArgs +
$this->namedArgs
;
1427 foreach ( $args as $name => $value ) {
1433 $s .= "\"$name\":\"" .
1434 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1441 * Returns true if there are no arguments in this frame
1445 function isEmpty() {
1446 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1449 function getArguments() {
1450 $arguments = array();
1451 foreach ( array_merge(
1452 array_keys($this->numberedArgs
),
1453 array_keys($this->namedArgs
)) as $key ) {
1454 $arguments[$key] = $this->getArgument($key);
1459 function getNumberedArguments() {
1460 $arguments = array();
1461 foreach ( array_keys($this->numberedArgs
) as $key ) {
1462 $arguments[$key] = $this->getArgument($key);
1467 function getNamedArguments() {
1468 $arguments = array();
1469 foreach ( array_keys($this->namedArgs
) as $key ) {
1470 $arguments[$key] = $this->getArgument($key);
1475 function getNumberedArgument( $index ) {
1476 if ( !isset( $this->numberedArgs
[$index] ) ) {
1479 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1480 # No trimming for unnamed arguments
1481 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1483 return $this->numberedExpansionCache
[$index];
1486 function getNamedArgument( $name ) {
1487 if ( !isset( $this->namedArgs
[$name] ) ) {
1490 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1491 # Trim named arguments post-expand, for backwards compatibility
1492 $this->namedExpansionCache
[$name] = trim(
1493 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1495 return $this->namedExpansionCache
[$name];
1498 function getArgument( $name ) {
1499 $text = $this->getNumberedArgument( $name );
1500 if ( $text === false ) {
1501 $text = $this->getNamedArgument( $name );
1507 * Return true if the frame is a template frame
1511 function isTemplate() {
1517 * Expansion frame with custom arguments
1520 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1523 function __construct( $preprocessor, $args ) {
1524 parent
::__construct( $preprocessor );
1525 $this->args
= $args;
1528 function __toString() {
1531 foreach ( $this->args
as $name => $value ) {
1537 $s .= "\"$name\":\"" .
1538 str_replace( '"', '\\"', $value->__toString() ) . '"';
1547 function isEmpty() {
1548 return !count( $this->args
);
1551 function getArgument( $index ) {
1552 if ( !isset( $this->args
[$index] ) ) {
1555 return $this->args
[$index];
1558 function getArguments() {
1566 class PPNode_DOM
implements PPNode
{
1574 function __construct( $node, $xpath = false ) {
1575 $this->node
= $node;
1581 function getXPath() {
1582 if ( $this->xpath
=== null ) {
1583 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1585 return $this->xpath
;
1588 function __toString() {
1589 if ( $this->node
instanceof DOMNodeList
) {
1591 foreach ( $this->node
as $node ) {
1592 $s .= $node->ownerDocument
->saveXML( $node );
1595 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1601 * @return bool|PPNode_DOM
1603 function getChildren() {
1604 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1608 * @return bool|PPNode_DOM
1610 function getFirstChild() {
1611 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1615 * @return bool|PPNode_DOM
1617 function getNextSibling() {
1618 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1624 * @return bool|PPNode_DOM
1626 function getChildrenOfType( $type ) {
1627 return new self( $this->getXPath()->query( $type, $this->node
) );
1633 function getLength() {
1634 if ( $this->node
instanceof DOMNodeList
) {
1635 return $this->node
->length
;
1643 * @return bool|PPNode_DOM
1645 function item( $i ) {
1646 $item = $this->node
->item( $i );
1647 return $item ?
new self( $item ) : false;
1653 function getName() {
1654 if ( $this->node
instanceof DOMNodeList
) {
1657 return $this->node
->nodeName
;
1662 * Split a "<part>" node into an associative array containing:
1663 * - name PPNode name
1664 * - index String index
1665 * - value PPNode value
1669 function splitArg() {
1670 $xpath = $this->getXPath();
1671 $names = $xpath->query( 'name', $this->node
);
1672 $values = $xpath->query( 'value', $this->node
);
1673 if ( !$names->length ||
!$values->length
) {
1674 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1676 $name = $names->item( 0 );
1677 $index = $name->getAttribute( 'index' );
1679 'name' => new self( $name ),
1681 'value' => new self( $values->item( 0 ) ) );
1685 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1686 * All values in the resulting array are PPNodes. Inner and close are optional.
1690 function splitExt() {
1691 $xpath = $this->getXPath();
1692 $names = $xpath->query( 'name', $this->node
);
1693 $attrs = $xpath->query( 'attr', $this->node
);
1694 $inners = $xpath->query( 'inner', $this->node
);
1695 $closes = $xpath->query( 'close', $this->node
);
1696 if ( !$names->length ||
!$attrs->length
) {
1697 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1700 'name' => new self( $names->item( 0 ) ),
1701 'attr' => new self( $attrs->item( 0 ) ) );
1702 if ( $inners->length
) {
1703 $parts['inner'] = new self( $inners->item( 0 ) );
1705 if ( $closes->length
) {
1706 $parts['close'] = new self( $closes->item( 0 ) );
1712 * Split a "<h>" node
1715 function splitHeading() {
1716 if ( $this->getName() !== 'h' ) {
1717 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1720 'i' => $this->node
->getAttribute( 'i' ),
1721 'level' => $this->node
->getAttribute( 'level' ),
1722 'contents' => $this->getChildren()