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 );
67 * @param array $values
70 function newPartNodeArray( $values ) {
71 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
74 foreach ( $values as $k => $val ) {
76 $xml .= "<part><name index=\"$k\"/><value>"
77 . htmlspecialchars( $val ) . "</value></part>";
79 $xml .= "<part><name>" . htmlspecialchars( $k )
80 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
86 wfProfileIn( __METHOD__
. '-loadXML' );
87 $dom = new DOMDocument();
89 $result = $dom->loadXML( $xml );
92 // Try running the XML through UtfNormal to get rid of invalid characters
93 $xml = UtfNormal
::cleanUp( $xml );
94 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
95 $result = $dom->loadXML( $xml, 1 << 19 );
97 wfProfileOut( __METHOD__
. '-loadXML' );
100 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
103 $root = $dom->documentElement
;
104 $node = new PPNode_DOM( $root->childNodes
);
109 * @throws MWException
112 function memCheck() {
113 if ( $this->memoryLimit
=== false ) {
116 $usage = memory_get_usage();
117 if ( $usage > $this->memoryLimit
* 0.9 ) {
118 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
119 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
121 return $usage <= $this->memoryLimit
* 0.8;
125 * Preprocess some wikitext and return the document tree.
126 * This is the ghost of Parser::replace_variables().
128 * @param string $text The text to parse
129 * @param int $flags Bitwise combination of:
130 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
131 * as if the text is being included. Default
132 * is to assume a direct page view.
134 * The generated DOM tree must depend only on the input text and the flags.
135 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
137 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
138 * change in the DOM tree for a given text, must be passed through the section identifier
139 * in the section edit link and thus back to extractSections().
141 * The output of this function is currently only cached in process memory, but a persistent
142 * cache may be implemented at a later date which takes further advantage of these strict
143 * dependency requirements.
145 * @throws MWException
148 function preprocessToObj( $text, $flags = 0 ) {
149 wfProfileIn( __METHOD__
);
150 global $wgMemc, $wgPreprocessorCacheThreshold;
153 $cacheable = ( $wgPreprocessorCacheThreshold !== false
154 && strlen( $text ) > $wgPreprocessorCacheThreshold );
156 wfProfileIn( __METHOD__
. '-cacheable' );
158 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
159 $cacheValue = $wgMemc->get( $cacheKey );
161 $version = substr( $cacheValue, 0, 8 );
162 if ( intval( $version ) == self
::CACHE_VERSION
) {
163 $xml = substr( $cacheValue, 8 );
165 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
168 if ( $xml === false ) {
169 wfProfileIn( __METHOD__
. '-cache-miss' );
170 $xml = $this->preprocessToXml( $text, $flags );
171 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
172 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
173 wfProfileOut( __METHOD__
. '-cache-miss' );
174 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
177 $xml = $this->preprocessToXml( $text, $flags );
180 // Fail if the number of elements exceeds acceptable limits
181 // Do not attempt to generate the DOM
182 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
183 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
184 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
186 wfProfileOut( __METHOD__
. '-cacheable' );
188 wfProfileOut( __METHOD__
);
189 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
192 wfProfileIn( __METHOD__
. '-loadXML' );
193 $dom = new DOMDocument
;
194 wfSuppressWarnings();
195 $result = $dom->loadXML( $xml );
198 // Try running the XML through UtfNormal to get rid of invalid characters
199 $xml = UtfNormal
::cleanUp( $xml );
200 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
201 // don't barf when the XML is >256 levels deep.
202 $result = $dom->loadXML( $xml, 1 << 19 );
205 $obj = new PPNode_DOM( $dom->documentElement
);
207 wfProfileOut( __METHOD__
. '-loadXML' );
210 wfProfileOut( __METHOD__
. '-cacheable' );
213 wfProfileOut( __METHOD__
);
216 throw new MWException( __METHOD__
. ' generated invalid XML' );
222 * @param string $text
226 function preprocessToXml( $text, $flags = 0 ) {
227 wfProfileIn( __METHOD__
);
240 'names' => array( 2 => null ),
246 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
248 $xmlishElements = $this->parser
->getStripList();
249 $enableOnlyinclude = false;
250 if ( $forInclusion ) {
251 $ignoredTags = array( 'includeonly', '/includeonly' );
252 $ignoredElements = array( 'noinclude' );
253 $xmlishElements[] = 'noinclude';
254 if ( strpos( $text, '<onlyinclude>' ) !== false
255 && strpos( $text, '</onlyinclude>' ) !== false
257 $enableOnlyinclude = true;
260 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
261 $ignoredElements = array( 'includeonly' );
262 $xmlishElements[] = 'includeonly';
264 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
266 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
267 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
269 $stack = new PPDStack
;
271 $searchBase = "[{<\n"; #}
272 // For fast reverse searches
273 $revText = strrev( $text );
274 $lengthText = strlen( $text );
276 // Input pointer, starts out pointing to a pseudo-newline before the start
278 // Current accumulator
279 $accum =& $stack->getAccum();
281 // True to find equals signs in arguments
283 // True to take notice of pipe characters
286 // True if $i is inside a possible heading
288 // True if there are no more greater-than (>) signs right of $i
290 // True to ignore all input up to the next <onlyinclude>
291 $findOnlyinclude = $enableOnlyinclude;
292 // Do a line-start run without outputting an LF character
293 $fakeLineStart = true;
298 if ( $findOnlyinclude ) {
299 // Ignore all input up to the next <onlyinclude>
300 $startPos = strpos( $text, '<onlyinclude>', $i );
301 if ( $startPos === false ) {
302 // Ignored section runs to the end
303 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
306 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
307 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
309 $findOnlyinclude = false;
312 if ( $fakeLineStart ) {
313 $found = 'line-start';
316 # Find next opening brace, closing brace or pipe
317 $search = $searchBase;
318 if ( $stack->top
=== false ) {
319 $currentClosing = '';
321 $currentClosing = $stack->top
->close
;
322 $search .= $currentClosing;
328 // First equals will be for the template
332 # Output literal section, advance input counter
333 $literalLength = strcspn( $text, $search, $i );
334 if ( $literalLength > 0 ) {
335 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
336 $i +
= $literalLength;
338 if ( $i >= $lengthText ) {
339 if ( $currentClosing == "\n" ) {
340 // Do a past-the-end run to finish off the heading
348 $curChar = $text[$i];
349 if ( $curChar == '|' ) {
351 } elseif ( $curChar == '=' ) {
353 } elseif ( $curChar == '<' ) {
355 } elseif ( $curChar == "\n" ) {
359 $found = 'line-start';
361 } elseif ( $curChar == $currentClosing ) {
363 } elseif ( isset( $rules[$curChar] ) ) {
365 $rule = $rules[$curChar];
367 # Some versions of PHP have a strcspn which stops on null characters
368 # Ignore and continue
375 if ( $found == 'angle' ) {
377 // Handle </onlyinclude>
378 if ( $enableOnlyinclude
379 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
381 $findOnlyinclude = true;
385 // Determine element name
386 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
387 // Element name missing or not listed
393 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
395 // To avoid leaving blank lines, when a sequence of
396 // space-separated comments is both preceded and followed by
397 // a newline (ignoring spaces), then
398 // trim leading and trailing spaces and the trailing newline.
401 $endPos = strpos( $text, '-->', $i +
4 );
402 if ( $endPos === false ) {
403 // Unclosed comment in input, runs to end
404 $inner = substr( $text, $i );
405 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
408 // Search backwards for leading whitespace
409 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
411 // Search forwards for trailing whitespace
412 // $wsEnd will be the position of the last space (or the '>' if there's none)
413 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
415 // Keep looking forward as long as we're finding more
417 $comments = array( array( $wsStart, $wsEnd ) );
418 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
419 $c = strpos( $text, '-->', $wsEnd +
4 );
420 if ( $c === false ) {
423 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
424 $comments[] = array( $wsEnd +
1, $c );
428 // Eat the line if possible
429 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
430 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
431 // it's a possible beneficial b/c break.
432 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
433 && substr( $text, $wsEnd +
1, 1 ) == "\n"
435 // Remove leading whitespace from the end of the accumulator
436 // Sanity check first though
437 $wsLength = $i - $wsStart;
439 && strspn( $accum, " \t", -$wsLength ) === $wsLength
441 $accum = substr( $accum, 0, -$wsLength );
444 // Dump all but the last comment to the accumulator
445 foreach ( $comments as $j => $com ) {
447 $endPos = $com[1] +
1;
448 if ( $j == ( count( $comments ) - 1 ) ) {
451 $inner = substr( $text, $startPos, $endPos - $startPos );
452 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
455 // Do a line-start run next time to look for headings after the comment
456 $fakeLineStart = true;
458 // No line to eat, just take the comment itself
464 $part = $stack->top
->getCurrentPart();
465 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
466 $part->visualEnd
= $wsStart;
468 // Else comments abutting, no change in visual end
469 $part->commentEnd
= $endPos;
472 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
473 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
478 $lowerName = strtolower( $name );
479 $attrStart = $i +
strlen( $name ) +
1;
482 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
483 if ( $tagEndPos === false ) {
484 // Infinite backtrack
485 // Disable tag search to prevent worst-case O(N^2) performance
492 // Handle ignored tags
493 if ( in_array( $lowerName, $ignoredTags ) ) {
495 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
502 if ( $text[$tagEndPos - 1] == '/' ) {
503 $attrEnd = $tagEndPos - 1;
508 $attrEnd = $tagEndPos;
510 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
511 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
513 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
514 $i = $matches[0][1] +
strlen( $matches[0][0] );
515 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
517 // No end tag -- let it run out to the end of the text.
518 $inner = substr( $text, $tagEndPos +
1 );
523 // <includeonly> and <noinclude> just become <ignore> tags
524 if ( in_array( $lowerName, $ignoredElements ) ) {
525 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
531 if ( $attrEnd <= $attrStart ) {
534 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
536 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
537 // Note that the attr element contains the whitespace between name and attribute,
538 // this is necessary for precise reconstruction during pre-save transform.
539 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
540 if ( $inner !== null ) {
541 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
543 $accum .= $close . '</ext>';
544 } elseif ( $found == 'line-start' ) {
545 // Is this the start of a heading?
546 // Line break belongs before the heading element in any case
547 if ( $fakeLineStart ) {
548 $fakeLineStart = false;
554 $count = strspn( $text, '=', $i, 6 );
555 if ( $count == 1 && $findEquals ) {
556 // DWIM: This looks kind of like a name/value separator.
557 // Let's let the equals handler have it and break the
558 // potential heading. This is heuristic, but AFAICT the
559 // methods for completely correct disambiguation are very
561 } elseif ( $count > 0 ) {
565 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
568 $stack->push( $piece );
569 $accum =& $stack->getAccum();
570 $flags = $stack->getFlags();
574 } elseif ( $found == 'line-end' ) {
575 $piece = $stack->top
;
576 // A heading must be open, otherwise \n wouldn't have been in the search list
577 assert( '$piece->open == "\n"' );
578 $part = $piece->getCurrentPart();
579 // Search back through the input to see if it has a proper close.
580 // Do this using the reversed string since the other solutions
581 // (end anchor, etc.) are inefficient.
582 $wsLength = strspn( $revText, " \t", $lengthText - $i );
583 $searchStart = $i - $wsLength;
584 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
585 // Comment found at line end
586 // Search for equals signs before the comment
587 $searchStart = $part->visualEnd
;
588 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
590 $count = $piece->count
;
591 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
592 if ( $equalsLength > 0 ) {
593 if ( $searchStart - $equalsLength == $piece->startPos
) {
594 // This is just a single string of equals signs on its own line
595 // Replicate the doHeadings behavior /={count}(.+)={count}/
596 // First find out how many equals signs there really are (don't stop at 6)
597 $count = $equalsLength;
601 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
604 $count = min( $equalsLength, $count );
607 // Normal match, output <h>
608 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
611 // Single equals sign on its own line, count=0
615 // No match, no <h>, just pass down the inner text
620 $accum =& $stack->getAccum();
621 $flags = $stack->getFlags();
624 // Append the result to the enclosing accumulator
626 // Note that we do NOT increment the input pointer.
627 // This is because the closing linebreak could be the opening linebreak of
628 // another heading. Infinite loops are avoided because the next iteration MUST
629 // hit the heading open case above, which unconditionally increments the
631 } elseif ( $found == 'open' ) {
632 # count opening brace characters
633 $count = strspn( $text, $curChar, $i );
635 # we need to add to stack only if opening brace count is enough for one of the rules
636 if ( $count >= $rule['min'] ) {
637 # Add it to the stack
640 'close' => $rule['end'],
642 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
645 $stack->push( $piece );
646 $accum =& $stack->getAccum();
647 $flags = $stack->getFlags();
650 # Add literal brace(s)
651 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
654 } elseif ( $found == 'close' ) {
655 $piece = $stack->top
;
656 # lets check if there are enough characters for closing brace
657 $maxCount = $piece->count
;
658 $count = strspn( $text, $curChar, $i, $maxCount );
660 # check for maximum matching characters (if there are 5 closing
661 # characters, we will probably need only 3 - depending on the rules)
662 $rule = $rules[$piece->open
];
663 if ( $count > $rule['max'] ) {
664 # The specified maximum exists in the callback array, unless the caller
666 $matchingCount = $rule['max'];
668 # Count is less than the maximum
669 # Skip any gaps in the callback array to find the true largest match
670 # Need to use array_key_exists not isset because the callback can be null
671 $matchingCount = $count;
672 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
677 if ( $matchingCount <= 0 ) {
678 # No matching element found in callback array
679 # Output a literal closing brace and continue
680 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
684 $name = $rule['names'][$matchingCount];
685 if ( $name === null ) {
686 // No element, just literal text
687 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
690 # Note: $parts is already XML, does not need to be encoded further
691 $parts = $piece->parts
;
692 $title = $parts[0]->out
;
695 # The invocation is at the start of the line if lineStart is set in
696 # the stack, and all opening brackets are used up.
697 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
698 $attr = ' lineStart="1"';
703 $element = "<$name$attr>";
704 $element .= "<title>$title</title>";
706 foreach ( $parts as $part ) {
707 if ( isset( $part->eqpos
) ) {
708 $argName = substr( $part->out
, 0, $part->eqpos
);
709 $argValue = substr( $part->out
, $part->eqpos +
1 );
710 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
712 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
716 $element .= "</$name>";
719 # Advance input pointer
720 $i +
= $matchingCount;
724 $accum =& $stack->getAccum();
726 # Re-add the old stack element if it still has unmatched opening characters remaining
727 if ( $matchingCount < $piece->count
) {
728 $piece->parts
= array( new PPDPart
);
729 $piece->count
-= $matchingCount;
730 # do we still qualify for any callback with remaining count?
731 $min = $rules[$piece->open
]['min'];
732 if ( $piece->count
>= $min ) {
733 $stack->push( $piece );
734 $accum =& $stack->getAccum();
736 $accum .= str_repeat( $piece->open
, $piece->count
);
739 $flags = $stack->getFlags();
742 # Add XML element to the enclosing accumulator
744 } elseif ( $found == 'pipe' ) {
745 $findEquals = true; // shortcut for getFlags()
747 $accum =& $stack->getAccum();
749 } elseif ( $found == 'equals' ) {
750 $findEquals = false; // shortcut for getFlags()
751 $stack->getCurrentPart()->eqpos
= strlen( $accum );
757 # Output any remaining unclosed brackets
758 foreach ( $stack->stack
as $piece ) {
759 $stack->rootAccum
.= $piece->breakSyntax();
761 $stack->rootAccum
.= '</root>';
762 $xml = $stack->rootAccum
;
764 wfProfileOut( __METHOD__
);
771 * Stack class to help Preprocessor::preprocessToObj()
775 var $stack, $rootAccum;
782 var $elementClass = 'PPDStackElement';
784 static $false = false;
786 function __construct() {
787 $this->stack
= array();
789 $this->rootAccum
= '';
790 $this->accum
=& $this->rootAccum
;
797 return count( $this->stack
);
800 function &getAccum() {
804 function getCurrentPart() {
805 if ( $this->top
=== false ) {
808 return $this->top
->getCurrentPart();
812 function push( $data ) {
813 if ( $data instanceof $this->elementClass
) {
814 $this->stack
[] = $data;
816 $class = $this->elementClass
;
817 $this->stack
[] = new $class( $data );
819 $this->top
= $this->stack
[count( $this->stack
) - 1];
820 $this->accum
=& $this->top
->getAccum();
824 if ( !count( $this->stack
) ) {
825 throw new MWException( __METHOD__
. ': no elements remaining' );
827 $temp = array_pop( $this->stack
);
829 if ( count( $this->stack
) ) {
830 $this->top
= $this->stack
[count( $this->stack
) - 1];
831 $this->accum
=& $this->top
->getAccum();
833 $this->top
= self
::$false;
834 $this->accum
=& $this->rootAccum
;
839 function addPart( $s = '' ) {
840 $this->top
->addPart( $s );
841 $this->accum
=& $this->top
->getAccum();
847 function getFlags() {
848 if ( !count( $this->stack
) ) {
850 'findEquals' => false,
852 'inHeading' => false,
855 return $this->top
->getFlags();
863 class PPDStackElement
{
864 var $open, // Opening character (\n for heading)
865 $close, // Matching closing character
866 $count, // Number of opening characters found (number of "=" for heading)
867 $parts, // Array of PPDPart objects describing pipe-separated parts.
868 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
870 var $partClass = 'PPDPart';
872 function __construct( $data = array() ) {
873 $class = $this->partClass
;
874 $this->parts
= array( new $class );
876 foreach ( $data as $name => $value ) {
877 $this->$name = $value;
881 function &getAccum() {
882 return $this->parts
[count( $this->parts
) - 1]->out
;
885 function addPart( $s = '' ) {
886 $class = $this->partClass
;
887 $this->parts
[] = new $class( $s );
890 function getCurrentPart() {
891 return $this->parts
[count( $this->parts
) - 1];
897 function getFlags() {
898 $partCount = count( $this->parts
);
899 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
901 'findPipe' => $findPipe,
902 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
903 'inHeading' => $this->open
== "\n",
908 * Get the output string that would result if the close is not found.
910 * @param bool|int $openingCount
913 function breakSyntax( $openingCount = false ) {
914 if ( $this->open
== "\n" ) {
915 $s = $this->parts
[0]->out
;
917 if ( $openingCount === false ) {
918 $openingCount = $this->count
;
920 $s = str_repeat( $this->open
, $openingCount );
922 foreach ( $this->parts
as $part ) {
939 var $out; // Output accumulator string
941 // Optional member variables:
942 // eqpos Position of equals sign in output accumulator
943 // commentEnd Past-the-end input pointer for the last comment encountered
944 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
946 function __construct( $out = '' ) {
952 * An expansion frame, used as a context to expand the result of preprocessToObj()
955 class PPFrame_DOM
implements PPFrame
{
974 * Hashtable listing templates which are disallowed for expansion in this frame,
975 * having been encountered previously in parent frames.
980 * Recursion depth of this frame, top = 0
981 * Note that this is NOT the same as expansion depth in expand()
986 * Construct a new preprocessor frame.
987 * @param Preprocessor $preprocessor The parent preprocessor
989 function __construct( $preprocessor ) {
990 $this->preprocessor
= $preprocessor;
991 $this->parser
= $preprocessor->parser
;
992 $this->title
= $this->parser
->mTitle
;
993 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
994 $this->loopCheckHash
= array();
999 * Create a new child frame
1000 * $args is optionally a multi-root PPNode or array containing the template arguments
1002 * @param bool|array $args
1003 * @param Title|bool $title
1004 * @param int $indexOffset
1005 * @return PPTemplateFrame_DOM
1007 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1008 $namedArgs = array();
1009 $numberedArgs = array();
1010 if ( $title === false ) {
1011 $title = $this->title
;
1013 if ( $args !== false ) {
1015 if ( $args instanceof PPNode
) {
1016 $args = $args->node
;
1018 foreach ( $args as $arg ) {
1019 if ( $arg instanceof PPNode
) {
1023 $xpath = new DOMXPath( $arg->ownerDocument
);
1026 $nameNodes = $xpath->query( 'name', $arg );
1027 $value = $xpath->query( 'value', $arg );
1028 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1029 // Numbered parameter
1030 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1031 $index = $index - $indexOffset;
1032 $numberedArgs[$index] = $value->item( 0 );
1033 unset( $namedArgs[$index] );
1036 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1037 $namedArgs[$name] = $value->item( 0 );
1038 unset( $numberedArgs[$name] );
1042 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1046 * @throws MWException
1047 * @param string|PPNode_DOM|DOMDocument $root
1051 function expand( $root, $flags = 0 ) {
1052 static $expansionDepth = 0;
1053 if ( is_string( $root ) ) {
1057 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1058 $this->parser
->limitationWarn( 'node-count-exceeded',
1059 $this->parser
->mPPNodeCount
,
1060 $this->parser
->mOptions
->getMaxPPNodeCount()
1062 return '<span class="error">Node-count limit exceeded</span>';
1065 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1066 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1068 $this->parser
->mOptions
->getMaxPPExpandDepth()
1070 return '<span class="error">Expansion depth limit exceeded</span>';
1072 wfProfileIn( __METHOD__
);
1074 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1075 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1078 if ( $root instanceof PPNode_DOM
) {
1079 $root = $root->node
;
1081 if ( $root instanceof DOMDocument
) {
1082 $root = $root->documentElement
;
1085 $outStack = array( '', '' );
1086 $iteratorStack = array( false, $root );
1087 $indexStack = array( 0, 0 );
1089 while ( count( $iteratorStack ) > 1 ) {
1090 $level = count( $outStack ) - 1;
1091 $iteratorNode =& $iteratorStack[$level];
1092 $out =& $outStack[$level];
1093 $index =& $indexStack[$level];
1095 if ( $iteratorNode instanceof PPNode_DOM
) {
1096 $iteratorNode = $iteratorNode->node
;
1099 if ( is_array( $iteratorNode ) ) {
1100 if ( $index >= count( $iteratorNode ) ) {
1101 // All done with this iterator
1102 $iteratorStack[$level] = false;
1103 $contextNode = false;
1105 $contextNode = $iteratorNode[$index];
1108 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1109 if ( $index >= $iteratorNode->length
) {
1110 // All done with this iterator
1111 $iteratorStack[$level] = false;
1112 $contextNode = false;
1114 $contextNode = $iteratorNode->item( $index );
1118 // Copy to $contextNode and then delete from iterator stack,
1119 // because this is not an iterator but we do have to execute it once
1120 $contextNode = $iteratorStack[$level];
1121 $iteratorStack[$level] = false;
1124 if ( $contextNode instanceof PPNode_DOM
) {
1125 $contextNode = $contextNode->node
;
1128 $newIterator = false;
1130 if ( $contextNode === false ) {
1132 } elseif ( is_string( $contextNode ) ) {
1133 $out .= $contextNode;
1134 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1135 $newIterator = $contextNode;
1136 } elseif ( $contextNode instanceof DOMNode
) {
1137 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1138 $out .= $contextNode->nodeValue
;
1139 } elseif ( $contextNode->nodeName
== 'template' ) {
1140 # Double-brace expansion
1141 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1142 $titles = $xpath->query( 'title', $contextNode );
1143 $title = $titles->item( 0 );
1144 $parts = $xpath->query( 'part', $contextNode );
1145 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1146 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1148 $lineStart = $contextNode->getAttribute( 'lineStart' );
1150 'title' => new PPNode_DOM( $title ),
1151 'parts' => new PPNode_DOM( $parts ),
1152 'lineStart' => $lineStart );
1153 $ret = $this->parser
->braceSubstitution( $params, $this );
1154 if ( isset( $ret['object'] ) ) {
1155 $newIterator = $ret['object'];
1157 $out .= $ret['text'];
1160 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1161 # Triple-brace expansion
1162 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1163 $titles = $xpath->query( 'title', $contextNode );
1164 $title = $titles->item( 0 );
1165 $parts = $xpath->query( 'part', $contextNode );
1166 if ( $flags & PPFrame
::NO_ARGS
) {
1167 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1170 'title' => new PPNode_DOM( $title ),
1171 'parts' => new PPNode_DOM( $parts ) );
1172 $ret = $this->parser
->argSubstitution( $params, $this );
1173 if ( isset( $ret['object'] ) ) {
1174 $newIterator = $ret['object'];
1176 $out .= $ret['text'];
1179 } elseif ( $contextNode->nodeName
== 'comment' ) {
1180 # HTML-style comment
1181 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1182 if ( $this->parser
->ot
['html']
1183 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1184 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1187 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1188 # Add a strip marker in PST mode so that pstPass2() can
1189 # run some old-fashioned regexes on the result.
1190 # Not in RECOVER_COMMENTS mode (extractSections) though.
1191 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1193 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1194 $out .= $contextNode->textContent
;
1196 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1197 # Output suppression used by <includeonly> etc.
1198 # OT_WIKI will only respect <ignore> in substed templates.
1199 # The other output types respect it unless NO_IGNORE is set.
1200 # extractSections() sets NO_IGNORE and so never respects it.
1201 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1202 ||
( $flags & PPFrame
::NO_IGNORE
)
1204 $out .= $contextNode->textContent
;
1208 } elseif ( $contextNode->nodeName
== 'ext' ) {
1210 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1211 $names = $xpath->query( 'name', $contextNode );
1212 $attrs = $xpath->query( 'attr', $contextNode );
1213 $inners = $xpath->query( 'inner', $contextNode );
1214 $closes = $xpath->query( 'close', $contextNode );
1216 'name' => new PPNode_DOM( $names->item( 0 ) ),
1217 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1218 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1219 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1221 $out .= $this->parser
->extensionSubstitution( $params, $this );
1222 } elseif ( $contextNode->nodeName
== 'h' ) {
1224 $s = $this->expand( $contextNode->childNodes
, $flags );
1226 # Insert a heading marker only for <h> children of <root>
1227 # This is to stop extractSections from going over multiple tree levels
1228 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1229 # Insert heading index marker
1230 $headingIndex = $contextNode->getAttribute( 'i' );
1231 $titleText = $this->title
->getPrefixedDBkey();
1232 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1233 $serial = count( $this->parser
->mHeadings
) - 1;
1234 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1235 $count = $contextNode->getAttribute( 'level' );
1236 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1237 $this->parser
->mStripState
->addGeneral( $marker, '' );
1241 # Generic recursive expansion
1242 $newIterator = $contextNode->childNodes
;
1245 wfProfileOut( __METHOD__
);
1246 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1249 if ( $newIterator !== false ) {
1250 if ( $newIterator instanceof PPNode_DOM
) {
1251 $newIterator = $newIterator->node
;
1254 $iteratorStack[] = $newIterator;
1256 } elseif ( $iteratorStack[$level] === false ) {
1257 // Return accumulated value to parent
1258 // With tail recursion
1259 while ( $iteratorStack[$level] === false && $level > 0 ) {
1260 $outStack[$level - 1] .= $out;
1261 array_pop( $outStack );
1262 array_pop( $iteratorStack );
1263 array_pop( $indexStack );
1269 wfProfileOut( __METHOD__
);
1270 return $outStack[0];
1274 * @param string $sep
1278 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1279 $args = array_slice( func_get_args(), 2 );
1283 foreach ( $args as $root ) {
1284 if ( $root instanceof PPNode_DOM
) {
1285 $root = $root->node
;
1287 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1288 $root = array( $root );
1290 foreach ( $root as $node ) {
1296 $s .= $this->expand( $node, $flags );
1303 * Implode with no flags specified
1304 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1306 * @param string $sep
1309 function implode( $sep /*, ... */ ) {
1310 $args = array_slice( func_get_args(), 1 );
1314 foreach ( $args as $root ) {
1315 if ( $root instanceof PPNode_DOM
) {
1316 $root = $root->node
;
1318 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1319 $root = array( $root );
1321 foreach ( $root as $node ) {
1327 $s .= $this->expand( $node );
1334 * Makes an object that, when expand()ed, will be the same as one obtained
1337 * @param string $sep
1340 function virtualImplode( $sep /*, ... */ ) {
1341 $args = array_slice( func_get_args(), 1 );
1345 foreach ( $args as $root ) {
1346 if ( $root instanceof PPNode_DOM
) {
1347 $root = $root->node
;
1349 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1350 $root = array( $root );
1352 foreach ( $root as $node ) {
1365 * Virtual implode with brackets
1366 * @param string $start
1367 * @param string $sep
1368 * @param string $end
1371 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1372 $args = array_slice( func_get_args(), 3 );
1373 $out = array( $start );
1376 foreach ( $args as $root ) {
1377 if ( $root instanceof PPNode_DOM
) {
1378 $root = $root->node
;
1380 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1381 $root = array( $root );
1383 foreach ( $root as $node ) {
1396 function __toString() {
1400 function getPDBK( $level = false ) {
1401 if ( $level === false ) {
1402 return $this->title
->getPrefixedDBkey();
1404 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1411 function getArguments() {
1418 function getNumberedArguments() {
1425 function getNamedArguments() {
1430 * Returns true if there are no arguments in this frame
1434 function isEmpty() {
1438 function getArgument( $name ) {
1443 * Returns true if the infinite loop check is OK, false if a loop is detected
1445 * @param Title $title
1448 function loopCheck( $title ) {
1449 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1453 * Return true if the frame is a template frame
1457 function isTemplate() {
1462 * Get a title of frame
1466 function getTitle() {
1467 return $this->title
;
1472 * Expansion frame with template arguments
1475 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1476 var $numberedArgs, $namedArgs;
1482 var $numberedExpansionCache, $namedExpansionCache;
1485 * @param Preprocessor $preprocessor
1486 * @param bool|PPFrame_DOM $parent
1487 * @param array $numberedArgs
1488 * @param array $namedArgs
1489 * @param bool|Title $title
1491 function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1492 $namedArgs = array(), $title = false
1494 parent
::__construct( $preprocessor );
1496 $this->parent
= $parent;
1497 $this->numberedArgs
= $numberedArgs;
1498 $this->namedArgs
= $namedArgs;
1499 $this->title
= $title;
1500 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1501 $this->titleCache
= $parent->titleCache
;
1502 $this->titleCache
[] = $pdbk;
1503 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1504 if ( $pdbk !== false ) {
1505 $this->loopCheckHash
[$pdbk] = true;
1507 $this->depth
= $parent->depth +
1;
1508 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1511 function __toString() {
1514 $args = $this->numberedArgs +
$this->namedArgs
;
1515 foreach ( $args as $name => $value ) {
1521 $s .= "\"$name\":\"" .
1522 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1529 * Returns true if there are no arguments in this frame
1533 function isEmpty() {
1534 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1537 function getArguments() {
1538 $arguments = array();
1539 foreach ( array_merge(
1540 array_keys( $this->numberedArgs
),
1541 array_keys( $this->namedArgs
) ) as $key ) {
1542 $arguments[$key] = $this->getArgument( $key );
1547 function getNumberedArguments() {
1548 $arguments = array();
1549 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1550 $arguments[$key] = $this->getArgument( $key );
1555 function getNamedArguments() {
1556 $arguments = array();
1557 foreach ( array_keys( $this->namedArgs
) as $key ) {
1558 $arguments[$key] = $this->getArgument( $key );
1563 function getNumberedArgument( $index ) {
1564 if ( !isset( $this->numberedArgs
[$index] ) ) {
1567 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1568 # No trimming for unnamed arguments
1569 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1570 $this->numberedArgs
[$index],
1571 PPFrame
::STRIP_COMMENTS
1574 return $this->numberedExpansionCache
[$index];
1577 function getNamedArgument( $name ) {
1578 if ( !isset( $this->namedArgs
[$name] ) ) {
1581 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1582 # Trim named arguments post-expand, for backwards compatibility
1583 $this->namedExpansionCache
[$name] = trim(
1584 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1586 return $this->namedExpansionCache
[$name];
1589 function getArgument( $name ) {
1590 $text = $this->getNumberedArgument( $name );
1591 if ( $text === false ) {
1592 $text = $this->getNamedArgument( $name );
1598 * Return true if the frame is a template frame
1602 function isTemplate() {
1608 * Expansion frame with custom arguments
1611 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1614 function __construct( $preprocessor, $args ) {
1615 parent
::__construct( $preprocessor );
1616 $this->args
= $args;
1619 function __toString() {
1622 foreach ( $this->args
as $name => $value ) {
1628 $s .= "\"$name\":\"" .
1629 str_replace( '"', '\\"', $value->__toString() ) . '"';
1638 function isEmpty() {
1639 return !count( $this->args
);
1642 function getArgument( $index ) {
1643 if ( !isset( $this->args
[$index] ) ) {
1646 return $this->args
[$index];
1649 function getArguments() {
1657 class PPNode_DOM
implements PPNode
{
1665 function __construct( $node, $xpath = false ) {
1666 $this->node
= $node;
1672 function getXPath() {
1673 if ( $this->xpath
=== null ) {
1674 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1676 return $this->xpath
;
1679 function __toString() {
1680 if ( $this->node
instanceof DOMNodeList
) {
1682 foreach ( $this->node
as $node ) {
1683 $s .= $node->ownerDocument
->saveXML( $node );
1686 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1692 * @return bool|PPNode_DOM
1694 function getChildren() {
1695 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1699 * @return bool|PPNode_DOM
1701 function getFirstChild() {
1702 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1706 * @return bool|PPNode_DOM
1708 function getNextSibling() {
1709 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1713 * @param string $type
1715 * @return bool|PPNode_DOM
1717 function getChildrenOfType( $type ) {
1718 return new self( $this->getXPath()->query( $type, $this->node
) );
1724 function getLength() {
1725 if ( $this->node
instanceof DOMNodeList
) {
1726 return $this->node
->length
;
1734 * @return bool|PPNode_DOM
1736 function item( $i ) {
1737 $item = $this->node
->item( $i );
1738 return $item ?
new self( $item ) : false;
1744 function getName() {
1745 if ( $this->node
instanceof DOMNodeList
) {
1748 return $this->node
->nodeName
;
1753 * Split a "<part>" node into an associative array containing:
1754 * - name PPNode name
1755 * - index String index
1756 * - value PPNode value
1758 * @throws MWException
1761 function splitArg() {
1762 $xpath = $this->getXPath();
1763 $names = $xpath->query( 'name', $this->node
);
1764 $values = $xpath->query( 'value', $this->node
);
1765 if ( !$names->length ||
!$values->length
) {
1766 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1768 $name = $names->item( 0 );
1769 $index = $name->getAttribute( 'index' );
1771 'name' => new self( $name ),
1773 'value' => new self( $values->item( 0 ) ) );
1777 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1778 * All values in the resulting array are PPNodes. Inner and close are optional.
1780 * @throws MWException
1783 function splitExt() {
1784 $xpath = $this->getXPath();
1785 $names = $xpath->query( 'name', $this->node
);
1786 $attrs = $xpath->query( 'attr', $this->node
);
1787 $inners = $xpath->query( 'inner', $this->node
);
1788 $closes = $xpath->query( 'close', $this->node
);
1789 if ( !$names->length ||
!$attrs->length
) {
1790 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1793 'name' => new self( $names->item( 0 ) ),
1794 'attr' => new self( $attrs->item( 0 ) ) );
1795 if ( $inners->length
) {
1796 $parts['inner'] = new self( $inners->item( 0 ) );
1798 if ( $closes->length
) {
1799 $parts['close'] = new self( $closes->item( 0 ) );
1805 * Split a "<h>" node
1806 * @throws MWException
1809 function splitHeading() {
1810 if ( $this->getName() !== 'h' ) {
1811 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1814 'i' => $this->node
->getAttribute( 'i' ),
1815 'level' => $this->node
->getAttribute( 'level' ),
1816 'contents' => $this->getChildren()