Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob343588191bae8436ab8311d093604beb77dd9cc7
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
71 * @throws MWException
73 public function newPartNodeArray( $values ) {
74 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
75 $xml = "<list>";
77 foreach ( $values as $k => $val ) {
78 if ( is_int( $k ) ) {
79 $xml .= "<part><name index=\"$k\"/><value>"
80 . htmlspecialchars( $val ) . "</value></part>";
81 } else {
82 $xml .= "<part><name>" . htmlspecialchars( $k )
83 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
87 $xml .= "</list>";
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 );
101 if ( !$result ) {
102 throw new MWException( 'Parameters passed to ' . __METHOD__ . ' result in invalid XML' );
105 $root = $dom->documentElement;
106 $node = new PPNode_DOM( $root->childNodes );
107 return $node;
111 * @throws MWException
112 * @return bool
114 public function memCheck() {
115 if ( $this->memoryLimit === false ) {
116 return true;
118 $usage = memory_get_usage();
119 if ( $usage > $this->memoryLimit * 0.9 ) {
120 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
121 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
123 return $usage <= $this->memoryLimit * 0.8;
127 * Preprocess some wikitext and return the document tree.
128 * This is the ghost of Parser::replace_variables().
130 * @param string $text The text to parse
131 * @param int $flags Bitwise combination of:
132 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
133 * as if the text is being included. Default
134 * is to assume a direct page view.
136 * The generated DOM tree must depend only on the input text and the flags.
137 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
139 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
140 * change in the DOM tree for a given text, must be passed through the section identifier
141 * in the section edit link and thus back to extractSections().
143 * The output of this function is currently only cached in process memory, but a persistent
144 * cache may be implemented at a later date which takes further advantage of these strict
145 * dependency requirements.
147 * @throws MWException
148 * @return PPNode_DOM
150 public function preprocessToObj( $text, $flags = 0 ) {
151 global $wgMemc, $wgPreprocessorCacheThreshold;
153 $xml = false;
154 $cacheable = ( $wgPreprocessorCacheThreshold !== false
155 && strlen( $text ) > $wgPreprocessorCacheThreshold );
156 if ( $cacheable ) {
158 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
159 $cacheValue = $wgMemc->get( $cacheKey );
160 if ( $cacheValue ) {
161 $version = substr( $cacheValue, 0, 8 );
162 if ( intval( $version ) == self::CACHE_VERSION ) {
163 $xml = substr( $cacheValue, 8 );
164 // From the cache
165 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
168 if ( $xml === false ) {
169 $xml = $this->preprocessToXml( $text, $flags );
170 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
171 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
172 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
174 } else {
175 $xml = $this->preprocessToXml( $text, $flags );
178 // Fail if the number of elements exceeds acceptable limits
179 // Do not attempt to generate the DOM
180 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
181 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
182 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
183 if ( $cacheable ) {
185 throw new MWException( __METHOD__ . ': generated node count limit exceeded' );
188 $dom = new DOMDocument;
189 wfSuppressWarnings();
190 $result = $dom->loadXML( $xml );
191 wfRestoreWarnings();
192 if ( !$result ) {
193 // Try running the XML through UtfNormal to get rid of invalid characters
194 $xml = UtfNormal::cleanUp( $xml );
195 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
196 // don't barf when the XML is >256 levels deep.
197 $result = $dom->loadXML( $xml, 1 << 19 );
199 if ( $result ) {
200 $obj = new PPNode_DOM( $dom->documentElement );
203 if ( $cacheable ) {
206 if ( !$result ) {
207 throw new MWException( __METHOD__ . ' generated invalid XML' );
209 return $obj;
213 * @param string $text
214 * @param int $flags
215 * @return string
217 public function preprocessToXml( $text, $flags = 0 ) {
218 $rules = array(
219 '{' => array(
220 'end' => '}',
221 'names' => array(
222 2 => 'template',
223 3 => 'tplarg',
225 'min' => 2,
226 'max' => 3,
228 '[' => array(
229 'end' => ']',
230 'names' => array( 2 => null ),
231 'min' => 2,
232 'max' => 2,
236 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
238 $xmlishElements = $this->parser->getStripList();
239 $enableOnlyinclude = false;
240 if ( $forInclusion ) {
241 $ignoredTags = array( 'includeonly', '/includeonly' );
242 $ignoredElements = array( 'noinclude' );
243 $xmlishElements[] = 'noinclude';
244 if ( strpos( $text, '<onlyinclude>' ) !== false
245 && strpos( $text, '</onlyinclude>' ) !== false
247 $enableOnlyinclude = true;
249 } else {
250 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
251 $ignoredElements = array( 'includeonly' );
252 $xmlishElements[] = 'includeonly';
254 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
256 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
257 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
259 $stack = new PPDStack;
261 $searchBase = "[{<\n"; #}
262 // For fast reverse searches
263 $revText = strrev( $text );
264 $lengthText = strlen( $text );
266 // Input pointer, starts out pointing to a pseudo-newline before the start
267 $i = 0;
268 // Current accumulator
269 $accum =& $stack->getAccum();
270 $accum = '<root>';
271 // True to find equals signs in arguments
272 $findEquals = false;
273 // True to take notice of pipe characters
274 $findPipe = false;
275 $headingIndex = 1;
276 // True if $i is inside a possible heading
277 $inHeading = false;
278 // True if there are no more greater-than (>) signs right of $i
279 $noMoreGT = false;
280 // True to ignore all input up to the next <onlyinclude>
281 $findOnlyinclude = $enableOnlyinclude;
282 // Do a line-start run without outputting an LF character
283 $fakeLineStart = true;
285 while ( true ) {
286 //$this->memCheck();
288 if ( $findOnlyinclude ) {
289 // Ignore all input up to the next <onlyinclude>
290 $startPos = strpos( $text, '<onlyinclude>', $i );
291 if ( $startPos === false ) {
292 // Ignored section runs to the end
293 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
294 break;
296 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
297 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
298 $i = $tagEndPos;
299 $findOnlyinclude = false;
302 if ( $fakeLineStart ) {
303 $found = 'line-start';
304 $curChar = '';
305 } else {
306 # Find next opening brace, closing brace or pipe
307 $search = $searchBase;
308 if ( $stack->top === false ) {
309 $currentClosing = '';
310 } else {
311 $currentClosing = $stack->top->close;
312 $search .= $currentClosing;
314 if ( $findPipe ) {
315 $search .= '|';
317 if ( $findEquals ) {
318 // First equals will be for the template
319 $search .= '=';
321 $rule = null;
322 # Output literal section, advance input counter
323 $literalLength = strcspn( $text, $search, $i );
324 if ( $literalLength > 0 ) {
325 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
326 $i += $literalLength;
328 if ( $i >= $lengthText ) {
329 if ( $currentClosing == "\n" ) {
330 // Do a past-the-end run to finish off the heading
331 $curChar = '';
332 $found = 'line-end';
333 } else {
334 # All done
335 break;
337 } else {
338 $curChar = $text[$i];
339 if ( $curChar == '|' ) {
340 $found = 'pipe';
341 } elseif ( $curChar == '=' ) {
342 $found = 'equals';
343 } elseif ( $curChar == '<' ) {
344 $found = 'angle';
345 } elseif ( $curChar == "\n" ) {
346 if ( $inHeading ) {
347 $found = 'line-end';
348 } else {
349 $found = 'line-start';
351 } elseif ( $curChar == $currentClosing ) {
352 $found = 'close';
353 } elseif ( isset( $rules[$curChar] ) ) {
354 $found = 'open';
355 $rule = $rules[$curChar];
356 } else {
357 # Some versions of PHP have a strcspn which stops on null characters
358 # Ignore and continue
359 ++$i;
360 continue;
365 if ( $found == 'angle' ) {
366 $matches = false;
367 // Handle </onlyinclude>
368 if ( $enableOnlyinclude
369 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
371 $findOnlyinclude = true;
372 continue;
375 // Determine element name
376 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
377 // Element name missing or not listed
378 $accum .= '&lt;';
379 ++$i;
380 continue;
382 // Handle comments
383 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
385 // To avoid leaving blank lines, when a sequence of
386 // space-separated comments is both preceded and followed by
387 // a newline (ignoring spaces), then
388 // trim leading and trailing spaces and the trailing newline.
390 // Find the end
391 $endPos = strpos( $text, '-->', $i + 4 );
392 if ( $endPos === false ) {
393 // Unclosed comment in input, runs to end
394 $inner = substr( $text, $i );
395 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
396 $i = $lengthText;
397 } else {
398 // Search backwards for leading whitespace
399 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
401 // Search forwards for trailing whitespace
402 // $wsEnd will be the position of the last space (or the '>' if there's none)
403 $wsEnd = $endPos + 2 + strspn( $text, " \t", $endPos + 3 );
405 // Keep looking forward as long as we're finding more
406 // comments.
407 $comments = array( array( $wsStart, $wsEnd ) );
408 while ( substr( $text, $wsEnd + 1, 4 ) == '<!--' ) {
409 $c = strpos( $text, '-->', $wsEnd + 4 );
410 if ( $c === false ) {
411 break;
413 $c = $c + 2 + strspn( $text, " \t", $c + 3 );
414 $comments[] = array( $wsEnd + 1, $c );
415 $wsEnd = $c;
418 // Eat the line if possible
419 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
420 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
421 // it's a possible beneficial b/c break.
422 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
423 && substr( $text, $wsEnd + 1, 1 ) == "\n"
425 // Remove leading whitespace from the end of the accumulator
426 // Sanity check first though
427 $wsLength = $i - $wsStart;
428 if ( $wsLength > 0
429 && strspn( $accum, " \t", -$wsLength ) === $wsLength
431 $accum = substr( $accum, 0, -$wsLength );
434 // Dump all but the last comment to the accumulator
435 foreach ( $comments as $j => $com ) {
436 $startPos = $com[0];
437 $endPos = $com[1] + 1;
438 if ( $j == ( count( $comments ) - 1 ) ) {
439 break;
441 $inner = substr( $text, $startPos, $endPos - $startPos );
442 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
445 // Do a line-start run next time to look for headings after the comment
446 $fakeLineStart = true;
447 } else {
448 // No line to eat, just take the comment itself
449 $startPos = $i;
450 $endPos += 2;
453 if ( $stack->top ) {
454 $part = $stack->top->getCurrentPart();
455 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
456 $part->visualEnd = $wsStart;
458 // Else comments abutting, no change in visual end
459 $part->commentEnd = $endPos;
461 $i = $endPos + 1;
462 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
463 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
465 continue;
467 $name = $matches[1];
468 $lowerName = strtolower( $name );
469 $attrStart = $i + strlen( $name ) + 1;
471 // Find end of tag
472 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
473 if ( $tagEndPos === false ) {
474 // Infinite backtrack
475 // Disable tag search to prevent worst-case O(N^2) performance
476 $noMoreGT = true;
477 $accum .= '&lt;';
478 ++$i;
479 continue;
482 // Handle ignored tags
483 if ( in_array( $lowerName, $ignoredTags ) ) {
484 $accum .= '<ignore>'
485 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) )
486 . '</ignore>';
487 $i = $tagEndPos + 1;
488 continue;
491 $tagStartPos = $i;
492 if ( $text[$tagEndPos - 1] == '/' ) {
493 $attrEnd = $tagEndPos - 1;
494 $inner = null;
495 $i = $tagEndPos + 1;
496 $close = '';
497 } else {
498 $attrEnd = $tagEndPos;
499 // Find closing tag
500 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
501 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
503 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
504 $i = $matches[0][1] + strlen( $matches[0][0] );
505 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
506 } else {
507 // No end tag -- let it run out to the end of the text.
508 $inner = substr( $text, $tagEndPos + 1 );
509 $i = $lengthText;
510 $close = '';
513 // <includeonly> and <noinclude> just become <ignore> tags
514 if ( in_array( $lowerName, $ignoredElements ) ) {
515 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
516 . '</ignore>';
517 continue;
520 $accum .= '<ext>';
521 if ( $attrEnd <= $attrStart ) {
522 $attr = '';
523 } else {
524 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
526 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
527 // Note that the attr element contains the whitespace between name and attribute,
528 // this is necessary for precise reconstruction during pre-save transform.
529 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
530 if ( $inner !== null ) {
531 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
533 $accum .= $close . '</ext>';
534 } elseif ( $found == 'line-start' ) {
535 // Is this the start of a heading?
536 // Line break belongs before the heading element in any case
537 if ( $fakeLineStart ) {
538 $fakeLineStart = false;
539 } else {
540 $accum .= $curChar;
541 $i++;
544 $count = strspn( $text, '=', $i, 6 );
545 if ( $count == 1 && $findEquals ) {
546 // DWIM: This looks kind of like a name/value separator.
547 // Let's let the equals handler have it and break the
548 // potential heading. This is heuristic, but AFAICT the
549 // methods for completely correct disambiguation are very
550 // complex.
551 } elseif ( $count > 0 ) {
552 $piece = array(
553 'open' => "\n",
554 'close' => "\n",
555 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
556 'startPos' => $i,
557 'count' => $count );
558 $stack->push( $piece );
559 $accum =& $stack->getAccum();
560 $flags = $stack->getFlags();
561 extract( $flags );
562 $i += $count;
564 } elseif ( $found == 'line-end' ) {
565 $piece = $stack->top;
566 // A heading must be open, otherwise \n wouldn't have been in the search list
567 assert( '$piece->open == "\n"' );
568 $part = $piece->getCurrentPart();
569 // Search back through the input to see if it has a proper close.
570 // Do this using the reversed string since the other solutions
571 // (end anchor, etc.) are inefficient.
572 $wsLength = strspn( $revText, " \t", $lengthText - $i );
573 $searchStart = $i - $wsLength;
574 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
575 // Comment found at line end
576 // Search for equals signs before the comment
577 $searchStart = $part->visualEnd;
578 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
580 $count = $piece->count;
581 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
582 if ( $equalsLength > 0 ) {
583 if ( $searchStart - $equalsLength == $piece->startPos ) {
584 // This is just a single string of equals signs on its own line
585 // Replicate the doHeadings behavior /={count}(.+)={count}/
586 // First find out how many equals signs there really are (don't stop at 6)
587 $count = $equalsLength;
588 if ( $count < 3 ) {
589 $count = 0;
590 } else {
591 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
593 } else {
594 $count = min( $equalsLength, $count );
596 if ( $count > 0 ) {
597 // Normal match, output <h>
598 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
599 $headingIndex++;
600 } else {
601 // Single equals sign on its own line, count=0
602 $element = $accum;
604 } else {
605 // No match, no <h>, just pass down the inner text
606 $element = $accum;
608 // Unwind the stack
609 $stack->pop();
610 $accum =& $stack->getAccum();
611 $flags = $stack->getFlags();
612 extract( $flags );
614 // Append the result to the enclosing accumulator
615 $accum .= $element;
616 // Note that we do NOT increment the input pointer.
617 // This is because the closing linebreak could be the opening linebreak of
618 // another heading. Infinite loops are avoided because the next iteration MUST
619 // hit the heading open case above, which unconditionally increments the
620 // input pointer.
621 } elseif ( $found == 'open' ) {
622 # count opening brace characters
623 $count = strspn( $text, $curChar, $i );
625 # we need to add to stack only if opening brace count is enough for one of the rules
626 if ( $count >= $rule['min'] ) {
627 # Add it to the stack
628 $piece = array(
629 'open' => $curChar,
630 'close' => $rule['end'],
631 'count' => $count,
632 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
635 $stack->push( $piece );
636 $accum =& $stack->getAccum();
637 $flags = $stack->getFlags();
638 extract( $flags );
639 } else {
640 # Add literal brace(s)
641 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
643 $i += $count;
644 } elseif ( $found == 'close' ) {
645 $piece = $stack->top;
646 # lets check if there are enough characters for closing brace
647 $maxCount = $piece->count;
648 $count = strspn( $text, $curChar, $i, $maxCount );
650 # check for maximum matching characters (if there are 5 closing
651 # characters, we will probably need only 3 - depending on the rules)
652 $rule = $rules[$piece->open];
653 if ( $count > $rule['max'] ) {
654 # The specified maximum exists in the callback array, unless the caller
655 # has made an error
656 $matchingCount = $rule['max'];
657 } else {
658 # Count is less than the maximum
659 # Skip any gaps in the callback array to find the true largest match
660 # Need to use array_key_exists not isset because the callback can be null
661 $matchingCount = $count;
662 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
663 --$matchingCount;
667 if ( $matchingCount <= 0 ) {
668 # No matching element found in callback array
669 # Output a literal closing brace and continue
670 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
671 $i += $count;
672 continue;
674 $name = $rule['names'][$matchingCount];
675 if ( $name === null ) {
676 // No element, just literal text
677 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
678 } else {
679 # Create XML element
680 # Note: $parts is already XML, does not need to be encoded further
681 $parts = $piece->parts;
682 $title = $parts[0]->out;
683 unset( $parts[0] );
685 # The invocation is at the start of the line if lineStart is set in
686 # the stack, and all opening brackets are used up.
687 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
688 $attr = ' lineStart="1"';
689 } else {
690 $attr = '';
693 $element = "<$name$attr>";
694 $element .= "<title>$title</title>";
695 $argIndex = 1;
696 foreach ( $parts as $part ) {
697 if ( isset( $part->eqpos ) ) {
698 $argName = substr( $part->out, 0, $part->eqpos );
699 $argValue = substr( $part->out, $part->eqpos + 1 );
700 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
701 } else {
702 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
703 $argIndex++;
706 $element .= "</$name>";
709 # Advance input pointer
710 $i += $matchingCount;
712 # Unwind the stack
713 $stack->pop();
714 $accum =& $stack->getAccum();
716 # Re-add the old stack element if it still has unmatched opening characters remaining
717 if ( $matchingCount < $piece->count ) {
718 $piece->parts = array( new PPDPart );
719 $piece->count -= $matchingCount;
720 # do we still qualify for any callback with remaining count?
721 $min = $rules[$piece->open]['min'];
722 if ( $piece->count >= $min ) {
723 $stack->push( $piece );
724 $accum =& $stack->getAccum();
725 } else {
726 $accum .= str_repeat( $piece->open, $piece->count );
729 $flags = $stack->getFlags();
730 extract( $flags );
732 # Add XML element to the enclosing accumulator
733 $accum .= $element;
734 } elseif ( $found == 'pipe' ) {
735 $findEquals = true; // shortcut for getFlags()
736 $stack->addPart();
737 $accum =& $stack->getAccum();
738 ++$i;
739 } elseif ( $found == 'equals' ) {
740 $findEquals = false; // shortcut for getFlags()
741 $stack->getCurrentPart()->eqpos = strlen( $accum );
742 $accum .= '=';
743 ++$i;
747 # Output any remaining unclosed brackets
748 foreach ( $stack->stack as $piece ) {
749 $stack->rootAccum .= $piece->breakSyntax();
751 $stack->rootAccum .= '</root>';
752 $xml = $stack->rootAccum;
754 return $xml;
759 * Stack class to help Preprocessor::preprocessToObj()
760 * @ingroup Parser
762 class PPDStack {
763 public $stack, $rootAccum;
766 * @var PPDStack
768 public $top;
769 public $out;
770 public $elementClass = 'PPDStackElement';
772 public static $false = false;
774 public function __construct() {
775 $this->stack = array();
776 $this->top = false;
777 $this->rootAccum = '';
778 $this->accum =& $this->rootAccum;
782 * @return int
784 public function count() {
785 return count( $this->stack );
788 public function &getAccum() {
789 return $this->accum;
792 public function getCurrentPart() {
793 if ( $this->top === false ) {
794 return false;
795 } else {
796 return $this->top->getCurrentPart();
800 public function push( $data ) {
801 if ( $data instanceof $this->elementClass ) {
802 $this->stack[] = $data;
803 } else {
804 $class = $this->elementClass;
805 $this->stack[] = new $class( $data );
807 $this->top = $this->stack[count( $this->stack ) - 1];
808 $this->accum =& $this->top->getAccum();
811 public function pop() {
812 if ( !count( $this->stack ) ) {
813 throw new MWException( __METHOD__ . ': no elements remaining' );
815 $temp = array_pop( $this->stack );
817 if ( count( $this->stack ) ) {
818 $this->top = $this->stack[count( $this->stack ) - 1];
819 $this->accum =& $this->top->getAccum();
820 } else {
821 $this->top = self::$false;
822 $this->accum =& $this->rootAccum;
824 return $temp;
827 public function addPart( $s = '' ) {
828 $this->top->addPart( $s );
829 $this->accum =& $this->top->getAccum();
833 * @return array
835 public function getFlags() {
836 if ( !count( $this->stack ) ) {
837 return array(
838 'findEquals' => false,
839 'findPipe' => false,
840 'inHeading' => false,
842 } else {
843 return $this->top->getFlags();
849 * @ingroup Parser
851 class PPDStackElement {
852 public $open, // Opening character (\n for heading)
853 $close, // Matching closing character
854 $count, // Number of opening characters found (number of "=" for heading)
855 $parts, // Array of PPDPart objects describing pipe-separated parts.
856 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
858 public $partClass = 'PPDPart';
860 public function __construct( $data = array() ) {
861 $class = $this->partClass;
862 $this->parts = array( new $class );
864 foreach ( $data as $name => $value ) {
865 $this->$name = $value;
869 public function &getAccum() {
870 return $this->parts[count( $this->parts ) - 1]->out;
873 public function addPart( $s = '' ) {
874 $class = $this->partClass;
875 $this->parts[] = new $class( $s );
878 public function getCurrentPart() {
879 return $this->parts[count( $this->parts ) - 1];
883 * @return array
885 public function getFlags() {
886 $partCount = count( $this->parts );
887 $findPipe = $this->open != "\n" && $this->open != '[';
888 return array(
889 'findPipe' => $findPipe,
890 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
891 'inHeading' => $this->open == "\n",
896 * Get the output string that would result if the close is not found.
898 * @param bool|int $openingCount
899 * @return string
901 public function breakSyntax( $openingCount = false ) {
902 if ( $this->open == "\n" ) {
903 $s = $this->parts[0]->out;
904 } else {
905 if ( $openingCount === false ) {
906 $openingCount = $this->count;
908 $s = str_repeat( $this->open, $openingCount );
909 $first = true;
910 foreach ( $this->parts as $part ) {
911 if ( $first ) {
912 $first = false;
913 } else {
914 $s .= '|';
916 $s .= $part->out;
919 return $s;
924 * @ingroup Parser
926 class PPDPart {
927 public $out; // Output accumulator string
929 // Optional member variables:
930 // eqpos Position of equals sign in output accumulator
931 // commentEnd Past-the-end input pointer for the last comment encountered
932 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
934 public function __construct( $out = '' ) {
935 $this->out = $out;
940 * An expansion frame, used as a context to expand the result of preprocessToObj()
941 * @ingroup Parser
942 * @codingStandardsIgnoreStart
944 class PPFrame_DOM implements PPFrame {
945 // @codingStandardsIgnoreEnd
948 * @var Preprocessor
950 public $preprocessor;
953 * @var Parser
955 public $parser;
958 * @var Title
960 public $title;
961 public $titleCache;
964 * Hashtable listing templates which are disallowed for expansion in this frame,
965 * having been encountered previously in parent frames.
967 public $loopCheckHash;
970 * Recursion depth of this frame, top = 0
971 * Note that this is NOT the same as expansion depth in expand()
973 public $depth;
975 private $volatile = false;
976 private $ttl = null;
979 * @var array
981 protected $childExpansionCache;
984 * Construct a new preprocessor frame.
985 * @param Preprocessor $preprocessor The parent preprocessor
987 public function __construct( $preprocessor ) {
988 $this->preprocessor = $preprocessor;
989 $this->parser = $preprocessor->parser;
990 $this->title = $this->parser->mTitle;
991 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
992 $this->loopCheckHash = array();
993 $this->depth = 0;
994 $this->childExpansionCache = array();
998 * Create a new child frame
999 * $args is optionally a multi-root PPNode or array containing the template arguments
1001 * @param bool|array $args
1002 * @param Title|bool $title
1003 * @param int $indexOffset
1004 * @return PPTemplateFrame_DOM
1006 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1007 $namedArgs = array();
1008 $numberedArgs = array();
1009 if ( $title === false ) {
1010 $title = $this->title;
1012 if ( $args !== false ) {
1013 $xpath = false;
1014 if ( $args instanceof PPNode ) {
1015 $args = $args->node;
1017 foreach ( $args as $arg ) {
1018 if ( $arg instanceof PPNode ) {
1019 $arg = $arg->node;
1021 if ( !$xpath || $xpath->document !== $arg->ownerDocument ) {
1022 $xpath = new DOMXPath( $arg->ownerDocument );
1025 $nameNodes = $xpath->query( 'name', $arg );
1026 $value = $xpath->query( 'value', $arg );
1027 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1028 // Numbered parameter
1029 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
1030 $index = $index - $indexOffset;
1031 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
1032 $this->parser->addTrackingCategory( 'duplicate-args-category' );
1034 $numberedArgs[$index] = $value->item( 0 );
1035 unset( $namedArgs[$index] );
1036 } else {
1037 // Named parameter
1038 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
1039 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
1040 $this->parser->addTrackingCategory( 'duplicate-args-category' );
1042 $namedArgs[$name] = $value->item( 0 );
1043 unset( $numberedArgs[$name] );
1047 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1051 * @throws MWException
1052 * @param string|int $key
1053 * @param string|PPNode_DOM|DOMDocument $root
1054 * @param int $flags
1055 * @return string
1057 public function cachedExpand( $key, $root, $flags = 0 ) {
1058 // we don't have a parent, so we don't have a cache
1059 return $this->expand( $root, $flags );
1063 * @throws MWException
1064 * @param string|PPNode_DOM|DOMDocument $root
1065 * @param int $flags
1066 * @return string
1068 public function expand( $root, $flags = 0 ) {
1069 static $expansionDepth = 0;
1070 if ( is_string( $root ) ) {
1071 return $root;
1074 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1075 $this->parser->limitationWarn( 'node-count-exceeded',
1076 $this->parser->mPPNodeCount,
1077 $this->parser->mOptions->getMaxPPNodeCount()
1079 return '<span class="error">Node-count limit exceeded</span>';
1082 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1083 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1084 $expansionDepth,
1085 $this->parser->mOptions->getMaxPPExpandDepth()
1087 return '<span class="error">Expansion depth limit exceeded</span>';
1089 ++$expansionDepth;
1090 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1091 $this->parser->mHighestExpansionDepth = $expansionDepth;
1094 if ( $root instanceof PPNode_DOM ) {
1095 $root = $root->node;
1097 if ( $root instanceof DOMDocument ) {
1098 $root = $root->documentElement;
1101 $outStack = array( '', '' );
1102 $iteratorStack = array( false, $root );
1103 $indexStack = array( 0, 0 );
1105 while ( count( $iteratorStack ) > 1 ) {
1106 $level = count( $outStack ) - 1;
1107 $iteratorNode =& $iteratorStack[$level];
1108 $out =& $outStack[$level];
1109 $index =& $indexStack[$level];
1111 if ( $iteratorNode instanceof PPNode_DOM ) {
1112 $iteratorNode = $iteratorNode->node;
1115 if ( is_array( $iteratorNode ) ) {
1116 if ( $index >= count( $iteratorNode ) ) {
1117 // All done with this iterator
1118 $iteratorStack[$level] = false;
1119 $contextNode = false;
1120 } else {
1121 $contextNode = $iteratorNode[$index];
1122 $index++;
1124 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1125 if ( $index >= $iteratorNode->length ) {
1126 // All done with this iterator
1127 $iteratorStack[$level] = false;
1128 $contextNode = false;
1129 } else {
1130 $contextNode = $iteratorNode->item( $index );
1131 $index++;
1133 } else {
1134 // Copy to $contextNode and then delete from iterator stack,
1135 // because this is not an iterator but we do have to execute it once
1136 $contextNode = $iteratorStack[$level];
1137 $iteratorStack[$level] = false;
1140 if ( $contextNode instanceof PPNode_DOM ) {
1141 $contextNode = $contextNode->node;
1144 $newIterator = false;
1146 if ( $contextNode === false ) {
1147 // nothing to do
1148 } elseif ( is_string( $contextNode ) ) {
1149 $out .= $contextNode;
1150 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1151 $newIterator = $contextNode;
1152 } elseif ( $contextNode instanceof DOMNode ) {
1153 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1154 $out .= $contextNode->nodeValue;
1155 } elseif ( $contextNode->nodeName == 'template' ) {
1156 # Double-brace expansion
1157 $xpath = new DOMXPath( $contextNode->ownerDocument );
1158 $titles = $xpath->query( 'title', $contextNode );
1159 $title = $titles->item( 0 );
1160 $parts = $xpath->query( 'part', $contextNode );
1161 if ( $flags & PPFrame::NO_TEMPLATES ) {
1162 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1163 } else {
1164 $lineStart = $contextNode->getAttribute( 'lineStart' );
1165 $params = array(
1166 'title' => new PPNode_DOM( $title ),
1167 'parts' => new PPNode_DOM( $parts ),
1168 'lineStart' => $lineStart );
1169 $ret = $this->parser->braceSubstitution( $params, $this );
1170 if ( isset( $ret['object'] ) ) {
1171 $newIterator = $ret['object'];
1172 } else {
1173 $out .= $ret['text'];
1176 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1177 # Triple-brace expansion
1178 $xpath = new DOMXPath( $contextNode->ownerDocument );
1179 $titles = $xpath->query( 'title', $contextNode );
1180 $title = $titles->item( 0 );
1181 $parts = $xpath->query( 'part', $contextNode );
1182 if ( $flags & PPFrame::NO_ARGS ) {
1183 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1184 } else {
1185 $params = array(
1186 'title' => new PPNode_DOM( $title ),
1187 'parts' => new PPNode_DOM( $parts ) );
1188 $ret = $this->parser->argSubstitution( $params, $this );
1189 if ( isset( $ret['object'] ) ) {
1190 $newIterator = $ret['object'];
1191 } else {
1192 $out .= $ret['text'];
1195 } elseif ( $contextNode->nodeName == 'comment' ) {
1196 # HTML-style comment
1197 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1198 if ( $this->parser->ot['html']
1199 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1200 || ( $flags & PPFrame::STRIP_COMMENTS )
1202 $out .= '';
1203 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1204 # Add a strip marker in PST mode so that pstPass2() can
1205 # run some old-fashioned regexes on the result.
1206 # Not in RECOVER_COMMENTS mode (extractSections) though.
1207 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1208 } else {
1209 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1210 $out .= $contextNode->textContent;
1212 } elseif ( $contextNode->nodeName == 'ignore' ) {
1213 # Output suppression used by <includeonly> etc.
1214 # OT_WIKI will only respect <ignore> in substed templates.
1215 # The other output types respect it unless NO_IGNORE is set.
1216 # extractSections() sets NO_IGNORE and so never respects it.
1217 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1218 || ( $flags & PPFrame::NO_IGNORE )
1220 $out .= $contextNode->textContent;
1221 } else {
1222 $out .= '';
1224 } elseif ( $contextNode->nodeName == 'ext' ) {
1225 # Extension tag
1226 $xpath = new DOMXPath( $contextNode->ownerDocument );
1227 $names = $xpath->query( 'name', $contextNode );
1228 $attrs = $xpath->query( 'attr', $contextNode );
1229 $inners = $xpath->query( 'inner', $contextNode );
1230 $closes = $xpath->query( 'close', $contextNode );
1231 if ( $flags & PPFrame::NO_TAGS ) {
1232 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1233 if ( $attrs->length > 0 ) {
1234 $s .= $this->expand( $attrs->item( 0 ), $flags );
1236 if ( $inners->length > 0 ) {
1237 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1238 if ( $closes->length > 0 ) {
1239 $s .= $this->expand( $closes->item( 0 ), $flags );
1241 } else {
1242 $s .= '/>';
1244 $out .= $s;
1245 } else {
1246 $params = array(
1247 'name' => new PPNode_DOM( $names->item( 0 ) ),
1248 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1249 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1250 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1252 $out .= $this->parser->extensionSubstitution( $params, $this );
1254 } elseif ( $contextNode->nodeName == 'h' ) {
1255 # Heading
1256 $s = $this->expand( $contextNode->childNodes, $flags );
1258 # Insert a heading marker only for <h> children of <root>
1259 # This is to stop extractSections from going over multiple tree levels
1260 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html'] ) {
1261 # Insert heading index marker
1262 $headingIndex = $contextNode->getAttribute( 'i' );
1263 $titleText = $this->title->getPrefixedDBkey();
1264 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1265 $serial = count( $this->parser->mHeadings ) - 1;
1266 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1267 $count = $contextNode->getAttribute( 'level' );
1268 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1269 $this->parser->mStripState->addGeneral( $marker, '' );
1271 $out .= $s;
1272 } else {
1273 # Generic recursive expansion
1274 $newIterator = $contextNode->childNodes;
1276 } else {
1277 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1280 if ( $newIterator !== false ) {
1281 if ( $newIterator instanceof PPNode_DOM ) {
1282 $newIterator = $newIterator->node;
1284 $outStack[] = '';
1285 $iteratorStack[] = $newIterator;
1286 $indexStack[] = 0;
1287 } elseif ( $iteratorStack[$level] === false ) {
1288 // Return accumulated value to parent
1289 // With tail recursion
1290 while ( $iteratorStack[$level] === false && $level > 0 ) {
1291 $outStack[$level - 1] .= $out;
1292 array_pop( $outStack );
1293 array_pop( $iteratorStack );
1294 array_pop( $indexStack );
1295 $level--;
1299 --$expansionDepth;
1300 return $outStack[0];
1304 * @param string $sep
1305 * @param int $flags
1306 * @param string|PPNode_DOM|DOMDocument $args,...
1307 * @return string
1309 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1310 $args = array_slice( func_get_args(), 2 );
1312 $first = true;
1313 $s = '';
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 ) {
1322 if ( $first ) {
1323 $first = false;
1324 } else {
1325 $s .= $sep;
1327 $s .= $this->expand( $node, $flags );
1330 return $s;
1334 * Implode with no flags specified
1335 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1337 * @param string $sep
1338 * @param string|PPNode_DOM|DOMDocument $args,...
1339 * @return string
1341 public function implode( $sep /*, ... */ ) {
1342 $args = array_slice( func_get_args(), 1 );
1344 $first = true;
1345 $s = '';
1346 foreach ( $args as $root ) {
1347 if ( $root instanceof PPNode_DOM ) {
1348 $root = $root->node;
1350 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1351 $root = array( $root );
1353 foreach ( $root as $node ) {
1354 if ( $first ) {
1355 $first = false;
1356 } else {
1357 $s .= $sep;
1359 $s .= $this->expand( $node );
1362 return $s;
1366 * Makes an object that, when expand()ed, will be the same as one obtained
1367 * with implode()
1369 * @param string $sep
1370 * @param string|PPNode_DOM|DOMDocument $args,...
1371 * @return array
1373 public function virtualImplode( $sep /*, ... */ ) {
1374 $args = array_slice( func_get_args(), 1 );
1375 $out = array();
1376 $first = true;
1378 foreach ( $args as $root ) {
1379 if ( $root instanceof PPNode_DOM ) {
1380 $root = $root->node;
1382 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1383 $root = array( $root );
1385 foreach ( $root as $node ) {
1386 if ( $first ) {
1387 $first = false;
1388 } else {
1389 $out[] = $sep;
1391 $out[] = $node;
1394 return $out;
1398 * Virtual implode with brackets
1399 * @param string $start
1400 * @param string $sep
1401 * @param string $end
1402 * @param string|PPNode_DOM|DOMDocument $args,...
1403 * @return array
1405 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1406 $args = array_slice( func_get_args(), 3 );
1407 $out = array( $start );
1408 $first = true;
1410 foreach ( $args as $root ) {
1411 if ( $root instanceof PPNode_DOM ) {
1412 $root = $root->node;
1414 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1415 $root = array( $root );
1417 foreach ( $root as $node ) {
1418 if ( $first ) {
1419 $first = false;
1420 } else {
1421 $out[] = $sep;
1423 $out[] = $node;
1426 $out[] = $end;
1427 return $out;
1430 public function __toString() {
1431 return 'frame{}';
1434 public function getPDBK( $level = false ) {
1435 if ( $level === false ) {
1436 return $this->title->getPrefixedDBkey();
1437 } else {
1438 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1443 * @return array
1445 public function getArguments() {
1446 return array();
1450 * @return array
1452 public function getNumberedArguments() {
1453 return array();
1457 * @return array
1459 public function getNamedArguments() {
1460 return array();
1464 * Returns true if there are no arguments in this frame
1466 * @return bool
1468 public function isEmpty() {
1469 return true;
1472 public function getArgument( $name ) {
1473 return false;
1477 * Returns true if the infinite loop check is OK, false if a loop is detected
1479 * @param Title $title
1480 * @return bool
1482 public function loopCheck( $title ) {
1483 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1487 * Return true if the frame is a template frame
1489 * @return bool
1491 public function isTemplate() {
1492 return false;
1496 * Get a title of frame
1498 * @return Title
1500 public function getTitle() {
1501 return $this->title;
1505 * Set the volatile flag
1507 * @param bool $flag
1509 public function setVolatile( $flag = true ) {
1510 $this->volatile = $flag;
1514 * Get the volatile flag
1516 * @return bool
1518 public function isVolatile() {
1519 return $this->volatile;
1523 * Set the TTL
1525 * @param int $ttl
1527 public function setTTL( $ttl ) {
1528 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1529 $this->ttl = $ttl;
1534 * Get the TTL
1536 * @return int|null
1538 public function getTTL() {
1539 return $this->ttl;
1544 * Expansion frame with template arguments
1545 * @ingroup Parser
1546 * @codingStandardsIgnoreStart
1548 class PPTemplateFrame_DOM extends PPFrame_DOM {
1549 // @codingStandardsIgnoreEnd
1551 public $numberedArgs, $namedArgs;
1554 * @var PPFrame_DOM
1556 public $parent;
1557 public $numberedExpansionCache, $namedExpansionCache;
1560 * @param Preprocessor $preprocessor
1561 * @param bool|PPFrame_DOM $parent
1562 * @param array $numberedArgs
1563 * @param array $namedArgs
1564 * @param bool|Title $title
1566 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1567 $namedArgs = array(), $title = false
1569 parent::__construct( $preprocessor );
1571 $this->parent = $parent;
1572 $this->numberedArgs = $numberedArgs;
1573 $this->namedArgs = $namedArgs;
1574 $this->title = $title;
1575 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1576 $this->titleCache = $parent->titleCache;
1577 $this->titleCache[] = $pdbk;
1578 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1579 if ( $pdbk !== false ) {
1580 $this->loopCheckHash[$pdbk] = true;
1582 $this->depth = $parent->depth + 1;
1583 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1586 public function __toString() {
1587 $s = 'tplframe{';
1588 $first = true;
1589 $args = $this->numberedArgs + $this->namedArgs;
1590 foreach ( $args as $name => $value ) {
1591 if ( $first ) {
1592 $first = false;
1593 } else {
1594 $s .= ', ';
1596 $s .= "\"$name\":\"" .
1597 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1599 $s .= '}';
1600 return $s;
1604 * @throws MWException
1605 * @param string|int $key
1606 * @param string|PPNode_DOM|DOMDocument $root
1607 * @param int $flags
1608 * @return string
1610 public function cachedExpand( $key, $root, $flags = 0 ) {
1611 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1612 return $this->parent->childExpansionCache[$key];
1614 $retval = $this->expand( $root, $flags );
1615 if ( !$this->isVolatile() ) {
1616 $this->parent->childExpansionCache[$key] = $retval;
1618 return $retval;
1622 * Returns true if there are no arguments in this frame
1624 * @return bool
1626 public function isEmpty() {
1627 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1630 public function getArguments() {
1631 $arguments = array();
1632 foreach ( array_merge(
1633 array_keys( $this->numberedArgs ),
1634 array_keys( $this->namedArgs ) ) as $key ) {
1635 $arguments[$key] = $this->getArgument( $key );
1637 return $arguments;
1640 public function getNumberedArguments() {
1641 $arguments = array();
1642 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1643 $arguments[$key] = $this->getArgument( $key );
1645 return $arguments;
1648 public function getNamedArguments() {
1649 $arguments = array();
1650 foreach ( array_keys( $this->namedArgs ) as $key ) {
1651 $arguments[$key] = $this->getArgument( $key );
1653 return $arguments;
1656 public function getNumberedArgument( $index ) {
1657 if ( !isset( $this->numberedArgs[$index] ) ) {
1658 return false;
1660 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1661 # No trimming for unnamed arguments
1662 $this->numberedExpansionCache[$index] = $this->parent->expand(
1663 $this->numberedArgs[$index],
1664 PPFrame::STRIP_COMMENTS
1667 return $this->numberedExpansionCache[$index];
1670 public function getNamedArgument( $name ) {
1671 if ( !isset( $this->namedArgs[$name] ) ) {
1672 return false;
1674 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1675 # Trim named arguments post-expand, for backwards compatibility
1676 $this->namedExpansionCache[$name] = trim(
1677 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1679 return $this->namedExpansionCache[$name];
1682 public function getArgument( $name ) {
1683 $text = $this->getNumberedArgument( $name );
1684 if ( $text === false ) {
1685 $text = $this->getNamedArgument( $name );
1687 return $text;
1691 * Return true if the frame is a template frame
1693 * @return bool
1695 public function isTemplate() {
1696 return true;
1699 public function setVolatile( $flag = true ) {
1700 parent::setVolatile( $flag );
1701 $this->parent->setVolatile( $flag );
1704 public function setTTL( $ttl ) {
1705 parent::setTTL( $ttl );
1706 $this->parent->setTTL( $ttl );
1711 * Expansion frame with custom arguments
1712 * @ingroup Parser
1713 * @codingStandardsIgnoreStart
1715 class PPCustomFrame_DOM extends PPFrame_DOM {
1716 // @codingStandardsIgnoreEnd
1718 public $args;
1720 public function __construct( $preprocessor, $args ) {
1721 parent::__construct( $preprocessor );
1722 $this->args = $args;
1725 public function __toString() {
1726 $s = 'cstmframe{';
1727 $first = true;
1728 foreach ( $this->args as $name => $value ) {
1729 if ( $first ) {
1730 $first = false;
1731 } else {
1732 $s .= ', ';
1734 $s .= "\"$name\":\"" .
1735 str_replace( '"', '\\"', $value->__toString() ) . '"';
1737 $s .= '}';
1738 return $s;
1742 * @return bool
1744 public function isEmpty() {
1745 return !count( $this->args );
1748 public function getArgument( $index ) {
1749 if ( !isset( $this->args[$index] ) ) {
1750 return false;
1752 return $this->args[$index];
1755 public function getArguments() {
1756 return $this->args;
1761 * @ingroup Parser
1762 * @codingStandardsIgnoreStart
1764 class PPNode_DOM implements PPNode {
1765 // @codingStandardsIgnoreEnd
1768 * @var DOMElement
1770 public $node;
1771 public $xpath;
1773 public function __construct( $node, $xpath = false ) {
1774 $this->node = $node;
1778 * @return DOMXPath
1780 public function getXPath() {
1781 if ( $this->xpath === null ) {
1782 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1784 return $this->xpath;
1787 public function __toString() {
1788 if ( $this->node instanceof DOMNodeList ) {
1789 $s = '';
1790 foreach ( $this->node as $node ) {
1791 $s .= $node->ownerDocument->saveXML( $node );
1793 } else {
1794 $s = $this->node->ownerDocument->saveXML( $this->node );
1796 return $s;
1800 * @return bool|PPNode_DOM
1802 public function getChildren() {
1803 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1807 * @return bool|PPNode_DOM
1809 public function getFirstChild() {
1810 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1814 * @return bool|PPNode_DOM
1816 public function getNextSibling() {
1817 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1821 * @param string $type
1823 * @return bool|PPNode_DOM
1825 public function getChildrenOfType( $type ) {
1826 return new self( $this->getXPath()->query( $type, $this->node ) );
1830 * @return int
1832 public function getLength() {
1833 if ( $this->node instanceof DOMNodeList ) {
1834 return $this->node->length;
1835 } else {
1836 return false;
1841 * @param int $i
1842 * @return bool|PPNode_DOM
1844 public function item( $i ) {
1845 $item = $this->node->item( $i );
1846 return $item ? new self( $item ) : false;
1850 * @return string
1852 public function getName() {
1853 if ( $this->node instanceof DOMNodeList ) {
1854 return '#nodelist';
1855 } else {
1856 return $this->node->nodeName;
1861 * Split a "<part>" node into an associative array containing:
1862 * - name PPNode name
1863 * - index String index
1864 * - value PPNode value
1866 * @throws MWException
1867 * @return array
1869 public function splitArg() {
1870 $xpath = $this->getXPath();
1871 $names = $xpath->query( 'name', $this->node );
1872 $values = $xpath->query( 'value', $this->node );
1873 if ( !$names->length || !$values->length ) {
1874 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1876 $name = $names->item( 0 );
1877 $index = $name->getAttribute( 'index' );
1878 return array(
1879 'name' => new self( $name ),
1880 'index' => $index,
1881 'value' => new self( $values->item( 0 ) ) );
1885 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1886 * All values in the resulting array are PPNodes. Inner and close are optional.
1888 * @throws MWException
1889 * @return array
1891 public function splitExt() {
1892 $xpath = $this->getXPath();
1893 $names = $xpath->query( 'name', $this->node );
1894 $attrs = $xpath->query( 'attr', $this->node );
1895 $inners = $xpath->query( 'inner', $this->node );
1896 $closes = $xpath->query( 'close', $this->node );
1897 if ( !$names->length || !$attrs->length ) {
1898 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1900 $parts = array(
1901 'name' => new self( $names->item( 0 ) ),
1902 'attr' => new self( $attrs->item( 0 ) ) );
1903 if ( $inners->length ) {
1904 $parts['inner'] = new self( $inners->item( 0 ) );
1906 if ( $closes->length ) {
1907 $parts['close'] = new self( $closes->item( 0 ) );
1909 return $parts;
1913 * Split a "<h>" node
1914 * @throws MWException
1915 * @return array
1917 public function splitHeading() {
1918 if ( $this->getName() !== 'h' ) {
1919 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1921 return array(
1922 'i' => $this->node->getAttribute( 'i' ),
1923 'level' => $this->node->getAttribute( 'level' ),
1924 'contents' => $this->getChildren()