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 assert( $piece->open
=== "\n" );
508 $part = $piece->getCurrentPart();
509 // Search back through the input to see if it has a proper close.
510 // Do this using the reversed string since the other solutions
511 // (end anchor, etc.) are inefficient.
512 $wsLength = strspn( $revText, " \t", $lengthText - $i );
513 $searchStart = $i - $wsLength;
514 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
515 // Comment found at line end
516 // Search for equals signs before the comment
517 $searchStart = $part->visualEnd
;
518 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
520 $count = $piece->count
;
521 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
522 if ( $equalsLength > 0 ) {
523 if ( $searchStart - $equalsLength == $piece->startPos
) {
524 // This is just a single string of equals signs on its own line
525 // Replicate the doHeadings behavior /={count}(.+)={count}/
526 // First find out how many equals signs there really are (don't stop at 6)
527 $count = $equalsLength;
531 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
534 $count = min( $equalsLength, $count );
537 // Normal match, output <h>
538 $element = [ [ 'possible-h',
541 [ '@level', [ $count ] ],
542 [ '@i', [ $headingIndex++
] ]
548 // Single equals sign on its own line, count=0
552 // No match, no <h>, just pass down the inner text
557 $accum =& $stack->getAccum();
558 $stackFlags = $stack->getFlags();
559 if ( isset( $stackFlags['findEquals'] ) ) {
560 $findEquals = $stackFlags['findEquals'];
562 if ( isset( $stackFlags['findPipe'] ) ) {
563 $findPipe = $stackFlags['findPipe'];
565 if ( isset( $stackFlags['inHeading'] ) ) {
566 $inHeading = $stackFlags['inHeading'];
569 // Append the result to the enclosing accumulator
570 array_splice( $accum, count( $accum ), 0, $element );
572 // Note that we do NOT increment the input pointer.
573 // This is because the closing linebreak could be the opening linebreak of
574 // another heading. Infinite loops are avoided because the next iteration MUST
575 // hit the heading open case above, which unconditionally increments the
577 } elseif ( $found == 'open' ) {
578 # count opening brace characters
579 $curLen = strlen( $curChar );
580 $count = ( $curLen > 1 ) ?
581 # allow the final character to repeat
582 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
583 strspn( $text, $curChar, $i );
586 $lineStart = ( $i > 0 && $text[$i - 1] == "\n" );
588 if ( $curChar === "-{" && $count > $curLen ) {
589 // -{ => {{ transition because rightmost wins
594 $rule = $this->rules
[$curChar];
597 # we need to add to stack only if opening brace count is enough for one of the rules
598 if ( $count >= $rule['min'] ) {
599 # Add it to the stack
602 'close' => $rule['end'],
603 'savedPrefix' => $savedPrefix,
605 'lineStart' => $lineStart,
608 $stack->push( $piece );
609 $accum =& $stack->getAccum();
610 $stackFlags = $stack->getFlags();
611 if ( isset( $stackFlags['findEquals'] ) ) {
612 $findEquals = $stackFlags['findEquals'];
614 if ( isset( $stackFlags['findPipe'] ) ) {
615 $findPipe = $stackFlags['findPipe'];
617 if ( isset( $stackFlags['inHeading'] ) ) {
618 $inHeading = $stackFlags['inHeading'];
621 # Add literal brace(s)
622 self
::addLiteral( $accum, $savedPrefix . str_repeat( $curChar, $count ) );
625 } elseif ( $found == 'close' ) {
626 $piece = $stack->top
;
627 # lets check if there are enough characters for closing brace
628 $maxCount = $piece->count
;
629 if ( $piece->close
=== '}-' && $curChar === '}' ) {
630 $maxCount--; # don't try to match closing '-' as a '}'
632 $curLen = strlen( $curChar );
633 $count = ( $curLen > 1 ) ?
$curLen :
634 strspn( $text, $curChar, $i, $maxCount );
636 # check for maximum matching characters (if there are 5 closing
637 # characters, we will probably need only 3 - depending on the rules)
638 $rule = $this->rules
[$piece->open
];
639 if ( $count > $rule['max'] ) {
640 # The specified maximum exists in the callback array, unless the caller
642 $matchingCount = $rule['max'];
644 # Count is less than the maximum
645 # Skip any gaps in the callback array to find the true largest match
646 # Need to use array_key_exists not isset because the callback can be null
647 $matchingCount = $count;
648 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
653 if ( $matchingCount <= 0 ) {
654 # No matching element found in callback array
655 # Output a literal closing brace and continue
656 $endText = substr( $text, $i, $count );
657 self
::addLiteral( $accum, $endText );
661 $name = $rule['names'][$matchingCount];
662 if ( $name === null ) {
663 // No element, just literal text
664 $endText = substr( $text, $i, $matchingCount );
665 $element = $piece->breakSyntax( $matchingCount );
666 self
::addLiteral( $element, $endText );
669 $parts = $piece->parts
;
670 $titleAccum = $parts[0]->out
;
675 # The invocation is at the start of the line if lineStart is set in
676 # the stack, and all opening brackets are used up.
677 if ( $maxCount == $matchingCount &&
678 !empty( $piece->lineStart
) &&
679 strlen( $piece->savedPrefix
) == 0 ) {
680 $children[] = [ '@lineStart', [ 1 ] ];
682 $titleNode = [ 'title', $titleAccum ];
683 $children[] = $titleNode;
685 foreach ( $parts as $part ) {
686 if ( isset( $part->eqpos
) ) {
687 $equalsNode = $part->out
[$part->eqpos
];
688 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
689 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
690 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
691 $children[] = $partNode;
693 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
694 $valueNode = [ 'value', $part->out
];
695 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
696 $children[] = $partNode;
699 $element = [ [ $name, $children ] ];
702 # Advance input pointer
703 $i +
= $matchingCount;
707 $accum =& $stack->getAccum();
709 # Re-add the old stack element if it still has unmatched opening characters remaining
710 if ( $matchingCount < $piece->count
) {
711 $piece->parts
= [ new PPDPart_Hash
];
712 $piece->count
-= $matchingCount;
713 # do we still qualify for any callback with remaining count?
714 $min = $this->rules
[$piece->open
]['min'];
715 if ( $piece->count
>= $min ) {
716 $stack->push( $piece );
717 $accum =& $stack->getAccum();
718 } elseif ( $piece->count
== 1 && $piece->open
=== '{' && $piece->savedPrefix
=== '-' ) {
719 $piece->savedPrefix
= '';
722 $piece->close
= $this->rules
[$piece->open
]['end'];
723 $stack->push( $piece );
724 $accum =& $stack->getAccum();
726 $s = substr( $piece->open
, 0, -1 );
728 substr( $piece->open
, -1 ),
729 $piece->count
- strlen( $s )
731 self
::addLiteral( $accum, $piece->savedPrefix
. $s );
733 } elseif ( $piece->savedPrefix
!== '' ) {
734 self
::addLiteral( $accum, $piece->savedPrefix
);
737 $stackFlags = $stack->getFlags();
738 if ( isset( $stackFlags['findEquals'] ) ) {
739 $findEquals = $stackFlags['findEquals'];
741 if ( isset( $stackFlags['findPipe'] ) ) {
742 $findPipe = $stackFlags['findPipe'];
744 if ( isset( $stackFlags['inHeading'] ) ) {
745 $inHeading = $stackFlags['inHeading'];
748 # Add XML element to the enclosing accumulator
749 array_splice( $accum, count( $accum ), 0, $element );
750 } elseif ( $found == 'pipe' ) {
751 $findEquals = true; // shortcut for getFlags()
753 $accum =& $stack->getAccum();
755 } elseif ( $found == 'equals' ) {
756 $findEquals = false; // shortcut for getFlags()
757 $accum[] = [ 'equals', [ '=' ] ];
758 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
763 # Output any remaining unclosed brackets
764 foreach ( $stack->stack
as $piece ) {
765 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
768 # Enable top-level headings
769 foreach ( $stack->rootAccum
as &$node ) {
770 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
771 $node[PPNode_Hash_Tree
::NAME
] = 'h';
775 $rootStore = [ [ 'root', $stack->rootAccum
] ];
776 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
779 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
780 if ( $tree !== false ) {
781 $this->cacheSetTree( $text, $flags, $tree );
787 private static function addLiteral( array &$accum, $text ) {
788 $n = count( $accum );
789 if ( $n && is_string( $accum[$n - 1] ) ) {
790 $accum[$n - 1] .= $text;
798 * Stack class to help Preprocessor::preprocessToObj()
801 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
802 class PPDStack_Hash
extends PPDStack
{
804 public function __construct() {
805 $this->elementClass
= PPDStackElement_Hash
::class;
806 parent
::__construct();
807 $this->rootAccum
= [];
814 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
815 class PPDStackElement_Hash
extends PPDStackElement
{
817 public function __construct( $data = [] ) {
818 $this->partClass
= PPDPart_Hash
::class;
819 parent
::__construct( $data );
823 * Get the accumulator that would result if the close is not found.
825 * @param int|bool $openingCount
828 public function breakSyntax( $openingCount = false ) {
829 if ( $this->open
== "\n" ) {
830 $accum = array_merge( [ $this->savedPrefix
], $this->parts
[0]->out
);
832 if ( $openingCount === false ) {
833 $openingCount = $this->count
;
835 $s = substr( $this->open
, 0, -1 );
837 substr( $this->open
, -1 ),
838 $openingCount - strlen( $s )
840 $accum = [ $this->savedPrefix
. $s ];
843 foreach ( $this->parts
as $part ) {
846 } elseif ( is_string( $accum[$lastIndex] ) ) {
847 $accum[$lastIndex] .= '|';
849 $accum[++
$lastIndex] = '|';
851 foreach ( $part->out
as $node ) {
852 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
853 $accum[$lastIndex] .= $node;
855 $accum[++
$lastIndex] = $node;
867 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
868 class PPDPart_Hash
extends PPDPart
{
870 public function __construct( $out = '' ) {
876 parent
::__construct( $accum );
881 * An expansion frame, used as a context to expand the result of preprocessToObj()
884 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
885 class PPFrame_Hash
implements PPFrame
{
895 public $preprocessor;
904 * Hashtable listing templates which are disallowed for expansion in this frame,
905 * having been encountered previously in parent frames.
907 public $loopCheckHash;
910 * Recursion depth of this frame, top = 0
911 * Note that this is NOT the same as expansion depth in expand()
915 private $volatile = false;
921 protected $childExpansionCache;
924 * Construct a new preprocessor frame.
925 * @param Preprocessor $preprocessor The parent preprocessor
927 public function __construct( $preprocessor ) {
928 $this->preprocessor
= $preprocessor;
929 $this->parser
= $preprocessor->parser
;
930 $this->title
= $this->parser
->mTitle
;
931 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
932 $this->loopCheckHash
= [];
934 $this->childExpansionCache
= [];
938 * Create a new child frame
939 * $args is optionally a multi-root PPNode or array containing the template arguments
941 * @param array|bool|PPNode_Hash_Array $args
942 * @param Title|bool $title
943 * @param int $indexOffset
944 * @throws MWException
945 * @return PPTemplateFrame_Hash
947 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
950 if ( $title === false ) {
951 $title = $this->title
;
953 if ( $args !== false ) {
954 if ( $args instanceof PPNode_Hash_Array
) {
955 $args = $args->value
;
956 } elseif ( !is_array( $args ) ) {
957 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
959 foreach ( $args as $arg ) {
960 $bits = $arg->splitArg();
961 if ( $bits['index'] !== '' ) {
962 // Numbered parameter
963 $index = $bits['index'] - $indexOffset;
964 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
965 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
966 wfEscapeWikiText( $this->title
),
967 wfEscapeWikiText( $title ),
968 wfEscapeWikiText( $index ) )->text() );
969 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
971 $numberedArgs[$index] = $bits['value'];
972 unset( $namedArgs[$index] );
975 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
976 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
977 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
978 wfEscapeWikiText( $this->title
),
979 wfEscapeWikiText( $title ),
980 wfEscapeWikiText( $name ) )->text() );
981 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
983 $namedArgs[$name] = $bits['value'];
984 unset( $numberedArgs[$name] );
988 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
992 * @throws MWException
993 * @param string|int $key
994 * @param string|PPNode $root
998 public function cachedExpand( $key, $root, $flags = 0 ) {
999 // we don't have a parent, so we don't have a cache
1000 return $this->expand( $root, $flags );
1004 * @throws MWException
1005 * @param string|PPNode $root
1009 public function expand( $root, $flags = 0 ) {
1010 static $expansionDepth = 0;
1011 if ( is_string( $root ) ) {
1015 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1016 $this->parser
->limitationWarn( 'node-count-exceeded',
1017 $this->parser
->mPPNodeCount
,
1018 $this->parser
->mOptions
->getMaxPPNodeCount()
1020 return '<span class="error">Node-count limit exceeded</span>';
1022 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1023 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1025 $this->parser
->mOptions
->getMaxPPExpandDepth()
1027 return '<span class="error">Expansion depth limit exceeded</span>';
1030 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1031 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1034 $outStack = [ '', '' ];
1035 $iteratorStack = [ false, $root ];
1036 $indexStack = [ 0, 0 ];
1038 while ( count( $iteratorStack ) > 1 ) {
1039 $level = count( $outStack ) - 1;
1040 $iteratorNode =& $iteratorStack[$level];
1041 $out =& $outStack[$level];
1042 $index =& $indexStack[$level];
1044 if ( is_array( $iteratorNode ) ) {
1045 if ( $index >= count( $iteratorNode ) ) {
1046 // All done with this iterator
1047 $iteratorStack[$level] = false;
1048 $contextNode = false;
1050 $contextNode = $iteratorNode[$index];
1053 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1054 if ( $index >= $iteratorNode->getLength() ) {
1055 // All done with this iterator
1056 $iteratorStack[$level] = false;
1057 $contextNode = false;
1059 $contextNode = $iteratorNode->item( $index );
1063 // Copy to $contextNode and then delete from iterator stack,
1064 // because this is not an iterator but we do have to execute it once
1065 $contextNode = $iteratorStack[$level];
1066 $iteratorStack[$level] = false;
1069 $newIterator = false;
1070 $contextName = false;
1071 $contextChildren = false;
1073 if ( $contextNode === false ) {
1075 } elseif ( is_string( $contextNode ) ) {
1076 $out .= $contextNode;
1077 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1078 $newIterator = $contextNode;
1079 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1081 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1082 $out .= $contextNode->value
;
1083 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1084 $contextName = $contextNode->name
;
1085 $contextChildren = $contextNode->getRawChildren();
1086 } elseif ( is_array( $contextNode ) ) {
1087 // Node descriptor array
1088 if ( count( $contextNode ) !== 2 ) {
1089 throw new MWException( __METHOD__
.
1090 ': found an array where a node descriptor should be' );
1092 list( $contextName, $contextChildren ) = $contextNode;
1094 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1097 // Handle node descriptor array or tree object
1098 if ( $contextName === false ) {
1099 // Not a node, already handled above
1100 } elseif ( $contextName[0] === '@' ) {
1101 // Attribute: no output
1102 } elseif ( $contextName === 'template' ) {
1103 # Double-brace expansion
1104 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1105 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1106 $newIterator = $this->virtualBracketedImplode(
1112 $ret = $this->parser
->braceSubstitution( $bits, $this );
1113 if ( isset( $ret['object'] ) ) {
1114 $newIterator = $ret['object'];
1116 $out .= $ret['text'];
1119 } elseif ( $contextName === 'tplarg' ) {
1120 # Triple-brace expansion
1121 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1122 if ( $flags & PPFrame
::NO_ARGS
) {
1123 $newIterator = $this->virtualBracketedImplode(
1129 $ret = $this->parser
->argSubstitution( $bits, $this );
1130 if ( isset( $ret['object'] ) ) {
1131 $newIterator = $ret['object'];
1133 $out .= $ret['text'];
1136 } elseif ( $contextName === 'comment' ) {
1137 # HTML-style comment
1138 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1139 # Not in RECOVER_COMMENTS mode (msgnw) though.
1140 if ( ( $this->parser
->ot
['html']
1141 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1142 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1143 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1146 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1147 # Add a strip marker in PST mode so that pstPass2() can
1148 # run some old-fashioned regexes on the result.
1149 # Not in RECOVER_COMMENTS mode (extractSections) though.
1150 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1152 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1153 $out .= $contextChildren[0];
1155 } elseif ( $contextName === 'ignore' ) {
1156 # Output suppression used by <includeonly> etc.
1157 # OT_WIKI will only respect <ignore> in substed templates.
1158 # The other output types respect it unless NO_IGNORE is set.
1159 # extractSections() sets NO_IGNORE and so never respects it.
1160 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1161 ||
( $flags & PPFrame
::NO_IGNORE
)
1163 $out .= $contextChildren[0];
1167 } elseif ( $contextName === 'ext' ) {
1169 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1170 [ 'attr' => null, 'inner' => null, 'close' => null ];
1171 if ( $flags & PPFrame
::NO_TAGS
) {
1172 $s = '<' . $bits['name']->getFirstChild()->value
;
1173 if ( $bits['attr'] ) {
1174 $s .= $bits['attr']->getFirstChild()->value
;
1176 if ( $bits['inner'] ) {
1177 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1178 if ( $bits['close'] ) {
1179 $s .= $bits['close']->getFirstChild()->value
;
1186 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1188 } elseif ( $contextName === 'h' ) {
1190 if ( $this->parser
->ot
['html'] ) {
1191 # Expand immediately and insert heading index marker
1192 $s = $this->expand( $contextChildren, $flags );
1193 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1194 $titleText = $this->title
->getPrefixedDBkey();
1195 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1196 $serial = count( $this->parser
->mHeadings
) - 1;
1197 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1198 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1199 $this->parser
->mStripState
->addGeneral( $marker, '' );
1202 # Expand in virtual stack
1203 $newIterator = $contextChildren;
1206 # Generic recursive expansion
1207 $newIterator = $contextChildren;
1210 if ( $newIterator !== false ) {
1212 $iteratorStack[] = $newIterator;
1214 } elseif ( $iteratorStack[$level] === false ) {
1215 // Return accumulated value to parent
1216 // With tail recursion
1217 while ( $iteratorStack[$level] === false && $level > 0 ) {
1218 $outStack[$level - 1] .= $out;
1219 array_pop( $outStack );
1220 array_pop( $iteratorStack );
1221 array_pop( $indexStack );
1227 return $outStack[0];
1231 * @param string $sep
1233 * @param string|PPNode $args,...
1236 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1237 $args = array_slice( func_get_args(), 2 );
1241 foreach ( $args as $root ) {
1242 if ( $root instanceof PPNode_Hash_Array
) {
1243 $root = $root->value
;
1245 if ( !is_array( $root ) ) {
1248 foreach ( $root as $node ) {
1254 $s .= $this->expand( $node, $flags );
1261 * Implode with no flags specified
1262 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1263 * @param string $sep
1264 * @param string|PPNode $args,...
1267 public function implode( $sep /*, ... */ ) {
1268 $args = array_slice( func_get_args(), 1 );
1272 foreach ( $args as $root ) {
1273 if ( $root instanceof PPNode_Hash_Array
) {
1274 $root = $root->value
;
1276 if ( !is_array( $root ) ) {
1279 foreach ( $root as $node ) {
1285 $s .= $this->expand( $node );
1292 * Makes an object that, when expand()ed, will be the same as one obtained
1295 * @param string $sep
1296 * @param string|PPNode $args,...
1297 * @return PPNode_Hash_Array
1299 public function virtualImplode( $sep /*, ... */ ) {
1300 $args = array_slice( func_get_args(), 1 );
1304 foreach ( $args as $root ) {
1305 if ( $root instanceof PPNode_Hash_Array
) {
1306 $root = $root->value
;
1308 if ( !is_array( $root ) ) {
1311 foreach ( $root as $node ) {
1320 return new PPNode_Hash_Array( $out );
1324 * Virtual implode with brackets
1326 * @param string $start
1327 * @param string $sep
1328 * @param string $end
1329 * @param string|PPNode $args,...
1330 * @return PPNode_Hash_Array
1332 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1333 $args = array_slice( func_get_args(), 3 );
1337 foreach ( $args as $root ) {
1338 if ( $root instanceof PPNode_Hash_Array
) {
1339 $root = $root->value
;
1341 if ( !is_array( $root ) ) {
1344 foreach ( $root as $node ) {
1354 return new PPNode_Hash_Array( $out );
1357 public function __toString() {
1362 * @param bool $level
1363 * @return array|bool|string
1365 public function getPDBK( $level = false ) {
1366 if ( $level === false ) {
1367 return $this->title
->getPrefixedDBkey();
1369 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1376 public function getArguments() {
1383 public function getNumberedArguments() {
1390 public function getNamedArguments() {
1395 * Returns true if there are no arguments in this frame
1399 public function isEmpty() {
1404 * @param int|string $name
1405 * @return bool Always false in this implementation.
1407 public function getArgument( $name ) {
1412 * Returns true if the infinite loop check is OK, false if a loop is detected
1414 * @param Title $title
1418 public function loopCheck( $title ) {
1419 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1423 * Return true if the frame is a template frame
1427 public function isTemplate() {
1432 * Get a title of frame
1436 public function getTitle() {
1437 return $this->title
;
1441 * Set the volatile flag
1445 public function setVolatile( $flag = true ) {
1446 $this->volatile
= $flag;
1450 * Get the volatile flag
1454 public function isVolatile() {
1455 return $this->volatile
;
1463 public function setTTL( $ttl ) {
1464 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1474 public function getTTL() {
1480 * Expansion frame with template arguments
1483 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1484 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1486 public $numberedArgs, $namedArgs, $parent;
1487 public $numberedExpansionCache, $namedExpansionCache;
1490 * @param Preprocessor $preprocessor
1491 * @param bool|PPFrame $parent
1492 * @param array $numberedArgs
1493 * @param array $namedArgs
1494 * @param bool|Title $title
1496 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1497 $namedArgs = [], $title = false
1499 parent
::__construct( $preprocessor );
1501 $this->parent
= $parent;
1502 $this->numberedArgs
= $numberedArgs;
1503 $this->namedArgs
= $namedArgs;
1504 $this->title
= $title;
1505 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1506 $this->titleCache
= $parent->titleCache
;
1507 $this->titleCache
[] = $pdbk;
1508 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1509 if ( $pdbk !== false ) {
1510 $this->loopCheckHash
[$pdbk] = true;
1512 $this->depth
= $parent->depth +
1;
1513 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1516 public function __toString() {
1519 $args = $this->numberedArgs +
$this->namedArgs
;
1520 foreach ( $args as $name => $value ) {
1526 $s .= "\"$name\":\"" .
1527 str_replace( '"', '\\"', $value->__toString() ) . '"';
1534 * @throws MWException
1535 * @param string|int $key
1536 * @param string|PPNode $root
1540 public function cachedExpand( $key, $root, $flags = 0 ) {
1541 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1542 return $this->parent
->childExpansionCache
[$key];
1544 $retval = $this->expand( $root, $flags );
1545 if ( !$this->isVolatile() ) {
1546 $this->parent
->childExpansionCache
[$key] = $retval;
1552 * Returns true if there are no arguments in this frame
1556 public function isEmpty() {
1557 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1563 public function getArguments() {
1565 foreach ( array_merge(
1566 array_keys( $this->numberedArgs
),
1567 array_keys( $this->namedArgs
) ) as $key ) {
1568 $arguments[$key] = $this->getArgument( $key );
1576 public function getNumberedArguments() {
1578 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1579 $arguments[$key] = $this->getArgument( $key );
1587 public function getNamedArguments() {
1589 foreach ( array_keys( $this->namedArgs
) as $key ) {
1590 $arguments[$key] = $this->getArgument( $key );
1597 * @return string|bool
1599 public function getNumberedArgument( $index ) {
1600 if ( !isset( $this->numberedArgs
[$index] ) ) {
1603 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1604 # No trimming for unnamed arguments
1605 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1606 $this->numberedArgs
[$index],
1607 PPFrame
::STRIP_COMMENTS
1610 return $this->numberedExpansionCache
[$index];
1614 * @param string $name
1615 * @return string|bool
1617 public function getNamedArgument( $name ) {
1618 if ( !isset( $this->namedArgs
[$name] ) ) {
1621 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1622 # Trim named arguments post-expand, for backwards compatibility
1623 $this->namedExpansionCache
[$name] = trim(
1624 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1626 return $this->namedExpansionCache
[$name];
1630 * @param int|string $name
1631 * @return string|bool
1633 public function getArgument( $name ) {
1634 $text = $this->getNumberedArgument( $name );
1635 if ( $text === false ) {
1636 $text = $this->getNamedArgument( $name );
1642 * Return true if the frame is a template frame
1646 public function isTemplate() {
1650 public function setVolatile( $flag = true ) {
1651 parent
::setVolatile( $flag );
1652 $this->parent
->setVolatile( $flag );
1655 public function setTTL( $ttl ) {
1656 parent
::setTTL( $ttl );
1657 $this->parent
->setTTL( $ttl );
1662 * Expansion frame with custom arguments
1665 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1666 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1670 public function __construct( $preprocessor, $args ) {
1671 parent
::__construct( $preprocessor );
1672 $this->args
= $args;
1675 public function __toString() {
1678 foreach ( $this->args
as $name => $value ) {
1684 $s .= "\"$name\":\"" .
1685 str_replace( '"', '\\"', $value->__toString() ) . '"';
1694 public function isEmpty() {
1695 return !count( $this->args
);
1699 * @param int|string $index
1700 * @return string|bool
1702 public function getArgument( $index ) {
1703 if ( !isset( $this->args
[$index] ) ) {
1706 return $this->args
[$index];
1709 public function getArguments() {
1717 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
1718 class PPNode_Hash_Tree
implements PPNode
{
1723 * The store array for children of this node. It is "raw" in the sense that
1724 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1727 private $rawChildren;
1730 * The store array for the siblings of this node, including this node itself.
1735 * The index into $this->store which contains the descriptor of this node.
1740 * The offset of the name within descriptors, used in some places for
1746 * The offset of the child list within descriptors, used in some places for
1752 * Construct an object using the data from $store[$index]. The rest of the
1753 * store array can be accessed via getNextSibling().
1755 * @param array $store
1758 public function __construct( array $store, $index ) {
1759 $this->store
= $store;
1760 $this->index
= $index;
1761 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1765 * Construct an appropriate PPNode_Hash_* object with a class that depends
1766 * on what is at the relevant store index.
1768 * @param array $store
1770 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1772 public static function factory( array $store, $index ) {
1773 if ( !isset( $store[$index] ) ) {
1777 $descriptor = $store[$index];
1778 if ( is_string( $descriptor ) ) {
1779 $class = PPNode_Hash_Text
::class;
1780 } elseif ( is_array( $descriptor ) ) {
1781 if ( $descriptor[self
::NAME
][0] === '@' ) {
1782 $class = PPNode_Hash_Attr
::class;
1784 $class = self
::class;
1787 throw new MWException( __METHOD__
.': invalid node descriptor' );
1789 return new $class( $store, $index );
1793 * Convert a node to XML, for debugging
1795 public function __toString() {
1798 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1799 if ( $node instanceof PPNode_Hash_Attr
) {
1800 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1802 $inner .= $node->__toString();
1805 if ( $inner === '' ) {
1806 return "<{$this->name}$attribs/>";
1808 return "<{$this->name}$attribs>$inner</{$this->name}>";
1813 * @return PPNode_Hash_Array
1815 public function getChildren() {
1817 foreach ( $this->rawChildren
as $i => $child ) {
1818 $children[] = self
::factory( $this->rawChildren
, $i );
1820 return new PPNode_Hash_Array( $children );
1824 * Get the first child, or false if there is none. Note that this will
1825 * return a temporary proxy object: different instances will be returned
1826 * if this is called more than once on the same node.
1828 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1830 public function getFirstChild() {
1831 if ( !isset( $this->rawChildren
[0] ) ) {
1834 return self
::factory( $this->rawChildren
, 0 );
1839 * Get the next sibling, or false if there is none. Note that this will
1840 * return a temporary proxy object: different instances will be returned
1841 * if this is called more than once on the same node.
1843 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1845 public function getNextSibling() {
1846 return self
::factory( $this->store
, $this->index +
1 );
1850 * Get an array of the children with a given node name
1852 * @param string $name
1853 * @return PPNode_Hash_Array
1855 public function getChildrenOfType( $name ) {
1857 foreach ( $this->rawChildren
as $i => $child ) {
1858 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1859 $children[] = self
::factory( $this->rawChildren
, $i );
1862 return new PPNode_Hash_Array( $children );
1866 * Get the raw child array. For internal use.
1869 public function getRawChildren() {
1870 return $this->rawChildren
;
1876 public function getLength() {
1884 public function item( $i ) {
1891 public function getName() {
1896 * Split a "<part>" node into an associative array containing:
1897 * - name PPNode name
1898 * - index String index
1899 * - value PPNode value
1901 * @throws MWException
1904 public function splitArg() {
1905 return self
::splitRawArg( $this->rawChildren
);
1909 * Like splitArg() but for a raw child array. For internal use only.
1910 * @param array $children
1913 public static function splitRawArg( array $children ) {
1915 foreach ( $children as $i => $child ) {
1916 if ( !is_array( $child ) ) {
1919 if ( $child[self
::NAME
] === 'name' ) {
1920 $bits['name'] = new self( $children, $i );
1921 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1922 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1924 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1926 } elseif ( $child[self
::NAME
] === 'value' ) {
1927 $bits['value'] = new self( $children, $i );
1931 if ( !isset( $bits['name'] ) ) {
1932 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1934 if ( !isset( $bits['index'] ) ) {
1935 $bits['index'] = '';
1941 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1942 * All values in the resulting array are PPNodes. Inner and close are optional.
1944 * @throws MWException
1947 public function splitExt() {
1948 return self
::splitRawExt( $this->rawChildren
);
1952 * Like splitExt() but for a raw child array. For internal use only.
1953 * @param array $children
1956 public static function splitRawExt( array $children ) {
1958 foreach ( $children as $i => $child ) {
1959 if ( !is_array( $child ) ) {
1962 switch ( $child[self
::NAME
] ) {
1964 $bits['name'] = new self( $children, $i );
1967 $bits['attr'] = new self( $children, $i );
1970 $bits['inner'] = new self( $children, $i );
1973 $bits['close'] = new self( $children, $i );
1977 if ( !isset( $bits['name'] ) ) {
1978 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1984 * Split an "<h>" node
1986 * @throws MWException
1989 public function splitHeading() {
1990 if ( $this->name
!== 'h' ) {
1991 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1993 return self
::splitRawHeading( $this->rawChildren
);
1997 * Like splitHeading() but for a raw child array. For internal use only.
1998 * @param array $children
2001 public static function splitRawHeading( array $children ) {
2003 foreach ( $children as $i => $child ) {
2004 if ( !is_array( $child ) ) {
2007 if ( $child[self
::NAME
] === '@i' ) {
2008 $bits['i'] = $child[self
::CHILDREN
][0];
2009 } elseif ( $child[self
::NAME
] === '@level' ) {
2010 $bits['level'] = $child[self
::CHILDREN
][0];
2013 if ( !isset( $bits['i'] ) ) {
2014 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2020 * Split a "<template>" or "<tplarg>" node
2022 * @throws MWException
2025 public function splitTemplate() {
2026 return self
::splitRawTemplate( $this->rawChildren
);
2030 * Like splitTemplate() but for a raw child array. For internal use only.
2031 * @param array $children
2034 public static function splitRawTemplate( array $children ) {
2036 $bits = [ 'lineStart' => '' ];
2037 foreach ( $children as $i => $child ) {
2038 if ( !is_array( $child ) ) {
2041 switch ( $child[self
::NAME
] ) {
2043 $bits['title'] = new self( $children, $i );
2046 $parts[] = new self( $children, $i );
2049 $bits['lineStart'] = '1';
2053 if ( !isset( $bits['title'] ) ) {
2054 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
2056 $bits['parts'] = new PPNode_Hash_Array( $parts );
2064 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2065 class PPNode_Hash_Text
implements PPNode
{
2068 private $store, $index;
2071 * Construct an object using the data from $store[$index]. The rest of the
2072 * store array can be accessed via getNextSibling().
2074 * @param array $store
2077 public function __construct( array $store, $index ) {
2078 $this->value
= $store[$index];
2079 if ( !is_scalar( $this->value
) ) {
2080 throw new MWException( __CLASS__
. ' given object instead of string' );
2082 $this->store
= $store;
2083 $this->index
= $index;
2086 public function __toString() {
2087 return htmlspecialchars( $this->value
);
2090 public function getNextSibling() {
2091 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2094 public function getChildren() {
2098 public function getFirstChild() {
2102 public function getChildrenOfType( $name ) {
2106 public function getLength() {
2110 public function item( $i ) {
2114 public function getName() {
2118 public function splitArg() {
2119 throw new MWException( __METHOD__
. ': not supported' );
2122 public function splitExt() {
2123 throw new MWException( __METHOD__
. ': not supported' );
2126 public function splitHeading() {
2127 throw new MWException( __METHOD__
. ': not supported' );
2134 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2135 class PPNode_Hash_Array
implements PPNode
{
2139 public function __construct( $value ) {
2140 $this->value
= $value;
2143 public function __toString() {
2144 return var_export( $this, true );
2147 public function getLength() {
2148 return count( $this->value
);
2151 public function item( $i ) {
2152 return $this->value
[$i];
2155 public function getName() {
2159 public function getNextSibling() {
2163 public function getChildren() {
2167 public function getFirstChild() {
2171 public function getChildrenOfType( $name ) {
2175 public function splitArg() {
2176 throw new MWException( __METHOD__
. ': not supported' );
2179 public function splitExt() {
2180 throw new MWException( __METHOD__
. ': not supported' );
2183 public function splitHeading() {
2184 throw new MWException( __METHOD__
. ': not supported' );
2191 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
2192 class PPNode_Hash_Attr
implements PPNode
{
2194 public $name, $value;
2195 private $store, $index;
2198 * Construct an object using the data from $store[$index]. The rest of the
2199 * store array can be accessed via getNextSibling().
2201 * @param array $store
2204 public function __construct( array $store, $index ) {
2205 $descriptor = $store[$index];
2206 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2207 throw new MWException( __METHOD__
.': invalid name in attribute descriptor' );
2209 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2210 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2211 $this->store
= $store;
2212 $this->index
= $index;
2215 public function __toString() {
2216 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2219 public function getName() {
2223 public function getNextSibling() {
2224 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2227 public function getChildren() {
2231 public function getFirstChild() {
2235 public function getChildrenOfType( $name ) {
2239 public function getLength() {
2243 public function item( $i ) {
2247 public function splitArg() {
2248 throw new MWException( __METHOD__
. ': not supported' );
2251 public function splitExt() {
2252 throw new MWException( __METHOD__
. ': not supported' );
2255 public function splitHeading() {
2256 throw new MWException( __METHOD__
. ': not supported' );