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;
571 assert( $piece->open ===
"\n" );
572 $part = $piece->getCurrentPart();
576 $wsLength = strspn( $revText,
" \t", $lengthText - $i );
577 $searchStart = $i - $wsLength;
578 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
581 $searchStart = $part->visualEnd;
582 $searchStart -= strspn( $revText,
" \t", $lengthText - $searchStart );
584 $count = $piece->count;
585 $equalsLength = strspn( $revText,
'=', $lengthText - $searchStart );
586 if ( $equalsLength > 0 ) {
587 if ( $searchStart - $equalsLength == $piece->startPos ) {
591 $count = $equalsLength;
595 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
598 $count = min( $equalsLength, $count );
602 $element =
"<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
614 $accum =& $stack->getAccum();
615 $stackFlags = $stack->getFlags();
616 if ( isset( $stackFlags[
'findEquals'] ) ) {
617 $findEquals = $stackFlags[
'findEquals'];
619 if ( isset( $stackFlags[
'findPipe'] ) ) {
620 $findPipe = $stackFlags[
'findPipe'];
622 if ( isset( $stackFlags[
'inHeading'] ) ) {
623 $inHeading = $stackFlags[
'inHeading'];
633 } elseif ( $found ==
'open' ) {
634 # count opening brace characters
635 $curLen = strlen( $curChar );
636 $count = ( $curLen > 1 ) ?
637 # allow the
final character to repeat
638 strspn( $text, $curChar[$curLen - 1], $i + 1 ) + 1 :
639 strspn( $text, $curChar, $i );
642 $lineStart = ( $i > 0 && $text[$i - 1] ==
"\n" );
644 if ( $curChar ===
"-{" && $count > $curLen ) {
650 $rule = $this->rules[$curChar];
653 # we need to add to stack only if opening brace count is enough for one of the rules
654 if ( $count >= $rule[
'min'] ) {
655 # Add it to the stack
658 'close' => $rule[
'end'],
659 'savedPrefix' => $savedPrefix,
661 'lineStart' => $lineStart,
664 $stack->push( $piece );
665 $accum =& $stack->getAccum();
666 $stackFlags = $stack->getFlags();
667 if ( isset( $stackFlags[
'findEquals'] ) ) {
668 $findEquals = $stackFlags[
'findEquals'];
670 if ( isset( $stackFlags[
'findPipe'] ) ) {
671 $findPipe = $stackFlags[
'findPipe'];
673 if ( isset( $stackFlags[
'inHeading'] ) ) {
674 $inHeading = $stackFlags[
'inHeading'];
677 # Add literal brace(s)
678 $accum .= htmlspecialchars( $savedPrefix . str_repeat( $curChar, $count ) );
681 } elseif ( $found ==
'close' ) {
682 $piece = $stack->top;
683 # lets check if there are enough characters for closing brace
684 $maxCount = $piece->count;
685 if ( $piece->close ===
'}-' && $curChar ===
'}' ) {
686 $maxCount--; # don
't try to match closing '-
' as a '}
'
688 $curLen = strlen( $curChar );
689 $count = ( $curLen > 1 ) ? $curLen :
690 strspn( $text, $curChar, $i, $maxCount );
692 # check for maximum matching characters (if there are 5 closing
693 # characters, we will probably need only 3 - depending on the rules)
694 $rule = $this->rules[$piece->open];
695 if ( $count > $rule['max
'] ) {
696 # The specified maximum exists in the callback array, unless the caller
698 $matchingCount = $rule['max
'];
700 # Count is less than the maximum
701 # Skip any gaps in the callback array to find the true largest match
702 # Need to use array_key_exists not isset because the callback can be null
703 $matchingCount = $count;
704 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
709 if ( $matchingCount <= 0 ) {
710 # No matching element found in callback array
711 # Output a literal closing brace and continue
712 $endText = substr( $text, $i, $count );
713 $accum .= htmlspecialchars( $endText );
717 $name = $rule['names'][$matchingCount];
718 if ( $name === null ) {
719 // No element, just literal text
720 $endText = substr( $text, $i, $matchingCount );
721 $element = $piece->breakSyntax( $matchingCount ) . $endText;
724 # Note: $parts is already XML, does not need to be encoded further
725 $parts = $piece->parts;
726 $title = $parts[0]->out;
729 # The invocation is at the start of the line if lineStart is set in
730 # the stack, and all opening brackets are used up.
731 if ( $maxCount == $matchingCount &&
732 !empty( $piece->lineStart ) &&
733 strlen( $piece->savedPrefix ) == 0 ) {
734 $attr = ' lineStart=
"1"';
739 $element = "<$name$attr>";
740 $element .= "<title>$title</title>";
742 foreach ( $parts as $part ) {
743 if ( isset( $part->eqpos ) ) {
744 $argName = substr( $part->out, 0, $part->eqpos );
745 $argValue = substr( $part->out, $part->eqpos + 1 );
746 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
748 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
752 $element .= "</$name>";
755 # Advance input pointer
756 $i += $matchingCount;
760 $accum =& $stack->getAccum();
762 # Re-add the old stack element if it still has unmatched opening characters remaining
763 if ( $matchingCount < $piece->count ) {
764 $piece->parts = [ new PPDPart ];
765 $piece->count -= $matchingCount;
766 # do we still qualify for any callback with remaining count?
767 $min = $this->rules[$piece->open]['min
'];
768 if ( $piece->count >= $min ) {
769 $stack->push( $piece );
770 $accum =& $stack->getAccum();
771 } elseif ( $piece->count == 1 && $piece->open === '{
' && $piece->savedPrefix === '-
' ) {
772 $piece->savedPrefix = '';
775 $piece->close = $this->rules[$piece->open]['end
'];
776 $stack->push( $piece );
777 $accum =& $stack->getAccum();
779 $s = substr( $piece->open, 0, -1 );
781 substr( $piece->open, -1 ),
782 $piece->count - strlen( $s )
784 $accum .= $piece->savedPrefix . $s;
786 } elseif ( $piece->savedPrefix !== '' ) {
787 $accum .= $piece->savedPrefix;
790 $stackFlags = $stack->getFlags();
791 if ( isset( $stackFlags['findEquals
'] ) ) {
792 $findEquals = $stackFlags['findEquals
'];
794 if ( isset( $stackFlags['findPipe
'] ) ) {
795 $findPipe = $stackFlags['findPipe
'];
797 if ( isset( $stackFlags['inHeading
'] ) ) {
798 $inHeading = $stackFlags['inHeading
'];
801 # Add XML element to the enclosing accumulator
803 } elseif ( $found == 'pipe
' ) {
804 $findEquals = true; // shortcut for getFlags()
806 $accum =& $stack->getAccum();
808 } elseif ( $found == 'equals
' ) {
809 $findEquals = false; // shortcut for getFlags()
810 $stack->getCurrentPart()->eqpos = strlen( $accum );
816 # Output any remaining unclosed brackets
817 foreach ( $stack->stack as $piece ) {
818 $stack->rootAccum .= $piece->breakSyntax();
820 $stack->rootAccum .= '</
root>
';
821 $xml = $stack->rootAccum;
832 public $stack, $rootAccum;
839 public $elementClass = PPDStackElement::class;
841 public static $false = false;
843 public function __construct() {
846 $this->rootAccum = '';
847 $this->accum =& $this->rootAccum;
853 public function count() {
854 return count( $this->stack );
857 public function &getAccum() {
864 public function getCurrentPart() {
865 if ( $this->top === false ) {
868 return $this->top->getCurrentPart();
872 public function push( $data ) {
873 if ( $data instanceof $this->elementClass ) {
874 $this->stack[] = $data;
876 $class = $this->elementClass;
877 $this->stack[] = new $class( $data );
879 $this->top = $this->stack[count( $this->stack ) - 1];
880 $this->accum =& $this->top->getAccum();
883 public function pop() {
884 if ( $this->stack === [] ) {
885 throw new MWException( __METHOD__ . ': no elements remaining
' );
887 $temp = array_pop( $this->stack );
889 if ( count( $this->stack ) ) {
890 $this->top = $this->stack[count( $this->stack ) - 1];
891 $this->accum =& $this->top->getAccum();
893 $this->top = self::$false;
894 $this->accum =& $this->rootAccum;
899 public function addPart( $s = '' ) {
900 $this->top->addPart( $s );
901 $this->accum =& $this->top->getAccum();
907 public function getFlags() {
908 if ( $this->stack === [] ) {
910 'findEquals
' => false,
912 'inHeading
' => false,
915 return $this->top->getFlags();
923 class PPDStackElement {
938 public $savedPrefix = '';
956 public $partClass = PPDPart::class;
958 public function __construct( $data = [] ) {
959 $class = $this->partClass;
960 $this->parts = [ new $class ];
962 foreach ( $data as $name => $value ) {
963 $this->$name = $value;
967 public function &getAccum() {
968 return $this->parts[count( $this->parts ) - 1]->out;
971 public function addPart( $s = '' ) {
972 $class = $this->partClass;
973 $this->parts[] = new $class( $s );
979 public function getCurrentPart() {
980 return $this->parts[count( $this->parts ) - 1];
986 public function getFlags() {
987 $partCount = count( $this->parts );
988 $findPipe = $this->open != "\n" && $this->open != '[
';
990 'findPipe
' => $findPipe,
991 'findEquals
' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
992 'inHeading
' => $this->open == "\n",
1002 public function breakSyntax( $openingCount = false ) {
1003 if ( $this->open == "\n" ) {
1004 $s = $this->savedPrefix . $this->parts[0]->out;
1006 if ( $openingCount === false ) {
1007 $openingCount = $this->count;
1009 $s = substr( $this->open, 0, -1 );
1011 substr( $this->open, -1 ),
1012 $openingCount - strlen( $s )
1014 $s = $this->savedPrefix . $s;
1016 foreach ( $this->parts as $part ) {
1038 // Optional member variables:
1039 // eqpos Position of equals sign in output accumulator
1040 // commentEnd Past-the-end input pointer for the last comment encountered
1041 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
1043 public function __construct( $out = '' ) {
1052 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1053 class PPFrame_DOM implements PPFrame {
1058 public $preprocessor;
1075 public $loopCheckHash;
1083 private $volatile = false;
1084 private $ttl = null;
1089 protected $childExpansionCache;
1095 public function __construct( $preprocessor ) {
1096 $this->preprocessor = $preprocessor;
1097 $this->parser = $preprocessor->parser;
1098 $this->title = $this->parser->mTitle;
1099 $this->titleCache = [ $this->title ? $this->title->getPrefixedDBkey() : false ];
1100 $this->loopCheckHash = [];
1102 $this->childExpansionCache = [];
1114 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1117 if ( $title === false ) {
1118 $title = $this->title;
1120 if ( $args !== false ) {
1122 if ( $args instanceof PPNode ) {
1123 $args = $args->node;
1125 foreach ( $args as $arg ) {
1126 if ( $arg instanceof PPNode ) {
1129 if ( !$xpath || $xpath->document !== $arg->ownerDocument ) {
1130 $xpath = new DOMXPath( $arg->ownerDocument );
1133 $nameNodes = $xpath->query( 'name', $arg );
1134 $value = $xpath->query( 'value', $arg );
1135 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1136 // Numbered parameter
1137 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index
' )->textContent;
1138 $index = $index - $indexOffset;
1139 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
1140 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-
args-warning
',
1141 wfEscapeWikiText( $this->title ),
1142 wfEscapeWikiText( $title ),
1143 wfEscapeWikiText( $index ) )->text() );
1144 $this->parser->addTrackingCategory( 'duplicate-
args-category
' );
1146 $numberedArgs[$index] = $value->item( 0 );
1147 unset( $namedArgs[$index] );
1150 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
1151 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
1152 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-
args-warning
',
1153 wfEscapeWikiText( $this->title ),
1154 wfEscapeWikiText( $title ),
1155 wfEscapeWikiText( $name ) )->text() );
1156 $this->parser->addTrackingCategory( 'duplicate-
args-category
' );
1158 $namedArgs[$name] = $value->item( 0 );
1159 unset( $numberedArgs[$name] );
1163 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1173 public function cachedExpand( $key, $root, $flags = 0 ) {
1174 // we don't have
a parent,
so we don
't have a cache
1175 return $this->expand( $root, $flags );
1184 public function expand( $root, $flags = 0 ) {
1185 static $expansionDepth = 0;
1186 if ( is_string( $root ) ) {
1190 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1191 $this->parser->limitationWarn( 'node-
count-exceeded
',
1192 $this->parser->mPPNodeCount,
1193 $this->parser->mOptions->getMaxPPNodeCount()
1195 return '<span
class=
"error">Node-
count limit exceeded</span>
';
1198 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1199 $this->parser->limitationWarn( 'expansion-depth-exceeded
',
1201 $this->parser->mOptions->getMaxPPExpandDepth()
1203 return '<span
class=
"error">Expansion depth limit exceeded</span>
';
1206 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1207 $this->parser->mHighestExpansionDepth = $expansionDepth;
1210 if ( $root instanceof PPNode_DOM ) {
1211 $root = $root->node;
1213 if ( $root instanceof DOMDocument ) {
1214 $root = $root->documentElement;
1217 $outStack = [ '', '' ];
1218 $iteratorStack = [ false, $root ];
1219 $indexStack = [ 0, 0 ];
1221 while ( count( $iteratorStack ) > 1 ) {
1222 $level = count( $outStack ) - 1;
1223 $iteratorNode =& $iteratorStack[$level];
1224 $out =& $outStack[$level];
1225 $index =& $indexStack[$level];
1227 if ( $iteratorNode instanceof PPNode_DOM ) {
1228 $iteratorNode = $iteratorNode->node;
1231 if ( is_array( $iteratorNode ) ) {
1232 if ( $index >= count( $iteratorNode ) ) {
1233 // All done with this iterator
1234 $iteratorStack[$level] = false;
1235 $contextNode = false;
1237 $contextNode = $iteratorNode[$index];
1240 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1241 if ( $index >= $iteratorNode->length ) {
1242 // All done with this iterator
1243 $iteratorStack[$level] = false;
1244 $contextNode = false;
1246 $contextNode = $iteratorNode->item( $index );
1250 // Copy to $contextNode and then delete from iterator stack,
1251 // because this is not an iterator but we do have to execute it once
1252 $contextNode = $iteratorStack[$level];
1253 $iteratorStack[$level] = false;
1256 if ( $contextNode instanceof PPNode_DOM ) {
1257 $contextNode = $contextNode->node;
1260 $newIterator = false;
1262 if ( $contextNode === false ) {
1264 } elseif ( is_string( $contextNode ) ) {
1265 $out .= $contextNode;
1266 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1267 $newIterator = $contextNode;
1268 } elseif ( $contextNode instanceof DOMNode ) {
1269 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1270 $out .= $contextNode->nodeValue;
1271 } elseif ( $contextNode->nodeName == 'template' ) {
1272 # Double-brace expansion
1273 $xpath = new DOMXPath( $contextNode->ownerDocument );
1274 $titles = $xpath->query( 'title', $contextNode );
1275 $title = $titles->item( 0 );
1276 $parts = $xpath->query( 'part', $contextNode );
1277 if ( $flags & PPFrame::NO_TEMPLATES ) {
1278 $newIterator = $this->virtualBracketedImplode( '{{
', '|
', '}}
', $title, $parts );
1280 $lineStart = $contextNode->getAttribute( 'lineStart
' );
1282 'title' => new PPNode_DOM( $title ),
1283 'parts
' => new PPNode_DOM( $parts ),
1284 'lineStart
' => $lineStart ];
1285 $ret = $this->parser->braceSubstitution( $params, $this );
1286 if ( isset( $ret['object'] ) ) {
1287 $newIterator = $ret['object'];
1289 $out .= $ret['text'];
1292 } elseif ( $contextNode->nodeName == 'tplarg
' ) {
1293 # Triple-brace expansion
1294 $xpath = new DOMXPath( $contextNode->ownerDocument );
1295 $titles = $xpath->query( 'title', $contextNode );
1296 $title = $titles->item( 0 );
1297 $parts = $xpath->query( 'part', $contextNode );
1298 if ( $flags & PPFrame::NO_ARGS ) {
1299 $newIterator = $this->virtualBracketedImplode( '{{{
', '|
', '}}}
', $title, $parts );
1302 'title' => new PPNode_DOM( $title ),
1303 'parts
' => new PPNode_DOM( $parts ) ];
1304 $ret = $this->parser->argSubstitution( $params, $this );
1305 if ( isset( $ret['object'] ) ) {
1306 $newIterator = $ret['object'];
1308 $out .= $ret['text'];
1311 } elseif ( $contextNode->nodeName == 'comment
' ) {
1312 # HTML-style comment
1313 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1314 # Not in RECOVER_COMMENTS mode (msgnw) though.
1315 if ( ( $this->parser->ot['html
']
1316 || ( $this->parser->ot['pre
'] && $this->parser->mOptions->getRemoveComments() )
1317 || ( $flags & PPFrame::STRIP_COMMENTS )
1318 ) && !( $flags & PPFrame::RECOVER_COMMENTS )
1321 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1322 # Add a strip marker in PST mode so that pstPass2() can
1323 # run some old-fashioned regexes on the result.
1324 # Not in RECOVER_COMMENTS mode (extractSections) though.
1325 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1327 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1328 $out .= $contextNode->textContent;
1330 } elseif ( $contextNode->nodeName == 'ignore
' ) {
1331 # Output suppression used by <includeonly> etc.
1332 # OT_WIKI will only respect <ignore> in substed templates.
1333 # The other output types respect it unless NO_IGNORE is set.
1334 # extractSections() sets NO_IGNORE and so never respects it.
1335 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1336 || ( $flags & PPFrame::NO_IGNORE )
1338 $out .= $contextNode->textContent;
1342 } elseif ( $contextNode->nodeName == 'ext
' ) {
1344 $xpath = new DOMXPath( $contextNode->ownerDocument );
1345 $names = $xpath->query( 'name', $contextNode );
1346 $attrs = $xpath->query( 'attr
', $contextNode );
1347 $inners = $xpath->query( 'inner
', $contextNode );
1348 $closes = $xpath->query( 'close
', $contextNode );
1349 if ( $flags & PPFrame::NO_TAGS ) {
1350 $s = '<
' . $this->expand( $names->item( 0 ), $flags );
1351 if ( $attrs->length > 0 ) {
1352 $s .= $this->expand( $attrs->item( 0 ), $flags );
1354 if ( $inners->length > 0 ) {
1355 $s .= '>
' . $this->expand( $inners->item( 0 ), $flags );
1356 if ( $closes->length > 0 ) {
1357 $s .= $this->expand( $closes->item( 0 ), $flags );
1365 'name' => new PPNode_DOM( $names->item( 0 ) ),
1366 'attr
' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1367 'inner
' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1368 'close
' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1370 $out .= $this->parser->extensionSubstitution( $params, $this );
1372 } elseif ( $contextNode->nodeName == 'h
' ) {
1374 $s = $this->expand( $contextNode->childNodes, $flags );
1376 # Insert a heading marker only for <h> children of <root>
1377 # This is to stop extractSections from going over multiple tree levels
1378 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html
'] ) {
1379 # Insert heading index marker
1380 $headingIndex = $contextNode->getAttribute( 'i
' );
1381 $titleText = $this->title->getPrefixedDBkey();
1382 $this->parser->mHeadings[] = [ $titleText, $headingIndex ];
1383 $serial = count( $this->parser->mHeadings ) - 1;
1384 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
1385 $count = $contextNode->getAttribute( 'level
' );
1386 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1387 $this->parser->mStripState->addGeneral( $marker, '' );
1391 # Generic recursive expansion
1392 $newIterator = $contextNode->childNodes;
1395 throw new MWException( __METHOD__ . ': Invalid parameter
type' );
1398 if ( $newIterator !== false ) {
1399 if ( $newIterator instanceof PPNode_DOM ) {
1400 $newIterator = $newIterator->node;
1403 $iteratorStack[] = $newIterator;
1405 } elseif ( $iteratorStack[$level] === false ) {
1406 // Return accumulated value to parent
1407 // With tail recursion
1408 while ( $iteratorStack[$level] === false && $level > 0 ) {
1409 $outStack[$level - 1] .= $out;
1410 array_pop( $outStack );
1411 array_pop( $iteratorStack );
1412 array_pop( $indexStack );
1418 return $outStack[0];
1427 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1428 $args = array_slice( func_get_args(), 2 );
1432 foreach ( $args as $root ) {
1433 if ( $root instanceof PPNode_DOM ) {
1434 $root = $root->node;
1436 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1439 foreach ( $root as $node ) {
1445 $s .= $this->expand( $node, $flags );
1459 public function implode( $sep /*, ... */ ) {
1460 $args = array_slice( func_get_args(), 1 );
1464 foreach ( $args as $root ) {
1465 if ( $root instanceof PPNode_DOM ) {
1466 $root = $root->node;
1468 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1471 foreach ( $root as $node ) {
1477 $s .= $this->expand( $node );
1491 public function virtualImplode( $sep /*, ... */ ) {
1492 $args = array_slice( func_get_args(), 1 );
1496 foreach ( $args as $root ) {
1497 if ( $root instanceof PPNode_DOM ) {
1498 $root = $root->node;
1500 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1503 foreach ( $root as $node ) {
1523 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1524 $args = array_slice( func_get_args(), 3 );
1528 foreach ( $args as $root ) {
1529 if ( $root instanceof PPNode_DOM ) {
1530 $root = $root->node;
1532 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1535 foreach ( $root as $node ) {
1548 public function __toString() {
1552 public function getPDBK( $level = false ) {
1553 if ( $level === false ) {
1554 return $this->title->getPrefixedDBkey();
1556 return $this->titleCache[$level] ?? false;
1563 public function getArguments() {
1570 public function getNumberedArguments() {
1577 public function getNamedArguments() {
1586 public function isEmpty() {
1594 public function getArgument( $name ) {
1604 public function loopCheck( $title ) {
1605 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1613 public function isTemplate() {
1622 public function getTitle() {
1623 return $this->title;
1631 public function setVolatile( $flag = true ) {
1632 $this->volatile = $flag;
1640 public function isVolatile() {
1641 return $this->volatile;
1649 public function setTTL( $ttl ) {
1650 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1660 public function getTTL() {
1669 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1670 class PPTemplateFrame_DOM extends PPFrame_DOM {
1672 public $numberedArgs, $namedArgs;
1678 public $numberedExpansionCache, $namedExpansionCache;
1687 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1688 $namedArgs = [], $title = false
1690 parent::__construct( $preprocessor );
1692 $this->parent = $parent;
1693 $this->numberedArgs = $numberedArgs;
1694 $this->namedArgs = $namedArgs;
1695 $this->title = $title;
1696 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1697 $this->titleCache = $parent->titleCache;
1698 $this->titleCache[] = $pdbk;
1699 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1700 if ( $pdbk !== false ) {
1701 $this->loopCheckHash[$pdbk] = true;
1703 $this->depth = $parent->depth + 1;
1704 $this->numberedExpansionCache = $this->namedExpansionCache = [];
1707 public function __toString() {
1710 $args = $this->numberedArgs + $this->namedArgs;
1711 foreach ( $args as $name => $value ) {
1717 $s .= "\"$name\":\"" .
1718 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1731 public function cachedExpand( $key, $root, $flags = 0 ) {
1732 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1733 return $this->parent->childExpansionCache[$key];
1735 $retval = $this->expand( $root, $flags );
1736 if ( !$this->isVolatile() ) {
1737 $this->parent->childExpansionCache[$key] = $retval;
1747 public function isEmpty() {
1748 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1751 public function getArguments() {
1753 foreach ( array_merge(
1754 array_keys( $this->numberedArgs ),
1755 array_keys( $this->namedArgs ) ) as $key ) {
1756 $arguments[$key] = $this->getArgument( $key );
1761 public function getNumberedArguments() {
1763 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1764 $arguments[$key] = $this->getArgument( $key );
1769 public function getNamedArguments() {
1771 foreach ( array_keys( $this->namedArgs ) as $key ) {
1772 $arguments[$key] = $this->getArgument( $key );
1781 public function getNumberedArgument( $index ) {
1782 if ( !isset( $this->numberedArgs[$index] ) ) {
1785 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1786 # No trimming for unnamed arguments
1787 $this->numberedExpansionCache[$index] = $this->parent->expand(
1788 $this->numberedArgs[$index],
1789 PPFrame::STRIP_COMMENTS
1792 return $this->numberedExpansionCache[$index];
1799 public function getNamedArgument( $name ) {
1800 if ( !isset( $this->namedArgs[$name] ) ) {
1803 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1804 # Trim named arguments post-expand, for backwards compatibility
1805 $this->namedExpansionCache[$name] = trim(
1806 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1808 return $this->namedExpansionCache[$name];
1815 public function getArgument( $name ) {
1816 $text = $this->getNumberedArgument( $name );
1817 if ( $text === false ) {
1818 $text = $this->getNamedArgument( $name );
1828 public function isTemplate() {
1832 public function setVolatile( $flag = true ) {
1833 parent::setVolatile( $flag );
1834 $this->parent->setVolatile( $flag );
1837 public function setTTL( $ttl ) {
1838 parent::setTTL( $ttl );
1839 $this->parent->setTTL( $ttl );
1847 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1848 class PPCustomFrame_DOM extends PPFrame_DOM {
1852 public function __construct( $preprocessor, $args ) {
1853 parent::__construct( $preprocessor );
1854 $this->args = $args;
1857 public function __toString() {
1860 foreach ( $this->args as $name => $value ) {
1866 $s .= "\
"$name\":\"" .
1867 str_replace(
'"',
'\\"',
$value->__toString() ) .
'"';
1885 return $this->
args[$index] ??
false;
1906 $this->node = $node;
1913 if ( $this->xpath ===
null ) {
1914 $this->xpath =
new DOMXPath( $this->node->ownerDocument );
1916 return $this->xpath;
1920 if ( $this->node instanceof DOMNodeList ) {
1922 foreach ( $this->node
as $node ) {
1923 $s .= $node->ownerDocument->saveXML( $node );
1926 $s = $this->node->ownerDocument->saveXML( $this->node );
1935 return $this->node->childNodes ?
new self( $this->node->childNodes ) :
false;
1942 return $this->node->firstChild ?
new self( $this->node->firstChild ) :
false;
1949 return $this->node->nextSibling ?
new self( $this->node->nextSibling ) :
false;
1958 return new self( $this->getXPath()->query(
$type, $this->node ) );
1965 if ( $this->node instanceof DOMNodeList ) {
1966 return $this->node->length;
1977 $item = $this->node->item( $i );
1978 return $item ?
new self( $item ) :
false;
1985 if ( $this->node instanceof DOMNodeList ) {
1988 return $this->node->nodeName;
2002 $xpath = $this->getXPath();
2003 $names = $xpath->query(
'name', $this->node );
2004 $values = $xpath->query(
'value', $this->node );
2005 if ( !$names->length || !$values->length ) {
2006 throw new MWException(
'Invalid brace node passed to ' . __METHOD__ );
2008 $name = $names->item( 0 );
2009 $index =
$name->getAttribute(
'index' );
2011 'name' =>
new self(
$name ),
2013 'value' =>
new self( $values->item( 0 ) ) ];
2024 $xpath = $this->getXPath();
2025 $names = $xpath->query(
'name', $this->node );
2026 $attrs = $xpath->query(
'attr', $this->node );
2027 $inners = $xpath->query(
'inner', $this->node );
2028 $closes = $xpath->query(
'close', $this->node );
2029 if ( !$names->length || !$attrs->length ) {
2030 throw new MWException(
'Invalid ext node passed to ' . __METHOD__ );
2033 'name' =>
new self( $names->item( 0 ) ),
2034 'attr' =>
new self( $attrs->item( 0 ) ) ];
2035 if ( $inners->length ) {
2036 $parts[
'inner'] =
new self( $inners->item( 0 ) );
2038 if ( $closes->length ) {
2039 $parts[
'close'] =
new self( $closes->item( 0 ) );
2050 if ( $this->getName() !==
'h' ) {
2051 throw new MWException(
'Invalid h node passed to ' . __METHOD__ );
2054 'i' => $this->node->getAttribute(
'i' ),
2055 'level' => $this->node->getAttribute(
'level' ),
2056 'contents' => $this->getChildren()