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 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
43 class Preprocessor_Hash
extends Preprocessor
{
44 // @codingStandardsIgnoreEnd
51 const CACHE_PREFIX
= 'preprocess-hash';
52 const CACHE_VERSION
= 2;
54 public function __construct( $parser ) {
55 $this->parser
= $parser;
59 * @return PPFrame_Hash
61 public function newFrame() {
62 return new PPFrame_Hash( $this );
67 * @return PPCustomFrame_Hash
69 public function newCustomFrame( $args ) {
70 return new PPCustomFrame_Hash( $this, $args );
74 * @param array $values
75 * @return PPNode_Hash_Array
77 public function newPartNodeArray( $values ) {
80 foreach ( $values as $k => $val ) {
82 $store = [ [ 'part', [
83 [ 'name', [ [ '@index', [ $k ] ] ] ],
84 [ 'value', [ strval( $val ) ] ],
87 $store = [ [ 'part', [
88 [ 'name', [ strval( $k ) ] ],
90 [ 'value', [ strval( $val ) ] ],
94 $list[] = new PPNode_Hash_Tree( $store, 0 );
97 $node = new PPNode_Hash_Array( $list );
102 * Preprocess some wikitext and return the document tree.
104 * @param string $text The text to parse
105 * @param int $flags Bitwise combination of:
106 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
107 * included. Default is to assume a direct page view.
109 * The generated DOM tree must depend only on the input text and the flags.
110 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
112 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
113 * change in the DOM tree for a given text, must be passed through the section identifier
114 * in the section edit link and thus back to extractSections().
116 * @throws MWException
117 * @return PPNode_Hash_Tree
119 public function preprocessToObj( $text, $flags = 0 ) {
120 global $wgDisableLangConversion;
122 $tree = $this->cacheGetTree( $text, $flags );
123 if ( $tree !== false ) {
124 $store = json_decode( $tree );
125 if ( is_array( $store ) ) {
126 return new PPNode_Hash_Tree( $store, 0 );
130 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
132 $xmlishElements = $this->parser
->getStripList();
133 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
134 $enableOnlyinclude = false;
135 if ( $forInclusion ) {
136 $ignoredTags = [ 'includeonly', '/includeonly' ];
137 $ignoredElements = [ 'noinclude' ];
138 $xmlishElements[] = 'noinclude';
139 if ( strpos( $text, '<onlyinclude>' ) !== false
140 && strpos( $text, '</onlyinclude>' ) !== false
142 $enableOnlyinclude = true;
145 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
146 $ignoredElements = [ 'includeonly' ];
147 $xmlishElements[] = 'includeonly';
149 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
151 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
152 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
154 $stack = new PPDStack_Hash
;
156 $searchBase = "[{<\n";
157 if ( !$wgDisableLangConversion ) {
161 // For fast reverse searches
162 $revText = strrev( $text );
163 $lengthText = strlen( $text );
165 // Input pointer, starts out pointing to a pseudo-newline before the start
167 // Current accumulator. See the doc comment for Preprocessor_Hash for the format.
168 $accum =& $stack->getAccum();
169 // True to find equals signs in arguments
171 // True to take notice of pipe characters
174 // True if $i is inside a possible heading
176 // True if there are no more greater-than (>) signs right of $i
178 // Map of tag name => true if there are no more closing tags of given type right of $i
179 $noMoreClosingTag = [];
180 // True to ignore all input up to the next <onlyinclude>
181 $findOnlyinclude = $enableOnlyinclude;
182 // Do a line-start run without outputting an LF character
183 $fakeLineStart = true;
186 // $this->memCheck();
188 if ( $findOnlyinclude ) {
189 // Ignore all input up to the next <onlyinclude>
190 $startPos = strpos( $text, '<onlyinclude>', $i );
191 if ( $startPos === false ) {
192 // Ignored section runs to the end
193 $accum[] = [ 'ignore', [ substr( $text, $i ) ] ];
196 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
197 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i ) ] ];
199 $findOnlyinclude = false;
202 if ( $fakeLineStart ) {
203 $found = 'line-start';
206 # Find next opening brace, closing brace or pipe
207 $search = $searchBase;
208 if ( $stack->top
=== false ) {
209 $currentClosing = '';
211 $stack->top
->close
=== '}-' &&
212 $stack->top
->count
> 2
214 # adjust closing for -{{{...{{
215 $currentClosing = '}';
216 $search .= $currentClosing;
218 $currentClosing = $stack->top
->close
;
219 $search .= $currentClosing;
225 // First equals will be for the template
229 # Output literal section, advance input counter
230 $literalLength = strcspn( $text, $search, $i );
231 if ( $literalLength > 0 ) {
232 self
::addLiteral( $accum, substr( $text, $i, $literalLength ) );
233 $i +
= $literalLength;
235 if ( $i >= $lengthText ) {
236 if ( $currentClosing == "\n" ) {
237 // Do a past-the-end run to finish off the heading
245 $curChar = $curTwoChar = $text[$i];
246 if ( ( $i +
1 ) < $lengthText ) {
247 $curTwoChar .= $text[$i +
1];
249 if ( $curChar == '|' ) {
251 } elseif ( $curChar == '=' ) {
253 } elseif ( $curChar == '<' ) {
255 } elseif ( $curChar == "\n" ) {
259 $found = 'line-start';
261 } elseif ( $curTwoChar == $currentClosing ) {
263 $curChar = $curTwoChar;
264 } elseif ( $curChar == $currentClosing ) {
266 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
267 $curChar = $curTwoChar;
269 $rule = $this->rules
[$curChar];
270 } elseif ( isset( $this->rules
[$curChar] ) ) {
272 $rule = $this->rules
[$curChar];
274 # Some versions of PHP have a strcspn which stops on
275 # null characters; ignore these and continue.
276 # We also may get '-' and '}' characters here which
277 # don't match -{ or $currentClosing. Add these to
278 # output and continue.
279 if ( $curChar == '-' ||
$curChar == '}' ) {
280 self
::addLiteral( $accum, $curChar );
288 if ( $found == 'angle' ) {
290 // Handle </onlyinclude>
291 if ( $enableOnlyinclude
292 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
294 $findOnlyinclude = true;
298 // Determine element name
299 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
300 // Element name missing or not listed
301 self
::addLiteral( $accum, '<' );
306 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
307 // To avoid leaving blank lines, when a sequence of
308 // space-separated comments is both preceded and followed by
309 // a newline (ignoring spaces), then
310 // trim leading and trailing spaces and the trailing newline.
313 $endPos = strpos( $text, '-->', $i +
4 );
314 if ( $endPos === false ) {
315 // Unclosed comment in input, runs to end
316 $inner = substr( $text, $i );
317 $accum[] = [ 'comment', [ $inner ] ];
320 // Search backwards for leading whitespace
321 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
323 // Search forwards for trailing whitespace
324 // $wsEnd will be the position of the last space (or the '>' if there's none)
325 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
327 // Keep looking forward as long as we're finding more
329 $comments = [ [ $wsStart, $wsEnd ] ];
330 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
331 $c = strpos( $text, '-->', $wsEnd +
4 );
332 if ( $c === false ) {
335 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
336 $comments[] = [ $wsEnd +
1, $c ];
340 // Eat the line if possible
341 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
342 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
343 // it's a possible beneficial b/c break.
344 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
345 && substr( $text, $wsEnd +
1, 1 ) == "\n"
347 // Remove leading whitespace from the end of the accumulator
348 $wsLength = $i - $wsStart;
349 $endIndex = count( $accum ) - 1;
354 && is_string( $accum[$endIndex] )
355 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
357 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
360 // Dump all but the last comment to the accumulator
361 foreach ( $comments as $j => $com ) {
363 $endPos = $com[1] +
1;
364 if ( $j == ( count( $comments ) - 1 ) ) {
367 $inner = substr( $text, $startPos, $endPos - $startPos );
368 $accum[] = [ 'comment', [ $inner ] ];
371 // Do a line-start run next time to look for headings after the comment
372 $fakeLineStart = true;
374 // No line to eat, just take the comment itself
380 $part = $stack->top
->getCurrentPart();
381 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
382 $part->visualEnd
= $wsStart;
384 // Else comments abutting, no change in visual end
385 $part->commentEnd
= $endPos;
388 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
389 $accum[] = [ 'comment', [ $inner ] ];
394 $lowerName = strtolower( $name );
395 $attrStart = $i +
strlen( $name ) +
1;
398 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
399 if ( $tagEndPos === false ) {
400 // Infinite backtrack
401 // Disable tag search to prevent worst-case O(N^2) performance
403 self
::addLiteral( $accum, '<' );
408 // Handle ignored tags
409 if ( in_array( $lowerName, $ignoredTags ) ) {
410 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i +
1 ) ] ];
416 if ( $text[$tagEndPos - 1] == '/' ) {
418 $attrEnd = $tagEndPos - 1;
423 $attrEnd = $tagEndPos;
426 !isset( $noMoreClosingTag[$name] ) &&
427 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
428 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
430 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
431 $i = $matches[0][1] +
strlen( $matches[0][0] );
432 $close = $matches[0][0];
435 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
436 // Let it run out to the end of the text.
437 $inner = substr( $text, $tagEndPos +
1 );
441 // Don't match the tag, treat opening tag as literal and resume parsing.
443 self
::addLiteral( $accum,
444 substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
445 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
446 $noMoreClosingTag[$name] = true;
451 // <includeonly> and <noinclude> just become <ignore> tags
452 if ( in_array( $lowerName, $ignoredElements ) ) {
453 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
457 if ( $attrEnd <= $attrStart ) {
460 // Note that the attr element contains the whitespace between name and attribute,
461 // this is necessary for precise reconstruction during pre-save transform.
462 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
466 [ 'name', [ $name ] ],
467 [ 'attr', [ $attr ] ] ];
468 if ( $inner !== null ) {
469 $children[] = [ 'inner', [ $inner ] ];
471 if ( $close !== null ) {
472 $children[] = [ 'close', [ $close ] ];
474 $accum[] = [ 'ext', $children ];
475 } elseif ( $found == 'line-start' ) {
476 // Is this the start of a heading?
477 // Line break belongs before the heading element in any case
478 if ( $fakeLineStart ) {
479 $fakeLineStart = false;
481 self
::addLiteral( $accum, $curChar );
485 $count = strspn( $text, '=', $i, 6 );
486 if ( $count == 1 && $findEquals ) {
487 // DWIM: This looks kind of like a name/value separator.
488 // Let's let the equals handler have it and break the potential
489 // heading. This is heuristic, but AFAICT the methods for
490 // completely correct disambiguation are very complex.
491 } elseif ( $count > 0 ) {
495 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
498 $stack->push( $piece );
499 $accum =& $stack->getAccum();
500 extract( $stack->getFlags() );
503 } elseif ( $found == 'line-end' ) {
504 $piece = $stack->top
;
505 // A heading must be open, otherwise \n wouldn't have been in the search list
506 assert( $piece->open
=== "\n" );
507 $part = $piece->getCurrentPart();
508 // Search back through the input to see if it has a proper close.
509 // Do this using the reversed string since the other solutions
510 // (end anchor, etc.) are inefficient.
511 $wsLength = strspn( $revText, " \t", $lengthText - $i );
512 $searchStart = $i - $wsLength;
513 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
514 // Comment found at line end
515 // Search for equals signs before the comment
516 $searchStart = $part->visualEnd
;
517 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
519 $count = $piece->count
;
520 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
521 if ( $equalsLength > 0 ) {
522 if ( $searchStart - $equalsLength == $piece->startPos
) {
523 // This is just a single string of equals signs on its own line
524 // Replicate the doHeadings behavior /={count}(.+)={count}/
525 // First find out how many equals signs there really are (don't stop at 6)
526 $count = $equalsLength;
530 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
533 $count = min( $equalsLength, $count );
536 // Normal match, output <h>
537 $element = [ [ 'possible-h',
540 [ '@level', [ $count ] ],
541 [ '@i', [ $headingIndex++
] ]
547 // Single equals sign on its own line, count=0
551 // No match, no <h>, just pass down the inner text
556 $accum =& $stack->getAccum();
557 extract( $stack->getFlags() );
559 // Append the result to the enclosing accumulator
560 array_splice( $accum, count( $accum ), 0, $element );
562 // Note that we do NOT increment the input pointer.
563 // This is because the closing linebreak could be the opening linebreak of
564 // another heading. Infinite loops are avoided because the next iteration MUST
565 // hit the heading open case above, which unconditionally increments the
567 } elseif ( $found == 'open' ) {
568 # count opening brace characters
569 $curLen = strlen( $curChar );
570 $count = ( $curLen > 1 ) ?
571 # allow the final character to repeat
572 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
573 strspn( $text, $curChar, $i );
575 # we need to add to stack only if opening brace count is enough for one of the rules
576 if ( $count >= $rule['min'] ) {
577 # Add it to the stack
580 'close' => $rule['end'],
582 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
585 $stack->push( $piece );
586 $accum =& $stack->getAccum();
587 extract( $stack->getFlags() );
589 # Add literal brace(s)
590 self
::addLiteral( $accum, str_repeat( $curChar, $count ) );
593 } elseif ( $found == 'close' ) {
594 $piece = $stack->top
;
595 # lets check if there are enough characters for closing brace
596 $maxCount = $piece->count
;
597 if ( $piece->close
=== '}-' && $curChar === '}' ) {
598 $maxCount--; # don't try to match closing '-' as a '}'
600 $curLen = strlen( $curChar );
601 $count = ( $curLen > 1 ) ?
$curLen :
602 strspn( $text, $curChar, $i, $maxCount );
604 # check for maximum matching characters (if there are 5 closing
605 # characters, we will probably need only 3 - depending on the rules)
606 $rule = $this->rules
[$piece->open
];
607 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
608 # tweak for -{..{{ }}..}-
609 $rule = $this->rules
['{'];
611 if ( $count > $rule['max'] ) {
612 # The specified maximum exists in the callback array, unless the caller
614 $matchingCount = $rule['max'];
616 # Count is less than the maximum
617 # Skip any gaps in the callback array to find the true largest match
618 # Need to use array_key_exists not isset because the callback can be null
619 $matchingCount = $count;
620 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
625 if ( $matchingCount <= 0 ) {
626 # No matching element found in callback array
627 # Output a literal closing brace and continue
628 $endText = substr( $text, $i, $count );
629 self
::addLiteral( $accum, $endText );
633 $name = $rule['names'][$matchingCount];
634 if ( $name === null ) {
635 // No element, just literal text
636 $endText = substr( $text, $i, $matchingCount );
637 $element = $piece->breakSyntax( $matchingCount );
638 self
::addLiteral( $element, $endText );
641 $parts = $piece->parts
;
642 $titleAccum = $parts[0]->out
;
647 # The invocation is at the start of the line if lineStart is set in
648 # the stack, and all opening brackets are used up.
649 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
650 $children[] = [ '@lineStart', [ 1 ] ];
652 $titleNode = [ 'title', $titleAccum ];
653 $children[] = $titleNode;
655 foreach ( $parts as $part ) {
656 if ( isset( $part->eqpos
) ) {
657 $equalsNode = $part->out
[$part->eqpos
];
658 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
659 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
660 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
661 $children[] = $partNode;
663 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
664 $valueNode = [ 'value', $part->out
];
665 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
666 $children[] = $partNode;
669 $element = [ [ $name, $children ] ];
672 # Advance input pointer
673 $i +
= $matchingCount;
677 $accum =& $stack->getAccum();
679 # Re-add the old stack element if it still has unmatched opening characters remaining
680 if ( $matchingCount < $piece->count
) {
681 $piece->parts
= [ new PPDPart_Hash
];
682 $piece->count
-= $matchingCount;
683 # do we still qualify for any callback with remaining count?
684 $min = $this->rules
[$piece->open
]['min'];
685 if ( $piece->count
>= $min ) {
686 $stack->push( $piece );
687 $accum =& $stack->getAccum();
689 $s = substr( $piece->open
, 0, -1 );
691 substr( $piece->open
, -1 ),
692 $piece->count
- strlen( $s )
694 self
::addLiteral( $accum, $s );
698 extract( $stack->getFlags() );
700 # Add XML element to the enclosing accumulator
701 array_splice( $accum, count( $accum ), 0, $element );
702 } elseif ( $found == 'pipe' ) {
703 $findEquals = true; // shortcut for getFlags()
705 $accum =& $stack->getAccum();
707 } elseif ( $found == 'equals' ) {
708 $findEquals = false; // shortcut for getFlags()
709 $accum[] = [ 'equals', [ '=' ] ];
710 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
712 } elseif ( $found == 'dash' ) {
713 self
::addLiteral( $accum, '-' );
718 # Output any remaining unclosed brackets
719 foreach ( $stack->stack
as $piece ) {
720 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
723 # Enable top-level headings
724 foreach ( $stack->rootAccum
as &$node ) {
725 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
726 $node[PPNode_Hash_Tree
::NAME
] = 'h';
730 $rootStore = [ [ 'root', $stack->rootAccum
] ];
731 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
734 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
735 if ( $tree !== false ) {
736 $this->cacheSetTree( $text, $flags, $tree );
742 private static function addLiteral( array &$accum, $text ) {
743 $n = count( $accum );
744 if ( $n && is_string( $accum[$n - 1] ) ) {
745 $accum[$n - 1] .= $text;
753 * Stack class to help Preprocessor::preprocessToObj()
756 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
757 class PPDStack_Hash
extends PPDStack
{
758 // @codingStandardsIgnoreEnd
760 public function __construct() {
761 $this->elementClass
= 'PPDStackElement_Hash';
762 parent
::__construct();
763 $this->rootAccum
= [];
770 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
771 class PPDStackElement_Hash
extends PPDStackElement
{
772 // @codingStandardsIgnoreEnd
774 public function __construct( $data = [] ) {
775 $this->partClass
= 'PPDPart_Hash';
776 parent
::__construct( $data );
780 * Get the accumulator that would result if the close is not found.
782 * @param int|bool $openingCount
785 public function breakSyntax( $openingCount = false ) {
786 if ( $this->open
== "\n" ) {
787 $accum = $this->parts
[0]->out
;
789 if ( $openingCount === false ) {
790 $openingCount = $this->count
;
792 $s = substr( $this->open
, 0, -1 );
794 substr( $this->open
, -1 ),
795 $openingCount - strlen( $s )
800 foreach ( $this->parts
as $part ) {
803 } elseif ( is_string( $accum[$lastIndex] ) ) {
804 $accum[$lastIndex] .= '|';
806 $accum[++
$lastIndex] = '|';
808 foreach ( $part->out
as $node ) {
809 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
810 $accum[$lastIndex] .= $node;
812 $accum[++
$lastIndex] = $node;
824 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
825 class PPDPart_Hash
extends PPDPart
{
826 // @codingStandardsIgnoreEnd
828 public function __construct( $out = '' ) {
834 parent
::__construct( $accum );
839 * An expansion frame, used as a context to expand the result of preprocessToObj()
842 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
843 class PPFrame_Hash
implements PPFrame
{
844 // @codingStandardsIgnoreEnd
854 public $preprocessor;
863 * Hashtable listing templates which are disallowed for expansion in this frame,
864 * having been encountered previously in parent frames.
866 public $loopCheckHash;
869 * Recursion depth of this frame, top = 0
870 * Note that this is NOT the same as expansion depth in expand()
874 private $volatile = false;
880 protected $childExpansionCache;
883 * Construct a new preprocessor frame.
884 * @param Preprocessor $preprocessor The parent preprocessor
886 public function __construct( $preprocessor ) {
887 $this->preprocessor
= $preprocessor;
888 $this->parser
= $preprocessor->parser
;
889 $this->title
= $this->parser
->mTitle
;
890 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
891 $this->loopCheckHash
= [];
893 $this->childExpansionCache
= [];
897 * Create a new child frame
898 * $args is optionally a multi-root PPNode or array containing the template arguments
900 * @param array|bool|PPNode_Hash_Array $args
901 * @param Title|bool $title
902 * @param int $indexOffset
903 * @throws MWException
904 * @return PPTemplateFrame_Hash
906 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
909 if ( $title === false ) {
910 $title = $this->title
;
912 if ( $args !== false ) {
913 if ( $args instanceof PPNode_Hash_Array
) {
914 $args = $args->value
;
915 } elseif ( !is_array( $args ) ) {
916 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
918 foreach ( $args as $arg ) {
919 $bits = $arg->splitArg();
920 if ( $bits['index'] !== '' ) {
921 // Numbered parameter
922 $index = $bits['index'] - $indexOffset;
923 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
924 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
925 wfEscapeWikiText( $this->title
),
926 wfEscapeWikiText( $title ),
927 wfEscapeWikiText( $index ) )->text() );
928 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
930 $numberedArgs[$index] = $bits['value'];
931 unset( $namedArgs[$index] );
934 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
935 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
936 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
937 wfEscapeWikiText( $this->title
),
938 wfEscapeWikiText( $title ),
939 wfEscapeWikiText( $name ) )->text() );
940 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
942 $namedArgs[$name] = $bits['value'];
943 unset( $numberedArgs[$name] );
947 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
951 * @throws MWException
952 * @param string|int $key
953 * @param string|PPNode $root
957 public function cachedExpand( $key, $root, $flags = 0 ) {
958 // we don't have a parent, so we don't have a cache
959 return $this->expand( $root, $flags );
963 * @throws MWException
964 * @param string|PPNode $root
968 public function expand( $root, $flags = 0 ) {
969 static $expansionDepth = 0;
970 if ( is_string( $root ) ) {
974 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
975 $this->parser
->limitationWarn( 'node-count-exceeded',
976 $this->parser
->mPPNodeCount
,
977 $this->parser
->mOptions
->getMaxPPNodeCount()
979 return '<span class="error">Node-count limit exceeded</span>';
981 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
982 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
984 $this->parser
->mOptions
->getMaxPPExpandDepth()
986 return '<span class="error">Expansion depth limit exceeded</span>';
989 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
990 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
993 $outStack = [ '', '' ];
994 $iteratorStack = [ false, $root ];
995 $indexStack = [ 0, 0 ];
997 while ( count( $iteratorStack ) > 1 ) {
998 $level = count( $outStack ) - 1;
999 $iteratorNode =& $iteratorStack[$level];
1000 $out =& $outStack[$level];
1001 $index =& $indexStack[$level];
1003 if ( is_array( $iteratorNode ) ) {
1004 if ( $index >= count( $iteratorNode ) ) {
1005 // All done with this iterator
1006 $iteratorStack[$level] = false;
1007 $contextNode = false;
1009 $contextNode = $iteratorNode[$index];
1012 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1013 if ( $index >= $iteratorNode->getLength() ) {
1014 // All done with this iterator
1015 $iteratorStack[$level] = false;
1016 $contextNode = false;
1018 $contextNode = $iteratorNode->item( $index );
1022 // Copy to $contextNode and then delete from iterator stack,
1023 // because this is not an iterator but we do have to execute it once
1024 $contextNode = $iteratorStack[$level];
1025 $iteratorStack[$level] = false;
1028 $newIterator = false;
1029 $contextName = false;
1030 $contextChildren = false;
1032 if ( $contextNode === false ) {
1034 } elseif ( is_string( $contextNode ) ) {
1035 $out .= $contextNode;
1036 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1037 $newIterator = $contextNode;
1038 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1040 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1041 $out .= $contextNode->value
;
1042 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1043 $contextName = $contextNode->name
;
1044 $contextChildren = $contextNode->getRawChildren();
1045 } elseif ( is_array( $contextNode ) ) {
1046 // Node descriptor array
1047 if ( count( $contextNode ) !== 2 ) {
1048 throw new MWException( __METHOD__
.
1049 ': found an array where a node descriptor should be' );
1051 list( $contextName, $contextChildren ) = $contextNode;
1053 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1056 // Handle node descriptor array or tree object
1057 if ( $contextName === false ) {
1058 // Not a node, already handled above
1059 } elseif ( $contextName[0] === '@' ) {
1060 // Attribute: no output
1061 } elseif ( $contextName === 'template' ) {
1062 # Double-brace expansion
1063 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1064 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1065 $newIterator = $this->virtualBracketedImplode(
1071 $ret = $this->parser
->braceSubstitution( $bits, $this );
1072 if ( isset( $ret['object'] ) ) {
1073 $newIterator = $ret['object'];
1075 $out .= $ret['text'];
1078 } elseif ( $contextName === 'tplarg' ) {
1079 # Triple-brace expansion
1080 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1081 if ( $flags & PPFrame
::NO_ARGS
) {
1082 $newIterator = $this->virtualBracketedImplode(
1088 $ret = $this->parser
->argSubstitution( $bits, $this );
1089 if ( isset( $ret['object'] ) ) {
1090 $newIterator = $ret['object'];
1092 $out .= $ret['text'];
1095 } elseif ( $contextName === 'comment' ) {
1096 # HTML-style comment
1097 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1098 # Not in RECOVER_COMMENTS mode (msgnw) though.
1099 if ( ( $this->parser
->ot
['html']
1100 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1101 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1102 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1105 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1106 # Add a strip marker in PST mode so that pstPass2() can
1107 # run some old-fashioned regexes on the result.
1108 # Not in RECOVER_COMMENTS mode (extractSections) though.
1109 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1111 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1112 $out .= $contextChildren[0];
1114 } elseif ( $contextName === 'ignore' ) {
1115 # Output suppression used by <includeonly> etc.
1116 # OT_WIKI will only respect <ignore> in substed templates.
1117 # The other output types respect it unless NO_IGNORE is set.
1118 # extractSections() sets NO_IGNORE and so never respects it.
1119 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1120 ||
( $flags & PPFrame
::NO_IGNORE
)
1122 $out .= $contextChildren[0];
1126 } elseif ( $contextName === 'ext' ) {
1128 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1129 [ 'attr' => null, 'inner' => null, 'close' => null ];
1130 if ( $flags & PPFrame
::NO_TAGS
) {
1131 $s = '<' . $bits['name']->getFirstChild()->value
;
1132 if ( $bits['attr'] ) {
1133 $s .= $bits['attr']->getFirstChild()->value
;
1135 if ( $bits['inner'] ) {
1136 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1137 if ( $bits['close'] ) {
1138 $s .= $bits['close']->getFirstChild()->value
;
1145 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1147 } elseif ( $contextName === 'h' ) {
1149 if ( $this->parser
->ot
['html'] ) {
1150 # Expand immediately and insert heading index marker
1151 $s = $this->expand( $contextChildren, $flags );
1152 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1153 $titleText = $this->title
->getPrefixedDBkey();
1154 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1155 $serial = count( $this->parser
->mHeadings
) - 1;
1156 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1157 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1158 $this->parser
->mStripState
->addGeneral( $marker, '' );
1161 # Expand in virtual stack
1162 $newIterator = $contextChildren;
1165 # Generic recursive expansion
1166 $newIterator = $contextChildren;
1169 if ( $newIterator !== false ) {
1171 $iteratorStack[] = $newIterator;
1173 } elseif ( $iteratorStack[$level] === false ) {
1174 // Return accumulated value to parent
1175 // With tail recursion
1176 while ( $iteratorStack[$level] === false && $level > 0 ) {
1177 $outStack[$level - 1] .= $out;
1178 array_pop( $outStack );
1179 array_pop( $iteratorStack );
1180 array_pop( $indexStack );
1186 return $outStack[0];
1190 * @param string $sep
1192 * @param string|PPNode $args,...
1195 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1196 $args = array_slice( func_get_args(), 2 );
1200 foreach ( $args as $root ) {
1201 if ( $root instanceof PPNode_Hash_Array
) {
1202 $root = $root->value
;
1204 if ( !is_array( $root ) ) {
1207 foreach ( $root as $node ) {
1213 $s .= $this->expand( $node, $flags );
1220 * Implode with no flags specified
1221 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1222 * @param string $sep
1223 * @param string|PPNode $args,...
1226 public function implode( $sep /*, ... */ ) {
1227 $args = array_slice( func_get_args(), 1 );
1231 foreach ( $args as $root ) {
1232 if ( $root instanceof PPNode_Hash_Array
) {
1233 $root = $root->value
;
1235 if ( !is_array( $root ) ) {
1238 foreach ( $root as $node ) {
1244 $s .= $this->expand( $node );
1251 * Makes an object that, when expand()ed, will be the same as one obtained
1254 * @param string $sep
1255 * @param string|PPNode $args,...
1256 * @return PPNode_Hash_Array
1258 public function virtualImplode( $sep /*, ... */ ) {
1259 $args = array_slice( func_get_args(), 1 );
1263 foreach ( $args as $root ) {
1264 if ( $root instanceof PPNode_Hash_Array
) {
1265 $root = $root->value
;
1267 if ( !is_array( $root ) ) {
1270 foreach ( $root as $node ) {
1279 return new PPNode_Hash_Array( $out );
1283 * Virtual implode with brackets
1285 * @param string $start
1286 * @param string $sep
1287 * @param string $end
1288 * @param string|PPNode $args,...
1289 * @return PPNode_Hash_Array
1291 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1292 $args = array_slice( func_get_args(), 3 );
1296 foreach ( $args as $root ) {
1297 if ( $root instanceof PPNode_Hash_Array
) {
1298 $root = $root->value
;
1300 if ( !is_array( $root ) ) {
1303 foreach ( $root as $node ) {
1313 return new PPNode_Hash_Array( $out );
1316 public function __toString() {
1321 * @param bool $level
1322 * @return array|bool|string
1324 public function getPDBK( $level = false ) {
1325 if ( $level === false ) {
1326 return $this->title
->getPrefixedDBkey();
1328 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1335 public function getArguments() {
1342 public function getNumberedArguments() {
1349 public function getNamedArguments() {
1354 * Returns true if there are no arguments in this frame
1358 public function isEmpty() {
1363 * @param int|string $name
1364 * @return bool Always false in this implementation.
1366 public function getArgument( $name ) {
1371 * Returns true if the infinite loop check is OK, false if a loop is detected
1373 * @param Title $title
1377 public function loopCheck( $title ) {
1378 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1382 * Return true if the frame is a template frame
1386 public function isTemplate() {
1391 * Get a title of frame
1395 public function getTitle() {
1396 return $this->title
;
1400 * Set the volatile flag
1404 public function setVolatile( $flag = true ) {
1405 $this->volatile
= $flag;
1409 * Get the volatile flag
1413 public function isVolatile() {
1414 return $this->volatile
;
1422 public function setTTL( $ttl ) {
1423 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1433 public function getTTL() {
1439 * Expansion frame with template arguments
1442 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1443 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1444 // @codingStandardsIgnoreEnd
1446 public $numberedArgs, $namedArgs, $parent;
1447 public $numberedExpansionCache, $namedExpansionCache;
1450 * @param Preprocessor $preprocessor
1451 * @param bool|PPFrame $parent
1452 * @param array $numberedArgs
1453 * @param array $namedArgs
1454 * @param bool|Title $title
1456 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1457 $namedArgs = [], $title = false
1459 parent
::__construct( $preprocessor );
1461 $this->parent
= $parent;
1462 $this->numberedArgs
= $numberedArgs;
1463 $this->namedArgs
= $namedArgs;
1464 $this->title
= $title;
1465 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1466 $this->titleCache
= $parent->titleCache
;
1467 $this->titleCache
[] = $pdbk;
1468 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1469 if ( $pdbk !== false ) {
1470 $this->loopCheckHash
[$pdbk] = true;
1472 $this->depth
= $parent->depth +
1;
1473 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1476 public function __toString() {
1479 $args = $this->numberedArgs +
$this->namedArgs
;
1480 foreach ( $args as $name => $value ) {
1486 $s .= "\"$name\":\"" .
1487 str_replace( '"', '\\"', $value->__toString() ) . '"';
1494 * @throws MWException
1495 * @param string|int $key
1496 * @param string|PPNode $root
1500 public function cachedExpand( $key, $root, $flags = 0 ) {
1501 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1502 return $this->parent
->childExpansionCache
[$key];
1504 $retval = $this->expand( $root, $flags );
1505 if ( !$this->isVolatile() ) {
1506 $this->parent
->childExpansionCache
[$key] = $retval;
1512 * Returns true if there are no arguments in this frame
1516 public function isEmpty() {
1517 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1523 public function getArguments() {
1525 foreach ( array_merge(
1526 array_keys( $this->numberedArgs
),
1527 array_keys( $this->namedArgs
) ) as $key ) {
1528 $arguments[$key] = $this->getArgument( $key );
1536 public function getNumberedArguments() {
1538 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1539 $arguments[$key] = $this->getArgument( $key );
1547 public function getNamedArguments() {
1549 foreach ( array_keys( $this->namedArgs
) as $key ) {
1550 $arguments[$key] = $this->getArgument( $key );
1557 * @return string|bool
1559 public function getNumberedArgument( $index ) {
1560 if ( !isset( $this->numberedArgs
[$index] ) ) {
1563 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1564 # No trimming for unnamed arguments
1565 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1566 $this->numberedArgs
[$index],
1567 PPFrame
::STRIP_COMMENTS
1570 return $this->numberedExpansionCache
[$index];
1574 * @param string $name
1575 * @return string|bool
1577 public function getNamedArgument( $name ) {
1578 if ( !isset( $this->namedArgs
[$name] ) ) {
1581 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1582 # Trim named arguments post-expand, for backwards compatibility
1583 $this->namedExpansionCache
[$name] = trim(
1584 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1586 return $this->namedExpansionCache
[$name];
1590 * @param int|string $name
1591 * @return string|bool
1593 public function getArgument( $name ) {
1594 $text = $this->getNumberedArgument( $name );
1595 if ( $text === false ) {
1596 $text = $this->getNamedArgument( $name );
1602 * Return true if the frame is a template frame
1606 public function isTemplate() {
1610 public function setVolatile( $flag = true ) {
1611 parent
::setVolatile( $flag );
1612 $this->parent
->setVolatile( $flag );
1615 public function setTTL( $ttl ) {
1616 parent
::setTTL( $ttl );
1617 $this->parent
->setTTL( $ttl );
1622 * Expansion frame with custom arguments
1625 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1626 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1627 // @codingStandardsIgnoreEnd
1631 public function __construct( $preprocessor, $args ) {
1632 parent
::__construct( $preprocessor );
1633 $this->args
= $args;
1636 public function __toString() {
1639 foreach ( $this->args
as $name => $value ) {
1645 $s .= "\"$name\":\"" .
1646 str_replace( '"', '\\"', $value->__toString() ) . '"';
1655 public function isEmpty() {
1656 return !count( $this->args
);
1660 * @param int|string $index
1661 * @return string|bool
1663 public function getArgument( $index ) {
1664 if ( !isset( $this->args
[$index] ) ) {
1667 return $this->args
[$index];
1670 public function getArguments() {
1678 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1679 class PPNode_Hash_Tree
implements PPNode
{
1680 // @codingStandardsIgnoreEnd
1685 * The store array for children of this node. It is "raw" in the sense that
1686 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1689 private $rawChildren;
1692 * The store array for the siblings of this node, including this node itself.
1697 * The index into $this->store which contains the descriptor of this node.
1702 * The offset of the name within descriptors, used in some places for
1708 * The offset of the child list within descriptors, used in some places for
1714 * Construct an object using the data from $store[$index]. The rest of the
1715 * store array can be accessed via getNextSibling().
1717 * @param array $store
1720 public function __construct( array $store, $index ) {
1721 $this->store
= $store;
1722 $this->index
= $index;
1723 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1727 * Construct an appropriate PPNode_Hash_* object with a class that depends
1728 * on what is at the relevant store index.
1730 * @param array $store
1732 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1734 public static function factory( array $store, $index ) {
1735 if ( !isset( $store[$index] ) ) {
1739 $descriptor = $store[$index];
1740 if ( is_string( $descriptor ) ) {
1741 $class = 'PPNode_Hash_Text';
1742 } elseif ( is_array( $descriptor ) ) {
1743 if ( $descriptor[self
::NAME
][0] === '@' ) {
1744 $class = 'PPNode_Hash_Attr';
1746 $class = 'PPNode_Hash_Tree';
1749 throw new MWException( __METHOD__
.': invalid node descriptor' );
1751 return new $class( $store, $index );
1755 * Convert a node to XML, for debugging
1757 public function __toString() {
1760 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1761 if ( $node instanceof PPNode_Hash_Attr
) {
1762 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1764 $inner .= $node->__toString();
1767 if ( $inner === '' ) {
1768 return "<{$this->name}$attribs/>";
1770 return "<{$this->name}$attribs>$inner</{$this->name}>";
1775 * @return PPNode_Hash_Array
1777 public function getChildren() {
1779 foreach ( $this->rawChildren
as $i => $child ) {
1780 $children[] = self
::factory( $this->rawChildren
, $i );
1782 return new PPNode_Hash_Array( $children );
1786 * Get the first child, or false if there is none. Note that this will
1787 * return a temporary proxy object: different instances will be returned
1788 * if this is called more than once on the same node.
1790 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1792 public function getFirstChild() {
1793 if ( !isset( $this->rawChildren
[0] ) ) {
1796 return self
::factory( $this->rawChildren
, 0 );
1801 * Get the next sibling, or false if there is none. Note that this will
1802 * return a temporary proxy object: different instances will be returned
1803 * if this is called more than once on the same node.
1805 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1807 public function getNextSibling() {
1808 return self
::factory( $this->store
, $this->index +
1 );
1812 * Get an array of the children with a given node name
1814 * @param string $name
1815 * @return PPNode_Hash_Array
1817 public function getChildrenOfType( $name ) {
1819 foreach ( $this->rawChildren
as $i => $child ) {
1820 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1821 $children[] = self
::factory( $this->rawChildren
, $i );
1824 return new PPNode_Hash_Array( $children );
1828 * Get the raw child array. For internal use.
1831 public function getRawChildren() {
1832 return $this->rawChildren
;
1838 public function getLength() {
1846 public function item( $i ) {
1853 public function getName() {
1858 * Split a "<part>" node into an associative array containing:
1859 * - name PPNode name
1860 * - index String index
1861 * - value PPNode value
1863 * @throws MWException
1866 public function splitArg() {
1867 return self
::splitRawArg( $this->rawChildren
);
1871 * Like splitArg() but for a raw child array. For internal use only.
1873 public static function splitRawArg( array $children ) {
1875 foreach ( $children as $i => $child ) {
1876 if ( !is_array( $child ) ) {
1879 if ( $child[self
::NAME
] === 'name' ) {
1880 $bits['name'] = new self( $children, $i );
1881 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1882 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1884 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1886 } elseif ( $child[self
::NAME
] === 'value' ) {
1887 $bits['value'] = new self( $children, $i );
1891 if ( !isset( $bits['name'] ) ) {
1892 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1894 if ( !isset( $bits['index'] ) ) {
1895 $bits['index'] = '';
1901 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1902 * All values in the resulting array are PPNodes. Inner and close are optional.
1904 * @throws MWException
1907 public function splitExt() {
1908 return self
::splitRawExt( $this->rawChildren
);
1912 * Like splitExt() but for a raw child array. For internal use only.
1914 public static function splitRawExt( array $children ) {
1916 foreach ( $children as $i => $child ) {
1917 if ( !is_array( $child ) ) {
1920 switch ( $child[self
::NAME
] ) {
1922 $bits['name'] = new self( $children, $i );
1925 $bits['attr'] = new self( $children, $i );
1928 $bits['inner'] = new self( $children, $i );
1931 $bits['close'] = new self( $children, $i );
1935 if ( !isset( $bits['name'] ) ) {
1936 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1942 * Split an "<h>" node
1944 * @throws MWException
1947 public function splitHeading() {
1948 if ( $this->name
!== 'h' ) {
1949 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1951 return self
::splitRawHeading( $this->rawChildren
);
1955 * Like splitHeading() but for a raw child array. For internal use only.
1957 public static function splitRawHeading( array $children ) {
1959 foreach ( $children as $i => $child ) {
1960 if ( !is_array( $child ) ) {
1963 if ( $child[self
::NAME
] === '@i' ) {
1964 $bits['i'] = $child[self
::CHILDREN
][0];
1965 } elseif ( $child[self
::NAME
] === '@level' ) {
1966 $bits['level'] = $child[self
::CHILDREN
][0];
1969 if ( !isset( $bits['i'] ) ) {
1970 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1976 * Split a "<template>" or "<tplarg>" node
1978 * @throws MWException
1981 public function splitTemplate() {
1982 return self
::splitRawTemplate( $this->rawChildren
);
1986 * Like splitTemplate() but for a raw child array. For internal use only.
1988 public static function splitRawTemplate( array $children ) {
1990 $bits = [ 'lineStart' => '' ];
1991 foreach ( $children as $i => $child ) {
1992 if ( !is_array( $child ) ) {
1995 switch ( $child[self
::NAME
] ) {
1997 $bits['title'] = new self( $children, $i );
2000 $parts[] = new self( $children, $i );
2003 $bits['lineStart'] = '1';
2007 if ( !isset( $bits['title'] ) ) {
2008 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
2010 $bits['parts'] = new PPNode_Hash_Array( $parts );
2018 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2019 class PPNode_Hash_Text
implements PPNode
{
2020 // @codingStandardsIgnoreEnd
2023 private $store, $index;
2026 * Construct an object using the data from $store[$index]. The rest of the
2027 * store array can be accessed via getNextSibling().
2029 * @param array $store
2032 public function __construct( array $store, $index ) {
2033 $this->value
= $store[$index];
2034 if ( !is_scalar( $this->value
) ) {
2035 throw new MWException( __CLASS__
. ' given object instead of string' );
2037 $this->store
= $store;
2038 $this->index
= $index;
2041 public function __toString() {
2042 return htmlspecialchars( $this->value
);
2045 public function getNextSibling() {
2046 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2049 public function getChildren() {
2053 public function getFirstChild() {
2057 public function getChildrenOfType( $name ) {
2061 public function getLength() {
2065 public function item( $i ) {
2069 public function getName() {
2073 public function splitArg() {
2074 throw new MWException( __METHOD__
. ': not supported' );
2077 public function splitExt() {
2078 throw new MWException( __METHOD__
. ': not supported' );
2081 public function splitHeading() {
2082 throw new MWException( __METHOD__
. ': not supported' );
2089 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2090 class PPNode_Hash_Array
implements PPNode
{
2091 // @codingStandardsIgnoreEnd
2095 public function __construct( $value ) {
2096 $this->value
= $value;
2099 public function __toString() {
2100 return var_export( $this, true );
2103 public function getLength() {
2104 return count( $this->value
);
2107 public function item( $i ) {
2108 return $this->value
[$i];
2111 public function getName() {
2115 public function getNextSibling() {
2119 public function getChildren() {
2123 public function getFirstChild() {
2127 public function getChildrenOfType( $name ) {
2131 public function splitArg() {
2132 throw new MWException( __METHOD__
. ': not supported' );
2135 public function splitExt() {
2136 throw new MWException( __METHOD__
. ': not supported' );
2139 public function splitHeading() {
2140 throw new MWException( __METHOD__
. ': not supported' );
2147 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2148 class PPNode_Hash_Attr
implements PPNode
{
2149 // @codingStandardsIgnoreEnd
2151 public $name, $value;
2152 private $store, $index;
2155 * Construct an object using the data from $store[$index]. The rest of the
2156 * store array can be accessed via getNextSibling().
2158 * @param array $store
2161 public function __construct( array $store, $index ) {
2162 $descriptor = $store[$index];
2163 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2164 throw new MWException( __METHOD__
.': invalid name in attribute descriptor' );
2166 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2167 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2168 $this->store
= $store;
2169 $this->index
= $index;
2172 public function __toString() {
2173 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2176 public function getName() {
2180 public function getNextSibling() {
2181 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2184 public function getChildren() {
2188 public function getFirstChild() {
2192 public function getChildrenOfType( $name ) {
2196 public function getLength() {
2200 public function item( $i ) {
2204 public function splitArg() {
2205 throw new MWException( __METHOD__
. ': not supported' );
2208 public function splitExt() {
2209 throw new MWException( __METHOD__
. ': not supported' );
2212 public function splitHeading() {
2213 throw new MWException( __METHOD__
. ': not supported' );