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;
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();
94 $xml = UtfNormal\Validator::cleanUp( $xml );
97 $result = $dom->loadXML( $xml, 1 << 19 );
101 throw new MWException(
'Parameters passed to ' . __METHOD__ .
' result in invalid XML' );
104 $root = $dom->documentElement;
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;
151 if ( $xml ===
false ) {
158 $this->
parser->mGeneratedPPNodeCount += substr_count( $xml,
'<' );
159 $max = $this->
parser->mOptions->getMaxGeneratedPPNodeCount();
160 if ( $this->
parser->mGeneratedPPNodeCount > $max ) {
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();
171 $xml = UtfNormal\Validator::cleanUp( $xml );
174 $result = $dom->loadXML( $xml, 1 << 19 );
177 $obj =
new PPNode_DOM( $dom->documentElement );
183 throw new MWException( __METHOD__ .
' generated invalid XML' );
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 ) );
218 $elementsRegex =
"~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
222 $searchBase =
"[{<\n"; # }
228 $revText = strrev( $text );
229 $lengthText = strlen( $text );
234 $accum =& $stack->getAccum();
246 $noMoreClosingTag = [];
248 $findOnlyinclude = $enableOnlyinclude;
250 $fakeLineStart =
true;
255 if ( $findOnlyinclude ) {
257 $startPos = strpos( $text,
'<onlyinclude>', $i );
258 if ( $startPos ===
false ) {
260 $accum .=
'<ignore>' . htmlspecialchars( substr( $text, $i ) ) .
'</ignore>';
263 $tagEndPos = $startPos + strlen(
'<onlyinclude>' );
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 $currentClosing = $stack->top->close;
279 $search .= $currentClosing;
289 # Output literal section, advance input counter
290 $literalLength = strcspn( $text, $search, $i );
291 if ( $literalLength > 0 ) {
292 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
293 $i += $literalLength;
295 if ( $i >= $lengthText ) {
296 if ( $currentClosing ==
"\n" ) {
305 $curChar = $curTwoChar = $text[$i];
306 if ( ( $i + 1 ) < $lengthText ) {
307 $curTwoChar .= $text[$i + 1];
309 if ( $curChar ==
'|' ) {
311 } elseif ( $curChar ==
'=' ) {
313 } elseif ( $curChar ==
'<' ) {
315 } elseif ( $curChar ==
"\n" ) {
319 $found =
'line-start';
321 } elseif ( $curTwoChar == $currentClosing ) {
323 $curChar = $curTwoChar;
324 } elseif ( $curChar == $currentClosing ) {
326 } elseif ( isset( $this->rules[$curTwoChar] ) ) {
327 $curChar = $curTwoChar;
329 $rule = $this->rules[$curChar];
330 } elseif ( isset( $this->rules[$curChar] ) ) {
332 $rule = $this->rules[$curChar];
334 # Some versions of PHP have a strcspn which stops on
335 # null characters; ignore these and continue.
336 # We also may get '-' and '}' characters here which
337 # don't match -{ or $currentClosing. Add these to
338 # output and continue.
339 if ( $curChar ==
'-' || $curChar ==
'}' ) {
348 if ( $found ==
'angle' ) {
351 if ( $enableOnlyinclude
352 && substr( $text, $i, strlen(
'</onlyinclude>' ) ) ==
'</onlyinclude>'
354 $findOnlyinclude =
true;
359 if ( !preg_match( $elementsRegex, $text,
$matches, 0, $i + 1 ) ) {
373 $endPos = strpos( $text,
'-->', $i + 4 );
374 if ( $endPos ===
false ) {
376 $inner = substr( $text, $i );
377 $accum .=
'<comment>' . htmlspecialchars( $inner ) .
'</comment>';
381 $wsStart = $i ? ( $i - strspn( $revText,
" \t", $lengthText - $i ) ) : 0;
385 $wsEnd = $endPos + 2 + strspn( $text,
" \t", $endPos + 3 );
389 $comments = [ [ $wsStart, $wsEnd ] ];
390 while ( substr( $text, $wsEnd + 1, 4 ) ==
'<!--' ) {
391 $c = strpos( $text,
'-->', $wsEnd + 4 );
392 if ( $c ===
false ) {
395 $c = $c + 2 + strspn( $text,
" \t", $c + 3 );
396 $comments[] = [ $wsEnd + 1, $c ];
404 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) ==
"\n"
405 && substr( $text, $wsEnd + 1, 1 ) ==
"\n"
409 $wsLength = $i - $wsStart;
411 && strspn( $accum,
" \t", -$wsLength ) === $wsLength
413 $accum = substr( $accum, 0, -$wsLength );
417 foreach ( $comments
as $j => $com ) {
419 $endPos = $com[1] + 1;
420 if ( $j == (
count( $comments ) - 1 ) ) {
423 $inner = substr( $text, $startPos, $endPos - $startPos );
424 $accum .=
'<comment>' . htmlspecialchars( $inner ) .
'</comment>';
428 $fakeLineStart =
true;
436 $part = $stack->top->getCurrentPart();
437 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
438 $part->visualEnd = $wsStart;
441 $part->commentEnd = $endPos;
444 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
445 $accum .=
'<comment>' . htmlspecialchars( $inner ) .
'</comment>';
450 $lowerName = strtolower(
$name );
451 $attrStart = $i + strlen(
$name ) + 1;
454 $tagEndPos = $noMoreGT ?
false : strpos( $text,
'>', $attrStart );
455 if ( $tagEndPos ===
false ) {
465 if ( in_array( $lowerName, $ignoredTags ) ) {
467 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) )
474 if ( $text[$tagEndPos - 1] ==
'/' ) {
475 $attrEnd = $tagEndPos - 1;
480 $attrEnd = $tagEndPos;
483 !isset( $noMoreClosingTag[
$name] ) &&
484 preg_match(
"/<\/" . preg_quote(
$name,
'/' ) .
"\s*>/i",
485 $text,
$matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
487 $inner = substr( $text, $tagEndPos + 1,
$matches[0][1] - $tagEndPos - 1 );
489 $close =
'<close>' . htmlspecialchars(
$matches[0][0] ) .
'</close>';
492 if ( in_array(
$name, $xmlishAllowMissingEndTag ) ) {
494 $inner = substr( $text, $tagEndPos + 1 );
500 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos + 1 - $tagStartPos ) );
502 $noMoreClosingTag[
$name] =
true;
508 if ( in_array( $lowerName, $ignoredElements ) ) {
509 $accum .=
'<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
515 if ( $attrEnd <= $attrStart ) {
518 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
520 $accum .=
'<name>' . htmlspecialchars(
$name ) .
'</name>' .
523 '<attr>' . htmlspecialchars( $attr ) .
'</attr>';
524 if ( $inner !==
null ) {
525 $accum .=
'<inner>' . htmlspecialchars( $inner ) .
'</inner>';
527 $accum .= $close .
'</ext>';
528 } elseif ( $found ==
'line-start' ) {
531 if ( $fakeLineStart ) {
532 $fakeLineStart =
false;
538 $count = strspn( $text,
'=', $i, 6 );
539 if ( $count == 1 && $findEquals ) {
545 } elseif ( $count > 0 ) {
549 'parts' => [
new PPDPart( str_repeat(
'=', $count ) ) ],
552 $stack->push( $piece );
553 $accum =& $stack->getAccum();
554 $stackFlags = $stack->getFlags();
555 if ( isset( $stackFlags[
'findEquals'] ) ) {
556 $findEquals = $stackFlags[
'findEquals'];
558 if ( isset( $stackFlags[
'findPipe'] ) ) {
559 $findPipe = $stackFlags[
'findPipe'];
561 if ( isset( $stackFlags[
'inHeading'] ) ) {
562 $inHeading = $stackFlags[
'inHeading'];
566 } elseif ( $found ==
'line-end' ) {
567 $piece = $stack->top;
569 assert( $piece->open ===
"\n" );
570 $part = $piece->getCurrentPart();
574 $wsLength = strspn( $revText,
" \t", $lengthText - $i );
575 $searchStart = $i - $wsLength;
576 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
579 $searchStart = $part->visualEnd;
580 $searchStart -= strspn( $revText,
" \t", $lengthText - $searchStart );
582 $count = $piece->count;
583 $equalsLength = strspn( $revText,
'=', $lengthText - $searchStart );
584 if ( $equalsLength > 0 ) {
585 if ( $searchStart - $equalsLength == $piece->startPos ) {
589 $count = $equalsLength;
593 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
596 $count = min( $equalsLength, $count );
600 $element =
"<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
612 $accum =& $stack->getAccum();
613 $stackFlags = $stack->getFlags();
614 if ( isset( $stackFlags[
'findEquals'] ) ) {
615 $findEquals = $stackFlags[
'findEquals'];
617 if ( isset( $stackFlags[
'findPipe'] ) ) {
618 $findPipe = $stackFlags[
'findPipe'];
620 if ( isset( $stackFlags[
'inHeading'] ) ) {
621 $inHeading = $stackFlags[
'inHeading'];
631 } elseif ( $found ==
'open' ) {
632 # count opening brace characters
633 $curLen = strlen( $curChar );
634 $count = ( $curLen > 1 ) ?
635 # allow the
final character to repeat
636 strspn( $text, $curChar[$curLen - 1], $i + 1 ) + 1 :
637 strspn( $text, $curChar, $i );
640 $lineStart = ( $i > 0 && $text[$i - 1] ==
"\n" );
642 if ( $curChar ===
"-{" && $count > $curLen ) {
648 $rule = $this->rules[$curChar];
651 # we need to add to stack only if opening brace count is enough for one of the rules
652 if ( $count >= $rule[
'min'] ) {
653 # Add it to the stack
656 'close' => $rule[
'end'],
657 'savedPrefix' => $savedPrefix,
659 'lineStart' => $lineStart,
662 $stack->push( $piece );
663 $accum =& $stack->getAccum();
664 $stackFlags = $stack->getFlags();
665 if ( isset( $stackFlags[
'findEquals'] ) ) {
666 $findEquals = $stackFlags[
'findEquals'];
668 if ( isset( $stackFlags[
'findPipe'] ) ) {
669 $findPipe = $stackFlags[
'findPipe'];
671 if ( isset( $stackFlags[
'inHeading'] ) ) {
672 $inHeading = $stackFlags[
'inHeading'];
675 # Add literal brace(s)
676 $accum .= htmlspecialchars( $savedPrefix . str_repeat( $curChar, $count ) );
679 } elseif ( $found ==
'close' ) {
680 $piece = $stack->top;
681 # lets check if there are enough characters for closing brace
682 $maxCount = $piece->count;
683 if ( $piece->close ===
'}-' && $curChar ===
'}' ) {
684 $maxCount--; # don
't try to match closing '-
' as a '}
'
686 $curLen = strlen( $curChar );
687 $count = ( $curLen > 1 ) ? $curLen :
688 strspn( $text, $curChar, $i, $maxCount );
690 # check for maximum matching characters (if there are 5 closing
691 # characters, we will probably need only 3 - depending on the rules)
692 $rule = $this->rules[$piece->open];
693 if ( $count > $rule['max
'] ) {
694 # The specified maximum exists in the callback array, unless the caller
696 $matchingCount = $rule['max
'];
698 # Count is less than the maximum
699 # Skip any gaps in the callback array to find the true largest match
700 # Need to use array_key_exists not isset because the callback can be null
701 $matchingCount = $count;
702 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
707 if ( $matchingCount <= 0 ) {
708 # No matching element found in callback array
709 # Output a literal closing brace and continue
710 $endText = substr( $text, $i, $count );
711 $accum .= htmlspecialchars( $endText );
715 $name = $rule['names'][$matchingCount];
716 if ( $name === null ) {
717 // No element, just literal text
718 $endText = substr( $text, $i, $matchingCount );
719 $element = $piece->breakSyntax( $matchingCount ) . $endText;
722 # Note: $parts is already XML, does not need to be encoded further
723 $parts = $piece->parts;
724 $title = $parts[0]->out;
727 # The invocation is at the start of the line if lineStart is set in
728 # the stack, and all opening brackets are used up.
729 if ( $maxCount == $matchingCount &&
730 !empty( $piece->lineStart ) &&
731 strlen( $piece->savedPrefix ) == 0 ) {
732 $attr = ' lineStart=
"1"';
737 $element = "<$name$attr>";
738 $element .= "<title>$title</title>";
740 foreach ( $parts as $part ) {
741 if ( isset( $part->eqpos ) ) {
742 $argName = substr( $part->out, 0, $part->eqpos );
743 $argValue = substr( $part->out, $part->eqpos + 1 );
744 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
746 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
750 $element .= "</$name>";
753 # Advance input pointer
754 $i += $matchingCount;
758 $accum =& $stack->getAccum();
760 # Re-add the old stack element if it still has unmatched opening characters remaining
761 if ( $matchingCount < $piece->count ) {
762 $piece->parts = [ new PPDPart ];
763 $piece->count -= $matchingCount;
764 # do we still qualify for any callback with remaining count?
765 $min = $this->rules[$piece->open]['min
'];
766 if ( $piece->count >= $min ) {
767 $stack->push( $piece );
768 $accum =& $stack->getAccum();
769 } elseif ( $piece->count == 1 && $piece->open === '{
' && $piece->savedPrefix === '-
' ) {
770 $piece->savedPrefix = '';
773 $piece->close = $this->rules[$piece->open]['end
'];
774 $stack->push( $piece );
775 $accum =& $stack->getAccum();
777 $s = substr( $piece->open, 0, -1 );
779 substr( $piece->open, -1 ),
780 $piece->count - strlen( $s )
782 $accum .= $piece->savedPrefix . $s;
784 } elseif ( $piece->savedPrefix !== '' ) {
785 $accum .= $piece->savedPrefix;
788 $stackFlags = $stack->getFlags();
789 if ( isset( $stackFlags['findEquals
'] ) ) {
790 $findEquals = $stackFlags['findEquals
'];
792 if ( isset( $stackFlags['findPipe
'] ) ) {
793 $findPipe = $stackFlags['findPipe
'];
795 if ( isset( $stackFlags['inHeading
'] ) ) {
796 $inHeading = $stackFlags['inHeading
'];
799 # Add XML element to the enclosing accumulator
801 } elseif ( $found == 'pipe
' ) {
802 $findEquals = true; // shortcut for getFlags()
804 $accum =& $stack->getAccum();
806 } elseif ( $found == 'equals
' ) {
807 $findEquals = false; // shortcut for getFlags()
808 $stack->getCurrentPart()->eqpos = strlen( $accum );
814 # Output any remaining unclosed brackets
815 foreach ( $stack->stack as $piece ) {
816 $stack->rootAccum .= $piece->breakSyntax();
818 $stack->rootAccum .= '</
root>
';
819 $xml = $stack->rootAccum;
830 public $stack, $rootAccum;
837 public $elementClass = PPDStackElement::class;
839 public static $false = false;
841 public function __construct() {
844 $this->rootAccum = '';
845 $this->accum =& $this->rootAccum;
851 public function count() {
852 return count( $this->stack );
855 public function &getAccum() {
859 public function getCurrentPart() {
860 if ( $this->top === false ) {
863 return $this->top->getCurrentPart();
867 public function push( $data ) {
868 if ( $data instanceof $this->elementClass ) {
869 $this->stack[] = $data;
871 $class = $this->elementClass;
872 $this->stack[] = new $class( $data );
874 $this->top = $this->stack[count( $this->stack ) - 1];
875 $this->accum =& $this->top->getAccum();
878 public function pop() {
879 if ( !count( $this->stack ) ) {
880 throw new MWException( __METHOD__ . ': no elements remaining
' );
882 $temp = array_pop( $this->stack );
884 if ( count( $this->stack ) ) {
885 $this->top = $this->stack[count( $this->stack ) - 1];
886 $this->accum =& $this->top->getAccum();
888 $this->top = self::$false;
889 $this->accum =& $this->rootAccum;
894 public function addPart( $s = '' ) {
895 $this->top->addPart( $s );
896 $this->accum =& $this->top->getAccum();
902 public function getFlags() {
903 if ( !count( $this->stack ) ) {
905 'findEquals
' => false,
907 'inHeading
' => false,
910 return $this->top->getFlags();
918 class PPDStackElement {
933 public $savedPrefix = '';
951 public $partClass = PPDPart::class;
953 public function __construct( $data = [] ) {
954 $class = $this->partClass;
955 $this->parts = [ new $class ];
957 foreach ( $data as $name => $value ) {
958 $this->$name = $value;
962 public function &getAccum() {
963 return $this->parts[count( $this->parts ) - 1]->out;
966 public function addPart( $s = '' ) {
967 $class = $this->partClass;
968 $this->parts[] = new $class( $s );
971 public function getCurrentPart() {
972 return $this->parts[count( $this->parts ) - 1];
978 public function getFlags() {
979 $partCount = count( $this->parts );
980 $findPipe = $this->open != "\n" && $this->open != '[
';
982 'findPipe
' => $findPipe,
983 'findEquals
' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
984 'inHeading
' => $this->open == "\n",
994 public function breakSyntax( $openingCount = false ) {
995 if ( $this->open == "\n" ) {
996 $s = $this->savedPrefix . $this->parts[0]->out;
998 if ( $openingCount === false ) {
999 $openingCount = $this->count;
1001 $s = substr( $this->open, 0, -1 );
1003 substr( $this->open, -1 ),
1004 $openingCount - strlen( $s )
1006 $s = $this->savedPrefix . $s;
1008 foreach ( $this->parts as $part ) {
1030 // Optional member variables:
1031 // eqpos Position of equals sign in output accumulator
1032 // commentEnd Past-the-end input pointer for the last comment encountered
1033 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
1035 public function __construct( $out = '' ) {
1044 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1045 class PPFrame_DOM implements PPFrame {
1050 public $preprocessor;
1067 public $loopCheckHash;
1075 private $volatile = false;
1076 private $ttl = null;
1081 protected $childExpansionCache;
1087 public function __construct( $preprocessor ) {
1088 $this->preprocessor = $preprocessor;
1089 $this->parser = $preprocessor->parser;
1090 $this->title = $this->parser->mTitle;
1091 $this->titleCache = [ $this->title ? $this->title->getPrefixedDBkey() : false ];
1092 $this->loopCheckHash = [];
1094 $this->childExpansionCache = [];
1106 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1109 if ( $title === false ) {
1110 $title = $this->title;
1112 if ( $args !== false ) {
1114 if ( $args instanceof PPNode ) {
1115 $args = $args->node;
1117 foreach ( $args as $arg ) {
1118 if ( $arg instanceof PPNode ) {
1121 if ( !$xpath || $xpath->document !== $arg->ownerDocument ) {
1122 $xpath = new DOMXPath( $arg->ownerDocument );
1125 $nameNodes = $xpath->query( 'name', $arg );
1126 $value = $xpath->query( 'value', $arg );
1127 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1128 // Numbered parameter
1129 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index
' )->textContent;
1130 $index = $index - $indexOffset;
1131 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
1132 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-
args-warning
',
1133 wfEscapeWikiText( $this->title ),
1134 wfEscapeWikiText( $title ),
1135 wfEscapeWikiText( $index ) )->text() );
1136 $this->parser->addTrackingCategory( 'duplicate-
args-category
' );
1138 $numberedArgs[$index] = $value->item( 0 );
1139 unset( $namedArgs[$index] );
1142 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
1143 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
1144 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-
args-warning
',
1145 wfEscapeWikiText( $this->title ),
1146 wfEscapeWikiText( $title ),
1147 wfEscapeWikiText( $name ) )->text() );
1148 $this->parser->addTrackingCategory( 'duplicate-
args-category
' );
1150 $namedArgs[$name] = $value->item( 0 );
1151 unset( $numberedArgs[$name] );
1155 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1165 public function cachedExpand( $key, $root, $flags = 0 ) {
1166 // we don't have
a parent,
so we don
't have a cache
1167 return $this->expand( $root, $flags );
1176 public function expand( $root, $flags = 0 ) {
1177 static $expansionDepth = 0;
1178 if ( is_string( $root ) ) {
1182 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1183 $this->parser->limitationWarn( 'node-
count-exceeded
',
1184 $this->parser->mPPNodeCount,
1185 $this->parser->mOptions->getMaxPPNodeCount()
1187 return '<span
class=
"error">Node-
count limit exceeded</span>
';
1190 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1191 $this->parser->limitationWarn( 'expansion-depth-exceeded
',
1193 $this->parser->mOptions->getMaxPPExpandDepth()
1195 return '<span
class=
"error">Expansion depth limit exceeded</span>
';
1198 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1199 $this->parser->mHighestExpansionDepth = $expansionDepth;
1202 if ( $root instanceof PPNode_DOM ) {
1203 $root = $root->node;
1205 if ( $root instanceof DOMDocument ) {
1206 $root = $root->documentElement;
1209 $outStack = [ '', '' ];
1210 $iteratorStack = [ false, $root ];
1211 $indexStack = [ 0, 0 ];
1213 while ( count( $iteratorStack ) > 1 ) {
1214 $level = count( $outStack ) - 1;
1215 $iteratorNode =& $iteratorStack[$level];
1216 $out =& $outStack[$level];
1217 $index =& $indexStack[$level];
1219 if ( $iteratorNode instanceof PPNode_DOM ) {
1220 $iteratorNode = $iteratorNode->node;
1223 if ( is_array( $iteratorNode ) ) {
1224 if ( $index >= count( $iteratorNode ) ) {
1225 // All done with this iterator
1226 $iteratorStack[$level] = false;
1227 $contextNode = false;
1229 $contextNode = $iteratorNode[$index];
1232 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1233 if ( $index >= $iteratorNode->length ) {
1234 // All done with this iterator
1235 $iteratorStack[$level] = false;
1236 $contextNode = false;
1238 $contextNode = $iteratorNode->item( $index );
1242 // Copy to $contextNode and then delete from iterator stack,
1243 // because this is not an iterator but we do have to execute it once
1244 $contextNode = $iteratorStack[$level];
1245 $iteratorStack[$level] = false;
1248 if ( $contextNode instanceof PPNode_DOM ) {
1249 $contextNode = $contextNode->node;
1252 $newIterator = false;
1254 if ( $contextNode === false ) {
1256 } elseif ( is_string( $contextNode ) ) {
1257 $out .= $contextNode;
1258 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1259 $newIterator = $contextNode;
1260 } elseif ( $contextNode instanceof DOMNode ) {
1261 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1262 $out .= $contextNode->nodeValue;
1263 } elseif ( $contextNode->nodeName == 'template' ) {
1264 # Double-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_TEMPLATES ) {
1270 $newIterator = $this->virtualBracketedImplode( '{{
', '|
', '}}
', $title, $parts );
1272 $lineStart = $contextNode->getAttribute( 'lineStart
' );
1274 'title' => new PPNode_DOM( $title ),
1275 'parts
' => new PPNode_DOM( $parts ),
1276 'lineStart
' => $lineStart ];
1277 $ret = $this->parser->braceSubstitution( $params, $this );
1278 if ( isset( $ret['object'] ) ) {
1279 $newIterator = $ret['object'];
1281 $out .= $ret['text'];
1284 } elseif ( $contextNode->nodeName == 'tplarg
' ) {
1285 # Triple-brace expansion
1286 $xpath = new DOMXPath( $contextNode->ownerDocument );
1287 $titles = $xpath->query( 'title', $contextNode );
1288 $title = $titles->item( 0 );
1289 $parts = $xpath->query( 'part', $contextNode );
1290 if ( $flags & PPFrame::NO_ARGS ) {
1291 $newIterator = $this->virtualBracketedImplode( '{{{
', '|
', '}}}
', $title, $parts );
1294 'title' => new PPNode_DOM( $title ),
1295 'parts
' => new PPNode_DOM( $parts ) ];
1296 $ret = $this->parser->argSubstitution( $params, $this );
1297 if ( isset( $ret['object'] ) ) {
1298 $newIterator = $ret['object'];
1300 $out .= $ret['text'];
1303 } elseif ( $contextNode->nodeName == 'comment
' ) {
1304 # HTML-style comment
1305 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1306 # Not in RECOVER_COMMENTS mode (msgnw) though.
1307 if ( ( $this->parser->ot['html
']
1308 || ( $this->parser->ot['pre
'] && $this->parser->mOptions->getRemoveComments() )
1309 || ( $flags & PPFrame::STRIP_COMMENTS )
1310 ) && !( $flags & PPFrame::RECOVER_COMMENTS )
1313 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1314 # Add a strip marker in PST mode so that pstPass2() can
1315 # run some old-fashioned regexes on the result.
1316 # Not in RECOVER_COMMENTS mode (extractSections) though.
1317 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1319 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1320 $out .= $contextNode->textContent;
1322 } elseif ( $contextNode->nodeName == 'ignore
' ) {
1323 # Output suppression used by <includeonly> etc.
1324 # OT_WIKI will only respect <ignore> in substed templates.
1325 # The other output types respect it unless NO_IGNORE is set.
1326 # extractSections() sets NO_IGNORE and so never respects it.
1327 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1328 || ( $flags & PPFrame::NO_IGNORE )
1330 $out .= $contextNode->textContent;
1334 } elseif ( $contextNode->nodeName == 'ext
' ) {
1336 $xpath = new DOMXPath( $contextNode->ownerDocument );
1337 $names = $xpath->query( 'name', $contextNode );
1338 $attrs = $xpath->query( 'attr
', $contextNode );
1339 $inners = $xpath->query( 'inner
', $contextNode );
1340 $closes = $xpath->query( 'close
', $contextNode );
1341 if ( $flags & PPFrame::NO_TAGS ) {
1342 $s = '<
' . $this->expand( $names->item( 0 ), $flags );
1343 if ( $attrs->length > 0 ) {
1344 $s .= $this->expand( $attrs->item( 0 ), $flags );
1346 if ( $inners->length > 0 ) {
1347 $s .= '>
' . $this->expand( $inners->item( 0 ), $flags );
1348 if ( $closes->length > 0 ) {
1349 $s .= $this->expand( $closes->item( 0 ), $flags );
1357 'name' => new PPNode_DOM( $names->item( 0 ) ),
1358 'attr
' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1359 'inner
' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1360 'close
' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1362 $out .= $this->parser->extensionSubstitution( $params, $this );
1364 } elseif ( $contextNode->nodeName == 'h
' ) {
1366 $s = $this->expand( $contextNode->childNodes, $flags );
1368 # Insert a heading marker only for <h> children of <root>
1369 # This is to stop extractSections from going over multiple tree levels
1370 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html
'] ) {
1371 # Insert heading index marker
1372 $headingIndex = $contextNode->getAttribute( 'i
' );
1373 $titleText = $this->title->getPrefixedDBkey();
1374 $this->parser->mHeadings[] = [ $titleText, $headingIndex ];
1375 $serial = count( $this->parser->mHeadings ) - 1;
1376 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
1377 $count = $contextNode->getAttribute( 'level
' );
1378 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1379 $this->parser->mStripState->addGeneral( $marker, '' );
1383 # Generic recursive expansion
1384 $newIterator = $contextNode->childNodes;
1387 throw new MWException( __METHOD__ . ': Invalid parameter
type' );
1390 if ( $newIterator !== false ) {
1391 if ( $newIterator instanceof PPNode_DOM ) {
1392 $newIterator = $newIterator->node;
1395 $iteratorStack[] = $newIterator;
1397 } elseif ( $iteratorStack[$level] === false ) {
1398 // Return accumulated value to parent
1399 // With tail recursion
1400 while ( $iteratorStack[$level] === false && $level > 0 ) {
1401 $outStack[$level - 1] .= $out;
1402 array_pop( $outStack );
1403 array_pop( $iteratorStack );
1404 array_pop( $indexStack );
1410 return $outStack[0];
1419 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1420 $args = array_slice( func_get_args(), 2 );
1424 foreach ( $args as $root ) {
1425 if ( $root instanceof PPNode_DOM ) {
1426 $root = $root->node;
1428 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1431 foreach ( $root as $node ) {
1437 $s .= $this->expand( $node, $flags );
1451 public function implode( $sep /*, ... */ ) {
1452 $args = array_slice( func_get_args(), 1 );
1456 foreach ( $args as $root ) {
1457 if ( $root instanceof PPNode_DOM ) {
1458 $root = $root->node;
1460 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1463 foreach ( $root as $node ) {
1469 $s .= $this->expand( $node );
1483 public function virtualImplode( $sep /*, ... */ ) {
1484 $args = array_slice( func_get_args(), 1 );
1488 foreach ( $args as $root ) {
1489 if ( $root instanceof PPNode_DOM ) {
1490 $root = $root->node;
1492 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1495 foreach ( $root as $node ) {
1515 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1516 $args = array_slice( func_get_args(), 3 );
1520 foreach ( $args as $root ) {
1521 if ( $root instanceof PPNode_DOM ) {
1522 $root = $root->node;
1524 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1527 foreach ( $root as $node ) {
1540 public function __toString() {
1544 public function getPDBK( $level = false ) {
1545 if ( $level === false ) {
1546 return $this->title->getPrefixedDBkey();
1548 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1555 public function getArguments() {
1562 public function getNumberedArguments() {
1569 public function getNamedArguments() {
1578 public function isEmpty() {
1586 public function getArgument( $name ) {
1596 public function loopCheck( $title ) {
1597 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1605 public function isTemplate() {
1614 public function getTitle() {
1615 return $this->title;
1623 public function setVolatile( $flag = true ) {
1624 $this->volatile = $flag;
1632 public function isVolatile() {
1633 return $this->volatile;
1641 public function setTTL( $ttl ) {
1642 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1652 public function getTTL() {
1661 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1662 class PPTemplateFrame_DOM extends PPFrame_DOM {
1664 public $numberedArgs, $namedArgs;
1670 public $numberedExpansionCache, $namedExpansionCache;
1679 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1680 $namedArgs = [], $title = false
1682 parent::__construct( $preprocessor );
1684 $this->parent = $parent;
1685 $this->numberedArgs = $numberedArgs;
1686 $this->namedArgs = $namedArgs;
1687 $this->title = $title;
1688 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1689 $this->titleCache = $parent->titleCache;
1690 $this->titleCache[] = $pdbk;
1691 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1692 if ( $pdbk !== false ) {
1693 $this->loopCheckHash[$pdbk] = true;
1695 $this->depth = $parent->depth + 1;
1696 $this->numberedExpansionCache = $this->namedExpansionCache = [];
1699 public function __toString() {
1702 $args = $this->numberedArgs + $this->namedArgs;
1703 foreach ( $args as $name => $value ) {
1709 $s .= "\"$name\":\"" .
1710 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1723 public function cachedExpand( $key, $root, $flags = 0 ) {
1724 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1725 return $this->parent->childExpansionCache[$key];
1727 $retval = $this->expand( $root, $flags );
1728 if ( !$this->isVolatile() ) {
1729 $this->parent->childExpansionCache[$key] = $retval;
1739 public function isEmpty() {
1740 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1743 public function getArguments() {
1745 foreach ( array_merge(
1746 array_keys( $this->numberedArgs ),
1747 array_keys( $this->namedArgs ) ) as $key ) {
1748 $arguments[$key] = $this->getArgument( $key );
1753 public function getNumberedArguments() {
1755 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1756 $arguments[$key] = $this->getArgument( $key );
1761 public function getNamedArguments() {
1763 foreach ( array_keys( $this->namedArgs ) as $key ) {
1764 $arguments[$key] = $this->getArgument( $key );
1773 public function getNumberedArgument( $index ) {
1774 if ( !isset( $this->numberedArgs[$index] ) ) {
1777 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1778 # No trimming for unnamed arguments
1779 $this->numberedExpansionCache[$index] = $this->parent->expand(
1780 $this->numberedArgs[$index],
1781 PPFrame::STRIP_COMMENTS
1784 return $this->numberedExpansionCache[$index];
1791 public function getNamedArgument( $name ) {
1792 if ( !isset( $this->namedArgs[$name] ) ) {
1795 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1796 # Trim named arguments post-expand, for backwards compatibility
1797 $this->namedExpansionCache[$name] = trim(
1798 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1800 return $this->namedExpansionCache[$name];
1807 public function getArgument( $name ) {
1808 $text = $this->getNumberedArgument( $name );
1809 if ( $text === false ) {
1810 $text = $this->getNamedArgument( $name );
1820 public function isTemplate() {
1824 public function setVolatile( $flag = true ) {
1825 parent::setVolatile( $flag );
1826 $this->parent->setVolatile( $flag );
1829 public function setTTL( $ttl ) {
1830 parent::setTTL( $ttl );
1831 $this->parent->setTTL( $ttl );
1839 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1840 class PPCustomFrame_DOM extends PPFrame_DOM {
1844 public function __construct( $preprocessor, $args ) {
1845 parent::__construct( $preprocessor );
1846 $this->args = $args;
1849 public function __toString() {
1852 foreach ( $this->args as $name => $value ) {
1858 $s .= "\
"$name\":\"" .
1859 str_replace(
'"',
'\\"',
$value->__toString() ) .
'"';
1877 if ( !isset( $this->
args[$index] ) ) {
1880 return $this->
args[$index];
1901 $this->node = $node;
1908 if ( $this->xpath ===
null ) {
1909 $this->xpath =
new DOMXPath( $this->node->ownerDocument );
1911 return $this->xpath;
1915 if ( $this->node instanceof DOMNodeList ) {
1917 foreach ( $this->node
as $node ) {
1918 $s .= $node->ownerDocument->saveXML( $node );
1921 $s = $this->node->ownerDocument->saveXML( $this->node );
1930 return $this->node->childNodes ?
new self( $this->node->childNodes ) :
false;
1937 return $this->node->firstChild ?
new self( $this->node->firstChild ) :
false;
1944 return $this->node->nextSibling ?
new self( $this->node->nextSibling ) :
false;
1953 return new self( $this->getXPath()->query(
$type, $this->node ) );
1960 if ( $this->node instanceof DOMNodeList ) {
1961 return $this->node->length;
1972 $item = $this->node->item( $i );
1973 return $item ?
new self( $item ) :
false;
1980 if ( $this->node instanceof DOMNodeList ) {
1983 return $this->node->nodeName;
1997 $xpath = $this->getXPath();
1998 $names = $xpath->query(
'name', $this->node );
1999 $values = $xpath->query(
'value', $this->node );
2000 if ( !$names->length || !$values->length ) {
2001 throw new MWException(
'Invalid brace node passed to ' . __METHOD__ );
2003 $name = $names->item( 0 );
2004 $index =
$name->getAttribute(
'index' );
2006 'name' =>
new self(
$name ),
2008 'value' =>
new self( $values->item( 0 ) ) ];
2019 $xpath = $this->getXPath();
2020 $names = $xpath->query(
'name', $this->node );
2021 $attrs = $xpath->query(
'attr', $this->node );
2022 $inners = $xpath->query(
'inner', $this->node );
2023 $closes = $xpath->query(
'close', $this->node );
2024 if ( !$names->length || !$attrs->length ) {
2025 throw new MWException(
'Invalid ext node passed to ' . __METHOD__ );
2028 'name' =>
new self( $names->item( 0 ) ),
2029 'attr' =>
new self( $attrs->item( 0 ) ) ];
2030 if ( $inners->length ) {
2031 $parts[
'inner'] =
new self( $inners->item( 0 ) );
2033 if ( $closes->length ) {
2034 $parts[
'close'] =
new self( $closes->item( 0 ) );
2045 if ( $this->getName() !==
'h' ) {
2046 throw new MWException(
'Invalid h node passed to ' . __METHOD__ );
2049 'i' => $this->node->getAttribute(
'i' ),
2050 'level' => $this->node->getAttribute(
'level' ),
2051 'contents' => $this->getChildren()