3 * Preprocessor using PHP arrays
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
25 * Differences from DOM schema:
26 * * attribute nodes are children
27 * * "<h>" nodes that aren't at the top are replaced with <possible-h>
29 * Nodes are stored in a recursive array data structure. A node store is an
30 * array where each element may be either a scalar (representing a text node)
31 * or a "descriptor", which is a two-element array where the first element is
32 * the node name and the second element is the node store for the children.
34 * Attributes are represented as children that have a node name starting with
35 * "@", and a single text node child.
37 * @todo: Consider replacing descriptor arrays with objects of a new class.
38 * Benchmark and measure resulting memory impact.
42 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
43 class Preprocessor_Hash
extends Preprocessor
{
50 const CACHE_PREFIX
= 'preprocess-hash';
51 const CACHE_VERSION
= 2;
53 public function __construct( $parser ) {
54 $this->parser
= $parser;
58 * @return PPFrame_Hash
60 public function newFrame() {
61 return new PPFrame_Hash( $this );
66 * @return PPCustomFrame_Hash
68 public function newCustomFrame( $args ) {
69 return new PPCustomFrame_Hash( $this, $args );
73 * @param array $values
74 * @return PPNode_Hash_Array
76 public function newPartNodeArray( $values ) {
79 foreach ( $values as $k => $val ) {
81 $store = [ [ 'part', [
82 [ 'name', [ [ '@index', [ $k ] ] ] ],
83 [ 'value', [ strval( $val ) ] ],
86 $store = [ [ 'part', [
87 [ 'name', [ strval( $k ) ] ],
89 [ 'value', [ strval( $val ) ] ],
93 $list[] = new PPNode_Hash_Tree( $store, 0 );
96 $node = new PPNode_Hash_Array( $list );
101 * Preprocess some wikitext and return the document tree.
103 * @param string $text The text to parse
104 * @param int $flags Bitwise combination of:
105 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
106 * included. Default is to assume a direct page view.
108 * The generated DOM tree must depend only on the input text and the flags.
109 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
111 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
112 * change in the DOM tree for a given text, must be passed through the section identifier
113 * in the section edit link and thus back to extractSections().
115 * @throws MWException
116 * @return PPNode_Hash_Tree
118 public function preprocessToObj( $text, $flags = 0 ) {
119 global $wgDisableLangConversion;
121 $tree = $this->cacheGetTree( $text, $flags );
122 if ( $tree !== false ) {
123 $store = json_decode( $tree );
124 if ( is_array( $store ) ) {
125 return new PPNode_Hash_Tree( $store, 0 );
129 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
131 $xmlishElements = $this->parser
->getStripList();
132 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
133 $enableOnlyinclude = false;
134 if ( $forInclusion ) {
135 $ignoredTags = [ 'includeonly', '/includeonly' ];
136 $ignoredElements = [ 'noinclude' ];
137 $xmlishElements[] = 'noinclude';
138 if ( strpos( $text, '<onlyinclude>' ) !== false
139 && strpos( $text, '</onlyinclude>' ) !== false
141 $enableOnlyinclude = true;
144 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
145 $ignoredElements = [ 'includeonly' ];
146 $xmlishElements[] = 'includeonly';
148 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
150 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
151 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
153 $stack = new PPDStack_Hash
;
155 $searchBase = "[{<\n";
156 if ( !$wgDisableLangConversion ) {
160 // For fast reverse searches
161 $revText = strrev( $text );
162 $lengthText = strlen( $text );
164 // Input pointer, starts out pointing to a pseudo-newline before the start
166 // Current accumulator. See the doc comment for Preprocessor_Hash for the format.
167 $accum =& $stack->getAccum();
168 // True to find equals signs in arguments
170 // True to take notice of pipe characters
173 // True if $i is inside a possible heading
175 // True if there are no more greater-than (>) signs right of $i
177 // Map of tag name => true if there are no more closing tags of given type right of $i
178 $noMoreClosingTag = [];
179 // True to ignore all input up to the next <onlyinclude>
180 $findOnlyinclude = $enableOnlyinclude;
181 // Do a line-start run without outputting an LF character
182 $fakeLineStart = true;
185 // $this->memCheck();
187 if ( $findOnlyinclude ) {
188 // Ignore all input up to the next <onlyinclude>
189 $startPos = strpos( $text, '<onlyinclude>', $i );
190 if ( $startPos === false ) {
191 // Ignored section runs to the end
192 $accum[] = [ 'ignore', [ substr( $text, $i ) ] ];
195 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
196 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i ) ] ];
198 $findOnlyinclude = false;
201 if ( $fakeLineStart ) {
202 $found = 'line-start';
205 # Find next opening brace, closing brace or pipe
206 $search = $searchBase;
207 if ( $stack->top
=== false ) {
208 $currentClosing = '';
210 $currentClosing = $stack->top
->close
;
211 $search .= $currentClosing;
217 // First equals will be for the template
221 # Output literal section, advance input counter
222 $literalLength = strcspn( $text, $search, $i );
223 if ( $literalLength > 0 ) {
224 self
::addLiteral( $accum, substr( $text, $i, $literalLength ) );
225 $i +
= $literalLength;
227 if ( $i >= $lengthText ) {
228 if ( $currentClosing == "\n" ) {
229 // Do a past-the-end run to finish off the heading
237 $curChar = $curTwoChar = $text[$i];
238 if ( ( $i +
1 ) < $lengthText ) {
239 $curTwoChar .= $text[$i +
1];
241 if ( $curChar == '|' ) {
243 } elseif ( $curChar == '=' ) {
245 } elseif ( $curChar == '<' ) {
247 } elseif ( $curChar == "\n" ) {
251 $found = 'line-start';
253 } elseif ( $curTwoChar == $currentClosing ) {
255 $curChar = $curTwoChar;
256 } elseif ( $curChar == $currentClosing ) {
258 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
259 $curChar = $curTwoChar;
261 $rule = $this->rules
[$curChar];
262 } elseif ( isset( $this->rules
[$curChar] ) ) {
264 $rule = $this->rules
[$curChar];
266 # Some versions of PHP have a strcspn which stops on
267 # null characters; ignore these and continue.
268 # We also may get '-' and '}' characters here which
269 # don't match -{ or $currentClosing. Add these to
270 # output and continue.
271 if ( $curChar == '-' ||
$curChar == '}' ) {
272 self
::addLiteral( $accum, $curChar );
280 if ( $found == 'angle' ) {
282 // Handle </onlyinclude>
283 if ( $enableOnlyinclude
284 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
286 $findOnlyinclude = true;
290 // Determine element name
291 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
292 // Element name missing or not listed
293 self
::addLiteral( $accum, '<' );
298 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
299 // To avoid leaving blank lines, when a sequence of
300 // space-separated comments is both preceded and followed by
301 // a newline (ignoring spaces), then
302 // trim leading and trailing spaces and the trailing newline.
305 $endPos = strpos( $text, '-->', $i +
4 );
306 if ( $endPos === false ) {
307 // Unclosed comment in input, runs to end
308 $inner = substr( $text, $i );
309 $accum[] = [ 'comment', [ $inner ] ];
312 // Search backwards for leading whitespace
313 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
315 // Search forwards for trailing whitespace
316 // $wsEnd will be the position of the last space (or the '>' if there's none)
317 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
319 // Keep looking forward as long as we're finding more
321 $comments = [ [ $wsStart, $wsEnd ] ];
322 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
323 $c = strpos( $text, '-->', $wsEnd +
4 );
324 if ( $c === false ) {
327 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
328 $comments[] = [ $wsEnd +
1, $c ];
332 // Eat the line if possible
333 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
334 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
335 // it's a possible beneficial b/c break.
336 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
337 && substr( $text, $wsEnd +
1, 1 ) == "\n"
339 // Remove leading whitespace from the end of the accumulator
340 $wsLength = $i - $wsStart;
341 $endIndex = count( $accum ) - 1;
346 && is_string( $accum[$endIndex] )
347 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
349 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
352 // Dump all but the last comment to the accumulator
353 foreach ( $comments as $j => $com ) {
355 $endPos = $com[1] +
1;
356 if ( $j == ( count( $comments ) - 1 ) ) {
359 $inner = substr( $text, $startPos, $endPos - $startPos );
360 $accum[] = [ 'comment', [ $inner ] ];
363 // Do a line-start run next time to look for headings after the comment
364 $fakeLineStart = true;
366 // No line to eat, just take the comment itself
372 $part = $stack->top
->getCurrentPart();
373 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
374 $part->visualEnd
= $wsStart;
376 // Else comments abutting, no change in visual end
377 $part->commentEnd
= $endPos;
380 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
381 $accum[] = [ 'comment', [ $inner ] ];
386 $lowerName = strtolower( $name );
387 $attrStart = $i +
strlen( $name ) +
1;
390 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
391 if ( $tagEndPos === false ) {
392 // Infinite backtrack
393 // Disable tag search to prevent worst-case O(N^2) performance
395 self
::addLiteral( $accum, '<' );
400 // Handle ignored tags
401 if ( in_array( $lowerName, $ignoredTags ) ) {
402 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i +
1 ) ] ];
408 if ( $text[$tagEndPos - 1] == '/' ) {
410 $attrEnd = $tagEndPos - 1;
415 $attrEnd = $tagEndPos;
418 !isset( $noMoreClosingTag[$name] ) &&
419 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
420 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
422 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
423 $i = $matches[0][1] +
strlen( $matches[0][0] );
424 $close = $matches[0][0];
427 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
428 // Let it run out to the end of the text.
429 $inner = substr( $text, $tagEndPos +
1 );
433 // Don't match the tag, treat opening tag as literal and resume parsing.
435 self
::addLiteral( $accum,
436 substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
437 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
438 $noMoreClosingTag[$name] = true;
443 // <includeonly> and <noinclude> just become <ignore> tags
444 if ( in_array( $lowerName, $ignoredElements ) ) {
445 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
449 if ( $attrEnd <= $attrStart ) {
452 // Note that the attr element contains the whitespace between name and attribute,
453 // this is necessary for precise reconstruction during pre-save transform.
454 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
458 [ 'name', [ $name ] ],
459 [ 'attr', [ $attr ] ] ];
460 if ( $inner !== null ) {
461 $children[] = [ 'inner', [ $inner ] ];
463 if ( $close !== null ) {
464 $children[] = [ 'close', [ $close ] ];
466 $accum[] = [ 'ext', $children ];
467 } elseif ( $found == 'line-start' ) {
468 // Is this the start of a heading?
469 // Line break belongs before the heading element in any case
470 if ( $fakeLineStart ) {
471 $fakeLineStart = false;
473 self
::addLiteral( $accum, $curChar );
477 $count = strspn( $text, '=', $i, 6 );
478 if ( $count == 1 && $findEquals ) {
479 // DWIM: This looks kind of like a name/value separator.
480 // Let's let the equals handler have it and break the potential
481 // heading. This is heuristic, but AFAICT the methods for
482 // completely correct disambiguation are very complex.
483 } elseif ( $count > 0 ) {
487 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
490 $stack->push( $piece );
491 $accum =& $stack->getAccum();
492 $stackFlags = $stack->getFlags();
493 if ( isset( $stackFlags['findEquals'] ) ) {
494 $findEquals = $stackFlags['findEquals'];
496 if ( isset( $stackFlags['findPipe'] ) ) {
497 $findPipe = $stackFlags['findPipe'];
499 if ( isset( $stackFlags['inHeading'] ) ) {
500 $inHeading = $stackFlags['inHeading'];
504 } elseif ( $found == 'line-end' ) {
505 $piece = $stack->top
;
506 // A heading must be open, otherwise \n wouldn't have been in the search list
507 // FIXME: Don't use assert()
508 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.assert
509 assert( $piece->open
=== "\n" );
510 $part = $piece->getCurrentPart();
511 // Search back through the input to see if it has a proper close.
512 // Do this using the reversed string since the other solutions
513 // (end anchor, etc.) are inefficient.
514 $wsLength = strspn( $revText, " \t", $lengthText - $i );
515 $searchStart = $i - $wsLength;
516 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
517 // Comment found at line end
518 // Search for equals signs before the comment
519 $searchStart = $part->visualEnd
;
520 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
522 $count = $piece->count
;
523 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
524 if ( $equalsLength > 0 ) {
525 if ( $searchStart - $equalsLength == $piece->startPos
) {
526 // This is just a single string of equals signs on its own line
527 // Replicate the doHeadings behavior /={count}(.+)={count}/
528 // First find out how many equals signs there really are (don't stop at 6)
529 $count = $equalsLength;
533 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
536 $count = min( $equalsLength, $count );
539 // Normal match, output <h>
540 $element = [ [ 'possible-h',
543 [ '@level', [ $count ] ],
544 [ '@i', [ $headingIndex++
] ]
550 // Single equals sign on its own line, count=0
554 // No match, no <h>, just pass down the inner text
559 $accum =& $stack->getAccum();
560 $stackFlags = $stack->getFlags();
561 if ( isset( $stackFlags['findEquals'] ) ) {
562 $findEquals = $stackFlags['findEquals'];
564 if ( isset( $stackFlags['findPipe'] ) ) {
565 $findPipe = $stackFlags['findPipe'];
567 if ( isset( $stackFlags['inHeading'] ) ) {
568 $inHeading = $stackFlags['inHeading'];
571 // Append the result to the enclosing accumulator
572 array_splice( $accum, count( $accum ), 0, $element );
574 // Note that we do NOT increment the input pointer.
575 // This is because the closing linebreak could be the opening linebreak of
576 // another heading. Infinite loops are avoided because the next iteration MUST
577 // hit the heading open case above, which unconditionally increments the
579 } elseif ( $found == 'open' ) {
580 # count opening brace characters
581 $curLen = strlen( $curChar );
582 $count = ( $curLen > 1 ) ?
583 # allow the final character to repeat
584 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
585 strspn( $text, $curChar, $i );
588 $lineStart = ( $i > 0 && $text[$i - 1] == "\n" );
590 if ( $curChar === "-{" && $count > $curLen ) {
591 // -{ => {{ transition because rightmost wins
596 $rule = $this->rules
[$curChar];
599 # we need to add to stack only if opening brace count is enough for one of the rules
600 if ( $count >= $rule['min'] ) {
601 # Add it to the stack
604 'close' => $rule['end'],
605 'savedPrefix' => $savedPrefix,
607 'lineStart' => $lineStart,
610 $stack->push( $piece );
611 $accum =& $stack->getAccum();
612 $stackFlags = $stack->getFlags();
613 if ( isset( $stackFlags['findEquals'] ) ) {
614 $findEquals = $stackFlags['findEquals'];
616 if ( isset( $stackFlags['findPipe'] ) ) {
617 $findPipe = $stackFlags['findPipe'];
619 if ( isset( $stackFlags['inHeading'] ) ) {
620 $inHeading = $stackFlags['inHeading'];
623 # Add literal brace(s)
624 self
::addLiteral( $accum, $savedPrefix . str_repeat( $curChar, $count ) );
627 } elseif ( $found == 'close' ) {
628 $piece = $stack->top
;
629 # lets check if there are enough characters for closing brace
630 $maxCount = $piece->count
;
631 if ( $piece->close
=== '}-' && $curChar === '}' ) {
632 $maxCount--; # don't try to match closing '-' as a '}'
634 $curLen = strlen( $curChar );
635 $count = ( $curLen > 1 ) ?
$curLen :
636 strspn( $text, $curChar, $i, $maxCount );
638 # check for maximum matching characters (if there are 5 closing
639 # characters, we will probably need only 3 - depending on the rules)
640 $rule = $this->rules
[$piece->open
];
641 if ( $count > $rule['max'] ) {
642 # The specified maximum exists in the callback array, unless the caller
644 $matchingCount = $rule['max'];
646 # Count is less than the maximum
647 # Skip any gaps in the callback array to find the true largest match
648 # Need to use array_key_exists not isset because the callback can be null
649 $matchingCount = $count;
650 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
655 if ( $matchingCount <= 0 ) {
656 # No matching element found in callback array
657 # Output a literal closing brace and continue
658 $endText = substr( $text, $i, $count );
659 self
::addLiteral( $accum, $endText );
663 $name = $rule['names'][$matchingCount];
664 if ( $name === null ) {
665 // No element, just literal text
666 $endText = substr( $text, $i, $matchingCount );
667 $element = $piece->breakSyntax( $matchingCount );
668 self
::addLiteral( $element, $endText );
671 $parts = $piece->parts
;
672 $titleAccum = $parts[0]->out
;
677 # The invocation is at the start of the line if lineStart is set in
678 # the stack, and all opening brackets are used up.
679 if ( $maxCount == $matchingCount &&
680 !empty( $piece->lineStart
) &&
681 strlen( $piece->savedPrefix
) == 0 ) {
682 $children[] = [ '@lineStart', [ 1 ] ];
684 $titleNode = [ 'title', $titleAccum ];
685 $children[] = $titleNode;
687 foreach ( $parts as $part ) {
688 if ( isset( $part->eqpos
) ) {
689 $equalsNode = $part->out
[$part->eqpos
];
690 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
691 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
692 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
693 $children[] = $partNode;
695 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
696 $valueNode = [ 'value', $part->out
];
697 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
698 $children[] = $partNode;
701 $element = [ [ $name, $children ] ];
704 # Advance input pointer
705 $i +
= $matchingCount;
709 $accum =& $stack->getAccum();
711 # Re-add the old stack element if it still has unmatched opening characters remaining
712 if ( $matchingCount < $piece->count
) {
713 $piece->parts
= [ new PPDPart_Hash
];
714 $piece->count
-= $matchingCount;
715 # do we still qualify for any callback with remaining count?
716 $min = $this->rules
[$piece->open
]['min'];
717 if ( $piece->count
>= $min ) {
718 $stack->push( $piece );
719 $accum =& $stack->getAccum();
720 } elseif ( $piece->count
== 1 && $piece->open
=== '{' && $piece->savedPrefix
=== '-' ) {
721 $piece->savedPrefix
= '';
724 $piece->close
= $this->rules
[$piece->open
]['end'];
725 $stack->push( $piece );
726 $accum =& $stack->getAccum();
728 $s = substr( $piece->open
, 0, -1 );
730 substr( $piece->open
, -1 ),
731 $piece->count
- strlen( $s )
733 self
::addLiteral( $accum, $piece->savedPrefix
. $s );
735 } elseif ( $piece->savedPrefix
!== '' ) {
736 self
::addLiteral( $accum, $piece->savedPrefix
);
739 $stackFlags = $stack->getFlags();
740 if ( isset( $stackFlags['findEquals'] ) ) {
741 $findEquals = $stackFlags['findEquals'];
743 if ( isset( $stackFlags['findPipe'] ) ) {
744 $findPipe = $stackFlags['findPipe'];
746 if ( isset( $stackFlags['inHeading'] ) ) {
747 $inHeading = $stackFlags['inHeading'];
750 # Add XML element to the enclosing accumulator
751 array_splice( $accum, count( $accum ), 0, $element );
752 } elseif ( $found == 'pipe' ) {
753 $findEquals = true; // shortcut for getFlags()
755 $accum =& $stack->getAccum();
757 } elseif ( $found == 'equals' ) {
758 $findEquals = false; // shortcut for getFlags()
759 $accum[] = [ 'equals', [ '=' ] ];
760 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
765 # Output any remaining unclosed brackets
766 foreach ( $stack->stack
as $piece ) {
767 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
770 # Enable top-level headings
771 foreach ( $stack->rootAccum
as &$node ) {
772 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
773 $node[PPNode_Hash_Tree
::NAME
] = 'h';
777 $rootStore = [ [ 'root', $stack->rootAccum
] ];
778 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
781 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
782 if ( $tree !== false ) {
783 $this->cacheSetTree( $text, $flags, $tree );
789 private static function addLiteral( array &$accum, $text ) {
790 $n = count( $accum );
791 if ( $n && is_string( $accum[$n - 1] ) ) {
792 $accum[$n - 1] .= $text;
800 * Stack class to help Preprocessor::preprocessToObj()
803 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
804 class PPDStack_Hash
extends PPDStack
{
806 public function __construct() {
807 $this->elementClass
= PPDStackElement_Hash
::class;
808 parent
::__construct();
809 $this->rootAccum
= [];
816 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
817 class PPDStackElement_Hash
extends PPDStackElement
{
819 public function __construct( $data = [] ) {
820 $this->partClass
= PPDPart_Hash
::class;
821 parent
::__construct( $data );
825 * Get the accumulator that would result if the close is not found.
827 * @param int|bool $openingCount
830 public function breakSyntax( $openingCount = false ) {
831 if ( $this->open
== "\n" ) {
832 $accum = array_merge( [ $this->savedPrefix
], $this->parts
[0]->out
);
834 if ( $openingCount === false ) {
835 $openingCount = $this->count
;
837 $s = substr( $this->open
, 0, -1 );
839 substr( $this->open
, -1 ),
840 $openingCount - strlen( $s )
842 $accum = [ $this->savedPrefix
. $s ];
845 foreach ( $this->parts
as $part ) {
848 } elseif ( is_string( $accum[$lastIndex] ) ) {
849 $accum[$lastIndex] .= '|';
851 $accum[++
$lastIndex] = '|';
853 foreach ( $part->out
as $node ) {
854 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
855 $accum[$lastIndex] .= $node;
857 $accum[++
$lastIndex] = $node;
869 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
870 class PPDPart_Hash
extends PPDPart
{
872 public function __construct( $out = '' ) {
878 parent
::__construct( $accum );
883 * An expansion frame, used as a context to expand the result of preprocessToObj()
886 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
887 class PPFrame_Hash
implements PPFrame
{
897 public $preprocessor;
906 * Hashtable listing templates which are disallowed for expansion in this frame,
907 * having been encountered previously in parent frames.
909 public $loopCheckHash;
912 * Recursion depth of this frame, top = 0
913 * Note that this is NOT the same as expansion depth in expand()
917 private $volatile = false;
923 protected $childExpansionCache;
926 * Construct a new preprocessor frame.
927 * @param Preprocessor $preprocessor The parent preprocessor
929 public function __construct( $preprocessor ) {
930 $this->preprocessor
= $preprocessor;
931 $this->parser
= $preprocessor->parser
;
932 $this->title
= $this->parser
->mTitle
;
933 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
934 $this->loopCheckHash
= [];
936 $this->childExpansionCache
= [];
940 * Create a new child frame
941 * $args is optionally a multi-root PPNode or array containing the template arguments
943 * @param array|bool|PPNode_Hash_Array $args
944 * @param Title|bool $title
945 * @param int $indexOffset
946 * @throws MWException
947 * @return PPTemplateFrame_Hash
949 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
952 if ( $title === false ) {
953 $title = $this->title
;
955 if ( $args !== false ) {
956 if ( $args instanceof PPNode_Hash_Array
) {
957 $args = $args->value
;
958 } elseif ( !is_array( $args ) ) {
959 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
961 foreach ( $args as $arg ) {
962 $bits = $arg->splitArg();
963 if ( $bits['index'] !== '' ) {
964 // Numbered parameter
965 $index = $bits['index'] - $indexOffset;
966 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
967 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
968 wfEscapeWikiText( $this->title
),
969 wfEscapeWikiText( $title ),
970 wfEscapeWikiText( $index ) )->text() );
971 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
973 $numberedArgs[$index] = $bits['value'];
974 unset( $namedArgs[$index] );
977 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
978 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
979 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
980 wfEscapeWikiText( $this->title
),
981 wfEscapeWikiText( $title ),
982 wfEscapeWikiText( $name ) )->text() );
983 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
985 $namedArgs[$name] = $bits['value'];
986 unset( $numberedArgs[$name] );
990 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
994 * @throws MWException
995 * @param string|int $key
996 * @param string|PPNode $root
1000 public function cachedExpand( $key, $root, $flags = 0 ) {
1001 // we don't have a parent, so we don't have a cache
1002 return $this->expand( $root, $flags );
1006 * @throws MWException
1007 * @param string|PPNode $root
1011 public function expand( $root, $flags = 0 ) {
1012 static $expansionDepth = 0;
1013 if ( is_string( $root ) ) {
1017 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1018 $this->parser
->limitationWarn( 'node-count-exceeded',
1019 $this->parser
->mPPNodeCount
,
1020 $this->parser
->mOptions
->getMaxPPNodeCount()
1022 return '<span class="error">Node-count limit exceeded</span>';
1024 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1025 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1027 $this->parser
->mOptions
->getMaxPPExpandDepth()
1029 return '<span class="error">Expansion depth limit exceeded</span>';
1032 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1033 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1036 $outStack = [ '', '' ];
1037 $iteratorStack = [ false, $root ];
1038 $indexStack = [ 0, 0 ];
1040 while ( count( $iteratorStack ) > 1 ) {
1041 $level = count( $outStack ) - 1;
1042 $iteratorNode =& $iteratorStack[$level];
1043 $out =& $outStack[$level];
1044 $index =& $indexStack[$level];
1046 if ( is_array( $iteratorNode ) ) {
1047 if ( $index >= count( $iteratorNode ) ) {
1048 // All done with this iterator
1049 $iteratorStack[$level] = false;
1050 $contextNode = false;
1052 $contextNode = $iteratorNode[$index];
1055 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1056 if ( $index >= $iteratorNode->getLength() ) {
1057 // All done with this iterator
1058 $iteratorStack[$level] = false;
1059 $contextNode = false;
1061 $contextNode = $iteratorNode->item( $index );
1065 // Copy to $contextNode and then delete from iterator stack,
1066 // because this is not an iterator but we do have to execute it once
1067 $contextNode = $iteratorStack[$level];
1068 $iteratorStack[$level] = false;
1071 $newIterator = false;
1072 $contextName = false;
1073 $contextChildren = false;
1075 if ( $contextNode === false ) {
1077 } elseif ( is_string( $contextNode ) ) {
1078 $out .= $contextNode;
1079 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1080 $newIterator = $contextNode;
1081 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1083 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1084 $out .= $contextNode->value
;
1085 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1086 $contextName = $contextNode->name
;
1087 $contextChildren = $contextNode->getRawChildren();
1088 } elseif ( is_array( $contextNode ) ) {
1089 // Node descriptor array
1090 if ( count( $contextNode ) !== 2 ) {
1091 throw new MWException( __METHOD__
.
1092 ': found an array where a node descriptor should be' );
1094 list( $contextName, $contextChildren ) = $contextNode;
1096 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1099 // Handle node descriptor array or tree object
1100 if ( $contextName === false ) {
1101 // Not a node, already handled above
1102 } elseif ( $contextName[0] === '@' ) {
1103 // Attribute: no output
1104 } elseif ( $contextName === 'template' ) {
1105 # Double-brace expansion
1106 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1107 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1108 $newIterator = $this->virtualBracketedImplode(
1114 $ret = $this->parser
->braceSubstitution( $bits, $this );
1115 if ( isset( $ret['object'] ) ) {
1116 $newIterator = $ret['object'];
1118 $out .= $ret['text'];
1121 } elseif ( $contextName === 'tplarg' ) {
1122 # Triple-brace expansion
1123 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1124 if ( $flags & PPFrame
::NO_ARGS
) {
1125 $newIterator = $this->virtualBracketedImplode(
1131 $ret = $this->parser
->argSubstitution( $bits, $this );
1132 if ( isset( $ret['object'] ) ) {
1133 $newIterator = $ret['object'];
1135 $out .= $ret['text'];
1138 } elseif ( $contextName === 'comment' ) {
1139 # HTML-style comment
1140 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1141 # Not in RECOVER_COMMENTS mode (msgnw) though.
1142 if ( ( $this->parser
->ot
['html']
1143 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1144 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1145 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1148 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1149 # Add a strip marker in PST mode so that pstPass2() can
1150 # run some old-fashioned regexes on the result.
1151 # Not in RECOVER_COMMENTS mode (extractSections) though.
1152 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1154 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1155 $out .= $contextChildren[0];
1157 } elseif ( $contextName === 'ignore' ) {
1158 # Output suppression used by <includeonly> etc.
1159 # OT_WIKI will only respect <ignore> in substed templates.
1160 # The other output types respect it unless NO_IGNORE is set.
1161 # extractSections() sets NO_IGNORE and so never respects it.
1162 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1163 ||
( $flags & PPFrame
::NO_IGNORE
)
1165 $out .= $contextChildren[0];
1169 } elseif ( $contextName === 'ext' ) {
1171 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1172 [ 'attr' => null, 'inner' => null, 'close' => null ];
1173 if ( $flags & PPFrame
::NO_TAGS
) {
1174 $s = '<' . $bits['name']->getFirstChild()->value
;
1175 if ( $bits['attr'] ) {
1176 $s .= $bits['attr']->getFirstChild()->value
;
1178 if ( $bits['inner'] ) {
1179 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1180 if ( $bits['close'] ) {
1181 $s .= $bits['close']->getFirstChild()->value
;
1188 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1190 } elseif ( $contextName === 'h' ) {
1192 if ( $this->parser
->ot
['html'] ) {
1193 # Expand immediately and insert heading index marker
1194 $s = $this->expand( $contextChildren, $flags );
1195 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1196 $titleText = $this->title
->getPrefixedDBkey();
1197 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1198 $serial = count( $this->parser
->mHeadings
) - 1;
1199 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1200 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1201 $this->parser
->mStripState
->addGeneral( $marker, '' );
1204 # Expand in virtual stack
1205 $newIterator = $contextChildren;
1208 # Generic recursive expansion
1209 $newIterator = $contextChildren;
1212 if ( $newIterator !== false ) {
1214 $iteratorStack[] = $newIterator;
1216 } elseif ( $iteratorStack[$level] === false ) {
1217 // Return accumulated value to parent
1218 // With tail recursion
1219 while ( $iteratorStack[$level] === false && $level > 0 ) {
1220 $outStack[$level - 1] .= $out;
1221 array_pop( $outStack );
1222 array_pop( $iteratorStack );
1223 array_pop( $indexStack );
1229 return $outStack[0];
1233 * @param string $sep
1235 * @param string|PPNode $args,...
1238 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1239 $args = array_slice( func_get_args(), 2 );
1243 foreach ( $args as $root ) {
1244 if ( $root instanceof PPNode_Hash_Array
) {
1245 $root = $root->value
;
1247 if ( !is_array( $root ) ) {
1250 foreach ( $root as $node ) {
1256 $s .= $this->expand( $node, $flags );
1263 * Implode with no flags specified
1264 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1265 * @param string $sep
1266 * @param string|PPNode $args,...
1269 public function implode( $sep /*, ... */ ) {
1270 $args = array_slice( func_get_args(), 1 );
1274 foreach ( $args as $root ) {
1275 if ( $root instanceof PPNode_Hash_Array
) {
1276 $root = $root->value
;
1278 if ( !is_array( $root ) ) {
1281 foreach ( $root as $node ) {
1287 $s .= $this->expand( $node );
1294 * Makes an object that, when expand()ed, will be the same as one obtained
1297 * @param string $sep
1298 * @param string|PPNode $args,...
1299 * @return PPNode_Hash_Array
1301 public function virtualImplode( $sep /*, ... */ ) {
1302 $args = array_slice( func_get_args(), 1 );
1306 foreach ( $args as $root ) {
1307 if ( $root instanceof PPNode_Hash_Array
) {
1308 $root = $root->value
;
1310 if ( !is_array( $root ) ) {
1313 foreach ( $root as $node ) {
1322 return new PPNode_Hash_Array( $out );
1326 * Virtual implode with brackets
1328 * @param string $start
1329 * @param string $sep
1330 * @param string $end
1331 * @param string|PPNode $args,...
1332 * @return PPNode_Hash_Array
1334 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1335 $args = array_slice( func_get_args(), 3 );
1339 foreach ( $args as $root ) {
1340 if ( $root instanceof PPNode_Hash_Array
) {
1341 $root = $root->value
;
1343 if ( !is_array( $root ) ) {
1346 foreach ( $root as $node ) {
1356 return new PPNode_Hash_Array( $out );
1359 public function __toString() {
1364 * @param bool $level
1365 * @return array|bool|string
1367 public function getPDBK( $level = false ) {
1368 if ( $level === false ) {
1369 return $this->title
->getPrefixedDBkey();
1371 return $this->titleCache
[$level] ??
false;
1378 public function getArguments() {
1385 public function getNumberedArguments() {
1392 public function getNamedArguments() {
1397 * Returns true if there are no arguments in this frame
1401 public function isEmpty() {
1406 * @param int|string $name
1407 * @return bool Always false in this implementation.
1409 public function getArgument( $name ) {
1414 * Returns true if the infinite loop check is OK, false if a loop is detected
1416 * @param Title $title
1420 public function loopCheck( $title ) {
1421 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1425 * Return true if the frame is a template frame
1429 public function isTemplate() {
1434 * Get a title of frame
1438 public function getTitle() {
1439 return $this->title
;
1443 * Set the volatile flag
1447 public function setVolatile( $flag = true ) {
1448 $this->volatile
= $flag;
1452 * Get the volatile flag
1456 public function isVolatile() {
1457 return $this->volatile
;
1465 public function setTTL( $ttl ) {
1466 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1476 public function getTTL() {
1482 * Expansion frame with template arguments
1485 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1486 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1488 public $numberedArgs, $namedArgs, $parent;
1489 public $numberedExpansionCache, $namedExpansionCache;
1492 * @param Preprocessor $preprocessor
1493 * @param bool|PPFrame $parent
1494 * @param array $numberedArgs
1495 * @param array $namedArgs
1496 * @param bool|Title $title
1498 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1499 $namedArgs = [], $title = false
1501 parent
::__construct( $preprocessor );
1503 $this->parent
= $parent;
1504 $this->numberedArgs
= $numberedArgs;
1505 $this->namedArgs
= $namedArgs;
1506 $this->title
= $title;
1507 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1508 $this->titleCache
= $parent->titleCache
;
1509 $this->titleCache
[] = $pdbk;
1510 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1511 if ( $pdbk !== false ) {
1512 $this->loopCheckHash
[$pdbk] = true;
1514 $this->depth
= $parent->depth +
1;
1515 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1518 public function __toString() {
1521 $args = $this->numberedArgs +
$this->namedArgs
;
1522 foreach ( $args as $name => $value ) {
1528 $s .= "\"$name\":\"" .
1529 str_replace( '"', '\\"', $value->__toString() ) . '"';
1536 * @throws MWException
1537 * @param string|int $key
1538 * @param string|PPNode $root
1542 public function cachedExpand( $key, $root, $flags = 0 ) {
1543 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1544 return $this->parent
->childExpansionCache
[$key];
1546 $retval = $this->expand( $root, $flags );
1547 if ( !$this->isVolatile() ) {
1548 $this->parent
->childExpansionCache
[$key] = $retval;
1554 * Returns true if there are no arguments in this frame
1558 public function isEmpty() {
1559 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1565 public function getArguments() {
1567 foreach ( array_merge(
1568 array_keys( $this->numberedArgs
),
1569 array_keys( $this->namedArgs
) ) as $key ) {
1570 $arguments[$key] = $this->getArgument( $key );
1578 public function getNumberedArguments() {
1580 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1581 $arguments[$key] = $this->getArgument( $key );
1589 public function getNamedArguments() {
1591 foreach ( array_keys( $this->namedArgs
) as $key ) {
1592 $arguments[$key] = $this->getArgument( $key );
1599 * @return string|bool
1601 public function getNumberedArgument( $index ) {
1602 if ( !isset( $this->numberedArgs
[$index] ) ) {
1605 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1606 # No trimming for unnamed arguments
1607 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1608 $this->numberedArgs
[$index],
1609 PPFrame
::STRIP_COMMENTS
1612 return $this->numberedExpansionCache
[$index];
1616 * @param string $name
1617 * @return string|bool
1619 public function getNamedArgument( $name ) {
1620 if ( !isset( $this->namedArgs
[$name] ) ) {
1623 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1624 # Trim named arguments post-expand, for backwards compatibility
1625 $this->namedExpansionCache
[$name] = trim(
1626 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1628 return $this->namedExpansionCache
[$name];
1632 * @param int|string $name
1633 * @return string|bool
1635 public function getArgument( $name ) {
1636 $text = $this->getNumberedArgument( $name );
1637 if ( $text === false ) {
1638 $text = $this->getNamedArgument( $name );
1644 * Return true if the frame is a template frame
1648 public function isTemplate() {
1652 public function setVolatile( $flag = true ) {
1653 parent
::setVolatile( $flag );
1654 $this->parent
->setVolatile( $flag );
1657 public function setTTL( $ttl ) {
1658 parent
::setTTL( $ttl );
1659 $this->parent
->setTTL( $ttl );
1664 * Expansion frame with custom arguments
1667 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1668 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1672 public function __construct( $preprocessor, $args ) {
1673 parent
::__construct( $preprocessor );
1674 $this->args
= $args;
1677 public function __toString() {
1680 foreach ( $this->args
as $name => $value ) {
1686 $s .= "\"$name\":\"" .
1687 str_replace( '"', '\\"', $value->__toString() ) . '"';
1696 public function isEmpty() {
1697 return !count( $this->args
);
1701 * @param int|string $index
1702 * @return string|bool
1704 public function getArgument( $index ) {
1705 return $this->args
[$index] ??
false;
1708 public function getArguments() {
1716 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1717 class PPNode_Hash_Tree
implements PPNode
{
1722 * The store array for children of this node. It is "raw" in the sense that
1723 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1726 private $rawChildren;
1729 * The store array for the siblings of this node, including this node itself.
1734 * The index into $this->store which contains the descriptor of this node.
1739 * The offset of the name within descriptors, used in some places for
1745 * The offset of the child list within descriptors, used in some places for
1751 * Construct an object using the data from $store[$index]. The rest of the
1752 * store array can be accessed via getNextSibling().
1754 * @param array $store
1757 public function __construct( array $store, $index ) {
1758 $this->store
= $store;
1759 $this->index
= $index;
1760 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1764 * Construct an appropriate PPNode_Hash_* object with a class that depends
1765 * on what is at the relevant store index.
1767 * @param array $store
1769 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1771 public static function factory( array $store, $index ) {
1772 if ( !isset( $store[$index] ) ) {
1776 $descriptor = $store[$index];
1777 if ( is_string( $descriptor ) ) {
1778 $class = PPNode_Hash_Text
::class;
1779 } elseif ( is_array( $descriptor ) ) {
1780 if ( $descriptor[self
::NAME
][0] === '@' ) {
1781 $class = PPNode_Hash_Attr
::class;
1783 $class = self
::class;
1786 throw new MWException( __METHOD__
. ': invalid node descriptor' );
1788 return new $class( $store, $index );
1792 * Convert a node to XML, for debugging
1794 public function __toString() {
1797 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1798 if ( $node instanceof PPNode_Hash_Attr
) {
1799 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1801 $inner .= $node->__toString();
1804 if ( $inner === '' ) {
1805 return "<{$this->name}$attribs/>";
1807 return "<{$this->name}$attribs>$inner</{$this->name}>";
1812 * @return PPNode_Hash_Array
1814 public function getChildren() {
1816 foreach ( $this->rawChildren
as $i => $child ) {
1817 $children[] = self
::factory( $this->rawChildren
, $i );
1819 return new PPNode_Hash_Array( $children );
1823 * Get the first child, or false if there is none. Note that this will
1824 * return a temporary proxy object: different instances will be returned
1825 * if this is called more than once on the same node.
1827 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1829 public function getFirstChild() {
1830 if ( !isset( $this->rawChildren
[0] ) ) {
1833 return self
::factory( $this->rawChildren
, 0 );
1838 * Get the next sibling, or false if there is none. Note that this will
1839 * return a temporary proxy object: different instances will be returned
1840 * if this is called more than once on the same node.
1842 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1844 public function getNextSibling() {
1845 return self
::factory( $this->store
, $this->index +
1 );
1849 * Get an array of the children with a given node name
1851 * @param string $name
1852 * @return PPNode_Hash_Array
1854 public function getChildrenOfType( $name ) {
1856 foreach ( $this->rawChildren
as $i => $child ) {
1857 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1858 $children[] = self
::factory( $this->rawChildren
, $i );
1861 return new PPNode_Hash_Array( $children );
1865 * Get the raw child array. For internal use.
1868 public function getRawChildren() {
1869 return $this->rawChildren
;
1875 public function getLength() {
1883 public function item( $i ) {
1890 public function getName() {
1895 * Split a "<part>" node into an associative array containing:
1896 * - name PPNode name
1897 * - index String index
1898 * - value PPNode value
1900 * @throws MWException
1903 public function splitArg() {
1904 return self
::splitRawArg( $this->rawChildren
);
1908 * Like splitArg() but for a raw child array. For internal use only.
1909 * @param array $children
1912 public static function splitRawArg( array $children ) {
1914 foreach ( $children as $i => $child ) {
1915 if ( !is_array( $child ) ) {
1918 if ( $child[self
::NAME
] === 'name' ) {
1919 $bits['name'] = new self( $children, $i );
1920 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1921 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1923 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1925 } elseif ( $child[self
::NAME
] === 'value' ) {
1926 $bits['value'] = new self( $children, $i );
1930 if ( !isset( $bits['name'] ) ) {
1931 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1933 if ( !isset( $bits['index'] ) ) {
1934 $bits['index'] = '';
1940 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1941 * All values in the resulting array are PPNodes. Inner and close are optional.
1943 * @throws MWException
1946 public function splitExt() {
1947 return self
::splitRawExt( $this->rawChildren
);
1951 * Like splitExt() but for a raw child array. For internal use only.
1952 * @param array $children
1955 public static function splitRawExt( array $children ) {
1957 foreach ( $children as $i => $child ) {
1958 if ( !is_array( $child ) ) {
1961 switch ( $child[self
::NAME
] ) {
1963 $bits['name'] = new self( $children, $i );
1966 $bits['attr'] = new self( $children, $i );
1969 $bits['inner'] = new self( $children, $i );
1972 $bits['close'] = new self( $children, $i );
1976 if ( !isset( $bits['name'] ) ) {
1977 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1983 * Split an "<h>" node
1985 * @throws MWException
1988 public function splitHeading() {
1989 if ( $this->name
!== 'h' ) {
1990 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1992 return self
::splitRawHeading( $this->rawChildren
);
1996 * Like splitHeading() but for a raw child array. For internal use only.
1997 * @param array $children
2000 public static function splitRawHeading( array $children ) {
2002 foreach ( $children as $i => $child ) {
2003 if ( !is_array( $child ) ) {
2006 if ( $child[self
::NAME
] === '@i' ) {
2007 $bits['i'] = $child[self
::CHILDREN
][0];
2008 } elseif ( $child[self
::NAME
] === '@level' ) {
2009 $bits['level'] = $child[self
::CHILDREN
][0];
2012 if ( !isset( $bits['i'] ) ) {
2013 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2019 * Split a "<template>" or "<tplarg>" node
2021 * @throws MWException
2024 public function splitTemplate() {
2025 return self
::splitRawTemplate( $this->rawChildren
);
2029 * Like splitTemplate() but for a raw child array. For internal use only.
2030 * @param array $children
2033 public static function splitRawTemplate( array $children ) {
2035 $bits = [ 'lineStart' => '' ];
2036 foreach ( $children as $i => $child ) {
2037 if ( !is_array( $child ) ) {
2040 switch ( $child[self
::NAME
] ) {
2042 $bits['title'] = new self( $children, $i );
2045 $parts[] = new self( $children, $i );
2048 $bits['lineStart'] = '1';
2052 if ( !isset( $bits['title'] ) ) {
2053 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
2055 $bits['parts'] = new PPNode_Hash_Array( $parts );
2063 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2064 class PPNode_Hash_Text
implements PPNode
{
2067 private $store, $index;
2070 * Construct an object using the data from $store[$index]. The rest of the
2071 * store array can be accessed via getNextSibling().
2073 * @param array $store
2076 public function __construct( array $store, $index ) {
2077 $this->value
= $store[$index];
2078 if ( !is_scalar( $this->value
) ) {
2079 throw new MWException( __CLASS__
. ' given object instead of string' );
2081 $this->store
= $store;
2082 $this->index
= $index;
2085 public function __toString() {
2086 return htmlspecialchars( $this->value
);
2089 public function getNextSibling() {
2090 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2093 public function getChildren() {
2097 public function getFirstChild() {
2101 public function getChildrenOfType( $name ) {
2105 public function getLength() {
2109 public function item( $i ) {
2113 public function getName() {
2117 public function splitArg() {
2118 throw new MWException( __METHOD__
. ': not supported' );
2121 public function splitExt() {
2122 throw new MWException( __METHOD__
. ': not supported' );
2125 public function splitHeading() {
2126 throw new MWException( __METHOD__
. ': not supported' );
2133 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2134 class PPNode_Hash_Array
implements PPNode
{
2138 public function __construct( $value ) {
2139 $this->value
= $value;
2142 public function __toString() {
2143 return var_export( $this, true );
2146 public function getLength() {
2147 return count( $this->value
);
2150 public function item( $i ) {
2151 return $this->value
[$i];
2154 public function getName() {
2158 public function getNextSibling() {
2162 public function getChildren() {
2166 public function getFirstChild() {
2170 public function getChildrenOfType( $name ) {
2174 public function splitArg() {
2175 throw new MWException( __METHOD__
. ': not supported' );
2178 public function splitExt() {
2179 throw new MWException( __METHOD__
. ': not supported' );
2182 public function splitHeading() {
2183 throw new MWException( __METHOD__
. ': not supported' );
2190 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2191 class PPNode_Hash_Attr
implements PPNode
{
2193 public $name, $value;
2194 private $store, $index;
2197 * Construct an object using the data from $store[$index]. The rest of the
2198 * store array can be accessed via getNextSibling().
2200 * @param array $store
2203 public function __construct( array $store, $index ) {
2204 $descriptor = $store[$index];
2205 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2206 throw new MWException( __METHOD__
. ': invalid name in attribute descriptor' );
2208 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2209 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2210 $this->store
= $store;
2211 $this->index
= $index;
2214 public function __toString() {
2215 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2218 public function getName() {
2222 public function getNextSibling() {
2223 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2226 public function getChildren() {
2230 public function getFirstChild() {
2234 public function getChildrenOfType( $name ) {
2238 public function getLength() {
2242 public function item( $i ) {
2246 public function splitArg() {
2247 throw new MWException( __METHOD__
. ': not supported' );
2250 public function splitExt() {
2251 throw new MWException( __METHOD__
. ': not supported' );
2254 public function splitHeading() {
2255 throw new MWException( __METHOD__
. ': not supported' );