3 * Preprocessor using PHP's dom extension
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
27 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
28 class Preprocessor_DOM
extends Preprocessor
{
37 const CACHE_PREFIX
= 'preprocess-xml';
39 public function __construct( $parser ) {
40 $this->parser
= $parser;
41 $mem = ini_get( 'memory_limit' );
42 $this->memoryLimit
= false;
43 if ( strval( $mem ) !== '' && $mem != -1 ) {
44 if ( preg_match( '/^\d+$/', $mem ) ) {
45 $this->memoryLimit
= $mem;
46 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
47 $this->memoryLimit
= $m[1] * 1048576;
55 public function newFrame() {
56 return new PPFrame_DOM( $this );
61 * @return PPCustomFrame_DOM
63 public function newCustomFrame( $args ) {
64 return new PPCustomFrame_DOM( $this, $args );
68 * @param array $values
72 public function newPartNodeArray( $values ) {
73 // NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
76 foreach ( $values as $k => $val ) {
78 $xml .= "<part><name index=\"$k\"/><value>"
79 . htmlspecialchars( $val ) . "</value></part>";
81 $xml .= "<part><name>" . htmlspecialchars( $k )
82 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
88 $dom = new DOMDocument();
89 MediaWiki\
suppressWarnings();
90 $result = $dom->loadXML( $xml );
91 MediaWiki\restoreWarnings
();
93 // Try running the XML through UtfNormal to get rid of invalid characters
94 $xml = UtfNormal\Validator
::cleanUp( $xml );
95 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
96 // don't barf when the XML is >256 levels deep
97 $result = $dom->loadXML( $xml, 1 << 19 );
101 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
104 $root = $dom->documentElement
;
105 $node = new PPNode_DOM( $root->childNodes
);
110 * @throws MWException
113 public function memCheck() {
114 if ( $this->memoryLimit
=== false ) {
117 $usage = memory_get_usage();
118 if ( $usage > $this->memoryLimit
* 0.9 ) {
119 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
120 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
122 return $usage <= $this->memoryLimit
* 0.8;
126 * Preprocess some wikitext and return the document tree.
127 * This is the ghost of Parser::replace_variables().
129 * @param string $text The text to parse
130 * @param int $flags Bitwise combination of:
131 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
132 * as if the text is being included. Default
133 * is to assume a direct page view.
135 * The generated DOM tree must depend only on the input text and the flags.
136 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
138 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
139 * change in the DOM tree for a given text, must be passed through the section identifier
140 * in the section edit link and thus back to extractSections().
142 * The output of this function is currently only cached in process memory, but a persistent
143 * cache may be implemented at a later date which takes further advantage of these strict
144 * dependency requirements.
146 * @throws MWException
149 public function preprocessToObj( $text, $flags = 0 ) {
150 $xml = $this->cacheGetTree( $text, $flags );
151 if ( $xml === false ) {
152 $xml = $this->preprocessToXml( $text, $flags );
153 $this->cacheSetTree( $text, $flags, $xml );
156 // Fail if the number of elements exceeds acceptable limits
157 // Do not attempt to generate the DOM
158 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
159 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
160 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
161 // if ( $cacheable ) { ... }
162 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
165 $dom = new DOMDocument
;
166 MediaWiki\
suppressWarnings();
167 $result = $dom->loadXML( $xml );
168 MediaWiki\restoreWarnings
();
170 // Try running the XML through UtfNormal to get rid of invalid characters
171 $xml = UtfNormal\Validator
::cleanUp( $xml );
172 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
173 // don't barf when the XML is >256 levels deep.
174 $result = $dom->loadXML( $xml, 1 << 19 );
177 $obj = new PPNode_DOM( $dom->documentElement
);
180 // if ( $cacheable ) { ... }
183 throw new MWException( __METHOD__
. ' generated invalid XML' );
189 * @param string $text
193 public function preprocessToXml( $text, $flags = 0 ) {
194 global $wgDisableLangConversion;
196 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
198 $xmlishElements = $this->parser
->getStripList();
199 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
200 $enableOnlyinclude = false;
201 if ( $forInclusion ) {
202 $ignoredTags = [ 'includeonly', '/includeonly' ];
203 $ignoredElements = [ 'noinclude' ];
204 $xmlishElements[] = 'noinclude';
205 if ( strpos( $text, '<onlyinclude>' ) !== false
206 && strpos( $text, '</onlyinclude>' ) !== false
208 $enableOnlyinclude = true;
211 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
212 $ignoredElements = [ 'includeonly' ];
213 $xmlishElements[] = 'includeonly';
215 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
217 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
218 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
220 $stack = new PPDStack
;
222 $searchBase = "[{<\n"; # }
223 if ( !$wgDisableLangConversion ) {
227 // For fast reverse searches
228 $revText = strrev( $text );
229 $lengthText = strlen( $text );
231 // Input pointer, starts out pointing to a pseudo-newline before the start
233 // Current accumulator
234 $accum =& $stack->getAccum();
236 // True to find equals signs in arguments
238 // True to take notice of pipe characters
241 // True if $i is inside a possible heading
243 // True if there are no more greater-than (>) signs right of $i
245 // Map of tag name => true if there are no more closing tags of given type right of $i
246 $noMoreClosingTag = [];
247 // True to ignore all input up to the next <onlyinclude>
248 $findOnlyinclude = $enableOnlyinclude;
249 // Do a line-start run without outputting an LF character
250 $fakeLineStart = true;
253 // $this->memCheck();
255 if ( $findOnlyinclude ) {
256 // Ignore all input up to the next <onlyinclude>
257 $startPos = strpos( $text, '<onlyinclude>', $i );
258 if ( $startPos === false ) {
259 // Ignored section runs to the end
260 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
263 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
264 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
266 $findOnlyinclude = false;
269 if ( $fakeLineStart ) {
270 $found = 'line-start';
273 # Find next opening brace, closing brace or pipe
274 $search = $searchBase;
275 if ( $stack->top
=== false ) {
276 $currentClosing = '';
278 $stack->top
->close
=== '}-' &&
279 $stack->top
->count
> 2
281 # adjust closing for -{{{...{{
282 $currentClosing = '}';
283 $search .= $currentClosing;
285 $currentClosing = $stack->top
->close
;
286 $search .= $currentClosing;
292 // First equals will be for the template
296 # Output literal section, advance input counter
297 $literalLength = strcspn( $text, $search, $i );
298 if ( $literalLength > 0 ) {
299 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
300 $i +
= $literalLength;
302 if ( $i >= $lengthText ) {
303 if ( $currentClosing == "\n" ) {
304 // Do a past-the-end run to finish off the heading
312 $curChar = $curTwoChar = $text[$i];
313 if ( ( $i +
1 ) < $lengthText ) {
314 $curTwoChar .= $text[$i +
1];
316 if ( $curChar == '|' ) {
318 } elseif ( $curChar == '=' ) {
320 } elseif ( $curChar == '<' ) {
322 } elseif ( $curChar == "\n" ) {
326 $found = 'line-start';
328 } elseif ( $curTwoChar == $currentClosing ) {
330 $curChar = $curTwoChar;
331 } elseif ( $curChar == $currentClosing ) {
333 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
334 $curChar = $curTwoChar;
336 $rule = $this->rules
[$curChar];
337 } elseif ( isset( $this->rules
[$curChar] ) ) {
339 $rule = $this->rules
[$curChar];
341 # Some versions of PHP have a strcspn which stops on
342 # null characters; ignore these and continue.
343 # We also may get '-' and '}' characters here which
344 # don't match -{ or $currentClosing. Add these to
345 # output and continue.
346 if ( $curChar == '-' ||
$curChar == '}' ) {
355 if ( $found == 'angle' ) {
357 // Handle </onlyinclude>
358 if ( $enableOnlyinclude
359 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
361 $findOnlyinclude = true;
365 // Determine element name
366 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
367 // Element name missing or not listed
373 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
374 // To avoid leaving blank lines, when a sequence of
375 // space-separated comments is both preceded and followed by
376 // a newline (ignoring spaces), then
377 // trim leading and trailing spaces and the trailing newline.
380 $endPos = strpos( $text, '-->', $i +
4 );
381 if ( $endPos === false ) {
382 // Unclosed comment in input, runs to end
383 $inner = substr( $text, $i );
384 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
387 // Search backwards for leading whitespace
388 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
390 // Search forwards for trailing whitespace
391 // $wsEnd will be the position of the last space (or the '>' if there's none)
392 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
394 // Keep looking forward as long as we're finding more
396 $comments = [ [ $wsStart, $wsEnd ] ];
397 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
398 $c = strpos( $text, '-->', $wsEnd +
4 );
399 if ( $c === false ) {
402 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
403 $comments[] = [ $wsEnd +
1, $c ];
407 // Eat the line if possible
408 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
409 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
410 // it's a possible beneficial b/c break.
411 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
412 && substr( $text, $wsEnd +
1, 1 ) == "\n"
414 // Remove leading whitespace from the end of the accumulator
415 // Sanity check first though
416 $wsLength = $i - $wsStart;
418 && strspn( $accum, " \t", -$wsLength ) === $wsLength
420 $accum = substr( $accum, 0, -$wsLength );
423 // Dump all but the last comment to the accumulator
424 foreach ( $comments as $j => $com ) {
426 $endPos = $com[1] +
1;
427 if ( $j == ( count( $comments ) - 1 ) ) {
430 $inner = substr( $text, $startPos, $endPos - $startPos );
431 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
434 // Do a line-start run next time to look for headings after the comment
435 $fakeLineStart = true;
437 // No line to eat, just take the comment itself
443 $part = $stack->top
->getCurrentPart();
444 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
445 $part->visualEnd
= $wsStart;
447 // Else comments abutting, no change in visual end
448 $part->commentEnd
= $endPos;
451 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
452 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
457 $lowerName = strtolower( $name );
458 $attrStart = $i +
strlen( $name ) +
1;
461 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
462 if ( $tagEndPos === false ) {
463 // Infinite backtrack
464 // Disable tag search to prevent worst-case O(N^2) performance
471 // Handle ignored tags
472 if ( in_array( $lowerName, $ignoredTags ) ) {
474 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
481 if ( $text[$tagEndPos - 1] == '/' ) {
482 $attrEnd = $tagEndPos - 1;
487 $attrEnd = $tagEndPos;
490 !isset( $noMoreClosingTag[$name] ) &&
491 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
492 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
494 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
495 $i = $matches[0][1] +
strlen( $matches[0][0] );
496 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
499 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
500 // Let it run out to the end of the text.
501 $inner = substr( $text, $tagEndPos +
1 );
505 // Don't match the tag, treat opening tag as literal and resume parsing.
507 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
508 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
509 $noMoreClosingTag[$name] = true;
514 // <includeonly> and <noinclude> just become <ignore> tags
515 if ( in_array( $lowerName, $ignoredElements ) ) {
516 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
522 if ( $attrEnd <= $attrStart ) {
525 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
527 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
528 // Note that the attr element contains the whitespace between name and attribute,
529 // this is necessary for precise reconstruction during pre-save transform.
530 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
531 if ( $inner !== null ) {
532 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
534 $accum .= $close . '</ext>';
535 } elseif ( $found == 'line-start' ) {
536 // Is this the start of a heading?
537 // Line break belongs before the heading element in any case
538 if ( $fakeLineStart ) {
539 $fakeLineStart = false;
545 $count = strspn( $text, '=', $i, 6 );
546 if ( $count == 1 && $findEquals ) {
547 // DWIM: This looks kind of like a name/value separator.
548 // Let's let the equals handler have it and break the
549 // potential heading. This is heuristic, but AFAICT the
550 // methods for completely correct disambiguation are very
552 } elseif ( $count > 0 ) {
556 'parts' => [ new PPDPart( str_repeat( '=', $count ) ) ],
559 $stack->push( $piece );
560 $accum =& $stack->getAccum();
561 $stackFlags = $stack->getFlags();
562 if ( isset( $stackFlags['findEquals'] ) ) {
563 $findEquals = $stackFlags['findEquals'];
565 if ( isset( $stackFlags['findPipe'] ) ) {
566 $findPipe = $stackFlags['findPipe'];
568 if ( isset( $stackFlags['inHeading'] ) ) {
569 $inHeading = $stackFlags['inHeading'];
573 } elseif ( $found == 'line-end' ) {
574 $piece = $stack->top
;
575 // A heading must be open, otherwise \n wouldn't have been in the search list
576 assert( $piece->open
=== "\n" );
577 $part = $piece->getCurrentPart();
578 // Search back through the input to see if it has a proper close.
579 // Do this using the reversed string since the other solutions
580 // (end anchor, etc.) are inefficient.
581 $wsLength = strspn( $revText, " \t", $lengthText - $i );
582 $searchStart = $i - $wsLength;
583 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
584 // Comment found at line end
585 // Search for equals signs before the comment
586 $searchStart = $part->visualEnd
;
587 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
589 $count = $piece->count
;
590 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
591 if ( $equalsLength > 0 ) {
592 if ( $searchStart - $equalsLength == $piece->startPos
) {
593 // This is just a single string of equals signs on its own line
594 // Replicate the doHeadings behavior /={count}(.+)={count}/
595 // First find out how many equals signs there really are (don't stop at 6)
596 $count = $equalsLength;
600 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
603 $count = min( $equalsLength, $count );
606 // Normal match, output <h>
607 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
610 // Single equals sign on its own line, count=0
614 // No match, no <h>, just pass down the inner text
619 $accum =& $stack->getAccum();
620 $stackFlags = $stack->getFlags();
621 if ( isset( $stackFlags['findEquals'] ) ) {
622 $findEquals = $stackFlags['findEquals'];
624 if ( isset( $stackFlags['findPipe'] ) ) {
625 $findPipe = $stackFlags['findPipe'];
627 if ( isset( $stackFlags['inHeading'] ) ) {
628 $inHeading = $stackFlags['inHeading'];
631 // Append the result to the enclosing accumulator
633 // Note that we do NOT increment the input pointer.
634 // This is because the closing linebreak could be the opening linebreak of
635 // another heading. Infinite loops are avoided because the next iteration MUST
636 // hit the heading open case above, which unconditionally increments the
638 } elseif ( $found == 'open' ) {
639 # count opening brace characters
640 $curLen = strlen( $curChar );
641 $count = ( $curLen > 1 ) ?
642 # allow the final character to repeat
643 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
644 strspn( $text, $curChar, $i );
646 # we need to add to stack only if opening brace count is enough for one of the rules
647 if ( $count >= $rule['min'] ) {
648 # Add it to the stack
651 'close' => $rule['end'],
653 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
656 $stack->push( $piece );
657 $accum =& $stack->getAccum();
658 $stackFlags = $stack->getFlags();
659 if ( isset( $stackFlags['findEquals'] ) ) {
660 $findEquals = $stackFlags['findEquals'];
662 if ( isset( $stackFlags['findPipe'] ) ) {
663 $findPipe = $stackFlags['findPipe'];
665 if ( isset( $stackFlags['inHeading'] ) ) {
666 $inHeading = $stackFlags['inHeading'];
669 # Add literal brace(s)
670 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
673 } elseif ( $found == 'close' ) {
674 $piece = $stack->top
;
675 # lets check if there are enough characters for closing brace
676 $maxCount = $piece->count
;
677 if ( $piece->close
=== '}-' && $curChar === '}' ) {
678 $maxCount--; # don't try to match closing '-' as a '}'
680 $curLen = strlen( $curChar );
681 $count = ( $curLen > 1 ) ?
$curLen :
682 strspn( $text, $curChar, $i, $maxCount );
684 # check for maximum matching characters (if there are 5 closing
685 # characters, we will probably need only 3 - depending on the rules)
686 $rule = $this->rules
[$piece->open
];
687 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
688 # tweak for -{..{{ }}..}-
689 $rule = $this->rules
['{'];
691 if ( $count > $rule['max'] ) {
692 # The specified maximum exists in the callback array, unless the caller
694 $matchingCount = $rule['max'];
696 # Count is less than the maximum
697 # Skip any gaps in the callback array to find the true largest match
698 # Need to use array_key_exists not isset because the callback can be null
699 $matchingCount = $count;
700 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
705 if ( $matchingCount <= 0 ) {
706 # No matching element found in callback array
707 # Output a literal closing brace and continue
708 $endText = substr( $text, $i, $count );
709 $accum .= htmlspecialchars( $endText );
713 $name = $rule['names'][$matchingCount];
714 if ( $name === null ) {
715 // No element, just literal text
716 $endText = substr( $text, $i, $matchingCount );
717 $element = $piece->breakSyntax( $matchingCount ) . $endText;
720 # Note: $parts is already XML, does not need to be encoded further
721 $parts = $piece->parts
;
722 $title = $parts[0]->out
;
725 # The invocation is at the start of the line if lineStart is set in
726 # the stack, and all opening brackets are used up.
727 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
728 $attr = ' lineStart="1"';
733 $element = "<$name$attr>";
734 $element .= "<title>$title</title>";
736 foreach ( $parts as $part ) {
737 if ( isset( $part->eqpos
) ) {
738 $argName = substr( $part->out
, 0, $part->eqpos
);
739 $argValue = substr( $part->out
, $part->eqpos +
1 );
740 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
742 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
746 $element .= "</$name>";
749 # Advance input pointer
750 $i +
= $matchingCount;
754 $accum =& $stack->getAccum();
756 # Re-add the old stack element if it still has unmatched opening characters remaining
757 if ( $matchingCount < $piece->count
) {
758 $piece->parts
= [ new PPDPart
];
759 $piece->count
-= $matchingCount;
760 # do we still qualify for any callback with remaining count?
761 $min = $this->rules
[$piece->open
]['min'];
762 if ( $piece->count
>= $min ) {
763 $stack->push( $piece );
764 $accum =& $stack->getAccum();
766 $s = substr( $piece->open
, 0, -1 );
768 substr( $piece->open
, -1 ),
769 $piece->count
- strlen( $s )
774 $stackFlags = $stack->getFlags();
775 if ( isset( $stackFlags['findEquals'] ) ) {
776 $findEquals = $stackFlags['findEquals'];
778 if ( isset( $stackFlags['findPipe'] ) ) {
779 $findPipe = $stackFlags['findPipe'];
781 if ( isset( $stackFlags['inHeading'] ) ) {
782 $inHeading = $stackFlags['inHeading'];
785 # Add XML element to the enclosing accumulator
787 } elseif ( $found == 'pipe' ) {
788 $findEquals = true; // shortcut for getFlags()
790 $accum =& $stack->getAccum();
792 } elseif ( $found == 'equals' ) {
793 $findEquals = false; // shortcut for getFlags()
794 $stack->getCurrentPart()->eqpos
= strlen( $accum );
797 } elseif ( $found == 'dash' ) {
803 # Output any remaining unclosed brackets
804 foreach ( $stack->stack
as $piece ) {
805 $stack->rootAccum
.= $piece->breakSyntax();
807 $stack->rootAccum
.= '</root>';
808 $xml = $stack->rootAccum
;
815 * Stack class to help Preprocessor::preprocessToObj()
819 public $stack, $rootAccum;
826 public $elementClass = PPDStackElement
::class;
828 public static $false = false;
830 public function __construct() {
833 $this->rootAccum
= '';
834 $this->accum
=& $this->rootAccum
;
840 public function count() {
841 return count( $this->stack
);
844 public function &getAccum() {
848 public function getCurrentPart() {
849 if ( $this->top
=== false ) {
852 return $this->top
->getCurrentPart();
856 public function push( $data ) {
857 if ( $data instanceof $this->elementClass
) {
858 $this->stack
[] = $data;
860 $class = $this->elementClass
;
861 $this->stack
[] = new $class( $data );
863 $this->top
= $this->stack
[count( $this->stack
) - 1];
864 $this->accum
=& $this->top
->getAccum();
867 public function pop() {
868 if ( !count( $this->stack
) ) {
869 throw new MWException( __METHOD__
. ': no elements remaining' );
871 $temp = array_pop( $this->stack
);
873 if ( count( $this->stack
) ) {
874 $this->top
= $this->stack
[count( $this->stack
) - 1];
875 $this->accum
=& $this->top
->getAccum();
877 $this->top
= self
::$false;
878 $this->accum
=& $this->rootAccum
;
883 public function addPart( $s = '' ) {
884 $this->top
->addPart( $s );
885 $this->accum
=& $this->top
->getAccum();
891 public function getFlags() {
892 if ( !count( $this->stack
) ) {
894 'findEquals' => false,
896 'inHeading' => false,
899 return $this->top
->getFlags();
907 class PPDStackElement
{
909 * @var string Opening character (\n for heading)
914 * @var string Matching closing character
919 * @var int Number of opening characters found (number of "=" for heading)
924 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
929 * @var bool True if the open char appeared at the start of the input line.
930 * Not set for headings.
934 public $partClass = PPDPart
::class;
936 public function __construct( $data = [] ) {
937 $class = $this->partClass
;
938 $this->parts
= [ new $class ];
940 foreach ( $data as $name => $value ) {
941 $this->$name = $value;
945 public function &getAccum() {
946 return $this->parts
[count( $this->parts
) - 1]->out
;
949 public function addPart( $s = '' ) {
950 $class = $this->partClass
;
951 $this->parts
[] = new $class( $s );
954 public function getCurrentPart() {
955 return $this->parts
[count( $this->parts
) - 1];
961 public function getFlags() {
962 $partCount = count( $this->parts
);
963 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
965 'findPipe' => $findPipe,
966 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
967 'inHeading' => $this->open
== "\n",
972 * Get the output string that would result if the close is not found.
974 * @param bool|int $openingCount
977 public function breakSyntax( $openingCount = false ) {
978 if ( $this->open
== "\n" ) {
979 $s = $this->parts
[0]->out
;
981 if ( $openingCount === false ) {
982 $openingCount = $this->count
;
984 $s = substr( $this->open
, 0, -1 );
986 substr( $this->open
, -1 ),
987 $openingCount - strlen( $s )
990 foreach ( $this->parts
as $part ) {
1008 * @var string Output accumulator string
1012 // Optional member variables:
1013 // eqpos Position of equals sign in output accumulator
1014 // commentEnd Past-the-end input pointer for the last comment encountered
1015 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
1017 public function __construct( $out = '' ) {
1023 * An expansion frame, used as a context to expand the result of preprocessToObj()
1026 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1027 class PPFrame_DOM
implements PPFrame
{
1032 public $preprocessor;
1046 * Hashtable listing templates which are disallowed for expansion in this frame,
1047 * having been encountered previously in parent frames.
1049 public $loopCheckHash;
1052 * Recursion depth of this frame, top = 0
1053 * Note that this is NOT the same as expansion depth in expand()
1057 private $volatile = false;
1058 private $ttl = null;
1063 protected $childExpansionCache;
1066 * Construct a new preprocessor frame.
1067 * @param Preprocessor $preprocessor The parent preprocessor
1069 public function __construct( $preprocessor ) {
1070 $this->preprocessor
= $preprocessor;
1071 $this->parser
= $preprocessor->parser
;
1072 $this->title
= $this->parser
->mTitle
;
1073 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
1074 $this->loopCheckHash
= [];
1076 $this->childExpansionCache
= [];
1080 * Create a new child frame
1081 * $args is optionally a multi-root PPNode or array containing the template arguments
1083 * @param bool|array $args
1084 * @param Title|bool $title
1085 * @param int $indexOffset
1086 * @return PPTemplateFrame_DOM
1088 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1091 if ( $title === false ) {
1092 $title = $this->title
;
1094 if ( $args !== false ) {
1096 if ( $args instanceof PPNode
) {
1097 $args = $args->node
;
1099 foreach ( $args as $arg ) {
1100 if ( $arg instanceof PPNode
) {
1103 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1104 $xpath = new DOMXPath( $arg->ownerDocument
);
1107 $nameNodes = $xpath->query( 'name', $arg );
1108 $value = $xpath->query( 'value', $arg );
1109 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1110 // Numbered parameter
1111 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1112 $index = $index - $indexOffset;
1113 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1114 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1115 wfEscapeWikiText( $this->title
),
1116 wfEscapeWikiText( $title ),
1117 wfEscapeWikiText( $index ) )->text() );
1118 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1120 $numberedArgs[$index] = $value->item( 0 );
1121 unset( $namedArgs[$index] );
1124 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1125 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1126 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1127 wfEscapeWikiText( $this->title
),
1128 wfEscapeWikiText( $title ),
1129 wfEscapeWikiText( $name ) )->text() );
1130 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1132 $namedArgs[$name] = $value->item( 0 );
1133 unset( $numberedArgs[$name] );
1137 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1141 * @throws MWException
1142 * @param string|int $key
1143 * @param string|PPNode_DOM|DOMDocument $root
1147 public function cachedExpand( $key, $root, $flags = 0 ) {
1148 // we don't have a parent, so we don't have a cache
1149 return $this->expand( $root, $flags );
1153 * @throws MWException
1154 * @param string|PPNode_DOM|DOMDocument $root
1158 public function expand( $root, $flags = 0 ) {
1159 static $expansionDepth = 0;
1160 if ( is_string( $root ) ) {
1164 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1165 $this->parser
->limitationWarn( 'node-count-exceeded',
1166 $this->parser
->mPPNodeCount
,
1167 $this->parser
->mOptions
->getMaxPPNodeCount()
1169 return '<span class="error">Node-count limit exceeded</span>';
1172 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1173 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1175 $this->parser
->mOptions
->getMaxPPExpandDepth()
1177 return '<span class="error">Expansion depth limit exceeded</span>';
1180 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1181 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1184 if ( $root instanceof PPNode_DOM
) {
1185 $root = $root->node
;
1187 if ( $root instanceof DOMDocument
) {
1188 $root = $root->documentElement
;
1191 $outStack = [ '', '' ];
1192 $iteratorStack = [ false, $root ];
1193 $indexStack = [ 0, 0 ];
1195 while ( count( $iteratorStack ) > 1 ) {
1196 $level = count( $outStack ) - 1;
1197 $iteratorNode =& $iteratorStack[$level];
1198 $out =& $outStack[$level];
1199 $index =& $indexStack[$level];
1201 if ( $iteratorNode instanceof PPNode_DOM
) {
1202 $iteratorNode = $iteratorNode->node
;
1205 if ( is_array( $iteratorNode ) ) {
1206 if ( $index >= count( $iteratorNode ) ) {
1207 // All done with this iterator
1208 $iteratorStack[$level] = false;
1209 $contextNode = false;
1211 $contextNode = $iteratorNode[$index];
1214 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1215 if ( $index >= $iteratorNode->length
) {
1216 // All done with this iterator
1217 $iteratorStack[$level] = false;
1218 $contextNode = false;
1220 $contextNode = $iteratorNode->item( $index );
1224 // Copy to $contextNode and then delete from iterator stack,
1225 // because this is not an iterator but we do have to execute it once
1226 $contextNode = $iteratorStack[$level];
1227 $iteratorStack[$level] = false;
1230 if ( $contextNode instanceof PPNode_DOM
) {
1231 $contextNode = $contextNode->node
;
1234 $newIterator = false;
1236 if ( $contextNode === false ) {
1238 } elseif ( is_string( $contextNode ) ) {
1239 $out .= $contextNode;
1240 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1241 $newIterator = $contextNode;
1242 } elseif ( $contextNode instanceof DOMNode
) {
1243 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1244 $out .= $contextNode->nodeValue
;
1245 } elseif ( $contextNode->nodeName
== 'template' ) {
1246 # Double-brace expansion
1247 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1248 $titles = $xpath->query( 'title', $contextNode );
1249 $title = $titles->item( 0 );
1250 $parts = $xpath->query( 'part', $contextNode );
1251 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1252 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1254 $lineStart = $contextNode->getAttribute( 'lineStart' );
1256 'title' => new PPNode_DOM( $title ),
1257 'parts' => new PPNode_DOM( $parts ),
1258 'lineStart' => $lineStart ];
1259 $ret = $this->parser
->braceSubstitution( $params, $this );
1260 if ( isset( $ret['object'] ) ) {
1261 $newIterator = $ret['object'];
1263 $out .= $ret['text'];
1266 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1267 # Triple-brace expansion
1268 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1269 $titles = $xpath->query( 'title', $contextNode );
1270 $title = $titles->item( 0 );
1271 $parts = $xpath->query( 'part', $contextNode );
1272 if ( $flags & PPFrame
::NO_ARGS
) {
1273 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1276 'title' => new PPNode_DOM( $title ),
1277 'parts' => new PPNode_DOM( $parts ) ];
1278 $ret = $this->parser
->argSubstitution( $params, $this );
1279 if ( isset( $ret['object'] ) ) {
1280 $newIterator = $ret['object'];
1282 $out .= $ret['text'];
1285 } elseif ( $contextNode->nodeName
== 'comment' ) {
1286 # HTML-style comment
1287 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1288 # Not in RECOVER_COMMENTS mode (msgnw) though.
1289 if ( ( $this->parser
->ot
['html']
1290 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1291 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1292 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1295 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1296 # Add a strip marker in PST mode so that pstPass2() can
1297 # run some old-fashioned regexes on the result.
1298 # Not in RECOVER_COMMENTS mode (extractSections) though.
1299 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1301 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1302 $out .= $contextNode->textContent
;
1304 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1305 # Output suppression used by <includeonly> etc.
1306 # OT_WIKI will only respect <ignore> in substed templates.
1307 # The other output types respect it unless NO_IGNORE is set.
1308 # extractSections() sets NO_IGNORE and so never respects it.
1309 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1310 ||
( $flags & PPFrame
::NO_IGNORE
)
1312 $out .= $contextNode->textContent
;
1316 } elseif ( $contextNode->nodeName
== 'ext' ) {
1318 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1319 $names = $xpath->query( 'name', $contextNode );
1320 $attrs = $xpath->query( 'attr', $contextNode );
1321 $inners = $xpath->query( 'inner', $contextNode );
1322 $closes = $xpath->query( 'close', $contextNode );
1323 if ( $flags & PPFrame
::NO_TAGS
) {
1324 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1325 if ( $attrs->length
> 0 ) {
1326 $s .= $this->expand( $attrs->item( 0 ), $flags );
1328 if ( $inners->length
> 0 ) {
1329 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1330 if ( $closes->length
> 0 ) {
1331 $s .= $this->expand( $closes->item( 0 ), $flags );
1339 'name' => new PPNode_DOM( $names->item( 0 ) ),
1340 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1341 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1342 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1344 $out .= $this->parser
->extensionSubstitution( $params, $this );
1346 } elseif ( $contextNode->nodeName
== 'h' ) {
1348 $s = $this->expand( $contextNode->childNodes
, $flags );
1350 # Insert a heading marker only for <h> children of <root>
1351 # This is to stop extractSections from going over multiple tree levels
1352 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1353 # Insert heading index marker
1354 $headingIndex = $contextNode->getAttribute( 'i' );
1355 $titleText = $this->title
->getPrefixedDBkey();
1356 $this->parser
->mHeadings
[] = [ $titleText, $headingIndex ];
1357 $serial = count( $this->parser
->mHeadings
) - 1;
1358 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1359 $count = $contextNode->getAttribute( 'level' );
1360 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1361 $this->parser
->mStripState
->addGeneral( $marker, '' );
1365 # Generic recursive expansion
1366 $newIterator = $contextNode->childNodes
;
1369 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1372 if ( $newIterator !== false ) {
1373 if ( $newIterator instanceof PPNode_DOM
) {
1374 $newIterator = $newIterator->node
;
1377 $iteratorStack[] = $newIterator;
1379 } elseif ( $iteratorStack[$level] === false ) {
1380 // Return accumulated value to parent
1381 // With tail recursion
1382 while ( $iteratorStack[$level] === false && $level > 0 ) {
1383 $outStack[$level - 1] .= $out;
1384 array_pop( $outStack );
1385 array_pop( $iteratorStack );
1386 array_pop( $indexStack );
1392 return $outStack[0];
1396 * @param string $sep
1398 * @param string|PPNode_DOM|DOMDocument $args,...
1401 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1402 $args = array_slice( func_get_args(), 2 );
1406 foreach ( $args as $root ) {
1407 if ( $root instanceof PPNode_DOM
) {
1408 $root = $root->node
;
1410 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1413 foreach ( $root as $node ) {
1419 $s .= $this->expand( $node, $flags );
1426 * Implode with no flags specified
1427 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1429 * @param string $sep
1430 * @param string|PPNode_DOM|DOMDocument $args,...
1433 public function implode( $sep /*, ... */ ) {
1434 $args = array_slice( func_get_args(), 1 );
1438 foreach ( $args as $root ) {
1439 if ( $root instanceof PPNode_DOM
) {
1440 $root = $root->node
;
1442 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1445 foreach ( $root as $node ) {
1451 $s .= $this->expand( $node );
1458 * Makes an object that, when expand()ed, will be the same as one obtained
1461 * @param string $sep
1462 * @param string|PPNode_DOM|DOMDocument $args,...
1465 public function virtualImplode( $sep /*, ... */ ) {
1466 $args = array_slice( func_get_args(), 1 );
1470 foreach ( $args as $root ) {
1471 if ( $root instanceof PPNode_DOM
) {
1472 $root = $root->node
;
1474 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1477 foreach ( $root as $node ) {
1490 * Virtual implode with brackets
1491 * @param string $start
1492 * @param string $sep
1493 * @param string $end
1494 * @param string|PPNode_DOM|DOMDocument $args,...
1497 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1498 $args = array_slice( func_get_args(), 3 );
1502 foreach ( $args as $root ) {
1503 if ( $root instanceof PPNode_DOM
) {
1504 $root = $root->node
;
1506 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1509 foreach ( $root as $node ) {
1522 public function __toString() {
1526 public function getPDBK( $level = false ) {
1527 if ( $level === false ) {
1528 return $this->title
->getPrefixedDBkey();
1530 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1537 public function getArguments() {
1544 public function getNumberedArguments() {
1551 public function getNamedArguments() {
1556 * Returns true if there are no arguments in this frame
1560 public function isEmpty() {
1565 * @param int|string $name
1566 * @return bool Always false in this implementation.
1568 public function getArgument( $name ) {
1573 * Returns true if the infinite loop check is OK, false if a loop is detected
1575 * @param Title $title
1578 public function loopCheck( $title ) {
1579 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1583 * Return true if the frame is a template frame
1587 public function isTemplate() {
1592 * Get a title of frame
1596 public function getTitle() {
1597 return $this->title
;
1601 * Set the volatile flag
1605 public function setVolatile( $flag = true ) {
1606 $this->volatile
= $flag;
1610 * Get the volatile flag
1614 public function isVolatile() {
1615 return $this->volatile
;
1623 public function setTTL( $ttl ) {
1624 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1634 public function getTTL() {
1640 * Expansion frame with template arguments
1643 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1644 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1646 public $numberedArgs, $namedArgs;
1652 public $numberedExpansionCache, $namedExpansionCache;
1655 * @param Preprocessor $preprocessor
1656 * @param bool|PPFrame_DOM $parent
1657 * @param array $numberedArgs
1658 * @param array $namedArgs
1659 * @param bool|Title $title
1661 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1662 $namedArgs = [], $title = false
1664 parent
::__construct( $preprocessor );
1666 $this->parent
= $parent;
1667 $this->numberedArgs
= $numberedArgs;
1668 $this->namedArgs
= $namedArgs;
1669 $this->title
= $title;
1670 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1671 $this->titleCache
= $parent->titleCache
;
1672 $this->titleCache
[] = $pdbk;
1673 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1674 if ( $pdbk !== false ) {
1675 $this->loopCheckHash
[$pdbk] = true;
1677 $this->depth
= $parent->depth +
1;
1678 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1681 public function __toString() {
1684 $args = $this->numberedArgs +
$this->namedArgs
;
1685 foreach ( $args as $name => $value ) {
1691 $s .= "\"$name\":\"" .
1692 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1699 * @throws MWException
1700 * @param string|int $key
1701 * @param string|PPNode_DOM|DOMDocument $root
1705 public function cachedExpand( $key, $root, $flags = 0 ) {
1706 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1707 return $this->parent
->childExpansionCache
[$key];
1709 $retval = $this->expand( $root, $flags );
1710 if ( !$this->isVolatile() ) {
1711 $this->parent
->childExpansionCache
[$key] = $retval;
1717 * Returns true if there are no arguments in this frame
1721 public function isEmpty() {
1722 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1725 public function getArguments() {
1727 foreach ( array_merge(
1728 array_keys( $this->numberedArgs
),
1729 array_keys( $this->namedArgs
) ) as $key ) {
1730 $arguments[$key] = $this->getArgument( $key );
1735 public function getNumberedArguments() {
1737 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1738 $arguments[$key] = $this->getArgument( $key );
1743 public function getNamedArguments() {
1745 foreach ( array_keys( $this->namedArgs
) as $key ) {
1746 $arguments[$key] = $this->getArgument( $key );
1753 * @return string|bool
1755 public function getNumberedArgument( $index ) {
1756 if ( !isset( $this->numberedArgs
[$index] ) ) {
1759 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1760 # No trimming for unnamed arguments
1761 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1762 $this->numberedArgs
[$index],
1763 PPFrame
::STRIP_COMMENTS
1766 return $this->numberedExpansionCache
[$index];
1770 * @param string $name
1771 * @return string|bool
1773 public function getNamedArgument( $name ) {
1774 if ( !isset( $this->namedArgs
[$name] ) ) {
1777 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1778 # Trim named arguments post-expand, for backwards compatibility
1779 $this->namedExpansionCache
[$name] = trim(
1780 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1782 return $this->namedExpansionCache
[$name];
1786 * @param int|string $name
1787 * @return string|bool
1789 public function getArgument( $name ) {
1790 $text = $this->getNumberedArgument( $name );
1791 if ( $text === false ) {
1792 $text = $this->getNamedArgument( $name );
1798 * Return true if the frame is a template frame
1802 public function isTemplate() {
1806 public function setVolatile( $flag = true ) {
1807 parent
::setVolatile( $flag );
1808 $this->parent
->setVolatile( $flag );
1811 public function setTTL( $ttl ) {
1812 parent
::setTTL( $ttl );
1813 $this->parent
->setTTL( $ttl );
1818 * Expansion frame with custom arguments
1821 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1822 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1826 public function __construct( $preprocessor, $args ) {
1827 parent
::__construct( $preprocessor );
1828 $this->args
= $args;
1831 public function __toString() {
1834 foreach ( $this->args
as $name => $value ) {
1840 $s .= "\"$name\":\"" .
1841 str_replace( '"', '\\"', $value->__toString() ) . '"';
1850 public function isEmpty() {
1851 return !count( $this->args
);
1855 * @param int|string $index
1856 * @return string|bool
1858 public function getArgument( $index ) {
1859 if ( !isset( $this->args
[$index] ) ) {
1862 return $this->args
[$index];
1865 public function getArguments() {
1873 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1874 class PPNode_DOM
implements PPNode
{
1882 public function __construct( $node, $xpath = false ) {
1883 $this->node
= $node;
1889 public function getXPath() {
1890 if ( $this->xpath
=== null ) {
1891 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1893 return $this->xpath
;
1896 public function __toString() {
1897 if ( $this->node
instanceof DOMNodeList
) {
1899 foreach ( $this->node
as $node ) {
1900 $s .= $node->ownerDocument
->saveXML( $node );
1903 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1909 * @return bool|PPNode_DOM
1911 public function getChildren() {
1912 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1916 * @return bool|PPNode_DOM
1918 public function getFirstChild() {
1919 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1923 * @return bool|PPNode_DOM
1925 public function getNextSibling() {
1926 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1930 * @param string $type
1932 * @return bool|PPNode_DOM
1934 public function getChildrenOfType( $type ) {
1935 return new self( $this->getXPath()->query( $type, $this->node
) );
1941 public function getLength() {
1942 if ( $this->node
instanceof DOMNodeList
) {
1943 return $this->node
->length
;
1951 * @return bool|PPNode_DOM
1953 public function item( $i ) {
1954 $item = $this->node
->item( $i );
1955 return $item ?
new self( $item ) : false;
1961 public function getName() {
1962 if ( $this->node
instanceof DOMNodeList
) {
1965 return $this->node
->nodeName
;
1970 * Split a "<part>" node into an associative array containing:
1971 * - name PPNode name
1972 * - index String index
1973 * - value PPNode value
1975 * @throws MWException
1978 public function splitArg() {
1979 $xpath = $this->getXPath();
1980 $names = $xpath->query( 'name', $this->node
);
1981 $values = $xpath->query( 'value', $this->node
);
1982 if ( !$names->length ||
!$values->length
) {
1983 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1985 $name = $names->item( 0 );
1986 $index = $name->getAttribute( 'index' );
1988 'name' => new self( $name ),
1990 'value' => new self( $values->item( 0 ) ) ];
1994 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1995 * All values in the resulting array are PPNodes. Inner and close are optional.
1997 * @throws MWException
2000 public function splitExt() {
2001 $xpath = $this->getXPath();
2002 $names = $xpath->query( 'name', $this->node
);
2003 $attrs = $xpath->query( 'attr', $this->node
);
2004 $inners = $xpath->query( 'inner', $this->node
);
2005 $closes = $xpath->query( 'close', $this->node
);
2006 if ( !$names->length ||
!$attrs->length
) {
2007 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
2010 'name' => new self( $names->item( 0 ) ),
2011 'attr' => new self( $attrs->item( 0 ) ) ];
2012 if ( $inners->length
) {
2013 $parts['inner'] = new self( $inners->item( 0 ) );
2015 if ( $closes->length
) {
2016 $parts['close'] = new self( $closes->item( 0 ) );
2022 * Split a "<h>" node
2023 * @throws MWException
2026 public function splitHeading() {
2027 if ( $this->getName() !== 'h' ) {
2028 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2031 'i' => $this->node
->getAttribute( 'i' ),
2032 'level' => $this->node
->getAttribute( 'level' ),
2033 'contents' => $this->getChildren()