Support offsets in prefix searching
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob2cce57493435bc257ccae196453858e980eb0d7f
1 <?php
2 /**
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
20 * @file
21 * @ingroup Parser
24 /**
25 * @ingroup Parser
26 * @codingStandardsIgnoreStart
28 class Preprocessor_DOM implements Preprocessor {
29 // @codingStandardsIgnoreEnd
31 /**
32 * @var Parser
34 public $parser;
36 public $memoryLimit;
38 const CACHE_VERSION = 1;
40 public function __construct( $parser ) {
41 $this->parser = $parser;
42 $mem = ini_get( 'memory_limit' );
43 $this->memoryLimit = false;
44 if ( strval( $mem ) !== '' && $mem != -1 ) {
45 if ( preg_match( '/^\d+$/', $mem ) ) {
46 $this->memoryLimit = $mem;
47 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
48 $this->memoryLimit = $m[1] * 1048576;
53 /**
54 * @return PPFrame_DOM
56 public function newFrame() {
57 return new PPFrame_DOM( $this );
60 /**
61 * @param array $args
62 * @return PPCustomFrame_DOM
64 public function newCustomFrame( $args ) {
65 return new PPCustomFrame_DOM( $this, $args );
68 /**
69 * @param array $values
70 * @return PPNode_DOM
72 public function newPartNodeArray( $values ) {
73 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
74 $xml = "<list>";
76 foreach ( $values as $k => $val ) {
77 if ( is_int( $k ) ) {
78 $xml .= "<part><name index=\"$k\"/><value>"
79 . htmlspecialchars( $val ) . "</value></part>";
80 } else {
81 $xml .= "<part><name>" . htmlspecialchars( $k )
82 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
86 $xml .= "</list>";
88 wfProfileIn( __METHOD__ . '-loadXML' );
89 $dom = new DOMDocument();
90 wfSuppressWarnings();
91 $result = $dom->loadXML( $xml );
92 wfRestoreWarnings();
93 if ( !$result ) {
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal::cleanUp( $xml );
96 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
97 // don't barf when the XML is >256 levels deep
98 $result = $dom->loadXML( $xml, 1 << 19 );
100 wfProfileOut( __METHOD__ . '-loadXML' );
102 if ( !$result ) {
103 throw new MWException( 'Parameters passed to ' . __METHOD__ . ' result in invalid XML' );
106 $root = $dom->documentElement;
107 $node = new PPNode_DOM( $root->childNodes );
108 return $node;
112 * @throws MWException
113 * @return bool
115 public function memCheck() {
116 if ( $this->memoryLimit === false ) {
117 return true;
119 $usage = memory_get_usage();
120 if ( $usage > $this->memoryLimit * 0.9 ) {
121 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
122 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
124 return $usage <= $this->memoryLimit * 0.8;
128 * Preprocess some wikitext and return the document tree.
129 * This is the ghost of Parser::replace_variables().
131 * @param string $text The text to parse
132 * @param int $flags Bitwise combination of:
133 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
134 * as if the text is being included. Default
135 * is to assume a direct page view.
137 * The generated DOM tree must depend only on the input text and the flags.
138 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
140 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
141 * change in the DOM tree for a given text, must be passed through the section identifier
142 * in the section edit link and thus back to extractSections().
144 * The output of this function is currently only cached in process memory, but a persistent
145 * cache may be implemented at a later date which takes further advantage of these strict
146 * dependency requirements.
148 * @throws MWException
149 * @return PPNode_DOM
151 public function preprocessToObj( $text, $flags = 0 ) {
152 wfProfileIn( __METHOD__ );
153 global $wgMemc, $wgPreprocessorCacheThreshold;
155 $xml = false;
156 $cacheable = ( $wgPreprocessorCacheThreshold !== false
157 && strlen( $text ) > $wgPreprocessorCacheThreshold );
158 if ( $cacheable ) {
159 wfProfileIn( __METHOD__ . '-cacheable' );
161 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
162 $cacheValue = $wgMemc->get( $cacheKey );
163 if ( $cacheValue ) {
164 $version = substr( $cacheValue, 0, 8 );
165 if ( intval( $version ) == self::CACHE_VERSION ) {
166 $xml = substr( $cacheValue, 8 );
167 // From the cache
168 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
171 if ( $xml === false ) {
172 wfProfileIn( __METHOD__ . '-cache-miss' );
173 $xml = $this->preprocessToXml( $text, $flags );
174 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
175 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
176 wfProfileOut( __METHOD__ . '-cache-miss' );
177 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
179 } else {
180 $xml = $this->preprocessToXml( $text, $flags );
183 // Fail if the number of elements exceeds acceptable limits
184 // Do not attempt to generate the DOM
185 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
186 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
187 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
188 if ( $cacheable ) {
189 wfProfileOut( __METHOD__ . '-cacheable' );
191 wfProfileOut( __METHOD__ );
192 throw new MWException( __METHOD__ . ': generated node count limit exceeded' );
195 wfProfileIn( __METHOD__ . '-loadXML' );
196 $dom = new DOMDocument;
197 wfSuppressWarnings();
198 $result = $dom->loadXML( $xml );
199 wfRestoreWarnings();
200 if ( !$result ) {
201 // Try running the XML through UtfNormal to get rid of invalid characters
202 $xml = UtfNormal::cleanUp( $xml );
203 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
204 // don't barf when the XML is >256 levels deep.
205 $result = $dom->loadXML( $xml, 1 << 19 );
207 if ( $result ) {
208 $obj = new PPNode_DOM( $dom->documentElement );
210 wfProfileOut( __METHOD__ . '-loadXML' );
212 if ( $cacheable ) {
213 wfProfileOut( __METHOD__ . '-cacheable' );
216 wfProfileOut( __METHOD__ );
218 if ( !$result ) {
219 throw new MWException( __METHOD__ . ' generated invalid XML' );
221 return $obj;
225 * @param string $text
226 * @param int $flags
227 * @return string
229 public function preprocessToXml( $text, $flags = 0 ) {
230 wfProfileIn( __METHOD__ );
231 $rules = array(
232 '{' => array(
233 'end' => '}',
234 'names' => array(
235 2 => 'template',
236 3 => 'tplarg',
238 'min' => 2,
239 'max' => 3,
241 '[' => array(
242 'end' => ']',
243 'names' => array( 2 => null ),
244 'min' => 2,
245 'max' => 2,
249 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
251 $xmlishElements = $this->parser->getStripList();
252 $enableOnlyinclude = false;
253 if ( $forInclusion ) {
254 $ignoredTags = array( 'includeonly', '/includeonly' );
255 $ignoredElements = array( 'noinclude' );
256 $xmlishElements[] = 'noinclude';
257 if ( strpos( $text, '<onlyinclude>' ) !== false
258 && strpos( $text, '</onlyinclude>' ) !== false
260 $enableOnlyinclude = true;
262 } else {
263 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
264 $ignoredElements = array( 'includeonly' );
265 $xmlishElements[] = 'includeonly';
267 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
269 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
270 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
272 $stack = new PPDStack;
274 $searchBase = "[{<\n"; #}
275 // For fast reverse searches
276 $revText = strrev( $text );
277 $lengthText = strlen( $text );
279 // Input pointer, starts out pointing to a pseudo-newline before the start
280 $i = 0;
281 // Current accumulator
282 $accum =& $stack->getAccum();
283 $accum = '<root>';
284 // True to find equals signs in arguments
285 $findEquals = false;
286 // True to take notice of pipe characters
287 $findPipe = false;
288 $headingIndex = 1;
289 // True if $i is inside a possible heading
290 $inHeading = false;
291 // True if there are no more greater-than (>) signs right of $i
292 $noMoreGT = false;
293 // True to ignore all input up to the next <onlyinclude>
294 $findOnlyinclude = $enableOnlyinclude;
295 // Do a line-start run without outputting an LF character
296 $fakeLineStart = true;
298 while ( true ) {
299 //$this->memCheck();
301 if ( $findOnlyinclude ) {
302 // Ignore all input up to the next <onlyinclude>
303 $startPos = strpos( $text, '<onlyinclude>', $i );
304 if ( $startPos === false ) {
305 // Ignored section runs to the end
306 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
307 break;
309 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
310 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
311 $i = $tagEndPos;
312 $findOnlyinclude = false;
315 if ( $fakeLineStart ) {
316 $found = 'line-start';
317 $curChar = '';
318 } else {
319 # Find next opening brace, closing brace or pipe
320 $search = $searchBase;
321 if ( $stack->top === false ) {
322 $currentClosing = '';
323 } else {
324 $currentClosing = $stack->top->close;
325 $search .= $currentClosing;
327 if ( $findPipe ) {
328 $search .= '|';
330 if ( $findEquals ) {
331 // First equals will be for the template
332 $search .= '=';
334 $rule = null;
335 # Output literal section, advance input counter
336 $literalLength = strcspn( $text, $search, $i );
337 if ( $literalLength > 0 ) {
338 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
339 $i += $literalLength;
341 if ( $i >= $lengthText ) {
342 if ( $currentClosing == "\n" ) {
343 // Do a past-the-end run to finish off the heading
344 $curChar = '';
345 $found = 'line-end';
346 } else {
347 # All done
348 break;
350 } else {
351 $curChar = $text[$i];
352 if ( $curChar == '|' ) {
353 $found = 'pipe';
354 } elseif ( $curChar == '=' ) {
355 $found = 'equals';
356 } elseif ( $curChar == '<' ) {
357 $found = 'angle';
358 } elseif ( $curChar == "\n" ) {
359 if ( $inHeading ) {
360 $found = 'line-end';
361 } else {
362 $found = 'line-start';
364 } elseif ( $curChar == $currentClosing ) {
365 $found = 'close';
366 } elseif ( isset( $rules[$curChar] ) ) {
367 $found = 'open';
368 $rule = $rules[$curChar];
369 } else {
370 # Some versions of PHP have a strcspn which stops on null characters
371 # Ignore and continue
372 ++$i;
373 continue;
378 if ( $found == 'angle' ) {
379 $matches = false;
380 // Handle </onlyinclude>
381 if ( $enableOnlyinclude
382 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
384 $findOnlyinclude = true;
385 continue;
388 // Determine element name
389 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
390 // Element name missing or not listed
391 $accum .= '&lt;';
392 ++$i;
393 continue;
395 // Handle comments
396 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
398 // To avoid leaving blank lines, when a sequence of
399 // space-separated comments is both preceded and followed by
400 // a newline (ignoring spaces), then
401 // trim leading and trailing spaces and the trailing newline.
403 // Find the end
404 $endPos = strpos( $text, '-->', $i + 4 );
405 if ( $endPos === false ) {
406 // Unclosed comment in input, runs to end
407 $inner = substr( $text, $i );
408 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
409 $i = $lengthText;
410 } else {
411 // Search backwards for leading whitespace
412 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
414 // Search forwards for trailing whitespace
415 // $wsEnd will be the position of the last space (or the '>' if there's none)
416 $wsEnd = $endPos + 2 + strspn( $text, " \t", $endPos + 3 );
418 // Keep looking forward as long as we're finding more
419 // comments.
420 $comments = array( array( $wsStart, $wsEnd ) );
421 while ( substr( $text, $wsEnd + 1, 4 ) == '<!--' ) {
422 $c = strpos( $text, '-->', $wsEnd + 4 );
423 if ( $c === false ) {
424 break;
426 $c = $c + 2 + strspn( $text, " \t", $c + 3 );
427 $comments[] = array( $wsEnd + 1, $c );
428 $wsEnd = $c;
431 // Eat the line if possible
432 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
433 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
434 // it's a possible beneficial b/c break.
435 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
436 && substr( $text, $wsEnd + 1, 1 ) == "\n"
438 // Remove leading whitespace from the end of the accumulator
439 // Sanity check first though
440 $wsLength = $i - $wsStart;
441 if ( $wsLength > 0
442 && strspn( $accum, " \t", -$wsLength ) === $wsLength
444 $accum = substr( $accum, 0, -$wsLength );
447 // Dump all but the last comment to the accumulator
448 foreach ( $comments as $j => $com ) {
449 $startPos = $com[0];
450 $endPos = $com[1] + 1;
451 if ( $j == ( count( $comments ) - 1 ) ) {
452 break;
454 $inner = substr( $text, $startPos, $endPos - $startPos );
455 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
458 // Do a line-start run next time to look for headings after the comment
459 $fakeLineStart = true;
460 } else {
461 // No line to eat, just take the comment itself
462 $startPos = $i;
463 $endPos += 2;
466 if ( $stack->top ) {
467 $part = $stack->top->getCurrentPart();
468 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
469 $part->visualEnd = $wsStart;
471 // Else comments abutting, no change in visual end
472 $part->commentEnd = $endPos;
474 $i = $endPos + 1;
475 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
476 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
478 continue;
480 $name = $matches[1];
481 $lowerName = strtolower( $name );
482 $attrStart = $i + strlen( $name ) + 1;
484 // Find end of tag
485 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
486 if ( $tagEndPos === false ) {
487 // Infinite backtrack
488 // Disable tag search to prevent worst-case O(N^2) performance
489 $noMoreGT = true;
490 $accum .= '&lt;';
491 ++$i;
492 continue;
495 // Handle ignored tags
496 if ( in_array( $lowerName, $ignoredTags ) ) {
497 $accum .= '<ignore>'
498 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) )
499 . '</ignore>';
500 $i = $tagEndPos + 1;
501 continue;
504 $tagStartPos = $i;
505 if ( $text[$tagEndPos - 1] == '/' ) {
506 $attrEnd = $tagEndPos - 1;
507 $inner = null;
508 $i = $tagEndPos + 1;
509 $close = '';
510 } else {
511 $attrEnd = $tagEndPos;
512 // Find closing tag
513 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
514 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
516 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
517 $i = $matches[0][1] + strlen( $matches[0][0] );
518 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
519 } else {
520 // No end tag -- let it run out to the end of the text.
521 $inner = substr( $text, $tagEndPos + 1 );
522 $i = $lengthText;
523 $close = '';
526 // <includeonly> and <noinclude> just become <ignore> tags
527 if ( in_array( $lowerName, $ignoredElements ) ) {
528 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
529 . '</ignore>';
530 continue;
533 $accum .= '<ext>';
534 if ( $attrEnd <= $attrStart ) {
535 $attr = '';
536 } else {
537 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
539 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
540 // Note that the attr element contains the whitespace between name and attribute,
541 // this is necessary for precise reconstruction during pre-save transform.
542 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
543 if ( $inner !== null ) {
544 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
546 $accum .= $close . '</ext>';
547 } elseif ( $found == 'line-start' ) {
548 // Is this the start of a heading?
549 // Line break belongs before the heading element in any case
550 if ( $fakeLineStart ) {
551 $fakeLineStart = false;
552 } else {
553 $accum .= $curChar;
554 $i++;
557 $count = strspn( $text, '=', $i, 6 );
558 if ( $count == 1 && $findEquals ) {
559 // DWIM: This looks kind of like a name/value separator.
560 // Let's let the equals handler have it and break the
561 // potential heading. This is heuristic, but AFAICT the
562 // methods for completely correct disambiguation are very
563 // complex.
564 } elseif ( $count > 0 ) {
565 $piece = array(
566 'open' => "\n",
567 'close' => "\n",
568 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
569 'startPos' => $i,
570 'count' => $count );
571 $stack->push( $piece );
572 $accum =& $stack->getAccum();
573 $flags = $stack->getFlags();
574 extract( $flags );
575 $i += $count;
577 } elseif ( $found == 'line-end' ) {
578 $piece = $stack->top;
579 // A heading must be open, otherwise \n wouldn't have been in the search list
580 assert( '$piece->open == "\n"' );
581 $part = $piece->getCurrentPart();
582 // Search back through the input to see if it has a proper close.
583 // Do this using the reversed string since the other solutions
584 // (end anchor, etc.) are inefficient.
585 $wsLength = strspn( $revText, " \t", $lengthText - $i );
586 $searchStart = $i - $wsLength;
587 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
588 // Comment found at line end
589 // Search for equals signs before the comment
590 $searchStart = $part->visualEnd;
591 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
593 $count = $piece->count;
594 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
595 if ( $equalsLength > 0 ) {
596 if ( $searchStart - $equalsLength == $piece->startPos ) {
597 // This is just a single string of equals signs on its own line
598 // Replicate the doHeadings behavior /={count}(.+)={count}/
599 // First find out how many equals signs there really are (don't stop at 6)
600 $count = $equalsLength;
601 if ( $count < 3 ) {
602 $count = 0;
603 } else {
604 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
606 } else {
607 $count = min( $equalsLength, $count );
609 if ( $count > 0 ) {
610 // Normal match, output <h>
611 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
612 $headingIndex++;
613 } else {
614 // Single equals sign on its own line, count=0
615 $element = $accum;
617 } else {
618 // No match, no <h>, just pass down the inner text
619 $element = $accum;
621 // Unwind the stack
622 $stack->pop();
623 $accum =& $stack->getAccum();
624 $flags = $stack->getFlags();
625 extract( $flags );
627 // Append the result to the enclosing accumulator
628 $accum .= $element;
629 // Note that we do NOT increment the input pointer.
630 // This is because the closing linebreak could be the opening linebreak of
631 // another heading. Infinite loops are avoided because the next iteration MUST
632 // hit the heading open case above, which unconditionally increments the
633 // input pointer.
634 } elseif ( $found == 'open' ) {
635 # count opening brace characters
636 $count = strspn( $text, $curChar, $i );
638 # we need to add to stack only if opening brace count is enough for one of the rules
639 if ( $count >= $rule['min'] ) {
640 # Add it to the stack
641 $piece = array(
642 'open' => $curChar,
643 'close' => $rule['end'],
644 'count' => $count,
645 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
648 $stack->push( $piece );
649 $accum =& $stack->getAccum();
650 $flags = $stack->getFlags();
651 extract( $flags );
652 } else {
653 # Add literal brace(s)
654 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
656 $i += $count;
657 } elseif ( $found == 'close' ) {
658 $piece = $stack->top;
659 # lets check if there are enough characters for closing brace
660 $maxCount = $piece->count;
661 $count = strspn( $text, $curChar, $i, $maxCount );
663 # check for maximum matching characters (if there are 5 closing
664 # characters, we will probably need only 3 - depending on the rules)
665 $rule = $rules[$piece->open];
666 if ( $count > $rule['max'] ) {
667 # The specified maximum exists in the callback array, unless the caller
668 # has made an error
669 $matchingCount = $rule['max'];
670 } else {
671 # Count is less than the maximum
672 # Skip any gaps in the callback array to find the true largest match
673 # Need to use array_key_exists not isset because the callback can be null
674 $matchingCount = $count;
675 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
676 --$matchingCount;
680 if ( $matchingCount <= 0 ) {
681 # No matching element found in callback array
682 # Output a literal closing brace and continue
683 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
684 $i += $count;
685 continue;
687 $name = $rule['names'][$matchingCount];
688 if ( $name === null ) {
689 // No element, just literal text
690 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
691 } else {
692 # Create XML element
693 # Note: $parts is already XML, does not need to be encoded further
694 $parts = $piece->parts;
695 $title = $parts[0]->out;
696 unset( $parts[0] );
698 # The invocation is at the start of the line if lineStart is set in
699 # the stack, and all opening brackets are used up.
700 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
701 $attr = ' lineStart="1"';
702 } else {
703 $attr = '';
706 $element = "<$name$attr>";
707 $element .= "<title>$title</title>";
708 $argIndex = 1;
709 foreach ( $parts as $part ) {
710 if ( isset( $part->eqpos ) ) {
711 $argName = substr( $part->out, 0, $part->eqpos );
712 $argValue = substr( $part->out, $part->eqpos + 1 );
713 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
714 } else {
715 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
716 $argIndex++;
719 $element .= "</$name>";
722 # Advance input pointer
723 $i += $matchingCount;
725 # Unwind the stack
726 $stack->pop();
727 $accum =& $stack->getAccum();
729 # Re-add the old stack element if it still has unmatched opening characters remaining
730 if ( $matchingCount < $piece->count ) {
731 $piece->parts = array( new PPDPart );
732 $piece->count -= $matchingCount;
733 # do we still qualify for any callback with remaining count?
734 $min = $rules[$piece->open]['min'];
735 if ( $piece->count >= $min ) {
736 $stack->push( $piece );
737 $accum =& $stack->getAccum();
738 } else {
739 $accum .= str_repeat( $piece->open, $piece->count );
742 $flags = $stack->getFlags();
743 extract( $flags );
745 # Add XML element to the enclosing accumulator
746 $accum .= $element;
747 } elseif ( $found == 'pipe' ) {
748 $findEquals = true; // shortcut for getFlags()
749 $stack->addPart();
750 $accum =& $stack->getAccum();
751 ++$i;
752 } elseif ( $found == 'equals' ) {
753 $findEquals = false; // shortcut for getFlags()
754 $stack->getCurrentPart()->eqpos = strlen( $accum );
755 $accum .= '=';
756 ++$i;
760 # Output any remaining unclosed brackets
761 foreach ( $stack->stack as $piece ) {
762 $stack->rootAccum .= $piece->breakSyntax();
764 $stack->rootAccum .= '</root>';
765 $xml = $stack->rootAccum;
767 wfProfileOut( __METHOD__ );
769 return $xml;
774 * Stack class to help Preprocessor::preprocessToObj()
775 * @ingroup Parser
777 class PPDStack {
778 public $stack, $rootAccum;
781 * @var PPDStack
783 public $top;
784 public $out;
785 public $elementClass = 'PPDStackElement';
787 public static $false = false;
789 public function __construct() {
790 $this->stack = array();
791 $this->top = false;
792 $this->rootAccum = '';
793 $this->accum =& $this->rootAccum;
797 * @return int
799 public function count() {
800 return count( $this->stack );
803 public function &getAccum() {
804 return $this->accum;
807 public function getCurrentPart() {
808 if ( $this->top === false ) {
809 return false;
810 } else {
811 return $this->top->getCurrentPart();
815 public function push( $data ) {
816 if ( $data instanceof $this->elementClass ) {
817 $this->stack[] = $data;
818 } else {
819 $class = $this->elementClass;
820 $this->stack[] = new $class( $data );
822 $this->top = $this->stack[count( $this->stack ) - 1];
823 $this->accum =& $this->top->getAccum();
826 public function pop() {
827 if ( !count( $this->stack ) ) {
828 throw new MWException( __METHOD__ . ': no elements remaining' );
830 $temp = array_pop( $this->stack );
832 if ( count( $this->stack ) ) {
833 $this->top = $this->stack[count( $this->stack ) - 1];
834 $this->accum =& $this->top->getAccum();
835 } else {
836 $this->top = self::$false;
837 $this->accum =& $this->rootAccum;
839 return $temp;
842 public function addPart( $s = '' ) {
843 $this->top->addPart( $s );
844 $this->accum =& $this->top->getAccum();
848 * @return array
850 public function getFlags() {
851 if ( !count( $this->stack ) ) {
852 return array(
853 'findEquals' => false,
854 'findPipe' => false,
855 'inHeading' => false,
857 } else {
858 return $this->top->getFlags();
864 * @ingroup Parser
866 class PPDStackElement {
867 public $open, // Opening character (\n for heading)
868 $close, // Matching closing character
869 $count, // Number of opening characters found (number of "=" for heading)
870 $parts, // Array of PPDPart objects describing pipe-separated parts.
871 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
873 public $partClass = 'PPDPart';
875 public function __construct( $data = array() ) {
876 $class = $this->partClass;
877 $this->parts = array( new $class );
879 foreach ( $data as $name => $value ) {
880 $this->$name = $value;
884 public function &getAccum() {
885 return $this->parts[count( $this->parts ) - 1]->out;
888 public function addPart( $s = '' ) {
889 $class = $this->partClass;
890 $this->parts[] = new $class( $s );
893 public function getCurrentPart() {
894 return $this->parts[count( $this->parts ) - 1];
898 * @return array
900 public function getFlags() {
901 $partCount = count( $this->parts );
902 $findPipe = $this->open != "\n" && $this->open != '[';
903 return array(
904 'findPipe' => $findPipe,
905 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
906 'inHeading' => $this->open == "\n",
911 * Get the output string that would result if the close is not found.
913 * @param bool|int $openingCount
914 * @return string
916 public function breakSyntax( $openingCount = false ) {
917 if ( $this->open == "\n" ) {
918 $s = $this->parts[0]->out;
919 } else {
920 if ( $openingCount === false ) {
921 $openingCount = $this->count;
923 $s = str_repeat( $this->open, $openingCount );
924 $first = true;
925 foreach ( $this->parts as $part ) {
926 if ( $first ) {
927 $first = false;
928 } else {
929 $s .= '|';
931 $s .= $part->out;
934 return $s;
939 * @ingroup Parser
941 class PPDPart {
942 public $out; // Output accumulator string
944 // Optional member variables:
945 // eqpos Position of equals sign in output accumulator
946 // commentEnd Past-the-end input pointer for the last comment encountered
947 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
949 public function __construct( $out = '' ) {
950 $this->out = $out;
955 * An expansion frame, used as a context to expand the result of preprocessToObj()
956 * @ingroup Parser
957 * @codingStandardsIgnoreStart
959 class PPFrame_DOM implements PPFrame {
960 // @codingStandardsIgnoreEnd
963 * @var Preprocessor
965 public $preprocessor;
968 * @var Parser
970 public $parser;
973 * @var Title
975 public $title;
976 public $titleCache;
979 * Hashtable listing templates which are disallowed for expansion in this frame,
980 * having been encountered previously in parent frames.
982 public $loopCheckHash;
985 * Recursion depth of this frame, top = 0
986 * Note that this is NOT the same as expansion depth in expand()
988 public $depth;
990 private $volatile = false;
991 private $ttl = null;
994 * @var array
996 protected $childExpansionCache;
999 * Construct a new preprocessor frame.
1000 * @param Preprocessor $preprocessor The parent preprocessor
1002 public function __construct( $preprocessor ) {
1003 $this->preprocessor = $preprocessor;
1004 $this->parser = $preprocessor->parser;
1005 $this->title = $this->parser->mTitle;
1006 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
1007 $this->loopCheckHash = array();
1008 $this->depth = 0;
1009 $this->childExpansionCache = array();
1013 * Create a new child frame
1014 * $args is optionally a multi-root PPNode or array containing the template arguments
1016 * @param bool|array $args
1017 * @param Title|bool $title
1018 * @param int $indexOffset
1019 * @return PPTemplateFrame_DOM
1021 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1022 $namedArgs = array();
1023 $numberedArgs = array();
1024 if ( $title === false ) {
1025 $title = $this->title;
1027 if ( $args !== false ) {
1028 $xpath = false;
1029 if ( $args instanceof PPNode ) {
1030 $args = $args->node;
1032 foreach ( $args as $arg ) {
1033 if ( $arg instanceof PPNode ) {
1034 $arg = $arg->node;
1036 if ( !$xpath || $xpath->document !== $arg->ownerDocument ) {
1037 $xpath = new DOMXPath( $arg->ownerDocument );
1040 $nameNodes = $xpath->query( 'name', $arg );
1041 $value = $xpath->query( 'value', $arg );
1042 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1043 // Numbered parameter
1044 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
1045 $index = $index - $indexOffset;
1046 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
1047 $this->parser->addTrackingCategory( 'duplicate-args-category' );
1049 $numberedArgs[$index] = $value->item( 0 );
1050 unset( $namedArgs[$index] );
1051 } else {
1052 // Named parameter
1053 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
1054 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
1055 $this->parser->addTrackingCategory( 'duplicate-args-category' );
1057 $namedArgs[$name] = $value->item( 0 );
1058 unset( $numberedArgs[$name] );
1062 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1066 * @throws MWException
1067 * @param string|int $key
1068 * @param string|PPNode_DOM|DOMDocument $root
1069 * @param int $flags
1070 * @return string
1072 public function cachedExpand( $key, $root, $flags = 0 ) {
1073 // we don't have a parent, so we don't have a cache
1074 return $this->expand( $root, $flags );
1078 * @throws MWException
1079 * @param string|PPNode_DOM|DOMDocument $root
1080 * @param int $flags
1081 * @return string
1083 public function expand( $root, $flags = 0 ) {
1084 static $expansionDepth = 0;
1085 if ( is_string( $root ) ) {
1086 return $root;
1089 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1090 $this->parser->limitationWarn( 'node-count-exceeded',
1091 $this->parser->mPPNodeCount,
1092 $this->parser->mOptions->getMaxPPNodeCount()
1094 return '<span class="error">Node-count limit exceeded</span>';
1097 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1098 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1099 $expansionDepth,
1100 $this->parser->mOptions->getMaxPPExpandDepth()
1102 return '<span class="error">Expansion depth limit exceeded</span>';
1104 wfProfileIn( __METHOD__ );
1105 ++$expansionDepth;
1106 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1107 $this->parser->mHighestExpansionDepth = $expansionDepth;
1110 if ( $root instanceof PPNode_DOM ) {
1111 $root = $root->node;
1113 if ( $root instanceof DOMDocument ) {
1114 $root = $root->documentElement;
1117 $outStack = array( '', '' );
1118 $iteratorStack = array( false, $root );
1119 $indexStack = array( 0, 0 );
1121 while ( count( $iteratorStack ) > 1 ) {
1122 $level = count( $outStack ) - 1;
1123 $iteratorNode =& $iteratorStack[$level];
1124 $out =& $outStack[$level];
1125 $index =& $indexStack[$level];
1127 if ( $iteratorNode instanceof PPNode_DOM ) {
1128 $iteratorNode = $iteratorNode->node;
1131 if ( is_array( $iteratorNode ) ) {
1132 if ( $index >= count( $iteratorNode ) ) {
1133 // All done with this iterator
1134 $iteratorStack[$level] = false;
1135 $contextNode = false;
1136 } else {
1137 $contextNode = $iteratorNode[$index];
1138 $index++;
1140 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1141 if ( $index >= $iteratorNode->length ) {
1142 // All done with this iterator
1143 $iteratorStack[$level] = false;
1144 $contextNode = false;
1145 } else {
1146 $contextNode = $iteratorNode->item( $index );
1147 $index++;
1149 } else {
1150 // Copy to $contextNode and then delete from iterator stack,
1151 // because this is not an iterator but we do have to execute it once
1152 $contextNode = $iteratorStack[$level];
1153 $iteratorStack[$level] = false;
1156 if ( $contextNode instanceof PPNode_DOM ) {
1157 $contextNode = $contextNode->node;
1160 $newIterator = false;
1162 if ( $contextNode === false ) {
1163 // nothing to do
1164 } elseif ( is_string( $contextNode ) ) {
1165 $out .= $contextNode;
1166 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1167 $newIterator = $contextNode;
1168 } elseif ( $contextNode instanceof DOMNode ) {
1169 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1170 $out .= $contextNode->nodeValue;
1171 } elseif ( $contextNode->nodeName == 'template' ) {
1172 # Double-brace expansion
1173 $xpath = new DOMXPath( $contextNode->ownerDocument );
1174 $titles = $xpath->query( 'title', $contextNode );
1175 $title = $titles->item( 0 );
1176 $parts = $xpath->query( 'part', $contextNode );
1177 if ( $flags & PPFrame::NO_TEMPLATES ) {
1178 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1179 } else {
1180 $lineStart = $contextNode->getAttribute( 'lineStart' );
1181 $params = array(
1182 'title' => new PPNode_DOM( $title ),
1183 'parts' => new PPNode_DOM( $parts ),
1184 'lineStart' => $lineStart );
1185 $ret = $this->parser->braceSubstitution( $params, $this );
1186 if ( isset( $ret['object'] ) ) {
1187 $newIterator = $ret['object'];
1188 } else {
1189 $out .= $ret['text'];
1192 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1193 # Triple-brace expansion
1194 $xpath = new DOMXPath( $contextNode->ownerDocument );
1195 $titles = $xpath->query( 'title', $contextNode );
1196 $title = $titles->item( 0 );
1197 $parts = $xpath->query( 'part', $contextNode );
1198 if ( $flags & PPFrame::NO_ARGS ) {
1199 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1200 } else {
1201 $params = array(
1202 'title' => new PPNode_DOM( $title ),
1203 'parts' => new PPNode_DOM( $parts ) );
1204 $ret = $this->parser->argSubstitution( $params, $this );
1205 if ( isset( $ret['object'] ) ) {
1206 $newIterator = $ret['object'];
1207 } else {
1208 $out .= $ret['text'];
1211 } elseif ( $contextNode->nodeName == 'comment' ) {
1212 # HTML-style comment
1213 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1214 if ( $this->parser->ot['html']
1215 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1216 || ( $flags & PPFrame::STRIP_COMMENTS )
1218 $out .= '';
1219 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1220 # Add a strip marker in PST mode so that pstPass2() can
1221 # run some old-fashioned regexes on the result.
1222 # Not in RECOVER_COMMENTS mode (extractSections) though.
1223 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1224 } else {
1225 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1226 $out .= $contextNode->textContent;
1228 } elseif ( $contextNode->nodeName == 'ignore' ) {
1229 # Output suppression used by <includeonly> etc.
1230 # OT_WIKI will only respect <ignore> in substed templates.
1231 # The other output types respect it unless NO_IGNORE is set.
1232 # extractSections() sets NO_IGNORE and so never respects it.
1233 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1234 || ( $flags & PPFrame::NO_IGNORE )
1236 $out .= $contextNode->textContent;
1237 } else {
1238 $out .= '';
1240 } elseif ( $contextNode->nodeName == 'ext' ) {
1241 # Extension tag
1242 $xpath = new DOMXPath( $contextNode->ownerDocument );
1243 $names = $xpath->query( 'name', $contextNode );
1244 $attrs = $xpath->query( 'attr', $contextNode );
1245 $inners = $xpath->query( 'inner', $contextNode );
1246 $closes = $xpath->query( 'close', $contextNode );
1247 if ( $flags & PPFrame::NO_TAGS ) {
1248 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1249 if ( $attrs->length > 0 ) {
1250 $s .= $this->expand( $attrs->item( 0 ), $flags );
1252 if ( $inners->length > 0 ) {
1253 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1254 if ( $closes->length > 0 ) {
1255 $s .= $this->expand( $closes->item( 0 ), $flags );
1257 } else {
1258 $s .= '/>';
1260 $out .= $s;
1261 } else {
1262 $params = array(
1263 'name' => new PPNode_DOM( $names->item( 0 ) ),
1264 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1265 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1266 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1268 $out .= $this->parser->extensionSubstitution( $params, $this );
1270 } elseif ( $contextNode->nodeName == 'h' ) {
1271 # Heading
1272 $s = $this->expand( $contextNode->childNodes, $flags );
1274 # Insert a heading marker only for <h> children of <root>
1275 # This is to stop extractSections from going over multiple tree levels
1276 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html'] ) {
1277 # Insert heading index marker
1278 $headingIndex = $contextNode->getAttribute( 'i' );
1279 $titleText = $this->title->getPrefixedDBkey();
1280 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1281 $serial = count( $this->parser->mHeadings ) - 1;
1282 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1283 $count = $contextNode->getAttribute( 'level' );
1284 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1285 $this->parser->mStripState->addGeneral( $marker, '' );
1287 $out .= $s;
1288 } else {
1289 # Generic recursive expansion
1290 $newIterator = $contextNode->childNodes;
1292 } else {
1293 wfProfileOut( __METHOD__ );
1294 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1297 if ( $newIterator !== false ) {
1298 if ( $newIterator instanceof PPNode_DOM ) {
1299 $newIterator = $newIterator->node;
1301 $outStack[] = '';
1302 $iteratorStack[] = $newIterator;
1303 $indexStack[] = 0;
1304 } elseif ( $iteratorStack[$level] === false ) {
1305 // Return accumulated value to parent
1306 // With tail recursion
1307 while ( $iteratorStack[$level] === false && $level > 0 ) {
1308 $outStack[$level - 1] .= $out;
1309 array_pop( $outStack );
1310 array_pop( $iteratorStack );
1311 array_pop( $indexStack );
1312 $level--;
1316 --$expansionDepth;
1317 wfProfileOut( __METHOD__ );
1318 return $outStack[0];
1322 * @param string $sep
1323 * @param int $flags
1324 * @param string|PPNode_DOM|DOMDocument $args,...
1325 * @return string
1327 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1328 $args = array_slice( func_get_args(), 2 );
1330 $first = true;
1331 $s = '';
1332 foreach ( $args as $root ) {
1333 if ( $root instanceof PPNode_DOM ) {
1334 $root = $root->node;
1336 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1337 $root = array( $root );
1339 foreach ( $root as $node ) {
1340 if ( $first ) {
1341 $first = false;
1342 } else {
1343 $s .= $sep;
1345 $s .= $this->expand( $node, $flags );
1348 return $s;
1352 * Implode with no flags specified
1353 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1355 * @param string $sep
1356 * @param string|PPNode_DOM|DOMDocument $args,...
1357 * @return string
1359 public function implode( $sep /*, ... */ ) {
1360 $args = array_slice( func_get_args(), 1 );
1362 $first = true;
1363 $s = '';
1364 foreach ( $args as $root ) {
1365 if ( $root instanceof PPNode_DOM ) {
1366 $root = $root->node;
1368 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1369 $root = array( $root );
1371 foreach ( $root as $node ) {
1372 if ( $first ) {
1373 $first = false;
1374 } else {
1375 $s .= $sep;
1377 $s .= $this->expand( $node );
1380 return $s;
1384 * Makes an object that, when expand()ed, will be the same as one obtained
1385 * with implode()
1387 * @param string $sep
1388 * @param string|PPNode_DOM|DOMDocument $args,...
1389 * @return array
1391 public function virtualImplode( $sep /*, ... */ ) {
1392 $args = array_slice( func_get_args(), 1 );
1393 $out = array();
1394 $first = true;
1396 foreach ( $args as $root ) {
1397 if ( $root instanceof PPNode_DOM ) {
1398 $root = $root->node;
1400 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1401 $root = array( $root );
1403 foreach ( $root as $node ) {
1404 if ( $first ) {
1405 $first = false;
1406 } else {
1407 $out[] = $sep;
1409 $out[] = $node;
1412 return $out;
1416 * Virtual implode with brackets
1417 * @param string $start
1418 * @param string $sep
1419 * @param string $end
1420 * @param string|PPNode_DOM|DOMDocument $args,...
1421 * @return array
1423 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1424 $args = array_slice( func_get_args(), 3 );
1425 $out = array( $start );
1426 $first = true;
1428 foreach ( $args as $root ) {
1429 if ( $root instanceof PPNode_DOM ) {
1430 $root = $root->node;
1432 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1433 $root = array( $root );
1435 foreach ( $root as $node ) {
1436 if ( $first ) {
1437 $first = false;
1438 } else {
1439 $out[] = $sep;
1441 $out[] = $node;
1444 $out[] = $end;
1445 return $out;
1448 public function __toString() {
1449 return 'frame{}';
1452 public function getPDBK( $level = false ) {
1453 if ( $level === false ) {
1454 return $this->title->getPrefixedDBkey();
1455 } else {
1456 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1461 * @return array
1463 public function getArguments() {
1464 return array();
1468 * @return array
1470 public function getNumberedArguments() {
1471 return array();
1475 * @return array
1477 public function getNamedArguments() {
1478 return array();
1482 * Returns true if there are no arguments in this frame
1484 * @return bool
1486 public function isEmpty() {
1487 return true;
1490 public function getArgument( $name ) {
1491 return false;
1495 * Returns true if the infinite loop check is OK, false if a loop is detected
1497 * @param Title $title
1498 * @return bool
1500 public function loopCheck( $title ) {
1501 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1505 * Return true if the frame is a template frame
1507 * @return bool
1509 public function isTemplate() {
1510 return false;
1514 * Get a title of frame
1516 * @return Title
1518 public function getTitle() {
1519 return $this->title;
1523 * Set the volatile flag
1525 * @param bool $flag
1527 public function setVolatile( $flag = true ) {
1528 $this->volatile = $flag;
1532 * Get the volatile flag
1534 * @return bool
1536 public function isVolatile() {
1537 return $this->volatile;
1541 * Set the TTL
1543 * @param int $ttl
1545 public function setTTL( $ttl ) {
1546 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1547 $this->ttl = $ttl;
1552 * Get the TTL
1554 * @return int|null
1556 public function getTTL() {
1557 return $this->ttl;
1562 * Expansion frame with template arguments
1563 * @ingroup Parser
1564 * @codingStandardsIgnoreStart
1566 class PPTemplateFrame_DOM extends PPFrame_DOM {
1567 // @codingStandardsIgnoreEnd
1569 public $numberedArgs, $namedArgs;
1572 * @var PPFrame_DOM
1574 public $parent;
1575 public $numberedExpansionCache, $namedExpansionCache;
1578 * @param Preprocessor $preprocessor
1579 * @param bool|PPFrame_DOM $parent
1580 * @param array $numberedArgs
1581 * @param array $namedArgs
1582 * @param bool|Title $title
1584 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1585 $namedArgs = array(), $title = false
1587 parent::__construct( $preprocessor );
1589 $this->parent = $parent;
1590 $this->numberedArgs = $numberedArgs;
1591 $this->namedArgs = $namedArgs;
1592 $this->title = $title;
1593 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1594 $this->titleCache = $parent->titleCache;
1595 $this->titleCache[] = $pdbk;
1596 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1597 if ( $pdbk !== false ) {
1598 $this->loopCheckHash[$pdbk] = true;
1600 $this->depth = $parent->depth + 1;
1601 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1604 public function __toString() {
1605 $s = 'tplframe{';
1606 $first = true;
1607 $args = $this->numberedArgs + $this->namedArgs;
1608 foreach ( $args as $name => $value ) {
1609 if ( $first ) {
1610 $first = false;
1611 } else {
1612 $s .= ', ';
1614 $s .= "\"$name\":\"" .
1615 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1617 $s .= '}';
1618 return $s;
1622 * @throws MWException
1623 * @param string|int $key
1624 * @param string|PPNode_DOM|DOMDocument $root
1625 * @param int $flags
1626 * @return string
1628 public function cachedExpand( $key, $root, $flags = 0 ) {
1629 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1630 return $this->parent->childExpansionCache[$key];
1632 $retval = $this->expand( $root, $flags );
1633 if ( !$this->isVolatile() ) {
1634 $this->parent->childExpansionCache[$key] = $retval;
1636 return $retval;
1640 * Returns true if there are no arguments in this frame
1642 * @return bool
1644 public function isEmpty() {
1645 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1648 public function getArguments() {
1649 $arguments = array();
1650 foreach ( array_merge(
1651 array_keys( $this->numberedArgs ),
1652 array_keys( $this->namedArgs ) ) as $key ) {
1653 $arguments[$key] = $this->getArgument( $key );
1655 return $arguments;
1658 public function getNumberedArguments() {
1659 $arguments = array();
1660 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1661 $arguments[$key] = $this->getArgument( $key );
1663 return $arguments;
1666 public function getNamedArguments() {
1667 $arguments = array();
1668 foreach ( array_keys( $this->namedArgs ) as $key ) {
1669 $arguments[$key] = $this->getArgument( $key );
1671 return $arguments;
1674 public function getNumberedArgument( $index ) {
1675 if ( !isset( $this->numberedArgs[$index] ) ) {
1676 return false;
1678 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1679 # No trimming for unnamed arguments
1680 $this->numberedExpansionCache[$index] = $this->parent->expand(
1681 $this->numberedArgs[$index],
1682 PPFrame::STRIP_COMMENTS
1685 return $this->numberedExpansionCache[$index];
1688 public function getNamedArgument( $name ) {
1689 if ( !isset( $this->namedArgs[$name] ) ) {
1690 return false;
1692 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1693 # Trim named arguments post-expand, for backwards compatibility
1694 $this->namedExpansionCache[$name] = trim(
1695 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1697 return $this->namedExpansionCache[$name];
1700 public function getArgument( $name ) {
1701 $text = $this->getNumberedArgument( $name );
1702 if ( $text === false ) {
1703 $text = $this->getNamedArgument( $name );
1705 return $text;
1709 * Return true if the frame is a template frame
1711 * @return bool
1713 public function isTemplate() {
1714 return true;
1717 public function setVolatile( $flag = true ) {
1718 parent::setVolatile( $flag );
1719 $this->parent->setVolatile( $flag );
1722 public function setTTL( $ttl ) {
1723 parent::setTTL( $ttl );
1724 $this->parent->setTTL( $ttl );
1729 * Expansion frame with custom arguments
1730 * @ingroup Parser
1731 * @codingStandardsIgnoreStart
1733 class PPCustomFrame_DOM extends PPFrame_DOM {
1734 // @codingStandardsIgnoreEnd
1736 public $args;
1738 public function __construct( $preprocessor, $args ) {
1739 parent::__construct( $preprocessor );
1740 $this->args = $args;
1743 public function __toString() {
1744 $s = 'cstmframe{';
1745 $first = true;
1746 foreach ( $this->args as $name => $value ) {
1747 if ( $first ) {
1748 $first = false;
1749 } else {
1750 $s .= ', ';
1752 $s .= "\"$name\":\"" .
1753 str_replace( '"', '\\"', $value->__toString() ) . '"';
1755 $s .= '}';
1756 return $s;
1760 * @return bool
1762 public function isEmpty() {
1763 return !count( $this->args );
1766 public function getArgument( $index ) {
1767 if ( !isset( $this->args[$index] ) ) {
1768 return false;
1770 return $this->args[$index];
1773 public function getArguments() {
1774 return $this->args;
1779 * @ingroup Parser
1780 * @codingStandardsIgnoreStart
1782 class PPNode_DOM implements PPNode {
1783 // @codingStandardsIgnoreEnd
1786 * @var DOMElement
1788 public $node;
1789 public $xpath;
1791 public function __construct( $node, $xpath = false ) {
1792 $this->node = $node;
1796 * @return DOMXPath
1798 public function getXPath() {
1799 if ( $this->xpath === null ) {
1800 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1802 return $this->xpath;
1805 public function __toString() {
1806 if ( $this->node instanceof DOMNodeList ) {
1807 $s = '';
1808 foreach ( $this->node as $node ) {
1809 $s .= $node->ownerDocument->saveXML( $node );
1811 } else {
1812 $s = $this->node->ownerDocument->saveXML( $this->node );
1814 return $s;
1818 * @return bool|PPNode_DOM
1820 public function getChildren() {
1821 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1825 * @return bool|PPNode_DOM
1827 public function getFirstChild() {
1828 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1832 * @return bool|PPNode_DOM
1834 public function getNextSibling() {
1835 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1839 * @param string $type
1841 * @return bool|PPNode_DOM
1843 public function getChildrenOfType( $type ) {
1844 return new self( $this->getXPath()->query( $type, $this->node ) );
1848 * @return int
1850 public function getLength() {
1851 if ( $this->node instanceof DOMNodeList ) {
1852 return $this->node->length;
1853 } else {
1854 return false;
1859 * @param int $i
1860 * @return bool|PPNode_DOM
1862 public function item( $i ) {
1863 $item = $this->node->item( $i );
1864 return $item ? new self( $item ) : false;
1868 * @return string
1870 public function getName() {
1871 if ( $this->node instanceof DOMNodeList ) {
1872 return '#nodelist';
1873 } else {
1874 return $this->node->nodeName;
1879 * Split a "<part>" node into an associative array containing:
1880 * - name PPNode name
1881 * - index String index
1882 * - value PPNode value
1884 * @throws MWException
1885 * @return array
1887 public function splitArg() {
1888 $xpath = $this->getXPath();
1889 $names = $xpath->query( 'name', $this->node );
1890 $values = $xpath->query( 'value', $this->node );
1891 if ( !$names->length || !$values->length ) {
1892 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1894 $name = $names->item( 0 );
1895 $index = $name->getAttribute( 'index' );
1896 return array(
1897 'name' => new self( $name ),
1898 'index' => $index,
1899 'value' => new self( $values->item( 0 ) ) );
1903 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1904 * All values in the resulting array are PPNodes. Inner and close are optional.
1906 * @throws MWException
1907 * @return array
1909 public function splitExt() {
1910 $xpath = $this->getXPath();
1911 $names = $xpath->query( 'name', $this->node );
1912 $attrs = $xpath->query( 'attr', $this->node );
1913 $inners = $xpath->query( 'inner', $this->node );
1914 $closes = $xpath->query( 'close', $this->node );
1915 if ( !$names->length || !$attrs->length ) {
1916 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1918 $parts = array(
1919 'name' => new self( $names->item( 0 ) ),
1920 'attr' => new self( $attrs->item( 0 ) ) );
1921 if ( $inners->length ) {
1922 $parts['inner'] = new self( $inners->item( 0 ) );
1924 if ( $closes->length ) {
1925 $parts['close'] = new self( $closes->item( 0 ) );
1927 return $parts;
1931 * Split a "<h>" node
1932 * @throws MWException
1933 * @return array
1935 public function splitHeading() {
1936 if ( $this->getName() !== 'h' ) {
1937 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1939 return array(
1940 'i' => $this->node->getAttribute( 'i' ),
1941 'level' => $this->node->getAttribute( 'level' ),
1942 'contents' => $this->getChildren()