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 Wikimedia\
suppressWarnings();
90 $result = $dom->loadXML( $xml );
91 Wikimedia\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 Wikimedia\
suppressWarnings();
167 $result = $dom->loadXML( $xml );
168 Wikimedia\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 );
800 # Output any remaining unclosed brackets
801 foreach ( $stack->stack
as $piece ) {
802 $stack->rootAccum
.= $piece->breakSyntax();
804 $stack->rootAccum
.= '</root>';
805 $xml = $stack->rootAccum
;
812 * Stack class to help Preprocessor::preprocessToObj()
816 public $stack, $rootAccum;
823 public $elementClass = PPDStackElement
::class;
825 public static $false = false;
827 public function __construct() {
830 $this->rootAccum
= '';
831 $this->accum
=& $this->rootAccum
;
837 public function count() {
838 return count( $this->stack
);
841 public function &getAccum() {
845 public function getCurrentPart() {
846 if ( $this->top
=== false ) {
849 return $this->top
->getCurrentPart();
853 public function push( $data ) {
854 if ( $data instanceof $this->elementClass
) {
855 $this->stack
[] = $data;
857 $class = $this->elementClass
;
858 $this->stack
[] = new $class( $data );
860 $this->top
= $this->stack
[count( $this->stack
) - 1];
861 $this->accum
=& $this->top
->getAccum();
864 public function pop() {
865 if ( !count( $this->stack
) ) {
866 throw new MWException( __METHOD__
. ': no elements remaining' );
868 $temp = array_pop( $this->stack
);
870 if ( count( $this->stack
) ) {
871 $this->top
= $this->stack
[count( $this->stack
) - 1];
872 $this->accum
=& $this->top
->getAccum();
874 $this->top
= self
::$false;
875 $this->accum
=& $this->rootAccum
;
880 public function addPart( $s = '' ) {
881 $this->top
->addPart( $s );
882 $this->accum
=& $this->top
->getAccum();
888 public function getFlags() {
889 if ( !count( $this->stack
) ) {
891 'findEquals' => false,
893 'inHeading' => false,
896 return $this->top
->getFlags();
904 class PPDStackElement
{
906 * @var string Opening character (\n for heading)
911 * @var string Matching closing character
916 * @var int Number of opening characters found (number of "=" for heading)
921 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
926 * @var bool True if the open char appeared at the start of the input line.
927 * Not set for headings.
931 public $partClass = PPDPart
::class;
933 public function __construct( $data = [] ) {
934 $class = $this->partClass
;
935 $this->parts
= [ new $class ];
937 foreach ( $data as $name => $value ) {
938 $this->$name = $value;
942 public function &getAccum() {
943 return $this->parts
[count( $this->parts
) - 1]->out
;
946 public function addPart( $s = '' ) {
947 $class = $this->partClass
;
948 $this->parts
[] = new $class( $s );
951 public function getCurrentPart() {
952 return $this->parts
[count( $this->parts
) - 1];
958 public function getFlags() {
959 $partCount = count( $this->parts
);
960 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
962 'findPipe' => $findPipe,
963 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
964 'inHeading' => $this->open
== "\n",
969 * Get the output string that would result if the close is not found.
971 * @param bool|int $openingCount
974 public function breakSyntax( $openingCount = false ) {
975 if ( $this->open
== "\n" ) {
976 $s = $this->parts
[0]->out
;
978 if ( $openingCount === false ) {
979 $openingCount = $this->count
;
981 $s = substr( $this->open
, 0, -1 );
983 substr( $this->open
, -1 ),
984 $openingCount - strlen( $s )
987 foreach ( $this->parts
as $part ) {
1005 * @var string Output accumulator string
1009 // Optional member variables:
1010 // eqpos Position of equals sign in output accumulator
1011 // commentEnd Past-the-end input pointer for the last comment encountered
1012 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
1014 public function __construct( $out = '' ) {
1020 * An expansion frame, used as a context to expand the result of preprocessToObj()
1023 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1024 class PPFrame_DOM
implements PPFrame
{
1029 public $preprocessor;
1043 * Hashtable listing templates which are disallowed for expansion in this frame,
1044 * having been encountered previously in parent frames.
1046 public $loopCheckHash;
1049 * Recursion depth of this frame, top = 0
1050 * Note that this is NOT the same as expansion depth in expand()
1054 private $volatile = false;
1055 private $ttl = null;
1060 protected $childExpansionCache;
1063 * Construct a new preprocessor frame.
1064 * @param Preprocessor $preprocessor The parent preprocessor
1066 public function __construct( $preprocessor ) {
1067 $this->preprocessor
= $preprocessor;
1068 $this->parser
= $preprocessor->parser
;
1069 $this->title
= $this->parser
->mTitle
;
1070 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
1071 $this->loopCheckHash
= [];
1073 $this->childExpansionCache
= [];
1077 * Create a new child frame
1078 * $args is optionally a multi-root PPNode or array containing the template arguments
1080 * @param bool|array $args
1081 * @param Title|bool $title
1082 * @param int $indexOffset
1083 * @return PPTemplateFrame_DOM
1085 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1088 if ( $title === false ) {
1089 $title = $this->title
;
1091 if ( $args !== false ) {
1093 if ( $args instanceof PPNode
) {
1094 $args = $args->node
;
1096 foreach ( $args as $arg ) {
1097 if ( $arg instanceof PPNode
) {
1100 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1101 $xpath = new DOMXPath( $arg->ownerDocument
);
1104 $nameNodes = $xpath->query( 'name', $arg );
1105 $value = $xpath->query( 'value', $arg );
1106 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1107 // Numbered parameter
1108 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1109 $index = $index - $indexOffset;
1110 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1111 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1112 wfEscapeWikiText( $this->title
),
1113 wfEscapeWikiText( $title ),
1114 wfEscapeWikiText( $index ) )->text() );
1115 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1117 $numberedArgs[$index] = $value->item( 0 );
1118 unset( $namedArgs[$index] );
1121 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1122 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1123 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1124 wfEscapeWikiText( $this->title
),
1125 wfEscapeWikiText( $title ),
1126 wfEscapeWikiText( $name ) )->text() );
1127 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1129 $namedArgs[$name] = $value->item( 0 );
1130 unset( $numberedArgs[$name] );
1134 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1138 * @throws MWException
1139 * @param string|int $key
1140 * @param string|PPNode_DOM|DOMDocument $root
1144 public function cachedExpand( $key, $root, $flags = 0 ) {
1145 // we don't have a parent, so we don't have a cache
1146 return $this->expand( $root, $flags );
1150 * @throws MWException
1151 * @param string|PPNode_DOM|DOMDocument $root
1155 public function expand( $root, $flags = 0 ) {
1156 static $expansionDepth = 0;
1157 if ( is_string( $root ) ) {
1161 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1162 $this->parser
->limitationWarn( 'node-count-exceeded',
1163 $this->parser
->mPPNodeCount
,
1164 $this->parser
->mOptions
->getMaxPPNodeCount()
1166 return '<span class="error">Node-count limit exceeded</span>';
1169 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1170 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1172 $this->parser
->mOptions
->getMaxPPExpandDepth()
1174 return '<span class="error">Expansion depth limit exceeded</span>';
1177 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1178 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1181 if ( $root instanceof PPNode_DOM
) {
1182 $root = $root->node
;
1184 if ( $root instanceof DOMDocument
) {
1185 $root = $root->documentElement
;
1188 $outStack = [ '', '' ];
1189 $iteratorStack = [ false, $root ];
1190 $indexStack = [ 0, 0 ];
1192 while ( count( $iteratorStack ) > 1 ) {
1193 $level = count( $outStack ) - 1;
1194 $iteratorNode =& $iteratorStack[$level];
1195 $out =& $outStack[$level];
1196 $index =& $indexStack[$level];
1198 if ( $iteratorNode instanceof PPNode_DOM
) {
1199 $iteratorNode = $iteratorNode->node
;
1202 if ( is_array( $iteratorNode ) ) {
1203 if ( $index >= count( $iteratorNode ) ) {
1204 // All done with this iterator
1205 $iteratorStack[$level] = false;
1206 $contextNode = false;
1208 $contextNode = $iteratorNode[$index];
1211 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1212 if ( $index >= $iteratorNode->length
) {
1213 // All done with this iterator
1214 $iteratorStack[$level] = false;
1215 $contextNode = false;
1217 $contextNode = $iteratorNode->item( $index );
1221 // Copy to $contextNode and then delete from iterator stack,
1222 // because this is not an iterator but we do have to execute it once
1223 $contextNode = $iteratorStack[$level];
1224 $iteratorStack[$level] = false;
1227 if ( $contextNode instanceof PPNode_DOM
) {
1228 $contextNode = $contextNode->node
;
1231 $newIterator = false;
1233 if ( $contextNode === false ) {
1235 } elseif ( is_string( $contextNode ) ) {
1236 $out .= $contextNode;
1237 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1238 $newIterator = $contextNode;
1239 } elseif ( $contextNode instanceof DOMNode
) {
1240 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1241 $out .= $contextNode->nodeValue
;
1242 } elseif ( $contextNode->nodeName
== 'template' ) {
1243 # Double-brace expansion
1244 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1245 $titles = $xpath->query( 'title', $contextNode );
1246 $title = $titles->item( 0 );
1247 $parts = $xpath->query( 'part', $contextNode );
1248 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1249 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1251 $lineStart = $contextNode->getAttribute( 'lineStart' );
1253 'title' => new PPNode_DOM( $title ),
1254 'parts' => new PPNode_DOM( $parts ),
1255 'lineStart' => $lineStart ];
1256 $ret = $this->parser
->braceSubstitution( $params, $this );
1257 if ( isset( $ret['object'] ) ) {
1258 $newIterator = $ret['object'];
1260 $out .= $ret['text'];
1263 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1264 # Triple-brace expansion
1265 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1266 $titles = $xpath->query( 'title', $contextNode );
1267 $title = $titles->item( 0 );
1268 $parts = $xpath->query( 'part', $contextNode );
1269 if ( $flags & PPFrame
::NO_ARGS
) {
1270 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1273 'title' => new PPNode_DOM( $title ),
1274 'parts' => new PPNode_DOM( $parts ) ];
1275 $ret = $this->parser
->argSubstitution( $params, $this );
1276 if ( isset( $ret['object'] ) ) {
1277 $newIterator = $ret['object'];
1279 $out .= $ret['text'];
1282 } elseif ( $contextNode->nodeName
== 'comment' ) {
1283 # HTML-style comment
1284 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1285 # Not in RECOVER_COMMENTS mode (msgnw) though.
1286 if ( ( $this->parser
->ot
['html']
1287 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1288 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1289 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1292 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1293 # Add a strip marker in PST mode so that pstPass2() can
1294 # run some old-fashioned regexes on the result.
1295 # Not in RECOVER_COMMENTS mode (extractSections) though.
1296 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1298 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1299 $out .= $contextNode->textContent
;
1301 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1302 # Output suppression used by <includeonly> etc.
1303 # OT_WIKI will only respect <ignore> in substed templates.
1304 # The other output types respect it unless NO_IGNORE is set.
1305 # extractSections() sets NO_IGNORE and so never respects it.
1306 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1307 ||
( $flags & PPFrame
::NO_IGNORE
)
1309 $out .= $contextNode->textContent
;
1313 } elseif ( $contextNode->nodeName
== 'ext' ) {
1315 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1316 $names = $xpath->query( 'name', $contextNode );
1317 $attrs = $xpath->query( 'attr', $contextNode );
1318 $inners = $xpath->query( 'inner', $contextNode );
1319 $closes = $xpath->query( 'close', $contextNode );
1320 if ( $flags & PPFrame
::NO_TAGS
) {
1321 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1322 if ( $attrs->length
> 0 ) {
1323 $s .= $this->expand( $attrs->item( 0 ), $flags );
1325 if ( $inners->length
> 0 ) {
1326 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1327 if ( $closes->length
> 0 ) {
1328 $s .= $this->expand( $closes->item( 0 ), $flags );
1336 'name' => new PPNode_DOM( $names->item( 0 ) ),
1337 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1338 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1339 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1341 $out .= $this->parser
->extensionSubstitution( $params, $this );
1343 } elseif ( $contextNode->nodeName
== 'h' ) {
1345 $s = $this->expand( $contextNode->childNodes
, $flags );
1347 # Insert a heading marker only for <h> children of <root>
1348 # This is to stop extractSections from going over multiple tree levels
1349 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1350 # Insert heading index marker
1351 $headingIndex = $contextNode->getAttribute( 'i' );
1352 $titleText = $this->title
->getPrefixedDBkey();
1353 $this->parser
->mHeadings
[] = [ $titleText, $headingIndex ];
1354 $serial = count( $this->parser
->mHeadings
) - 1;
1355 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1356 $count = $contextNode->getAttribute( 'level' );
1357 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1358 $this->parser
->mStripState
->addGeneral( $marker, '' );
1362 # Generic recursive expansion
1363 $newIterator = $contextNode->childNodes
;
1366 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1369 if ( $newIterator !== false ) {
1370 if ( $newIterator instanceof PPNode_DOM
) {
1371 $newIterator = $newIterator->node
;
1374 $iteratorStack[] = $newIterator;
1376 } elseif ( $iteratorStack[$level] === false ) {
1377 // Return accumulated value to parent
1378 // With tail recursion
1379 while ( $iteratorStack[$level] === false && $level > 0 ) {
1380 $outStack[$level - 1] .= $out;
1381 array_pop( $outStack );
1382 array_pop( $iteratorStack );
1383 array_pop( $indexStack );
1389 return $outStack[0];
1393 * @param string $sep
1395 * @param string|PPNode_DOM|DOMDocument $args,...
1398 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1399 $args = array_slice( func_get_args(), 2 );
1403 foreach ( $args as $root ) {
1404 if ( $root instanceof PPNode_DOM
) {
1405 $root = $root->node
;
1407 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1410 foreach ( $root as $node ) {
1416 $s .= $this->expand( $node, $flags );
1423 * Implode with no flags specified
1424 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1426 * @param string $sep
1427 * @param string|PPNode_DOM|DOMDocument $args,...
1430 public function implode( $sep /*, ... */ ) {
1431 $args = array_slice( func_get_args(), 1 );
1435 foreach ( $args as $root ) {
1436 if ( $root instanceof PPNode_DOM
) {
1437 $root = $root->node
;
1439 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1442 foreach ( $root as $node ) {
1448 $s .= $this->expand( $node );
1455 * Makes an object that, when expand()ed, will be the same as one obtained
1458 * @param string $sep
1459 * @param string|PPNode_DOM|DOMDocument $args,...
1462 public function virtualImplode( $sep /*, ... */ ) {
1463 $args = array_slice( func_get_args(), 1 );
1467 foreach ( $args as $root ) {
1468 if ( $root instanceof PPNode_DOM
) {
1469 $root = $root->node
;
1471 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1474 foreach ( $root as $node ) {
1487 * Virtual implode with brackets
1488 * @param string $start
1489 * @param string $sep
1490 * @param string $end
1491 * @param string|PPNode_DOM|DOMDocument $args,...
1494 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1495 $args = array_slice( func_get_args(), 3 );
1499 foreach ( $args as $root ) {
1500 if ( $root instanceof PPNode_DOM
) {
1501 $root = $root->node
;
1503 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1506 foreach ( $root as $node ) {
1519 public function __toString() {
1523 public function getPDBK( $level = false ) {
1524 if ( $level === false ) {
1525 return $this->title
->getPrefixedDBkey();
1527 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1534 public function getArguments() {
1541 public function getNumberedArguments() {
1548 public function getNamedArguments() {
1553 * Returns true if there are no arguments in this frame
1557 public function isEmpty() {
1562 * @param int|string $name
1563 * @return bool Always false in this implementation.
1565 public function getArgument( $name ) {
1570 * Returns true if the infinite loop check is OK, false if a loop is detected
1572 * @param Title $title
1575 public function loopCheck( $title ) {
1576 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1580 * Return true if the frame is a template frame
1584 public function isTemplate() {
1589 * Get a title of frame
1593 public function getTitle() {
1594 return $this->title
;
1598 * Set the volatile flag
1602 public function setVolatile( $flag = true ) {
1603 $this->volatile
= $flag;
1607 * Get the volatile flag
1611 public function isVolatile() {
1612 return $this->volatile
;
1620 public function setTTL( $ttl ) {
1621 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1631 public function getTTL() {
1637 * Expansion frame with template arguments
1640 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1641 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1643 public $numberedArgs, $namedArgs;
1649 public $numberedExpansionCache, $namedExpansionCache;
1652 * @param Preprocessor $preprocessor
1653 * @param bool|PPFrame_DOM $parent
1654 * @param array $numberedArgs
1655 * @param array $namedArgs
1656 * @param bool|Title $title
1658 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1659 $namedArgs = [], $title = false
1661 parent
::__construct( $preprocessor );
1663 $this->parent
= $parent;
1664 $this->numberedArgs
= $numberedArgs;
1665 $this->namedArgs
= $namedArgs;
1666 $this->title
= $title;
1667 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1668 $this->titleCache
= $parent->titleCache
;
1669 $this->titleCache
[] = $pdbk;
1670 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1671 if ( $pdbk !== false ) {
1672 $this->loopCheckHash
[$pdbk] = true;
1674 $this->depth
= $parent->depth +
1;
1675 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1678 public function __toString() {
1681 $args = $this->numberedArgs +
$this->namedArgs
;
1682 foreach ( $args as $name => $value ) {
1688 $s .= "\"$name\":\"" .
1689 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1696 * @throws MWException
1697 * @param string|int $key
1698 * @param string|PPNode_DOM|DOMDocument $root
1702 public function cachedExpand( $key, $root, $flags = 0 ) {
1703 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1704 return $this->parent
->childExpansionCache
[$key];
1706 $retval = $this->expand( $root, $flags );
1707 if ( !$this->isVolatile() ) {
1708 $this->parent
->childExpansionCache
[$key] = $retval;
1714 * Returns true if there are no arguments in this frame
1718 public function isEmpty() {
1719 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1722 public function getArguments() {
1724 foreach ( array_merge(
1725 array_keys( $this->numberedArgs
),
1726 array_keys( $this->namedArgs
) ) as $key ) {
1727 $arguments[$key] = $this->getArgument( $key );
1732 public function getNumberedArguments() {
1734 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1735 $arguments[$key] = $this->getArgument( $key );
1740 public function getNamedArguments() {
1742 foreach ( array_keys( $this->namedArgs
) as $key ) {
1743 $arguments[$key] = $this->getArgument( $key );
1750 * @return string|bool
1752 public function getNumberedArgument( $index ) {
1753 if ( !isset( $this->numberedArgs
[$index] ) ) {
1756 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1757 # No trimming for unnamed arguments
1758 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1759 $this->numberedArgs
[$index],
1760 PPFrame
::STRIP_COMMENTS
1763 return $this->numberedExpansionCache
[$index];
1767 * @param string $name
1768 * @return string|bool
1770 public function getNamedArgument( $name ) {
1771 if ( !isset( $this->namedArgs
[$name] ) ) {
1774 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1775 # Trim named arguments post-expand, for backwards compatibility
1776 $this->namedExpansionCache
[$name] = trim(
1777 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1779 return $this->namedExpansionCache
[$name];
1783 * @param int|string $name
1784 * @return string|bool
1786 public function getArgument( $name ) {
1787 $text = $this->getNumberedArgument( $name );
1788 if ( $text === false ) {
1789 $text = $this->getNamedArgument( $name );
1795 * Return true if the frame is a template frame
1799 public function isTemplate() {
1803 public function setVolatile( $flag = true ) {
1804 parent
::setVolatile( $flag );
1805 $this->parent
->setVolatile( $flag );
1808 public function setTTL( $ttl ) {
1809 parent
::setTTL( $ttl );
1810 $this->parent
->setTTL( $ttl );
1815 * Expansion frame with custom arguments
1818 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1819 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1823 public function __construct( $preprocessor, $args ) {
1824 parent
::__construct( $preprocessor );
1825 $this->args
= $args;
1828 public function __toString() {
1831 foreach ( $this->args
as $name => $value ) {
1837 $s .= "\"$name\":\"" .
1838 str_replace( '"', '\\"', $value->__toString() ) . '"';
1847 public function isEmpty() {
1848 return !count( $this->args
);
1852 * @param int|string $index
1853 * @return string|bool
1855 public function getArgument( $index ) {
1856 if ( !isset( $this->args
[$index] ) ) {
1859 return $this->args
[$index];
1862 public function getArguments() {
1870 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1871 class PPNode_DOM
implements PPNode
{
1879 public function __construct( $node, $xpath = false ) {
1880 $this->node
= $node;
1886 public function getXPath() {
1887 if ( $this->xpath
=== null ) {
1888 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1890 return $this->xpath
;
1893 public function __toString() {
1894 if ( $this->node
instanceof DOMNodeList
) {
1896 foreach ( $this->node
as $node ) {
1897 $s .= $node->ownerDocument
->saveXML( $node );
1900 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1906 * @return bool|PPNode_DOM
1908 public function getChildren() {
1909 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1913 * @return bool|PPNode_DOM
1915 public function getFirstChild() {
1916 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1920 * @return bool|PPNode_DOM
1922 public function getNextSibling() {
1923 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1927 * @param string $type
1929 * @return bool|PPNode_DOM
1931 public function getChildrenOfType( $type ) {
1932 return new self( $this->getXPath()->query( $type, $this->node
) );
1938 public function getLength() {
1939 if ( $this->node
instanceof DOMNodeList
) {
1940 return $this->node
->length
;
1948 * @return bool|PPNode_DOM
1950 public function item( $i ) {
1951 $item = $this->node
->item( $i );
1952 return $item ?
new self( $item ) : false;
1958 public function getName() {
1959 if ( $this->node
instanceof DOMNodeList
) {
1962 return $this->node
->nodeName
;
1967 * Split a "<part>" node into an associative array containing:
1968 * - name PPNode name
1969 * - index String index
1970 * - value PPNode value
1972 * @throws MWException
1975 public function splitArg() {
1976 $xpath = $this->getXPath();
1977 $names = $xpath->query( 'name', $this->node
);
1978 $values = $xpath->query( 'value', $this->node
);
1979 if ( !$names->length ||
!$values->length
) {
1980 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1982 $name = $names->item( 0 );
1983 $index = $name->getAttribute( 'index' );
1985 'name' => new self( $name ),
1987 'value' => new self( $values->item( 0 ) ) ];
1991 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1992 * All values in the resulting array are PPNodes. Inner and close are optional.
1994 * @throws MWException
1997 public function splitExt() {
1998 $xpath = $this->getXPath();
1999 $names = $xpath->query( 'name', $this->node
);
2000 $attrs = $xpath->query( 'attr', $this->node
);
2001 $inners = $xpath->query( 'inner', $this->node
);
2002 $closes = $xpath->query( 'close', $this->node
);
2003 if ( !$names->length ||
!$attrs->length
) {
2004 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
2007 'name' => new self( $names->item( 0 ) ),
2008 'attr' => new self( $attrs->item( 0 ) ) ];
2009 if ( $inners->length
) {
2010 $parts['inner'] = new self( $inners->item( 0 ) );
2012 if ( $closes->length
) {
2013 $parts['close'] = new self( $closes->item( 0 ) );
2019 * Split a "<h>" node
2020 * @throws MWException
2023 public function splitHeading() {
2024 if ( $this->getName() !== 'h' ) {
2025 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2028 'i' => $this->node
->getAttribute( 'i' ),
2029 'level' => $this->node
->getAttribute( 'level' ),
2030 'contents' => $this->getChildren()