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 $stack->top
->close
=== '}-' &&
211 $stack->top
->count
> 2
213 # adjust closing for -{{{...{{
214 $currentClosing = '}';
215 $search .= $currentClosing;
217 $currentClosing = $stack->top
->close
;
218 $search .= $currentClosing;
224 // First equals will be for the template
228 # Output literal section, advance input counter
229 $literalLength = strcspn( $text, $search, $i );
230 if ( $literalLength > 0 ) {
231 self
::addLiteral( $accum, substr( $text, $i, $literalLength ) );
232 $i +
= $literalLength;
234 if ( $i >= $lengthText ) {
235 if ( $currentClosing == "\n" ) {
236 // Do a past-the-end run to finish off the heading
244 $curChar = $curTwoChar = $text[$i];
245 if ( ( $i +
1 ) < $lengthText ) {
246 $curTwoChar .= $text[$i +
1];
248 if ( $curChar == '|' ) {
250 } elseif ( $curChar == '=' ) {
252 } elseif ( $curChar == '<' ) {
254 } elseif ( $curChar == "\n" ) {
258 $found = 'line-start';
260 } elseif ( $curTwoChar == $currentClosing ) {
262 $curChar = $curTwoChar;
263 } elseif ( $curChar == $currentClosing ) {
265 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
266 $curChar = $curTwoChar;
268 $rule = $this->rules
[$curChar];
269 } elseif ( isset( $this->rules
[$curChar] ) ) {
271 $rule = $this->rules
[$curChar];
273 # Some versions of PHP have a strcspn which stops on
274 # null characters; ignore these and continue.
275 # We also may get '-' and '}' characters here which
276 # don't match -{ or $currentClosing. Add these to
277 # output and continue.
278 if ( $curChar == '-' ||
$curChar == '}' ) {
279 self
::addLiteral( $accum, $curChar );
287 if ( $found == 'angle' ) {
289 // Handle </onlyinclude>
290 if ( $enableOnlyinclude
291 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
293 $findOnlyinclude = true;
297 // Determine element name
298 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
299 // Element name missing or not listed
300 self
::addLiteral( $accum, '<' );
305 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
306 // To avoid leaving blank lines, when a sequence of
307 // space-separated comments is both preceded and followed by
308 // a newline (ignoring spaces), then
309 // trim leading and trailing spaces and the trailing newline.
312 $endPos = strpos( $text, '-->', $i +
4 );
313 if ( $endPos === false ) {
314 // Unclosed comment in input, runs to end
315 $inner = substr( $text, $i );
316 $accum[] = [ 'comment', [ $inner ] ];
319 // Search backwards for leading whitespace
320 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
322 // Search forwards for trailing whitespace
323 // $wsEnd will be the position of the last space (or the '>' if there's none)
324 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
326 // Keep looking forward as long as we're finding more
328 $comments = [ [ $wsStart, $wsEnd ] ];
329 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
330 $c = strpos( $text, '-->', $wsEnd +
4 );
331 if ( $c === false ) {
334 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
335 $comments[] = [ $wsEnd +
1, $c ];
339 // Eat the line if possible
340 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
341 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
342 // it's a possible beneficial b/c break.
343 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
344 && substr( $text, $wsEnd +
1, 1 ) == "\n"
346 // Remove leading whitespace from the end of the accumulator
347 $wsLength = $i - $wsStart;
348 $endIndex = count( $accum ) - 1;
353 && is_string( $accum[$endIndex] )
354 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
356 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
359 // Dump all but the last comment to the accumulator
360 foreach ( $comments as $j => $com ) {
362 $endPos = $com[1] +
1;
363 if ( $j == ( count( $comments ) - 1 ) ) {
366 $inner = substr( $text, $startPos, $endPos - $startPos );
367 $accum[] = [ 'comment', [ $inner ] ];
370 // Do a line-start run next time to look for headings after the comment
371 $fakeLineStart = true;
373 // No line to eat, just take the comment itself
379 $part = $stack->top
->getCurrentPart();
380 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
381 $part->visualEnd
= $wsStart;
383 // Else comments abutting, no change in visual end
384 $part->commentEnd
= $endPos;
387 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
388 $accum[] = [ 'comment', [ $inner ] ];
393 $lowerName = strtolower( $name );
394 $attrStart = $i +
strlen( $name ) +
1;
397 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
398 if ( $tagEndPos === false ) {
399 // Infinite backtrack
400 // Disable tag search to prevent worst-case O(N^2) performance
402 self
::addLiteral( $accum, '<' );
407 // Handle ignored tags
408 if ( in_array( $lowerName, $ignoredTags ) ) {
409 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i +
1 ) ] ];
415 if ( $text[$tagEndPos - 1] == '/' ) {
417 $attrEnd = $tagEndPos - 1;
422 $attrEnd = $tagEndPos;
425 !isset( $noMoreClosingTag[$name] ) &&
426 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
427 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
429 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
430 $i = $matches[0][1] +
strlen( $matches[0][0] );
431 $close = $matches[0][0];
434 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
435 // Let it run out to the end of the text.
436 $inner = substr( $text, $tagEndPos +
1 );
440 // Don't match the tag, treat opening tag as literal and resume parsing.
442 self
::addLiteral( $accum,
443 substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
444 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
445 $noMoreClosingTag[$name] = true;
450 // <includeonly> and <noinclude> just become <ignore> tags
451 if ( in_array( $lowerName, $ignoredElements ) ) {
452 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
456 if ( $attrEnd <= $attrStart ) {
459 // Note that the attr element contains the whitespace between name and attribute,
460 // this is necessary for precise reconstruction during pre-save transform.
461 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
465 [ 'name', [ $name ] ],
466 [ 'attr', [ $attr ] ] ];
467 if ( $inner !== null ) {
468 $children[] = [ 'inner', [ $inner ] ];
470 if ( $close !== null ) {
471 $children[] = [ 'close', [ $close ] ];
473 $accum[] = [ 'ext', $children ];
474 } elseif ( $found == 'line-start' ) {
475 // Is this the start of a heading?
476 // Line break belongs before the heading element in any case
477 if ( $fakeLineStart ) {
478 $fakeLineStart = false;
480 self
::addLiteral( $accum, $curChar );
484 $count = strspn( $text, '=', $i, 6 );
485 if ( $count == 1 && $findEquals ) {
486 // DWIM: This looks kind of like a name/value separator.
487 // Let's let the equals handler have it and break the potential
488 // heading. This is heuristic, but AFAICT the methods for
489 // completely correct disambiguation are very complex.
490 } elseif ( $count > 0 ) {
494 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
497 $stack->push( $piece );
498 $accum =& $stack->getAccum();
499 $stackFlags = $stack->getFlags();
500 if ( isset( $stackFlags['findEquals'] ) ) {
501 $findEquals = $stackFlags['findEquals'];
503 if ( isset( $stackFlags['findPipe'] ) ) {
504 $findPipe = $stackFlags['findPipe'];
506 if ( isset( $stackFlags['inHeading'] ) ) {
507 $inHeading = $stackFlags['inHeading'];
511 } elseif ( $found == 'line-end' ) {
512 $piece = $stack->top
;
513 // A heading must be open, otherwise \n wouldn't have been in the search list
514 assert( $piece->open
=== "\n" );
515 $part = $piece->getCurrentPart();
516 // Search back through the input to see if it has a proper close.
517 // Do this using the reversed string since the other solutions
518 // (end anchor, etc.) are inefficient.
519 $wsLength = strspn( $revText, " \t", $lengthText - $i );
520 $searchStart = $i - $wsLength;
521 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
522 // Comment found at line end
523 // Search for equals signs before the comment
524 $searchStart = $part->visualEnd
;
525 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
527 $count = $piece->count
;
528 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
529 if ( $equalsLength > 0 ) {
530 if ( $searchStart - $equalsLength == $piece->startPos
) {
531 // This is just a single string of equals signs on its own line
532 // Replicate the doHeadings behavior /={count}(.+)={count}/
533 // First find out how many equals signs there really are (don't stop at 6)
534 $count = $equalsLength;
538 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
541 $count = min( $equalsLength, $count );
544 // Normal match, output <h>
545 $element = [ [ 'possible-h',
548 [ '@level', [ $count ] ],
549 [ '@i', [ $headingIndex++
] ]
555 // Single equals sign on its own line, count=0
559 // No match, no <h>, just pass down the inner text
564 $accum =& $stack->getAccum();
565 $stackFlags = $stack->getFlags();
566 if ( isset( $stackFlags['findEquals'] ) ) {
567 $findEquals = $stackFlags['findEquals'];
569 if ( isset( $stackFlags['findPipe'] ) ) {
570 $findPipe = $stackFlags['findPipe'];
572 if ( isset( $stackFlags['inHeading'] ) ) {
573 $inHeading = $stackFlags['inHeading'];
576 // Append the result to the enclosing accumulator
577 array_splice( $accum, count( $accum ), 0, $element );
579 // Note that we do NOT increment the input pointer.
580 // This is because the closing linebreak could be the opening linebreak of
581 // another heading. Infinite loops are avoided because the next iteration MUST
582 // hit the heading open case above, which unconditionally increments the
584 } elseif ( $found == 'open' ) {
585 # count opening brace characters
586 $curLen = strlen( $curChar );
587 $count = ( $curLen > 1 ) ?
588 # allow the final character to repeat
589 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
590 strspn( $text, $curChar, $i );
592 # we need to add to stack only if opening brace count is enough for one of the rules
593 if ( $count >= $rule['min'] ) {
594 # Add it to the stack
597 'close' => $rule['end'],
599 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
602 $stack->push( $piece );
603 $accum =& $stack->getAccum();
604 $stackFlags = $stack->getFlags();
605 if ( isset( $stackFlags['findEquals'] ) ) {
606 $findEquals = $stackFlags['findEquals'];
608 if ( isset( $stackFlags['findPipe'] ) ) {
609 $findPipe = $stackFlags['findPipe'];
611 if ( isset( $stackFlags['inHeading'] ) ) {
612 $inHeading = $stackFlags['inHeading'];
615 # Add literal brace(s)
616 self
::addLiteral( $accum, str_repeat( $curChar, $count ) );
619 } elseif ( $found == 'close' ) {
620 $piece = $stack->top
;
621 # lets check if there are enough characters for closing brace
622 $maxCount = $piece->count
;
623 if ( $piece->close
=== '}-' && $curChar === '}' ) {
624 $maxCount--; # don't try to match closing '-' as a '}'
626 $curLen = strlen( $curChar );
627 $count = ( $curLen > 1 ) ?
$curLen :
628 strspn( $text, $curChar, $i, $maxCount );
630 # check for maximum matching characters (if there are 5 closing
631 # characters, we will probably need only 3 - depending on the rules)
632 $rule = $this->rules
[$piece->open
];
633 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
634 # tweak for -{..{{ }}..}-
635 $rule = $this->rules
['{'];
637 if ( $count > $rule['max'] ) {
638 # The specified maximum exists in the callback array, unless the caller
640 $matchingCount = $rule['max'];
642 # Count is less than the maximum
643 # Skip any gaps in the callback array to find the true largest match
644 # Need to use array_key_exists not isset because the callback can be null
645 $matchingCount = $count;
646 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
651 if ( $matchingCount <= 0 ) {
652 # No matching element found in callback array
653 # Output a literal closing brace and continue
654 $endText = substr( $text, $i, $count );
655 self
::addLiteral( $accum, $endText );
659 $name = $rule['names'][$matchingCount];
660 if ( $name === null ) {
661 // No element, just literal text
662 $endText = substr( $text, $i, $matchingCount );
663 $element = $piece->breakSyntax( $matchingCount );
664 self
::addLiteral( $element, $endText );
667 $parts = $piece->parts
;
668 $titleAccum = $parts[0]->out
;
673 # The invocation is at the start of the line if lineStart is set in
674 # the stack, and all opening brackets are used up.
675 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
676 $children[] = [ '@lineStart', [ 1 ] ];
678 $titleNode = [ 'title', $titleAccum ];
679 $children[] = $titleNode;
681 foreach ( $parts as $part ) {
682 if ( isset( $part->eqpos
) ) {
683 $equalsNode = $part->out
[$part->eqpos
];
684 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
685 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
686 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
687 $children[] = $partNode;
689 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
690 $valueNode = [ 'value', $part->out
];
691 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
692 $children[] = $partNode;
695 $element = [ [ $name, $children ] ];
698 # Advance input pointer
699 $i +
= $matchingCount;
703 $accum =& $stack->getAccum();
705 # Re-add the old stack element if it still has unmatched opening characters remaining
706 if ( $matchingCount < $piece->count
) {
707 $piece->parts
= [ new PPDPart_Hash
];
708 $piece->count
-= $matchingCount;
709 # do we still qualify for any callback with remaining count?
710 $min = $this->rules
[$piece->open
]['min'];
711 if ( $piece->count
>= $min ) {
712 $stack->push( $piece );
713 $accum =& $stack->getAccum();
715 $s = substr( $piece->open
, 0, -1 );
717 substr( $piece->open
, -1 ),
718 $piece->count
- strlen( $s )
720 self
::addLiteral( $accum, $s );
724 $stackFlags = $stack->getFlags();
725 if ( isset( $stackFlags['findEquals'] ) ) {
726 $findEquals = $stackFlags['findEquals'];
728 if ( isset( $stackFlags['findPipe'] ) ) {
729 $findPipe = $stackFlags['findPipe'];
731 if ( isset( $stackFlags['inHeading'] ) ) {
732 $inHeading = $stackFlags['inHeading'];
735 # Add XML element to the enclosing accumulator
736 array_splice( $accum, count( $accum ), 0, $element );
737 } elseif ( $found == 'pipe' ) {
738 $findEquals = true; // shortcut for getFlags()
740 $accum =& $stack->getAccum();
742 } elseif ( $found == 'equals' ) {
743 $findEquals = false; // shortcut for getFlags()
744 $accum[] = [ 'equals', [ '=' ] ];
745 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
750 # Output any remaining unclosed brackets
751 foreach ( $stack->stack
as $piece ) {
752 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
755 # Enable top-level headings
756 foreach ( $stack->rootAccum
as &$node ) {
757 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
758 $node[PPNode_Hash_Tree
::NAME
] = 'h';
762 $rootStore = [ [ 'root', $stack->rootAccum
] ];
763 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
766 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
767 if ( $tree !== false ) {
768 $this->cacheSetTree( $text, $flags, $tree );
774 private static function addLiteral( array &$accum, $text ) {
775 $n = count( $accum );
776 if ( $n && is_string( $accum[$n - 1] ) ) {
777 $accum[$n - 1] .= $text;
785 * Stack class to help Preprocessor::preprocessToObj()
788 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
789 class PPDStack_Hash
extends PPDStack
{
791 public function __construct() {
792 $this->elementClass
= PPDStackElement_Hash
::class;
793 parent
::__construct();
794 $this->rootAccum
= [];
801 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
802 class PPDStackElement_Hash
extends PPDStackElement
{
804 public function __construct( $data = [] ) {
805 $this->partClass
= PPDPart_Hash
::class;
806 parent
::__construct( $data );
810 * Get the accumulator that would result if the close is not found.
812 * @param int|bool $openingCount
815 public function breakSyntax( $openingCount = false ) {
816 if ( $this->open
== "\n" ) {
817 $accum = $this->parts
[0]->out
;
819 if ( $openingCount === false ) {
820 $openingCount = $this->count
;
822 $s = substr( $this->open
, 0, -1 );
824 substr( $this->open
, -1 ),
825 $openingCount - strlen( $s )
830 foreach ( $this->parts
as $part ) {
833 } elseif ( is_string( $accum[$lastIndex] ) ) {
834 $accum[$lastIndex] .= '|';
836 $accum[++
$lastIndex] = '|';
838 foreach ( $part->out
as $node ) {
839 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
840 $accum[$lastIndex] .= $node;
842 $accum[++
$lastIndex] = $node;
854 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
855 class PPDPart_Hash
extends PPDPart
{
857 public function __construct( $out = '' ) {
863 parent
::__construct( $accum );
868 * An expansion frame, used as a context to expand the result of preprocessToObj()
871 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
872 class PPFrame_Hash
implements PPFrame
{
882 public $preprocessor;
891 * Hashtable listing templates which are disallowed for expansion in this frame,
892 * having been encountered previously in parent frames.
894 public $loopCheckHash;
897 * Recursion depth of this frame, top = 0
898 * Note that this is NOT the same as expansion depth in expand()
902 private $volatile = false;
908 protected $childExpansionCache;
911 * Construct a new preprocessor frame.
912 * @param Preprocessor $preprocessor The parent preprocessor
914 public function __construct( $preprocessor ) {
915 $this->preprocessor
= $preprocessor;
916 $this->parser
= $preprocessor->parser
;
917 $this->title
= $this->parser
->mTitle
;
918 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
919 $this->loopCheckHash
= [];
921 $this->childExpansionCache
= [];
925 * Create a new child frame
926 * $args is optionally a multi-root PPNode or array containing the template arguments
928 * @param array|bool|PPNode_Hash_Array $args
929 * @param Title|bool $title
930 * @param int $indexOffset
931 * @throws MWException
932 * @return PPTemplateFrame_Hash
934 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
937 if ( $title === false ) {
938 $title = $this->title
;
940 if ( $args !== false ) {
941 if ( $args instanceof PPNode_Hash_Array
) {
942 $args = $args->value
;
943 } elseif ( !is_array( $args ) ) {
944 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
946 foreach ( $args as $arg ) {
947 $bits = $arg->splitArg();
948 if ( $bits['index'] !== '' ) {
949 // Numbered parameter
950 $index = $bits['index'] - $indexOffset;
951 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
952 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
953 wfEscapeWikiText( $this->title
),
954 wfEscapeWikiText( $title ),
955 wfEscapeWikiText( $index ) )->text() );
956 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
958 $numberedArgs[$index] = $bits['value'];
959 unset( $namedArgs[$index] );
962 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
963 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
964 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
965 wfEscapeWikiText( $this->title
),
966 wfEscapeWikiText( $title ),
967 wfEscapeWikiText( $name ) )->text() );
968 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
970 $namedArgs[$name] = $bits['value'];
971 unset( $numberedArgs[$name] );
975 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
979 * @throws MWException
980 * @param string|int $key
981 * @param string|PPNode $root
985 public function cachedExpand( $key, $root, $flags = 0 ) {
986 // we don't have a parent, so we don't have a cache
987 return $this->expand( $root, $flags );
991 * @throws MWException
992 * @param string|PPNode $root
996 public function expand( $root, $flags = 0 ) {
997 static $expansionDepth = 0;
998 if ( is_string( $root ) ) {
1002 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1003 $this->parser
->limitationWarn( 'node-count-exceeded',
1004 $this->parser
->mPPNodeCount
,
1005 $this->parser
->mOptions
->getMaxPPNodeCount()
1007 return '<span class="error">Node-count limit exceeded</span>';
1009 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1010 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1012 $this->parser
->mOptions
->getMaxPPExpandDepth()
1014 return '<span class="error">Expansion depth limit exceeded</span>';
1017 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1018 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1021 $outStack = [ '', '' ];
1022 $iteratorStack = [ false, $root ];
1023 $indexStack = [ 0, 0 ];
1025 while ( count( $iteratorStack ) > 1 ) {
1026 $level = count( $outStack ) - 1;
1027 $iteratorNode =& $iteratorStack[$level];
1028 $out =& $outStack[$level];
1029 $index =& $indexStack[$level];
1031 if ( is_array( $iteratorNode ) ) {
1032 if ( $index >= count( $iteratorNode ) ) {
1033 // All done with this iterator
1034 $iteratorStack[$level] = false;
1035 $contextNode = false;
1037 $contextNode = $iteratorNode[$index];
1040 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1041 if ( $index >= $iteratorNode->getLength() ) {
1042 // All done with this iterator
1043 $iteratorStack[$level] = false;
1044 $contextNode = false;
1046 $contextNode = $iteratorNode->item( $index );
1050 // Copy to $contextNode and then delete from iterator stack,
1051 // because this is not an iterator but we do have to execute it once
1052 $contextNode = $iteratorStack[$level];
1053 $iteratorStack[$level] = false;
1056 $newIterator = false;
1057 $contextName = false;
1058 $contextChildren = false;
1060 if ( $contextNode === false ) {
1062 } elseif ( is_string( $contextNode ) ) {
1063 $out .= $contextNode;
1064 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1065 $newIterator = $contextNode;
1066 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1068 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1069 $out .= $contextNode->value
;
1070 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1071 $contextName = $contextNode->name
;
1072 $contextChildren = $contextNode->getRawChildren();
1073 } elseif ( is_array( $contextNode ) ) {
1074 // Node descriptor array
1075 if ( count( $contextNode ) !== 2 ) {
1076 throw new MWException( __METHOD__
.
1077 ': found an array where a node descriptor should be' );
1079 list( $contextName, $contextChildren ) = $contextNode;
1081 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1084 // Handle node descriptor array or tree object
1085 if ( $contextName === false ) {
1086 // Not a node, already handled above
1087 } elseif ( $contextName[0] === '@' ) {
1088 // Attribute: no output
1089 } elseif ( $contextName === 'template' ) {
1090 # Double-brace expansion
1091 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1092 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1093 $newIterator = $this->virtualBracketedImplode(
1099 $ret = $this->parser
->braceSubstitution( $bits, $this );
1100 if ( isset( $ret['object'] ) ) {
1101 $newIterator = $ret['object'];
1103 $out .= $ret['text'];
1106 } elseif ( $contextName === 'tplarg' ) {
1107 # Triple-brace expansion
1108 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1109 if ( $flags & PPFrame
::NO_ARGS
) {
1110 $newIterator = $this->virtualBracketedImplode(
1116 $ret = $this->parser
->argSubstitution( $bits, $this );
1117 if ( isset( $ret['object'] ) ) {
1118 $newIterator = $ret['object'];
1120 $out .= $ret['text'];
1123 } elseif ( $contextName === 'comment' ) {
1124 # HTML-style comment
1125 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1126 # Not in RECOVER_COMMENTS mode (msgnw) though.
1127 if ( ( $this->parser
->ot
['html']
1128 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1129 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1130 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1133 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1134 # Add a strip marker in PST mode so that pstPass2() can
1135 # run some old-fashioned regexes on the result.
1136 # Not in RECOVER_COMMENTS mode (extractSections) though.
1137 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1139 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1140 $out .= $contextChildren[0];
1142 } elseif ( $contextName === 'ignore' ) {
1143 # Output suppression used by <includeonly> etc.
1144 # OT_WIKI will only respect <ignore> in substed templates.
1145 # The other output types respect it unless NO_IGNORE is set.
1146 # extractSections() sets NO_IGNORE and so never respects it.
1147 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1148 ||
( $flags & PPFrame
::NO_IGNORE
)
1150 $out .= $contextChildren[0];
1154 } elseif ( $contextName === 'ext' ) {
1156 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1157 [ 'attr' => null, 'inner' => null, 'close' => null ];
1158 if ( $flags & PPFrame
::NO_TAGS
) {
1159 $s = '<' . $bits['name']->getFirstChild()->value
;
1160 if ( $bits['attr'] ) {
1161 $s .= $bits['attr']->getFirstChild()->value
;
1163 if ( $bits['inner'] ) {
1164 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1165 if ( $bits['close'] ) {
1166 $s .= $bits['close']->getFirstChild()->value
;
1173 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1175 } elseif ( $contextName === 'h' ) {
1177 if ( $this->parser
->ot
['html'] ) {
1178 # Expand immediately and insert heading index marker
1179 $s = $this->expand( $contextChildren, $flags );
1180 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1181 $titleText = $this->title
->getPrefixedDBkey();
1182 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1183 $serial = count( $this->parser
->mHeadings
) - 1;
1184 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1185 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1186 $this->parser
->mStripState
->addGeneral( $marker, '' );
1189 # Expand in virtual stack
1190 $newIterator = $contextChildren;
1193 # Generic recursive expansion
1194 $newIterator = $contextChildren;
1197 if ( $newIterator !== false ) {
1199 $iteratorStack[] = $newIterator;
1201 } elseif ( $iteratorStack[$level] === false ) {
1202 // Return accumulated value to parent
1203 // With tail recursion
1204 while ( $iteratorStack[$level] === false && $level > 0 ) {
1205 $outStack[$level - 1] .= $out;
1206 array_pop( $outStack );
1207 array_pop( $iteratorStack );
1208 array_pop( $indexStack );
1214 return $outStack[0];
1218 * @param string $sep
1220 * @param string|PPNode $args,...
1223 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1224 $args = array_slice( func_get_args(), 2 );
1228 foreach ( $args as $root ) {
1229 if ( $root instanceof PPNode_Hash_Array
) {
1230 $root = $root->value
;
1232 if ( !is_array( $root ) ) {
1235 foreach ( $root as $node ) {
1241 $s .= $this->expand( $node, $flags );
1248 * Implode with no flags specified
1249 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1250 * @param string $sep
1251 * @param string|PPNode $args,...
1254 public function implode( $sep /*, ... */ ) {
1255 $args = array_slice( func_get_args(), 1 );
1259 foreach ( $args as $root ) {
1260 if ( $root instanceof PPNode_Hash_Array
) {
1261 $root = $root->value
;
1263 if ( !is_array( $root ) ) {
1266 foreach ( $root as $node ) {
1272 $s .= $this->expand( $node );
1279 * Makes an object that, when expand()ed, will be the same as one obtained
1282 * @param string $sep
1283 * @param string|PPNode $args,...
1284 * @return PPNode_Hash_Array
1286 public function virtualImplode( $sep /*, ... */ ) {
1287 $args = array_slice( func_get_args(), 1 );
1291 foreach ( $args as $root ) {
1292 if ( $root instanceof PPNode_Hash_Array
) {
1293 $root = $root->value
;
1295 if ( !is_array( $root ) ) {
1298 foreach ( $root as $node ) {
1307 return new PPNode_Hash_Array( $out );
1311 * Virtual implode with brackets
1313 * @param string $start
1314 * @param string $sep
1315 * @param string $end
1316 * @param string|PPNode $args,...
1317 * @return PPNode_Hash_Array
1319 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1320 $args = array_slice( func_get_args(), 3 );
1324 foreach ( $args as $root ) {
1325 if ( $root instanceof PPNode_Hash_Array
) {
1326 $root = $root->value
;
1328 if ( !is_array( $root ) ) {
1331 foreach ( $root as $node ) {
1341 return new PPNode_Hash_Array( $out );
1344 public function __toString() {
1349 * @param bool $level
1350 * @return array|bool|string
1352 public function getPDBK( $level = false ) {
1353 if ( $level === false ) {
1354 return $this->title
->getPrefixedDBkey();
1356 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1363 public function getArguments() {
1370 public function getNumberedArguments() {
1377 public function getNamedArguments() {
1382 * Returns true if there are no arguments in this frame
1386 public function isEmpty() {
1391 * @param int|string $name
1392 * @return bool Always false in this implementation.
1394 public function getArgument( $name ) {
1399 * Returns true if the infinite loop check is OK, false if a loop is detected
1401 * @param Title $title
1405 public function loopCheck( $title ) {
1406 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1410 * Return true if the frame is a template frame
1414 public function isTemplate() {
1419 * Get a title of frame
1423 public function getTitle() {
1424 return $this->title
;
1428 * Set the volatile flag
1432 public function setVolatile( $flag = true ) {
1433 $this->volatile
= $flag;
1437 * Get the volatile flag
1441 public function isVolatile() {
1442 return $this->volatile
;
1450 public function setTTL( $ttl ) {
1451 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1461 public function getTTL() {
1467 * Expansion frame with template arguments
1470 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1471 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1473 public $numberedArgs, $namedArgs, $parent;
1474 public $numberedExpansionCache, $namedExpansionCache;
1477 * @param Preprocessor $preprocessor
1478 * @param bool|PPFrame $parent
1479 * @param array $numberedArgs
1480 * @param array $namedArgs
1481 * @param bool|Title $title
1483 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1484 $namedArgs = [], $title = false
1486 parent
::__construct( $preprocessor );
1488 $this->parent
= $parent;
1489 $this->numberedArgs
= $numberedArgs;
1490 $this->namedArgs
= $namedArgs;
1491 $this->title
= $title;
1492 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1493 $this->titleCache
= $parent->titleCache
;
1494 $this->titleCache
[] = $pdbk;
1495 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1496 if ( $pdbk !== false ) {
1497 $this->loopCheckHash
[$pdbk] = true;
1499 $this->depth
= $parent->depth +
1;
1500 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1503 public function __toString() {
1506 $args = $this->numberedArgs +
$this->namedArgs
;
1507 foreach ( $args as $name => $value ) {
1513 $s .= "\"$name\":\"" .
1514 str_replace( '"', '\\"', $value->__toString() ) . '"';
1521 * @throws MWException
1522 * @param string|int $key
1523 * @param string|PPNode $root
1527 public function cachedExpand( $key, $root, $flags = 0 ) {
1528 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1529 return $this->parent
->childExpansionCache
[$key];
1531 $retval = $this->expand( $root, $flags );
1532 if ( !$this->isVolatile() ) {
1533 $this->parent
->childExpansionCache
[$key] = $retval;
1539 * Returns true if there are no arguments in this frame
1543 public function isEmpty() {
1544 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1550 public function getArguments() {
1552 foreach ( array_merge(
1553 array_keys( $this->numberedArgs
),
1554 array_keys( $this->namedArgs
) ) as $key ) {
1555 $arguments[$key] = $this->getArgument( $key );
1563 public function getNumberedArguments() {
1565 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1566 $arguments[$key] = $this->getArgument( $key );
1574 public function getNamedArguments() {
1576 foreach ( array_keys( $this->namedArgs
) as $key ) {
1577 $arguments[$key] = $this->getArgument( $key );
1584 * @return string|bool
1586 public function getNumberedArgument( $index ) {
1587 if ( !isset( $this->numberedArgs
[$index] ) ) {
1590 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1591 # No trimming for unnamed arguments
1592 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1593 $this->numberedArgs
[$index],
1594 PPFrame
::STRIP_COMMENTS
1597 return $this->numberedExpansionCache
[$index];
1601 * @param string $name
1602 * @return string|bool
1604 public function getNamedArgument( $name ) {
1605 if ( !isset( $this->namedArgs
[$name] ) ) {
1608 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1609 # Trim named arguments post-expand, for backwards compatibility
1610 $this->namedExpansionCache
[$name] = trim(
1611 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1613 return $this->namedExpansionCache
[$name];
1617 * @param int|string $name
1618 * @return string|bool
1620 public function getArgument( $name ) {
1621 $text = $this->getNumberedArgument( $name );
1622 if ( $text === false ) {
1623 $text = $this->getNamedArgument( $name );
1629 * Return true if the frame is a template frame
1633 public function isTemplate() {
1637 public function setVolatile( $flag = true ) {
1638 parent
::setVolatile( $flag );
1639 $this->parent
->setVolatile( $flag );
1642 public function setTTL( $ttl ) {
1643 parent
::setTTL( $ttl );
1644 $this->parent
->setTTL( $ttl );
1649 * Expansion frame with custom arguments
1652 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1653 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1657 public function __construct( $preprocessor, $args ) {
1658 parent
::__construct( $preprocessor );
1659 $this->args
= $args;
1662 public function __toString() {
1665 foreach ( $this->args
as $name => $value ) {
1671 $s .= "\"$name\":\"" .
1672 str_replace( '"', '\\"', $value->__toString() ) . '"';
1681 public function isEmpty() {
1682 return !count( $this->args
);
1686 * @param int|string $index
1687 * @return string|bool
1689 public function getArgument( $index ) {
1690 if ( !isset( $this->args
[$index] ) ) {
1693 return $this->args
[$index];
1696 public function getArguments() {
1704 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1705 class PPNode_Hash_Tree
implements PPNode
{
1710 * The store array for children of this node. It is "raw" in the sense that
1711 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1714 private $rawChildren;
1717 * The store array for the siblings of this node, including this node itself.
1722 * The index into $this->store which contains the descriptor of this node.
1727 * The offset of the name within descriptors, used in some places for
1733 * The offset of the child list within descriptors, used in some places for
1739 * Construct an object using the data from $store[$index]. The rest of the
1740 * store array can be accessed via getNextSibling().
1742 * @param array $store
1745 public function __construct( array $store, $index ) {
1746 $this->store
= $store;
1747 $this->index
= $index;
1748 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1752 * Construct an appropriate PPNode_Hash_* object with a class that depends
1753 * on what is at the relevant store index.
1755 * @param array $store
1757 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1759 public static function factory( array $store, $index ) {
1760 if ( !isset( $store[$index] ) ) {
1764 $descriptor = $store[$index];
1765 if ( is_string( $descriptor ) ) {
1766 $class = PPNode_Hash_Text
::class;
1767 } elseif ( is_array( $descriptor ) ) {
1768 if ( $descriptor[self
::NAME
][0] === '@' ) {
1769 $class = PPNode_Hash_Attr
::class;
1771 $class = self
::class;
1774 throw new MWException( __METHOD__
.': invalid node descriptor' );
1776 return new $class( $store, $index );
1780 * Convert a node to XML, for debugging
1782 public function __toString() {
1785 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1786 if ( $node instanceof PPNode_Hash_Attr
) {
1787 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1789 $inner .= $node->__toString();
1792 if ( $inner === '' ) {
1793 return "<{$this->name}$attribs/>";
1795 return "<{$this->name}$attribs>$inner</{$this->name}>";
1800 * @return PPNode_Hash_Array
1802 public function getChildren() {
1804 foreach ( $this->rawChildren
as $i => $child ) {
1805 $children[] = self
::factory( $this->rawChildren
, $i );
1807 return new PPNode_Hash_Array( $children );
1811 * Get the first child, or false if there is none. Note that this will
1812 * return a temporary proxy object: different instances will be returned
1813 * if this is called more than once on the same node.
1815 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1817 public function getFirstChild() {
1818 if ( !isset( $this->rawChildren
[0] ) ) {
1821 return self
::factory( $this->rawChildren
, 0 );
1826 * Get the next sibling, or false if there is none. Note that this will
1827 * return a temporary proxy object: different instances will be returned
1828 * if this is called more than once on the same node.
1830 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1832 public function getNextSibling() {
1833 return self
::factory( $this->store
, $this->index +
1 );
1837 * Get an array of the children with a given node name
1839 * @param string $name
1840 * @return PPNode_Hash_Array
1842 public function getChildrenOfType( $name ) {
1844 foreach ( $this->rawChildren
as $i => $child ) {
1845 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1846 $children[] = self
::factory( $this->rawChildren
, $i );
1849 return new PPNode_Hash_Array( $children );
1853 * Get the raw child array. For internal use.
1856 public function getRawChildren() {
1857 return $this->rawChildren
;
1863 public function getLength() {
1871 public function item( $i ) {
1878 public function getName() {
1883 * Split a "<part>" node into an associative array containing:
1884 * - name PPNode name
1885 * - index String index
1886 * - value PPNode value
1888 * @throws MWException
1891 public function splitArg() {
1892 return self
::splitRawArg( $this->rawChildren
);
1896 * Like splitArg() but for a raw child array. For internal use only.
1897 * @param array $children
1900 public static function splitRawArg( array $children ) {
1902 foreach ( $children as $i => $child ) {
1903 if ( !is_array( $child ) ) {
1906 if ( $child[self
::NAME
] === 'name' ) {
1907 $bits['name'] = new self( $children, $i );
1908 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1909 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1911 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1913 } elseif ( $child[self
::NAME
] === 'value' ) {
1914 $bits['value'] = new self( $children, $i );
1918 if ( !isset( $bits['name'] ) ) {
1919 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1921 if ( !isset( $bits['index'] ) ) {
1922 $bits['index'] = '';
1928 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1929 * All values in the resulting array are PPNodes. Inner and close are optional.
1931 * @throws MWException
1934 public function splitExt() {
1935 return self
::splitRawExt( $this->rawChildren
);
1939 * Like splitExt() but for a raw child array. For internal use only.
1940 * @param array $children
1943 public static function splitRawExt( array $children ) {
1945 foreach ( $children as $i => $child ) {
1946 if ( !is_array( $child ) ) {
1949 switch ( $child[self
::NAME
] ) {
1951 $bits['name'] = new self( $children, $i );
1954 $bits['attr'] = new self( $children, $i );
1957 $bits['inner'] = new self( $children, $i );
1960 $bits['close'] = new self( $children, $i );
1964 if ( !isset( $bits['name'] ) ) {
1965 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1971 * Split an "<h>" node
1973 * @throws MWException
1976 public function splitHeading() {
1977 if ( $this->name
!== 'h' ) {
1978 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1980 return self
::splitRawHeading( $this->rawChildren
);
1984 * Like splitHeading() but for a raw child array. For internal use only.
1985 * @param array $children
1988 public static function splitRawHeading( array $children ) {
1990 foreach ( $children as $i => $child ) {
1991 if ( !is_array( $child ) ) {
1994 if ( $child[self
::NAME
] === '@i' ) {
1995 $bits['i'] = $child[self
::CHILDREN
][0];
1996 } elseif ( $child[self
::NAME
] === '@level' ) {
1997 $bits['level'] = $child[self
::CHILDREN
][0];
2000 if ( !isset( $bits['i'] ) ) {
2001 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2007 * Split a "<template>" or "<tplarg>" node
2009 * @throws MWException
2012 public function splitTemplate() {
2013 return self
::splitRawTemplate( $this->rawChildren
);
2017 * Like splitTemplate() but for a raw child array. For internal use only.
2018 * @param array $children
2021 public static function splitRawTemplate( array $children ) {
2023 $bits = [ 'lineStart' => '' ];
2024 foreach ( $children as $i => $child ) {
2025 if ( !is_array( $child ) ) {
2028 switch ( $child[self
::NAME
] ) {
2030 $bits['title'] = new self( $children, $i );
2033 $parts[] = new self( $children, $i );
2036 $bits['lineStart'] = '1';
2040 if ( !isset( $bits['title'] ) ) {
2041 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
2043 $bits['parts'] = new PPNode_Hash_Array( $parts );
2051 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2052 class PPNode_Hash_Text
implements PPNode
{
2055 private $store, $index;
2058 * Construct an object using the data from $store[$index]. The rest of the
2059 * store array can be accessed via getNextSibling().
2061 * @param array $store
2064 public function __construct( array $store, $index ) {
2065 $this->value
= $store[$index];
2066 if ( !is_scalar( $this->value
) ) {
2067 throw new MWException( __CLASS__
. ' given object instead of string' );
2069 $this->store
= $store;
2070 $this->index
= $index;
2073 public function __toString() {
2074 return htmlspecialchars( $this->value
);
2077 public function getNextSibling() {
2078 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2081 public function getChildren() {
2085 public function getFirstChild() {
2089 public function getChildrenOfType( $name ) {
2093 public function getLength() {
2097 public function item( $i ) {
2101 public function getName() {
2105 public function splitArg() {
2106 throw new MWException( __METHOD__
. ': not supported' );
2109 public function splitExt() {
2110 throw new MWException( __METHOD__
. ': not supported' );
2113 public function splitHeading() {
2114 throw new MWException( __METHOD__
. ': not supported' );
2121 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2122 class PPNode_Hash_Array
implements PPNode
{
2126 public function __construct( $value ) {
2127 $this->value
= $value;
2130 public function __toString() {
2131 return var_export( $this, true );
2134 public function getLength() {
2135 return count( $this->value
);
2138 public function item( $i ) {
2139 return $this->value
[$i];
2142 public function getName() {
2146 public function getNextSibling() {
2150 public function getChildren() {
2154 public function getFirstChild() {
2158 public function getChildrenOfType( $name ) {
2162 public function splitArg() {
2163 throw new MWException( __METHOD__
. ': not supported' );
2166 public function splitExt() {
2167 throw new MWException( __METHOD__
. ': not supported' );
2170 public function splitHeading() {
2171 throw new MWException( __METHOD__
. ': not supported' );
2178 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2179 class PPNode_Hash_Attr
implements PPNode
{
2181 public $name, $value;
2182 private $store, $index;
2185 * Construct an object using the data from $store[$index]. The rest of the
2186 * store array can be accessed via getNextSibling().
2188 * @param array $store
2191 public function __construct( array $store, $index ) {
2192 $descriptor = $store[$index];
2193 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2194 throw new MWException( __METHOD__
.': invalid name in attribute descriptor' );
2196 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2197 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2198 $this->store
= $store;
2199 $this->index
= $index;
2202 public function __toString() {
2203 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2206 public function getName() {
2210 public function getNextSibling() {
2211 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2214 public function getChildren() {
2218 public function getFirstChild() {
2222 public function getChildrenOfType( $name ) {
2226 public function getLength() {
2230 public function item( $i ) {
2234 public function splitArg() {
2235 throw new MWException( __METHOD__
. ': not supported' );
2238 public function splitExt() {
2239 throw new MWException( __METHOD__
. ': not supported' );
2242 public function splitHeading() {
2243 throw new MWException( __METHOD__
. ': not supported' );