SessionManager: Change behavior of getSessionById()
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob4ca3a878bd8775896b4d8e14e47143f95f128d2b
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
27 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
28 class Preprocessor_DOM extends Preprocessor {
29 // @codingStandardsIgnoreEnd
31 /**
32 * @var Parser
34 public $parser;
36 public $memoryLimit;
38 const CACHE_PREFIX = 'preprocess-xml';
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 MediaWiki\suppressWarnings();
91 $result = $dom->loadXML( $xml );
92 MediaWiki\restoreWarnings();
93 if ( !$result ) {
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal\Validator::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 ) {
152 $xml = $this->cacheGetTree( $text, $flags );
153 if ( $xml === false ) {
154 $xml = $this->preprocessToXml( $text, $flags );
155 $this->cacheSetTree( $text, $flags, $xml );
158 // Fail if the number of elements exceeds acceptable limits
159 // Do not attempt to generate the DOM
160 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
161 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
162 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
163 // if ( $cacheable ) { ... }
164 throw new MWException( __METHOD__ . ': generated node count limit exceeded' );
167 $dom = new DOMDocument;
168 MediaWiki\suppressWarnings();
169 $result = $dom->loadXML( $xml );
170 MediaWiki\restoreWarnings();
171 if ( !$result ) {
172 // Try running the XML through UtfNormal to get rid of invalid characters
173 $xml = UtfNormal\Validator::cleanUp( $xml );
174 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
175 // don't barf when the XML is >256 levels deep.
176 $result = $dom->loadXML( $xml, 1 << 19 );
178 if ( $result ) {
179 $obj = new PPNode_DOM( $dom->documentElement );
182 // if ( $cacheable ) { ... }
184 if ( !$result ) {
185 throw new MWException( __METHOD__ . ' generated invalid XML' );
187 return $obj;
191 * @param string $text
192 * @param int $flags
193 * @return string
195 public function preprocessToXml( $text, $flags = 0 ) {
196 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
198 $xmlishElements = $this->parser->getStripList();
199 $enableOnlyinclude = false;
200 if ( $forInclusion ) {
201 $ignoredTags = array( 'includeonly', '/includeonly' );
202 $ignoredElements = array( 'noinclude' );
203 $xmlishElements[] = 'noinclude';
204 if ( strpos( $text, '<onlyinclude>' ) !== false
205 && strpos( $text, '</onlyinclude>' ) !== false
207 $enableOnlyinclude = true;
209 } else {
210 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
211 $ignoredElements = array( 'includeonly' );
212 $xmlishElements[] = 'includeonly';
214 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
216 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
217 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
219 $stack = new PPDStack;
221 $searchBase = "[{<\n"; # }
222 // For fast reverse searches
223 $revText = strrev( $text );
224 $lengthText = strlen( $text );
226 // Input pointer, starts out pointing to a pseudo-newline before the start
227 $i = 0;
228 // Current accumulator
229 $accum =& $stack->getAccum();
230 $accum = '<root>';
231 // True to find equals signs in arguments
232 $findEquals = false;
233 // True to take notice of pipe characters
234 $findPipe = false;
235 $headingIndex = 1;
236 // True if $i is inside a possible heading
237 $inHeading = false;
238 // True if there are no more greater-than (>) signs right of $i
239 $noMoreGT = false;
240 // True to ignore all input up to the next <onlyinclude>
241 $findOnlyinclude = $enableOnlyinclude;
242 // Do a line-start run without outputting an LF character
243 $fakeLineStart = true;
245 while ( true ) {
246 // $this->memCheck();
248 if ( $findOnlyinclude ) {
249 // Ignore all input up to the next <onlyinclude>
250 $startPos = strpos( $text, '<onlyinclude>', $i );
251 if ( $startPos === false ) {
252 // Ignored section runs to the end
253 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
254 break;
256 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
257 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
258 $i = $tagEndPos;
259 $findOnlyinclude = false;
262 if ( $fakeLineStart ) {
263 $found = 'line-start';
264 $curChar = '';
265 } else {
266 # Find next opening brace, closing brace or pipe
267 $search = $searchBase;
268 if ( $stack->top === false ) {
269 $currentClosing = '';
270 } else {
271 $currentClosing = $stack->top->close;
272 $search .= $currentClosing;
274 if ( $findPipe ) {
275 $search .= '|';
277 if ( $findEquals ) {
278 // First equals will be for the template
279 $search .= '=';
281 $rule = null;
282 # Output literal section, advance input counter
283 $literalLength = strcspn( $text, $search, $i );
284 if ( $literalLength > 0 ) {
285 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
286 $i += $literalLength;
288 if ( $i >= $lengthText ) {
289 if ( $currentClosing == "\n" ) {
290 // Do a past-the-end run to finish off the heading
291 $curChar = '';
292 $found = 'line-end';
293 } else {
294 # All done
295 break;
297 } else {
298 $curChar = $text[$i];
299 if ( $curChar == '|' ) {
300 $found = 'pipe';
301 } elseif ( $curChar == '=' ) {
302 $found = 'equals';
303 } elseif ( $curChar == '<' ) {
304 $found = 'angle';
305 } elseif ( $curChar == "\n" ) {
306 if ( $inHeading ) {
307 $found = 'line-end';
308 } else {
309 $found = 'line-start';
311 } elseif ( $curChar == $currentClosing ) {
312 $found = 'close';
313 } elseif ( isset( $this->rules[$curChar] ) ) {
314 $found = 'open';
315 $rule = $this->rules[$curChar];
316 } else {
317 # Some versions of PHP have a strcspn which stops on null characters
318 # Ignore and continue
319 ++$i;
320 continue;
325 if ( $found == 'angle' ) {
326 $matches = false;
327 // Handle </onlyinclude>
328 if ( $enableOnlyinclude
329 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
331 $findOnlyinclude = true;
332 continue;
335 // Determine element name
336 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
337 // Element name missing or not listed
338 $accum .= '&lt;';
339 ++$i;
340 continue;
342 // Handle comments
343 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
345 // To avoid leaving blank lines, when a sequence of
346 // space-separated comments is both preceded and followed by
347 // a newline (ignoring spaces), then
348 // trim leading and trailing spaces and the trailing newline.
350 // Find the end
351 $endPos = strpos( $text, '-->', $i + 4 );
352 if ( $endPos === false ) {
353 // Unclosed comment in input, runs to end
354 $inner = substr( $text, $i );
355 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
356 $i = $lengthText;
357 } else {
358 // Search backwards for leading whitespace
359 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
361 // Search forwards for trailing whitespace
362 // $wsEnd will be the position of the last space (or the '>' if there's none)
363 $wsEnd = $endPos + 2 + strspn( $text, " \t", $endPos + 3 );
365 // Keep looking forward as long as we're finding more
366 // comments.
367 $comments = array( array( $wsStart, $wsEnd ) );
368 while ( substr( $text, $wsEnd + 1, 4 ) == '<!--' ) {
369 $c = strpos( $text, '-->', $wsEnd + 4 );
370 if ( $c === false ) {
371 break;
373 $c = $c + 2 + strspn( $text, " \t", $c + 3 );
374 $comments[] = array( $wsEnd + 1, $c );
375 $wsEnd = $c;
378 // Eat the line if possible
379 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
380 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
381 // it's a possible beneficial b/c break.
382 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
383 && substr( $text, $wsEnd + 1, 1 ) == "\n"
385 // Remove leading whitespace from the end of the accumulator
386 // Sanity check first though
387 $wsLength = $i - $wsStart;
388 if ( $wsLength > 0
389 && strspn( $accum, " \t", -$wsLength ) === $wsLength
391 $accum = substr( $accum, 0, -$wsLength );
394 // Dump all but the last comment to the accumulator
395 foreach ( $comments as $j => $com ) {
396 $startPos = $com[0];
397 $endPos = $com[1] + 1;
398 if ( $j == ( count( $comments ) - 1 ) ) {
399 break;
401 $inner = substr( $text, $startPos, $endPos - $startPos );
402 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
405 // Do a line-start run next time to look for headings after the comment
406 $fakeLineStart = true;
407 } else {
408 // No line to eat, just take the comment itself
409 $startPos = $i;
410 $endPos += 2;
413 if ( $stack->top ) {
414 $part = $stack->top->getCurrentPart();
415 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
416 $part->visualEnd = $wsStart;
418 // Else comments abutting, no change in visual end
419 $part->commentEnd = $endPos;
421 $i = $endPos + 1;
422 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
423 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
425 continue;
427 $name = $matches[1];
428 $lowerName = strtolower( $name );
429 $attrStart = $i + strlen( $name ) + 1;
431 // Find end of tag
432 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
433 if ( $tagEndPos === false ) {
434 // Infinite backtrack
435 // Disable tag search to prevent worst-case O(N^2) performance
436 $noMoreGT = true;
437 $accum .= '&lt;';
438 ++$i;
439 continue;
442 // Handle ignored tags
443 if ( in_array( $lowerName, $ignoredTags ) ) {
444 $accum .= '<ignore>'
445 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) )
446 . '</ignore>';
447 $i = $tagEndPos + 1;
448 continue;
451 $tagStartPos = $i;
452 if ( $text[$tagEndPos - 1] == '/' ) {
453 $attrEnd = $tagEndPos - 1;
454 $inner = null;
455 $i = $tagEndPos + 1;
456 $close = '';
457 } else {
458 $attrEnd = $tagEndPos;
459 // Find closing tag
460 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
461 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
463 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
464 $i = $matches[0][1] + strlen( $matches[0][0] );
465 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
466 } else {
467 // No end tag -- let it run out to the end of the text.
468 $inner = substr( $text, $tagEndPos + 1 );
469 $i = $lengthText;
470 $close = '';
473 // <includeonly> and <noinclude> just become <ignore> tags
474 if ( in_array( $lowerName, $ignoredElements ) ) {
475 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
476 . '</ignore>';
477 continue;
480 $accum .= '<ext>';
481 if ( $attrEnd <= $attrStart ) {
482 $attr = '';
483 } else {
484 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
486 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
487 // Note that the attr element contains the whitespace between name and attribute,
488 // this is necessary for precise reconstruction during pre-save transform.
489 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
490 if ( $inner !== null ) {
491 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
493 $accum .= $close . '</ext>';
494 } elseif ( $found == 'line-start' ) {
495 // Is this the start of a heading?
496 // Line break belongs before the heading element in any case
497 if ( $fakeLineStart ) {
498 $fakeLineStart = false;
499 } else {
500 $accum .= $curChar;
501 $i++;
504 $count = strspn( $text, '=', $i, 6 );
505 if ( $count == 1 && $findEquals ) {
506 // DWIM: This looks kind of like a name/value separator.
507 // Let's let the equals handler have it and break the
508 // potential heading. This is heuristic, but AFAICT the
509 // methods for completely correct disambiguation are very
510 // complex.
511 } elseif ( $count > 0 ) {
512 $piece = array(
513 'open' => "\n",
514 'close' => "\n",
515 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
516 'startPos' => $i,
517 'count' => $count );
518 $stack->push( $piece );
519 $accum =& $stack->getAccum();
520 $flags = $stack->getFlags();
521 extract( $flags );
522 $i += $count;
524 } elseif ( $found == 'line-end' ) {
525 $piece = $stack->top;
526 // A heading must be open, otherwise \n wouldn't have been in the search list
527 assert( '$piece->open == "\n"' );
528 $part = $piece->getCurrentPart();
529 // Search back through the input to see if it has a proper close.
530 // Do this using the reversed string since the other solutions
531 // (end anchor, etc.) are inefficient.
532 $wsLength = strspn( $revText, " \t", $lengthText - $i );
533 $searchStart = $i - $wsLength;
534 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
535 // Comment found at line end
536 // Search for equals signs before the comment
537 $searchStart = $part->visualEnd;
538 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
540 $count = $piece->count;
541 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
542 if ( $equalsLength > 0 ) {
543 if ( $searchStart - $equalsLength == $piece->startPos ) {
544 // This is just a single string of equals signs on its own line
545 // Replicate the doHeadings behavior /={count}(.+)={count}/
546 // First find out how many equals signs there really are (don't stop at 6)
547 $count = $equalsLength;
548 if ( $count < 3 ) {
549 $count = 0;
550 } else {
551 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
553 } else {
554 $count = min( $equalsLength, $count );
556 if ( $count > 0 ) {
557 // Normal match, output <h>
558 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
559 $headingIndex++;
560 } else {
561 // Single equals sign on its own line, count=0
562 $element = $accum;
564 } else {
565 // No match, no <h>, just pass down the inner text
566 $element = $accum;
568 // Unwind the stack
569 $stack->pop();
570 $accum =& $stack->getAccum();
571 $flags = $stack->getFlags();
572 extract( $flags );
574 // Append the result to the enclosing accumulator
575 $accum .= $element;
576 // Note that we do NOT increment the input pointer.
577 // This is because the closing linebreak could be the opening linebreak of
578 // another heading. Infinite loops are avoided because the next iteration MUST
579 // hit the heading open case above, which unconditionally increments the
580 // input pointer.
581 } elseif ( $found == 'open' ) {
582 # count opening brace characters
583 $count = strspn( $text, $curChar, $i );
585 # we need to add to stack only if opening brace count is enough for one of the rules
586 if ( $count >= $rule['min'] ) {
587 # Add it to the stack
588 $piece = array(
589 'open' => $curChar,
590 'close' => $rule['end'],
591 'count' => $count,
592 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
595 $stack->push( $piece );
596 $accum =& $stack->getAccum();
597 $flags = $stack->getFlags();
598 extract( $flags );
599 } else {
600 # Add literal brace(s)
601 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
603 $i += $count;
604 } elseif ( $found == 'close' ) {
605 $piece = $stack->top;
606 # lets check if there are enough characters for closing brace
607 $maxCount = $piece->count;
608 $count = strspn( $text, $curChar, $i, $maxCount );
610 # check for maximum matching characters (if there are 5 closing
611 # characters, we will probably need only 3 - depending on the rules)
612 $rule = $this->rules[$piece->open];
613 if ( $count > $rule['max'] ) {
614 # The specified maximum exists in the callback array, unless the caller
615 # has made an error
616 $matchingCount = $rule['max'];
617 } else {
618 # Count is less than the maximum
619 # Skip any gaps in the callback array to find the true largest match
620 # Need to use array_key_exists not isset because the callback can be null
621 $matchingCount = $count;
622 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
623 --$matchingCount;
627 if ( $matchingCount <= 0 ) {
628 # No matching element found in callback array
629 # Output a literal closing brace and continue
630 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
631 $i += $count;
632 continue;
634 $name = $rule['names'][$matchingCount];
635 if ( $name === null ) {
636 // No element, just literal text
637 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
638 } else {
639 # Create XML element
640 # Note: $parts is already XML, does not need to be encoded further
641 $parts = $piece->parts;
642 $title = $parts[0]->out;
643 unset( $parts[0] );
645 # The invocation is at the start of the line if lineStart is set in
646 # the stack, and all opening brackets are used up.
647 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
648 $attr = ' lineStart="1"';
649 } else {
650 $attr = '';
653 $element = "<$name$attr>";
654 $element .= "<title>$title</title>";
655 $argIndex = 1;
656 foreach ( $parts as $part ) {
657 if ( isset( $part->eqpos ) ) {
658 $argName = substr( $part->out, 0, $part->eqpos );
659 $argValue = substr( $part->out, $part->eqpos + 1 );
660 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
661 } else {
662 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
663 $argIndex++;
666 $element .= "</$name>";
669 # Advance input pointer
670 $i += $matchingCount;
672 # Unwind the stack
673 $stack->pop();
674 $accum =& $stack->getAccum();
676 # Re-add the old stack element if it still has unmatched opening characters remaining
677 if ( $matchingCount < $piece->count ) {
678 $piece->parts = array( new PPDPart );
679 $piece->count -= $matchingCount;
680 # do we still qualify for any callback with remaining count?
681 $min = $this->rules[$piece->open]['min'];
682 if ( $piece->count >= $min ) {
683 $stack->push( $piece );
684 $accum =& $stack->getAccum();
685 } else {
686 $accum .= str_repeat( $piece->open, $piece->count );
689 $flags = $stack->getFlags();
690 extract( $flags );
692 # Add XML element to the enclosing accumulator
693 $accum .= $element;
694 } elseif ( $found == 'pipe' ) {
695 $findEquals = true; // shortcut for getFlags()
696 $stack->addPart();
697 $accum =& $stack->getAccum();
698 ++$i;
699 } elseif ( $found == 'equals' ) {
700 $findEquals = false; // shortcut for getFlags()
701 $stack->getCurrentPart()->eqpos = strlen( $accum );
702 $accum .= '=';
703 ++$i;
707 # Output any remaining unclosed brackets
708 foreach ( $stack->stack as $piece ) {
709 $stack->rootAccum .= $piece->breakSyntax();
711 $stack->rootAccum .= '</root>';
712 $xml = $stack->rootAccum;
714 return $xml;
719 * Stack class to help Preprocessor::preprocessToObj()
720 * @ingroup Parser
722 class PPDStack {
723 public $stack, $rootAccum;
726 * @var PPDStack
728 public $top;
729 public $out;
730 public $elementClass = 'PPDStackElement';
732 public static $false = false;
734 public function __construct() {
735 $this->stack = array();
736 $this->top = false;
737 $this->rootAccum = '';
738 $this->accum =& $this->rootAccum;
742 * @return int
744 public function count() {
745 return count( $this->stack );
748 public function &getAccum() {
749 return $this->accum;
752 public function getCurrentPart() {
753 if ( $this->top === false ) {
754 return false;
755 } else {
756 return $this->top->getCurrentPart();
760 public function push( $data ) {
761 if ( $data instanceof $this->elementClass ) {
762 $this->stack[] = $data;
763 } else {
764 $class = $this->elementClass;
765 $this->stack[] = new $class( $data );
767 $this->top = $this->stack[count( $this->stack ) - 1];
768 $this->accum =& $this->top->getAccum();
771 public function pop() {
772 if ( !count( $this->stack ) ) {
773 throw new MWException( __METHOD__ . ': no elements remaining' );
775 $temp = array_pop( $this->stack );
777 if ( count( $this->stack ) ) {
778 $this->top = $this->stack[count( $this->stack ) - 1];
779 $this->accum =& $this->top->getAccum();
780 } else {
781 $this->top = self::$false;
782 $this->accum =& $this->rootAccum;
784 return $temp;
787 public function addPart( $s = '' ) {
788 $this->top->addPart( $s );
789 $this->accum =& $this->top->getAccum();
793 * @return array
795 public function getFlags() {
796 if ( !count( $this->stack ) ) {
797 return array(
798 'findEquals' => false,
799 'findPipe' => false,
800 'inHeading' => false,
802 } else {
803 return $this->top->getFlags();
809 * @ingroup Parser
811 class PPDStackElement {
813 * @var string Opening character (\n for heading)
815 public $open;
818 * @var string Matching closing character
820 public $close;
823 * @var int Number of opening characters found (number of "=" for heading)
825 public $count;
828 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
830 public $parts;
833 * @var bool True if the open char appeared at the start of the input line.
834 * Not set for headings.
836 public $lineStart;
838 public $partClass = 'PPDPart';
840 public function __construct( $data = array() ) {
841 $class = $this->partClass;
842 $this->parts = array( new $class );
844 foreach ( $data as $name => $value ) {
845 $this->$name = $value;
849 public function &getAccum() {
850 return $this->parts[count( $this->parts ) - 1]->out;
853 public function addPart( $s = '' ) {
854 $class = $this->partClass;
855 $this->parts[] = new $class( $s );
858 public function getCurrentPart() {
859 return $this->parts[count( $this->parts ) - 1];
863 * @return array
865 public function getFlags() {
866 $partCount = count( $this->parts );
867 $findPipe = $this->open != "\n" && $this->open != '[';
868 return array(
869 'findPipe' => $findPipe,
870 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
871 'inHeading' => $this->open == "\n",
876 * Get the output string that would result if the close is not found.
878 * @param bool|int $openingCount
879 * @return string
881 public function breakSyntax( $openingCount = false ) {
882 if ( $this->open == "\n" ) {
883 $s = $this->parts[0]->out;
884 } else {
885 if ( $openingCount === false ) {
886 $openingCount = $this->count;
888 $s = str_repeat( $this->open, $openingCount );
889 $first = true;
890 foreach ( $this->parts as $part ) {
891 if ( $first ) {
892 $first = false;
893 } else {
894 $s .= '|';
896 $s .= $part->out;
899 return $s;
904 * @ingroup Parser
906 class PPDPart {
908 * @var string Output accumulator string
910 public $out;
912 // Optional member variables:
913 // eqpos Position of equals sign in output accumulator
914 // commentEnd Past-the-end input pointer for the last comment encountered
915 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
917 public function __construct( $out = '' ) {
918 $this->out = $out;
923 * An expansion frame, used as a context to expand the result of preprocessToObj()
924 * @ingroup Parser
926 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
927 class PPFrame_DOM implements PPFrame {
928 // @codingStandardsIgnoreEnd
931 * @var Preprocessor
933 public $preprocessor;
936 * @var Parser
938 public $parser;
941 * @var Title
943 public $title;
944 public $titleCache;
947 * Hashtable listing templates which are disallowed for expansion in this frame,
948 * having been encountered previously in parent frames.
950 public $loopCheckHash;
953 * Recursion depth of this frame, top = 0
954 * Note that this is NOT the same as expansion depth in expand()
956 public $depth;
958 private $volatile = false;
959 private $ttl = null;
962 * @var array
964 protected $childExpansionCache;
967 * Construct a new preprocessor frame.
968 * @param Preprocessor $preprocessor The parent preprocessor
970 public function __construct( $preprocessor ) {
971 $this->preprocessor = $preprocessor;
972 $this->parser = $preprocessor->parser;
973 $this->title = $this->parser->mTitle;
974 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
975 $this->loopCheckHash = array();
976 $this->depth = 0;
977 $this->childExpansionCache = array();
981 * Create a new child frame
982 * $args is optionally a multi-root PPNode or array containing the template arguments
984 * @param bool|array $args
985 * @param Title|bool $title
986 * @param int $indexOffset
987 * @return PPTemplateFrame_DOM
989 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
990 $namedArgs = array();
991 $numberedArgs = array();
992 if ( $title === false ) {
993 $title = $this->title;
995 if ( $args !== false ) {
996 $xpath = false;
997 if ( $args instanceof PPNode ) {
998 $args = $args->node;
1000 foreach ( $args as $arg ) {
1001 if ( $arg instanceof PPNode ) {
1002 $arg = $arg->node;
1004 if ( !$xpath || $xpath->document !== $arg->ownerDocument ) {
1005 $xpath = new DOMXPath( $arg->ownerDocument );
1008 $nameNodes = $xpath->query( 'name', $arg );
1009 $value = $xpath->query( 'value', $arg );
1010 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1011 // Numbered parameter
1012 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
1013 $index = $index - $indexOffset;
1014 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
1015 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1016 wfEscapeWikiText( $this->title ),
1017 wfEscapeWikiText( $title ),
1018 wfEscapeWikiText( $index ) )->text() );
1019 $this->parser->addTrackingCategory( 'duplicate-args-category' );
1021 $numberedArgs[$index] = $value->item( 0 );
1022 unset( $namedArgs[$index] );
1023 } else {
1024 // Named parameter
1025 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
1026 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
1027 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1028 wfEscapeWikiText( $this->title ),
1029 wfEscapeWikiText( $title ),
1030 wfEscapeWikiText( $name ) )->text() );
1031 $this->parser->addTrackingCategory( 'duplicate-args-category' );
1033 $namedArgs[$name] = $value->item( 0 );
1034 unset( $numberedArgs[$name] );
1038 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1042 * @throws MWException
1043 * @param string|int $key
1044 * @param string|PPNode_DOM|DOMDocument $root
1045 * @param int $flags
1046 * @return string
1048 public function cachedExpand( $key, $root, $flags = 0 ) {
1049 // we don't have a parent, so we don't have a cache
1050 return $this->expand( $root, $flags );
1054 * @throws MWException
1055 * @param string|PPNode_DOM|DOMDocument $root
1056 * @param int $flags
1057 * @return string
1059 public function expand( $root, $flags = 0 ) {
1060 static $expansionDepth = 0;
1061 if ( is_string( $root ) ) {
1062 return $root;
1065 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1066 $this->parser->limitationWarn( 'node-count-exceeded',
1067 $this->parser->mPPNodeCount,
1068 $this->parser->mOptions->getMaxPPNodeCount()
1070 return '<span class="error">Node-count limit exceeded</span>';
1073 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1074 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1075 $expansionDepth,
1076 $this->parser->mOptions->getMaxPPExpandDepth()
1078 return '<span class="error">Expansion depth limit exceeded</span>';
1080 ++$expansionDepth;
1081 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1082 $this->parser->mHighestExpansionDepth = $expansionDepth;
1085 if ( $root instanceof PPNode_DOM ) {
1086 $root = $root->node;
1088 if ( $root instanceof DOMDocument ) {
1089 $root = $root->documentElement;
1092 $outStack = array( '', '' );
1093 $iteratorStack = array( false, $root );
1094 $indexStack = array( 0, 0 );
1096 while ( count( $iteratorStack ) > 1 ) {
1097 $level = count( $outStack ) - 1;
1098 $iteratorNode =& $iteratorStack[$level];
1099 $out =& $outStack[$level];
1100 $index =& $indexStack[$level];
1102 if ( $iteratorNode instanceof PPNode_DOM ) {
1103 $iteratorNode = $iteratorNode->node;
1106 if ( is_array( $iteratorNode ) ) {
1107 if ( $index >= count( $iteratorNode ) ) {
1108 // All done with this iterator
1109 $iteratorStack[$level] = false;
1110 $contextNode = false;
1111 } else {
1112 $contextNode = $iteratorNode[$index];
1113 $index++;
1115 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1116 if ( $index >= $iteratorNode->length ) {
1117 // All done with this iterator
1118 $iteratorStack[$level] = false;
1119 $contextNode = false;
1120 } else {
1121 $contextNode = $iteratorNode->item( $index );
1122 $index++;
1124 } else {
1125 // Copy to $contextNode and then delete from iterator stack,
1126 // because this is not an iterator but we do have to execute it once
1127 $contextNode = $iteratorStack[$level];
1128 $iteratorStack[$level] = false;
1131 if ( $contextNode instanceof PPNode_DOM ) {
1132 $contextNode = $contextNode->node;
1135 $newIterator = false;
1137 if ( $contextNode === false ) {
1138 // nothing to do
1139 } elseif ( is_string( $contextNode ) ) {
1140 $out .= $contextNode;
1141 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1142 $newIterator = $contextNode;
1143 } elseif ( $contextNode instanceof DOMNode ) {
1144 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1145 $out .= $contextNode->nodeValue;
1146 } elseif ( $contextNode->nodeName == 'template' ) {
1147 # Double-brace expansion
1148 $xpath = new DOMXPath( $contextNode->ownerDocument );
1149 $titles = $xpath->query( 'title', $contextNode );
1150 $title = $titles->item( 0 );
1151 $parts = $xpath->query( 'part', $contextNode );
1152 if ( $flags & PPFrame::NO_TEMPLATES ) {
1153 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1154 } else {
1155 $lineStart = $contextNode->getAttribute( 'lineStart' );
1156 $params = array(
1157 'title' => new PPNode_DOM( $title ),
1158 'parts' => new PPNode_DOM( $parts ),
1159 'lineStart' => $lineStart );
1160 $ret = $this->parser->braceSubstitution( $params, $this );
1161 if ( isset( $ret['object'] ) ) {
1162 $newIterator = $ret['object'];
1163 } else {
1164 $out .= $ret['text'];
1167 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1168 # Triple-brace expansion
1169 $xpath = new DOMXPath( $contextNode->ownerDocument );
1170 $titles = $xpath->query( 'title', $contextNode );
1171 $title = $titles->item( 0 );
1172 $parts = $xpath->query( 'part', $contextNode );
1173 if ( $flags & PPFrame::NO_ARGS ) {
1174 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1175 } else {
1176 $params = array(
1177 'title' => new PPNode_DOM( $title ),
1178 'parts' => new PPNode_DOM( $parts ) );
1179 $ret = $this->parser->argSubstitution( $params, $this );
1180 if ( isset( $ret['object'] ) ) {
1181 $newIterator = $ret['object'];
1182 } else {
1183 $out .= $ret['text'];
1186 } elseif ( $contextNode->nodeName == 'comment' ) {
1187 # HTML-style comment
1188 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1189 # Not in RECOVER_COMMENTS mode (msgnw) though.
1190 if ( ( $this->parser->ot['html']
1191 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1192 || ( $flags & PPFrame::STRIP_COMMENTS )
1193 ) && !( $flags & PPFrame::RECOVER_COMMENTS )
1195 $out .= '';
1196 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1197 # Add a strip marker in PST mode so that pstPass2() can
1198 # run some old-fashioned regexes on the result.
1199 # Not in RECOVER_COMMENTS mode (extractSections) though.
1200 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1201 } else {
1202 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1203 $out .= $contextNode->textContent;
1205 } elseif ( $contextNode->nodeName == 'ignore' ) {
1206 # Output suppression used by <includeonly> etc.
1207 # OT_WIKI will only respect <ignore> in substed templates.
1208 # The other output types respect it unless NO_IGNORE is set.
1209 # extractSections() sets NO_IGNORE and so never respects it.
1210 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1211 || ( $flags & PPFrame::NO_IGNORE )
1213 $out .= $contextNode->textContent;
1214 } else {
1215 $out .= '';
1217 } elseif ( $contextNode->nodeName == 'ext' ) {
1218 # Extension tag
1219 $xpath = new DOMXPath( $contextNode->ownerDocument );
1220 $names = $xpath->query( 'name', $contextNode );
1221 $attrs = $xpath->query( 'attr', $contextNode );
1222 $inners = $xpath->query( 'inner', $contextNode );
1223 $closes = $xpath->query( 'close', $contextNode );
1224 if ( $flags & PPFrame::NO_TAGS ) {
1225 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1226 if ( $attrs->length > 0 ) {
1227 $s .= $this->expand( $attrs->item( 0 ), $flags );
1229 if ( $inners->length > 0 ) {
1230 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1231 if ( $closes->length > 0 ) {
1232 $s .= $this->expand( $closes->item( 0 ), $flags );
1234 } else {
1235 $s .= '/>';
1237 $out .= $s;
1238 } else {
1239 $params = array(
1240 'name' => new PPNode_DOM( $names->item( 0 ) ),
1241 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1242 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1243 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1245 $out .= $this->parser->extensionSubstitution( $params, $this );
1247 } elseif ( $contextNode->nodeName == 'h' ) {
1248 # Heading
1249 $s = $this->expand( $contextNode->childNodes, $flags );
1251 # Insert a heading marker only for <h> children of <root>
1252 # This is to stop extractSections from going over multiple tree levels
1253 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html'] ) {
1254 # Insert heading index marker
1255 $headingIndex = $contextNode->getAttribute( 'i' );
1256 $titleText = $this->title->getPrefixedDBkey();
1257 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1258 $serial = count( $this->parser->mHeadings ) - 1;
1259 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
1260 $count = $contextNode->getAttribute( 'level' );
1261 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1262 $this->parser->mStripState->addGeneral( $marker, '' );
1264 $out .= $s;
1265 } else {
1266 # Generic recursive expansion
1267 $newIterator = $contextNode->childNodes;
1269 } else {
1270 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1273 if ( $newIterator !== false ) {
1274 if ( $newIterator instanceof PPNode_DOM ) {
1275 $newIterator = $newIterator->node;
1277 $outStack[] = '';
1278 $iteratorStack[] = $newIterator;
1279 $indexStack[] = 0;
1280 } elseif ( $iteratorStack[$level] === false ) {
1281 // Return accumulated value to parent
1282 // With tail recursion
1283 while ( $iteratorStack[$level] === false && $level > 0 ) {
1284 $outStack[$level - 1] .= $out;
1285 array_pop( $outStack );
1286 array_pop( $iteratorStack );
1287 array_pop( $indexStack );
1288 $level--;
1292 --$expansionDepth;
1293 return $outStack[0];
1297 * @param string $sep
1298 * @param int $flags
1299 * @param string|PPNode_DOM|DOMDocument $args,...
1300 * @return string
1302 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1303 $args = array_slice( func_get_args(), 2 );
1305 $first = true;
1306 $s = '';
1307 foreach ( $args as $root ) {
1308 if ( $root instanceof PPNode_DOM ) {
1309 $root = $root->node;
1311 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1312 $root = array( $root );
1314 foreach ( $root as $node ) {
1315 if ( $first ) {
1316 $first = false;
1317 } else {
1318 $s .= $sep;
1320 $s .= $this->expand( $node, $flags );
1323 return $s;
1327 * Implode with no flags specified
1328 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1330 * @param string $sep
1331 * @param string|PPNode_DOM|DOMDocument $args,...
1332 * @return string
1334 public function implode( $sep /*, ... */ ) {
1335 $args = array_slice( func_get_args(), 1 );
1337 $first = true;
1338 $s = '';
1339 foreach ( $args as $root ) {
1340 if ( $root instanceof PPNode_DOM ) {
1341 $root = $root->node;
1343 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1344 $root = array( $root );
1346 foreach ( $root as $node ) {
1347 if ( $first ) {
1348 $first = false;
1349 } else {
1350 $s .= $sep;
1352 $s .= $this->expand( $node );
1355 return $s;
1359 * Makes an object that, when expand()ed, will be the same as one obtained
1360 * with implode()
1362 * @param string $sep
1363 * @param string|PPNode_DOM|DOMDocument $args,...
1364 * @return array
1366 public function virtualImplode( $sep /*, ... */ ) {
1367 $args = array_slice( func_get_args(), 1 );
1368 $out = array();
1369 $first = true;
1371 foreach ( $args as $root ) {
1372 if ( $root instanceof PPNode_DOM ) {
1373 $root = $root->node;
1375 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1376 $root = array( $root );
1378 foreach ( $root as $node ) {
1379 if ( $first ) {
1380 $first = false;
1381 } else {
1382 $out[] = $sep;
1384 $out[] = $node;
1387 return $out;
1391 * Virtual implode with brackets
1392 * @param string $start
1393 * @param string $sep
1394 * @param string $end
1395 * @param string|PPNode_DOM|DOMDocument $args,...
1396 * @return array
1398 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1399 $args = array_slice( func_get_args(), 3 );
1400 $out = array( $start );
1401 $first = true;
1403 foreach ( $args as $root ) {
1404 if ( $root instanceof PPNode_DOM ) {
1405 $root = $root->node;
1407 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1408 $root = array( $root );
1410 foreach ( $root as $node ) {
1411 if ( $first ) {
1412 $first = false;
1413 } else {
1414 $out[] = $sep;
1416 $out[] = $node;
1419 $out[] = $end;
1420 return $out;
1423 public function __toString() {
1424 return 'frame{}';
1427 public function getPDBK( $level = false ) {
1428 if ( $level === false ) {
1429 return $this->title->getPrefixedDBkey();
1430 } else {
1431 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1436 * @return array
1438 public function getArguments() {
1439 return array();
1443 * @return array
1445 public function getNumberedArguments() {
1446 return array();
1450 * @return array
1452 public function getNamedArguments() {
1453 return array();
1457 * Returns true if there are no arguments in this frame
1459 * @return bool
1461 public function isEmpty() {
1462 return true;
1465 public function getArgument( $name ) {
1466 return false;
1470 * Returns true if the infinite loop check is OK, false if a loop is detected
1472 * @param Title $title
1473 * @return bool
1475 public function loopCheck( $title ) {
1476 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1480 * Return true if the frame is a template frame
1482 * @return bool
1484 public function isTemplate() {
1485 return false;
1489 * Get a title of frame
1491 * @return Title
1493 public function getTitle() {
1494 return $this->title;
1498 * Set the volatile flag
1500 * @param bool $flag
1502 public function setVolatile( $flag = true ) {
1503 $this->volatile = $flag;
1507 * Get the volatile flag
1509 * @return bool
1511 public function isVolatile() {
1512 return $this->volatile;
1516 * Set the TTL
1518 * @param int $ttl
1520 public function setTTL( $ttl ) {
1521 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1522 $this->ttl = $ttl;
1527 * Get the TTL
1529 * @return int|null
1531 public function getTTL() {
1532 return $this->ttl;
1537 * Expansion frame with template arguments
1538 * @ingroup Parser
1540 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1541 class PPTemplateFrame_DOM extends PPFrame_DOM {
1542 // @codingStandardsIgnoreEnd
1544 public $numberedArgs, $namedArgs;
1547 * @var PPFrame_DOM
1549 public $parent;
1550 public $numberedExpansionCache, $namedExpansionCache;
1553 * @param Preprocessor $preprocessor
1554 * @param bool|PPFrame_DOM $parent
1555 * @param array $numberedArgs
1556 * @param array $namedArgs
1557 * @param bool|Title $title
1559 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1560 $namedArgs = array(), $title = false
1562 parent::__construct( $preprocessor );
1564 $this->parent = $parent;
1565 $this->numberedArgs = $numberedArgs;
1566 $this->namedArgs = $namedArgs;
1567 $this->title = $title;
1568 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1569 $this->titleCache = $parent->titleCache;
1570 $this->titleCache[] = $pdbk;
1571 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1572 if ( $pdbk !== false ) {
1573 $this->loopCheckHash[$pdbk] = true;
1575 $this->depth = $parent->depth + 1;
1576 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1579 public function __toString() {
1580 $s = 'tplframe{';
1581 $first = true;
1582 $args = $this->numberedArgs + $this->namedArgs;
1583 foreach ( $args as $name => $value ) {
1584 if ( $first ) {
1585 $first = false;
1586 } else {
1587 $s .= ', ';
1589 $s .= "\"$name\":\"" .
1590 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1592 $s .= '}';
1593 return $s;
1597 * @throws MWException
1598 * @param string|int $key
1599 * @param string|PPNode_DOM|DOMDocument $root
1600 * @param int $flags
1601 * @return string
1603 public function cachedExpand( $key, $root, $flags = 0 ) {
1604 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1605 return $this->parent->childExpansionCache[$key];
1607 $retval = $this->expand( $root, $flags );
1608 if ( !$this->isVolatile() ) {
1609 $this->parent->childExpansionCache[$key] = $retval;
1611 return $retval;
1615 * Returns true if there are no arguments in this frame
1617 * @return bool
1619 public function isEmpty() {
1620 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1623 public function getArguments() {
1624 $arguments = array();
1625 foreach ( array_merge(
1626 array_keys( $this->numberedArgs ),
1627 array_keys( $this->namedArgs ) ) as $key ) {
1628 $arguments[$key] = $this->getArgument( $key );
1630 return $arguments;
1633 public function getNumberedArguments() {
1634 $arguments = array();
1635 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1636 $arguments[$key] = $this->getArgument( $key );
1638 return $arguments;
1641 public function getNamedArguments() {
1642 $arguments = array();
1643 foreach ( array_keys( $this->namedArgs ) as $key ) {
1644 $arguments[$key] = $this->getArgument( $key );
1646 return $arguments;
1649 public function getNumberedArgument( $index ) {
1650 if ( !isset( $this->numberedArgs[$index] ) ) {
1651 return false;
1653 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1654 # No trimming for unnamed arguments
1655 $this->numberedExpansionCache[$index] = $this->parent->expand(
1656 $this->numberedArgs[$index],
1657 PPFrame::STRIP_COMMENTS
1660 return $this->numberedExpansionCache[$index];
1663 public function getNamedArgument( $name ) {
1664 if ( !isset( $this->namedArgs[$name] ) ) {
1665 return false;
1667 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1668 # Trim named arguments post-expand, for backwards compatibility
1669 $this->namedExpansionCache[$name] = trim(
1670 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1672 return $this->namedExpansionCache[$name];
1675 public function getArgument( $name ) {
1676 $text = $this->getNumberedArgument( $name );
1677 if ( $text === false ) {
1678 $text = $this->getNamedArgument( $name );
1680 return $text;
1684 * Return true if the frame is a template frame
1686 * @return bool
1688 public function isTemplate() {
1689 return true;
1692 public function setVolatile( $flag = true ) {
1693 parent::setVolatile( $flag );
1694 $this->parent->setVolatile( $flag );
1697 public function setTTL( $ttl ) {
1698 parent::setTTL( $ttl );
1699 $this->parent->setTTL( $ttl );
1704 * Expansion frame with custom arguments
1705 * @ingroup Parser
1707 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1708 class PPCustomFrame_DOM extends PPFrame_DOM {
1709 // @codingStandardsIgnoreEnd
1711 public $args;
1713 public function __construct( $preprocessor, $args ) {
1714 parent::__construct( $preprocessor );
1715 $this->args = $args;
1718 public function __toString() {
1719 $s = 'cstmframe{';
1720 $first = true;
1721 foreach ( $this->args as $name => $value ) {
1722 if ( $first ) {
1723 $first = false;
1724 } else {
1725 $s .= ', ';
1727 $s .= "\"$name\":\"" .
1728 str_replace( '"', '\\"', $value->__toString() ) . '"';
1730 $s .= '}';
1731 return $s;
1735 * @return bool
1737 public function isEmpty() {
1738 return !count( $this->args );
1741 public function getArgument( $index ) {
1742 if ( !isset( $this->args[$index] ) ) {
1743 return false;
1745 return $this->args[$index];
1748 public function getArguments() {
1749 return $this->args;
1754 * @ingroup Parser
1756 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1757 class PPNode_DOM implements PPNode {
1758 // @codingStandardsIgnoreEnd
1761 * @var DOMElement
1763 public $node;
1764 public $xpath;
1766 public function __construct( $node, $xpath = false ) {
1767 $this->node = $node;
1771 * @return DOMXPath
1773 public function getXPath() {
1774 if ( $this->xpath === null ) {
1775 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1777 return $this->xpath;
1780 public function __toString() {
1781 if ( $this->node instanceof DOMNodeList ) {
1782 $s = '';
1783 foreach ( $this->node as $node ) {
1784 $s .= $node->ownerDocument->saveXML( $node );
1786 } else {
1787 $s = $this->node->ownerDocument->saveXML( $this->node );
1789 return $s;
1793 * @return bool|PPNode_DOM
1795 public function getChildren() {
1796 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1800 * @return bool|PPNode_DOM
1802 public function getFirstChild() {
1803 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1807 * @return bool|PPNode_DOM
1809 public function getNextSibling() {
1810 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1814 * @param string $type
1816 * @return bool|PPNode_DOM
1818 public function getChildrenOfType( $type ) {
1819 return new self( $this->getXPath()->query( $type, $this->node ) );
1823 * @return int
1825 public function getLength() {
1826 if ( $this->node instanceof DOMNodeList ) {
1827 return $this->node->length;
1828 } else {
1829 return false;
1834 * @param int $i
1835 * @return bool|PPNode_DOM
1837 public function item( $i ) {
1838 $item = $this->node->item( $i );
1839 return $item ? new self( $item ) : false;
1843 * @return string
1845 public function getName() {
1846 if ( $this->node instanceof DOMNodeList ) {
1847 return '#nodelist';
1848 } else {
1849 return $this->node->nodeName;
1854 * Split a "<part>" node into an associative array containing:
1855 * - name PPNode name
1856 * - index String index
1857 * - value PPNode value
1859 * @throws MWException
1860 * @return array
1862 public function splitArg() {
1863 $xpath = $this->getXPath();
1864 $names = $xpath->query( 'name', $this->node );
1865 $values = $xpath->query( 'value', $this->node );
1866 if ( !$names->length || !$values->length ) {
1867 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1869 $name = $names->item( 0 );
1870 $index = $name->getAttribute( 'index' );
1871 return array(
1872 'name' => new self( $name ),
1873 'index' => $index,
1874 'value' => new self( $values->item( 0 ) ) );
1878 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1879 * All values in the resulting array are PPNodes. Inner and close are optional.
1881 * @throws MWException
1882 * @return array
1884 public function splitExt() {
1885 $xpath = $this->getXPath();
1886 $names = $xpath->query( 'name', $this->node );
1887 $attrs = $xpath->query( 'attr', $this->node );
1888 $inners = $xpath->query( 'inner', $this->node );
1889 $closes = $xpath->query( 'close', $this->node );
1890 if ( !$names->length || !$attrs->length ) {
1891 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1893 $parts = array(
1894 'name' => new self( $names->item( 0 ) ),
1895 'attr' => new self( $attrs->item( 0 ) ) );
1896 if ( $inners->length ) {
1897 $parts['inner'] = new self( $inners->item( 0 ) );
1899 if ( $closes->length ) {
1900 $parts['close'] = new self( $closes->item( 0 ) );
1902 return $parts;
1906 * Split a "<h>" node
1907 * @throws MWException
1908 * @return array
1910 public function splitHeading() {
1911 if ( $this->getName() !== 'h' ) {
1912 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1914 return array(
1915 'i' => $this->node->getAttribute( 'i' ),
1916 'level' => $this->node->getAttribute( 'level' ),
1917 'contents' => $this->getChildren()