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] == '!--' ) {
308 // To avoid leaving blank lines, when a sequence of
309 // space-separated comments is both preceded and followed by
310 // a newline (ignoring spaces), then
311 // trim leading and trailing spaces and the trailing newline.
314 $endPos = strpos( $text, '-->', $i +
4 );
315 if ( $endPos === false ) {
316 // Unclosed comment in input, runs to end
317 $inner = substr( $text, $i );
318 $accum[] = [ 'comment', [ $inner ] ];
321 // Search backwards for leading whitespace
322 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
324 // Search forwards for trailing whitespace
325 // $wsEnd will be the position of the last space (or the '>' if there's none)
326 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
328 // Keep looking forward as long as we're finding more
330 $comments = [ [ $wsStart, $wsEnd ] ];
331 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
332 $c = strpos( $text, '-->', $wsEnd +
4 );
333 if ( $c === false ) {
336 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
337 $comments[] = [ $wsEnd +
1, $c ];
341 // Eat the line if possible
342 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
343 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
344 // it's a possible beneficial b/c break.
345 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
346 && substr( $text, $wsEnd +
1, 1 ) == "\n"
348 // Remove leading whitespace from the end of the accumulator
349 $wsLength = $i - $wsStart;
350 $endIndex = count( $accum ) - 1;
355 && is_string( $accum[$endIndex] )
356 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
358 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
361 // Dump all but the last comment to the accumulator
362 foreach ( $comments as $j => $com ) {
364 $endPos = $com[1] +
1;
365 if ( $j == ( count( $comments ) - 1 ) ) {
368 $inner = substr( $text, $startPos, $endPos - $startPos );
369 $accum[] = [ 'comment', [ $inner ] ];
372 // Do a line-start run next time to look for headings after the comment
373 $fakeLineStart = true;
375 // No line to eat, just take the comment itself
381 $part = $stack->top
->getCurrentPart();
382 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
383 $part->visualEnd
= $wsStart;
385 // Else comments abutting, no change in visual end
386 $part->commentEnd
= $endPos;
389 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
390 $accum[] = [ 'comment', [ $inner ] ];
395 $lowerName = strtolower( $name );
396 $attrStart = $i +
strlen( $name ) +
1;
399 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
400 if ( $tagEndPos === false ) {
401 // Infinite backtrack
402 // Disable tag search to prevent worst-case O(N^2) performance
404 self
::addLiteral( $accum, '<' );
409 // Handle ignored tags
410 if ( in_array( $lowerName, $ignoredTags ) ) {
411 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i +
1 ) ] ];
417 if ( $text[$tagEndPos - 1] == '/' ) {
419 $attrEnd = $tagEndPos - 1;
424 $attrEnd = $tagEndPos;
427 !isset( $noMoreClosingTag[$name] ) &&
428 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
429 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
431 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
432 $i = $matches[0][1] +
strlen( $matches[0][0] );
433 $close = $matches[0][0];
436 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
437 // Let it run out to the end of the text.
438 $inner = substr( $text, $tagEndPos +
1 );
442 // Don't match the tag, treat opening tag as literal and resume parsing.
444 self
::addLiteral( $accum,
445 substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
446 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
447 $noMoreClosingTag[$name] = true;
452 // <includeonly> and <noinclude> just become <ignore> tags
453 if ( in_array( $lowerName, $ignoredElements ) ) {
454 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
458 if ( $attrEnd <= $attrStart ) {
461 // Note that the attr element contains the whitespace between name and attribute,
462 // this is necessary for precise reconstruction during pre-save transform.
463 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
467 [ 'name', [ $name ] ],
468 [ 'attr', [ $attr ] ] ];
469 if ( $inner !== null ) {
470 $children[] = [ 'inner', [ $inner ] ];
472 if ( $close !== null ) {
473 $children[] = [ 'close', [ $close ] ];
475 $accum[] = [ 'ext', $children ];
476 } elseif ( $found == 'line-start' ) {
477 // Is this the start of a heading?
478 // Line break belongs before the heading element in any case
479 if ( $fakeLineStart ) {
480 $fakeLineStart = false;
482 self
::addLiteral( $accum, $curChar );
486 $count = strspn( $text, '=', $i, 6 );
487 if ( $count == 1 && $findEquals ) {
488 // DWIM: This looks kind of like a name/value separator.
489 // Let's let the equals handler have it and break the potential
490 // heading. This is heuristic, but AFAICT the methods for
491 // completely correct disambiguation are very complex.
492 } elseif ( $count > 0 ) {
496 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
499 $stack->push( $piece );
500 $accum =& $stack->getAccum();
501 extract( $stack->getFlags() );
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 extract( $stack->getFlags() );
560 // Append the result to the enclosing accumulator
561 array_splice( $accum, count( $accum ), 0, $element );
563 // Note that we do NOT increment the input pointer.
564 // This is because the closing linebreak could be the opening linebreak of
565 // another heading. Infinite loops are avoided because the next iteration MUST
566 // hit the heading open case above, which unconditionally increments the
568 } elseif ( $found == 'open' ) {
569 # count opening brace characters
570 $curLen = strlen( $curChar );
571 $count = ( $curLen > 1 ) ?
572 # allow the final character to repeat
573 strspn( $text, $curChar[$curLen-1], $i+
1 ) +
1 :
574 strspn( $text, $curChar, $i );
576 # we need to add to stack only if opening brace count is enough for one of the rules
577 if ( $count >= $rule['min'] ) {
578 # Add it to the stack
581 'close' => $rule['end'],
583 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
586 $stack->push( $piece );
587 $accum =& $stack->getAccum();
588 extract( $stack->getFlags() );
590 # Add literal brace(s)
591 self
::addLiteral( $accum, str_repeat( $curChar, $count ) );
594 } elseif ( $found == 'close' ) {
595 $piece = $stack->top
;
596 # lets check if there are enough characters for closing brace
597 $maxCount = $piece->count
;
598 if ( $piece->close
=== '}-' && $curChar === '}' ) {
599 $maxCount--; # don't try to match closing '-' as a '}'
601 $curLen = strlen( $curChar );
602 $count = ( $curLen > 1 ) ?
$curLen :
603 strspn( $text, $curChar, $i, $maxCount );
605 # check for maximum matching characters (if there are 5 closing
606 # characters, we will probably need only 3 - depending on the rules)
607 $rule = $this->rules
[$piece->open
];
608 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
609 # tweak for -{..{{ }}..}-
610 $rule = $this->rules
['{'];
612 if ( $count > $rule['max'] ) {
613 # The specified maximum exists in the callback array, unless the caller
615 $matchingCount = $rule['max'];
617 # Count is less than the maximum
618 # Skip any gaps in the callback array to find the true largest match
619 # Need to use array_key_exists not isset because the callback can be null
620 $matchingCount = $count;
621 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
626 if ( $matchingCount <= 0 ) {
627 # No matching element found in callback array
628 # Output a literal closing brace and continue
629 $endText = substr( $text, $i, $count );
630 self
::addLiteral( $accum, $endText );
634 $name = $rule['names'][$matchingCount];
635 if ( $name === null ) {
636 // No element, just literal text
637 $endText = substr( $text, $i, $matchingCount );
638 $element = $piece->breakSyntax( $matchingCount );
639 self
::addLiteral( $element, $endText );
642 $parts = $piece->parts
;
643 $titleAccum = $parts[0]->out
;
648 # The invocation is at the start of the line if lineStart is set in
649 # the stack, and all opening brackets are used up.
650 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
651 $children[] = [ '@lineStart', [ 1 ] ];
653 $titleNode = [ 'title', $titleAccum ];
654 $children[] = $titleNode;
656 foreach ( $parts as $part ) {
657 if ( isset( $part->eqpos
) ) {
658 $equalsNode = $part->out
[$part->eqpos
];
659 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
660 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
661 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
662 $children[] = $partNode;
664 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
665 $valueNode = [ 'value', $part->out
];
666 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
667 $children[] = $partNode;
670 $element = [ [ $name, $children ] ];
673 # Advance input pointer
674 $i +
= $matchingCount;
678 $accum =& $stack->getAccum();
680 # Re-add the old stack element if it still has unmatched opening characters remaining
681 if ( $matchingCount < $piece->count
) {
682 $piece->parts
= [ new PPDPart_Hash
];
683 $piece->count
-= $matchingCount;
684 # do we still qualify for any callback with remaining count?
685 $min = $this->rules
[$piece->open
]['min'];
686 if ( $piece->count
>= $min ) {
687 $stack->push( $piece );
688 $accum =& $stack->getAccum();
690 $s = substr( $piece->open
, 0, -1 );
692 substr( $piece->open
, -1 ),
693 $piece->count
- strlen( $s )
695 self
::addLiteral( $accum, $s );
699 extract( $stack->getFlags() );
701 # Add XML element to the enclosing accumulator
702 array_splice( $accum, count( $accum ), 0, $element );
703 } elseif ( $found == 'pipe' ) {
704 $findEquals = true; // shortcut for getFlags()
706 $accum =& $stack->getAccum();
708 } elseif ( $found == 'equals' ) {
709 $findEquals = false; // shortcut for getFlags()
710 $accum[] = [ 'equals', [ '=' ] ];
711 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
713 } elseif ( $found == 'dash' ) {
714 self
::addLiteral( $accum, '-' );
719 # Output any remaining unclosed brackets
720 foreach ( $stack->stack
as $piece ) {
721 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
724 # Enable top-level headings
725 foreach ( $stack->rootAccum
as &$node ) {
726 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
727 $node[PPNode_Hash_Tree
::NAME
] = 'h';
731 $rootStore = [ [ 'root', $stack->rootAccum
] ];
732 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
735 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
736 if ( $tree !== false ) {
737 $this->cacheSetTree( $text, $flags, $tree );
743 private static function addLiteral( array &$accum, $text ) {
744 $n = count( $accum );
745 if ( $n && is_string( $accum[$n - 1] ) ) {
746 $accum[$n - 1] .= $text;
754 * Stack class to help Preprocessor::preprocessToObj()
757 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
758 class PPDStack_Hash
extends PPDStack
{
759 // @codingStandardsIgnoreEnd
761 public function __construct() {
762 $this->elementClass
= 'PPDStackElement_Hash';
763 parent
::__construct();
764 $this->rootAccum
= [];
771 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
772 class PPDStackElement_Hash
extends PPDStackElement
{
773 // @codingStandardsIgnoreEnd
775 public function __construct( $data = [] ) {
776 $this->partClass
= 'PPDPart_Hash';
777 parent
::__construct( $data );
781 * Get the accumulator that would result if the close is not found.
783 * @param int|bool $openingCount
786 public function breakSyntax( $openingCount = false ) {
787 if ( $this->open
== "\n" ) {
788 $accum = $this->parts
[0]->out
;
790 if ( $openingCount === false ) {
791 $openingCount = $this->count
;
793 $s = substr( $this->open
, 0, -1 );
795 substr( $this->open
, -1 ),
796 $openingCount - strlen( $s )
801 foreach ( $this->parts
as $part ) {
804 } elseif ( is_string( $accum[$lastIndex] ) ) {
805 $accum[$lastIndex] .= '|';
807 $accum[++
$lastIndex] = '|';
809 foreach ( $part->out
as $node ) {
810 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
811 $accum[$lastIndex] .= $node;
813 $accum[++
$lastIndex] = $node;
825 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
826 class PPDPart_Hash
extends PPDPart
{
827 // @codingStandardsIgnoreEnd
829 public function __construct( $out = '' ) {
835 parent
::__construct( $accum );
840 * An expansion frame, used as a context to expand the result of preprocessToObj()
843 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
844 class PPFrame_Hash
implements PPFrame
{
845 // @codingStandardsIgnoreEnd
855 public $preprocessor;
864 * Hashtable listing templates which are disallowed for expansion in this frame,
865 * having been encountered previously in parent frames.
867 public $loopCheckHash;
870 * Recursion depth of this frame, top = 0
871 * Note that this is NOT the same as expansion depth in expand()
875 private $volatile = false;
881 protected $childExpansionCache;
884 * Construct a new preprocessor frame.
885 * @param Preprocessor $preprocessor The parent preprocessor
887 public function __construct( $preprocessor ) {
888 $this->preprocessor
= $preprocessor;
889 $this->parser
= $preprocessor->parser
;
890 $this->title
= $this->parser
->mTitle
;
891 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
892 $this->loopCheckHash
= [];
894 $this->childExpansionCache
= [];
898 * Create a new child frame
899 * $args is optionally a multi-root PPNode or array containing the template arguments
901 * @param array|bool|PPNode_Hash_Array $args
902 * @param Title|bool $title
903 * @param int $indexOffset
904 * @throws MWException
905 * @return PPTemplateFrame_Hash
907 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
910 if ( $title === false ) {
911 $title = $this->title
;
913 if ( $args !== false ) {
914 if ( $args instanceof PPNode_Hash_Array
) {
915 $args = $args->value
;
916 } elseif ( !is_array( $args ) ) {
917 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
919 foreach ( $args as $arg ) {
920 $bits = $arg->splitArg();
921 if ( $bits['index'] !== '' ) {
922 // Numbered parameter
923 $index = $bits['index'] - $indexOffset;
924 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
925 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
926 wfEscapeWikiText( $this->title
),
927 wfEscapeWikiText( $title ),
928 wfEscapeWikiText( $index ) )->text() );
929 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
931 $numberedArgs[$index] = $bits['value'];
932 unset( $namedArgs[$index] );
935 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
936 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
937 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
938 wfEscapeWikiText( $this->title
),
939 wfEscapeWikiText( $title ),
940 wfEscapeWikiText( $name ) )->text() );
941 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
943 $namedArgs[$name] = $bits['value'];
944 unset( $numberedArgs[$name] );
948 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
952 * @throws MWException
953 * @param string|int $key
954 * @param string|PPNode $root
958 public function cachedExpand( $key, $root, $flags = 0 ) {
959 // we don't have a parent, so we don't have a cache
960 return $this->expand( $root, $flags );
964 * @throws MWException
965 * @param string|PPNode $root
969 public function expand( $root, $flags = 0 ) {
970 static $expansionDepth = 0;
971 if ( is_string( $root ) ) {
975 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
976 $this->parser
->limitationWarn( 'node-count-exceeded',
977 $this->parser
->mPPNodeCount
,
978 $this->parser
->mOptions
->getMaxPPNodeCount()
980 return '<span class="error">Node-count limit exceeded</span>';
982 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
983 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
985 $this->parser
->mOptions
->getMaxPPExpandDepth()
987 return '<span class="error">Expansion depth limit exceeded</span>';
990 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
991 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
994 $outStack = [ '', '' ];
995 $iteratorStack = [ false, $root ];
996 $indexStack = [ 0, 0 ];
998 while ( count( $iteratorStack ) > 1 ) {
999 $level = count( $outStack ) - 1;
1000 $iteratorNode =& $iteratorStack[$level];
1001 $out =& $outStack[$level];
1002 $index =& $indexStack[$level];
1004 if ( is_array( $iteratorNode ) ) {
1005 if ( $index >= count( $iteratorNode ) ) {
1006 // All done with this iterator
1007 $iteratorStack[$level] = false;
1008 $contextNode = false;
1010 $contextNode = $iteratorNode[$index];
1013 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1014 if ( $index >= $iteratorNode->getLength() ) {
1015 // All done with this iterator
1016 $iteratorStack[$level] = false;
1017 $contextNode = false;
1019 $contextNode = $iteratorNode->item( $index );
1023 // Copy to $contextNode and then delete from iterator stack,
1024 // because this is not an iterator but we do have to execute it once
1025 $contextNode = $iteratorStack[$level];
1026 $iteratorStack[$level] = false;
1029 $newIterator = false;
1030 $contextName = false;
1031 $contextChildren = false;
1033 if ( $contextNode === false ) {
1035 } elseif ( is_string( $contextNode ) ) {
1036 $out .= $contextNode;
1037 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1038 $newIterator = $contextNode;
1039 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1041 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1042 $out .= $contextNode->value
;
1043 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1044 $contextName = $contextNode->name
;
1045 $contextChildren = $contextNode->getRawChildren();
1046 } elseif ( is_array( $contextNode ) ) {
1047 // Node descriptor array
1048 if ( count( $contextNode ) !== 2 ) {
1049 throw new MWException( __METHOD__
.
1050 ': found an array where a node descriptor should be' );
1052 list( $contextName, $contextChildren ) = $contextNode;
1054 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1057 // Handle node descriptor array or tree object
1058 if ( $contextName === false ) {
1059 // Not a node, already handled above
1060 } elseif ( $contextName[0] === '@' ) {
1061 // Attribute: no output
1062 } elseif ( $contextName === 'template' ) {
1063 # Double-brace expansion
1064 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1065 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1066 $newIterator = $this->virtualBracketedImplode(
1072 $ret = $this->parser
->braceSubstitution( $bits, $this );
1073 if ( isset( $ret['object'] ) ) {
1074 $newIterator = $ret['object'];
1076 $out .= $ret['text'];
1079 } elseif ( $contextName === 'tplarg' ) {
1080 # Triple-brace expansion
1081 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1082 if ( $flags & PPFrame
::NO_ARGS
) {
1083 $newIterator = $this->virtualBracketedImplode(
1089 $ret = $this->parser
->argSubstitution( $bits, $this );
1090 if ( isset( $ret['object'] ) ) {
1091 $newIterator = $ret['object'];
1093 $out .= $ret['text'];
1096 } elseif ( $contextName === 'comment' ) {
1097 # HTML-style comment
1098 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1099 # Not in RECOVER_COMMENTS mode (msgnw) though.
1100 if ( ( $this->parser
->ot
['html']
1101 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1102 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1103 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1106 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1107 # Add a strip marker in PST mode so that pstPass2() can
1108 # run some old-fashioned regexes on the result.
1109 # Not in RECOVER_COMMENTS mode (extractSections) though.
1110 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1112 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1113 $out .= $contextChildren[0];
1115 } elseif ( $contextName === 'ignore' ) {
1116 # Output suppression used by <includeonly> etc.
1117 # OT_WIKI will only respect <ignore> in substed templates.
1118 # The other output types respect it unless NO_IGNORE is set.
1119 # extractSections() sets NO_IGNORE and so never respects it.
1120 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1121 ||
( $flags & PPFrame
::NO_IGNORE
)
1123 $out .= $contextChildren[0];
1127 } elseif ( $contextName === 'ext' ) {
1129 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1130 [ 'attr' => null, 'inner' => null, 'close' => null ];
1131 if ( $flags & PPFrame
::NO_TAGS
) {
1132 $s = '<' . $bits['name']->getFirstChild()->value
;
1133 if ( $bits['attr'] ) {
1134 $s .= $bits['attr']->getFirstChild()->value
;
1136 if ( $bits['inner'] ) {
1137 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1138 if ( $bits['close'] ) {
1139 $s .= $bits['close']->getFirstChild()->value
;
1146 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1148 } elseif ( $contextName === 'h' ) {
1150 if ( $this->parser
->ot
['html'] ) {
1151 # Expand immediately and insert heading index marker
1152 $s = $this->expand( $contextChildren, $flags );
1153 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1154 $titleText = $this->title
->getPrefixedDBkey();
1155 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1156 $serial = count( $this->parser
->mHeadings
) - 1;
1157 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1158 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1159 $this->parser
->mStripState
->addGeneral( $marker, '' );
1162 # Expand in virtual stack
1163 $newIterator = $contextChildren;
1166 # Generic recursive expansion
1167 $newIterator = $contextChildren;
1170 if ( $newIterator !== false ) {
1172 $iteratorStack[] = $newIterator;
1174 } elseif ( $iteratorStack[$level] === false ) {
1175 // Return accumulated value to parent
1176 // With tail recursion
1177 while ( $iteratorStack[$level] === false && $level > 0 ) {
1178 $outStack[$level - 1] .= $out;
1179 array_pop( $outStack );
1180 array_pop( $iteratorStack );
1181 array_pop( $indexStack );
1187 return $outStack[0];
1191 * @param string $sep
1193 * @param string|PPNode $args,...
1196 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1197 $args = array_slice( func_get_args(), 2 );
1201 foreach ( $args as $root ) {
1202 if ( $root instanceof PPNode_Hash_Array
) {
1203 $root = $root->value
;
1205 if ( !is_array( $root ) ) {
1208 foreach ( $root as $node ) {
1214 $s .= $this->expand( $node, $flags );
1221 * Implode with no flags specified
1222 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1223 * @param string $sep
1224 * @param string|PPNode $args,...
1227 public function implode( $sep /*, ... */ ) {
1228 $args = array_slice( func_get_args(), 1 );
1232 foreach ( $args as $root ) {
1233 if ( $root instanceof PPNode_Hash_Array
) {
1234 $root = $root->value
;
1236 if ( !is_array( $root ) ) {
1239 foreach ( $root as $node ) {
1245 $s .= $this->expand( $node );
1252 * Makes an object that, when expand()ed, will be the same as one obtained
1255 * @param string $sep
1256 * @param string|PPNode $args,...
1257 * @return PPNode_Hash_Array
1259 public function virtualImplode( $sep /*, ... */ ) {
1260 $args = array_slice( func_get_args(), 1 );
1264 foreach ( $args as $root ) {
1265 if ( $root instanceof PPNode_Hash_Array
) {
1266 $root = $root->value
;
1268 if ( !is_array( $root ) ) {
1271 foreach ( $root as $node ) {
1280 return new PPNode_Hash_Array( $out );
1284 * Virtual implode with brackets
1286 * @param string $start
1287 * @param string $sep
1288 * @param string $end
1289 * @param string|PPNode $args,...
1290 * @return PPNode_Hash_Array
1292 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1293 $args = array_slice( func_get_args(), 3 );
1297 foreach ( $args as $root ) {
1298 if ( $root instanceof PPNode_Hash_Array
) {
1299 $root = $root->value
;
1301 if ( !is_array( $root ) ) {
1304 foreach ( $root as $node ) {
1314 return new PPNode_Hash_Array( $out );
1317 public function __toString() {
1322 * @param bool $level
1323 * @return array|bool|string
1325 public function getPDBK( $level = false ) {
1326 if ( $level === false ) {
1327 return $this->title
->getPrefixedDBkey();
1329 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1336 public function getArguments() {
1343 public function getNumberedArguments() {
1350 public function getNamedArguments() {
1355 * Returns true if there are no arguments in this frame
1359 public function isEmpty() {
1364 * @param int|string $name
1365 * @return bool Always false in this implementation.
1367 public function getArgument( $name ) {
1372 * Returns true if the infinite loop check is OK, false if a loop is detected
1374 * @param Title $title
1378 public function loopCheck( $title ) {
1379 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1383 * Return true if the frame is a template frame
1387 public function isTemplate() {
1392 * Get a title of frame
1396 public function getTitle() {
1397 return $this->title
;
1401 * Set the volatile flag
1405 public function setVolatile( $flag = true ) {
1406 $this->volatile
= $flag;
1410 * Get the volatile flag
1414 public function isVolatile() {
1415 return $this->volatile
;
1423 public function setTTL( $ttl ) {
1424 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1434 public function getTTL() {
1440 * Expansion frame with template arguments
1443 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1444 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1445 // @codingStandardsIgnoreEnd
1447 public $numberedArgs, $namedArgs, $parent;
1448 public $numberedExpansionCache, $namedExpansionCache;
1451 * @param Preprocessor $preprocessor
1452 * @param bool|PPFrame $parent
1453 * @param array $numberedArgs
1454 * @param array $namedArgs
1455 * @param bool|Title $title
1457 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1458 $namedArgs = [], $title = false
1460 parent
::__construct( $preprocessor );
1462 $this->parent
= $parent;
1463 $this->numberedArgs
= $numberedArgs;
1464 $this->namedArgs
= $namedArgs;
1465 $this->title
= $title;
1466 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1467 $this->titleCache
= $parent->titleCache
;
1468 $this->titleCache
[] = $pdbk;
1469 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1470 if ( $pdbk !== false ) {
1471 $this->loopCheckHash
[$pdbk] = true;
1473 $this->depth
= $parent->depth +
1;
1474 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1477 public function __toString() {
1480 $args = $this->numberedArgs +
$this->namedArgs
;
1481 foreach ( $args as $name => $value ) {
1487 $s .= "\"$name\":\"" .
1488 str_replace( '"', '\\"', $value->__toString() ) . '"';
1495 * @throws MWException
1496 * @param string|int $key
1497 * @param string|PPNode $root
1501 public function cachedExpand( $key, $root, $flags = 0 ) {
1502 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1503 return $this->parent
->childExpansionCache
[$key];
1505 $retval = $this->expand( $root, $flags );
1506 if ( !$this->isVolatile() ) {
1507 $this->parent
->childExpansionCache
[$key] = $retval;
1513 * Returns true if there are no arguments in this frame
1517 public function isEmpty() {
1518 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1524 public function getArguments() {
1526 foreach ( array_merge(
1527 array_keys( $this->numberedArgs
),
1528 array_keys( $this->namedArgs
) ) as $key ) {
1529 $arguments[$key] = $this->getArgument( $key );
1537 public function getNumberedArguments() {
1539 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1540 $arguments[$key] = $this->getArgument( $key );
1548 public function getNamedArguments() {
1550 foreach ( array_keys( $this->namedArgs
) as $key ) {
1551 $arguments[$key] = $this->getArgument( $key );
1558 * @return string|bool
1560 public function getNumberedArgument( $index ) {
1561 if ( !isset( $this->numberedArgs
[$index] ) ) {
1564 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1565 # No trimming for unnamed arguments
1566 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1567 $this->numberedArgs
[$index],
1568 PPFrame
::STRIP_COMMENTS
1571 return $this->numberedExpansionCache
[$index];
1575 * @param string $name
1576 * @return string|bool
1578 public function getNamedArgument( $name ) {
1579 if ( !isset( $this->namedArgs
[$name] ) ) {
1582 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1583 # Trim named arguments post-expand, for backwards compatibility
1584 $this->namedExpansionCache
[$name] = trim(
1585 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1587 return $this->namedExpansionCache
[$name];
1591 * @param int|string $name
1592 * @return string|bool
1594 public function getArgument( $name ) {
1595 $text = $this->getNumberedArgument( $name );
1596 if ( $text === false ) {
1597 $text = $this->getNamedArgument( $name );
1603 * Return true if the frame is a template frame
1607 public function isTemplate() {
1611 public function setVolatile( $flag = true ) {
1612 parent
::setVolatile( $flag );
1613 $this->parent
->setVolatile( $flag );
1616 public function setTTL( $ttl ) {
1617 parent
::setTTL( $ttl );
1618 $this->parent
->setTTL( $ttl );
1623 * Expansion frame with custom arguments
1626 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1627 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1628 // @codingStandardsIgnoreEnd
1632 public function __construct( $preprocessor, $args ) {
1633 parent
::__construct( $preprocessor );
1634 $this->args
= $args;
1637 public function __toString() {
1640 foreach ( $this->args
as $name => $value ) {
1646 $s .= "\"$name\":\"" .
1647 str_replace( '"', '\\"', $value->__toString() ) . '"';
1656 public function isEmpty() {
1657 return !count( $this->args
);
1661 * @param int|string $index
1662 * @return string|bool
1664 public function getArgument( $index ) {
1665 if ( !isset( $this->args
[$index] ) ) {
1668 return $this->args
[$index];
1671 public function getArguments() {
1679 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1680 class PPNode_Hash_Tree
implements PPNode
{
1681 // @codingStandardsIgnoreEnd
1686 * The store array for children of this node. It is "raw" in the sense that
1687 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1690 private $rawChildren;
1693 * The store array for the siblings of this node, including this node itself.
1698 * The index into $this->store which contains the descriptor of this node.
1703 * The offset of the name within descriptors, used in some places for
1709 * The offset of the child list within descriptors, used in some places for
1715 * Construct an object using the data from $store[$index]. The rest of the
1716 * store array can be accessed via getNextSibling().
1718 * @param array $store
1719 * @param integer $index
1721 public function __construct( array $store, $index ) {
1722 $this->store
= $store;
1723 $this->index
= $index;
1724 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1728 * Construct an appropriate PPNode_Hash_* object with a class that depends
1729 * on what is at the relevant store index.
1731 * @param array $store
1732 * @param integer $index
1733 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1735 public static function factory( array $store, $index ) {
1736 if ( !isset( $store[$index] ) ) {
1740 $descriptor = $store[$index];
1741 if ( is_string( $descriptor ) ) {
1742 $class = 'PPNode_Hash_Text';
1743 } elseif ( is_array( $descriptor ) ) {
1744 if ( $descriptor[self
::NAME
][0] === '@' ) {
1745 $class = 'PPNode_Hash_Attr';
1747 $class = 'PPNode_Hash_Tree';
1750 throw new MWException( __METHOD__
.': invalid node descriptor' );
1752 return new $class( $store, $index );
1756 * Convert a node to XML, for debugging
1758 public function __toString() {
1761 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1762 if ( $node instanceof PPNode_Hash_Attr
) {
1763 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1765 $inner .= $node->__toString();
1768 if ( $inner === '' ) {
1769 return "<{$this->name}$attribs/>";
1771 return "<{$this->name}$attribs>$inner</{$this->name}>";
1776 * @return PPNode_Hash_Array
1778 public function getChildren() {
1780 foreach ( $this->rawChildren
as $i => $child ) {
1781 $children[] = self
::factory( $this->rawChildren
, $i );
1783 return new PPNode_Hash_Array( $children );
1787 * Get the first child, or false if there is none. Note that this will
1788 * return a temporary proxy object: different instances will be returned
1789 * if this is called more than once on the same node.
1791 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|boolean
1793 public function getFirstChild() {
1794 if ( !isset( $this->rawChildren
[0] ) ) {
1797 return self
::factory( $this->rawChildren
, 0 );
1802 * Get the next sibling, or false if there is none. Note that this will
1803 * return a temporary proxy object: different instances will be returned
1804 * if this is called more than once on the same node.
1806 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|boolean
1808 public function getNextSibling() {
1809 return self
::factory( $this->store
, $this->index +
1 );
1813 * Get an array of the children with a given node name
1815 * @param string $name
1816 * @return PPNode_Hash_Array
1818 public function getChildrenOfType( $name ) {
1820 foreach ( $this->rawChildren
as $i => $child ) {
1821 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1822 $children[] = self
::factory( $this->rawChildren
, $i );
1825 return new PPNode_Hash_Array( $children );
1829 * Get the raw child array. For internal use.
1832 public function getRawChildren() {
1833 return $this->rawChildren
;
1839 public function getLength() {
1847 public function item( $i ) {
1854 public function getName() {
1859 * Split a "<part>" node into an associative array containing:
1860 * - name PPNode name
1861 * - index String index
1862 * - value PPNode value
1864 * @throws MWException
1867 public function splitArg() {
1868 return self
::splitRawArg( $this->rawChildren
);
1872 * Like splitArg() but for a raw child array. For internal use only.
1874 public static function splitRawArg( array $children ) {
1876 foreach ( $children as $i => $child ) {
1877 if ( !is_array( $child ) ) {
1880 if ( $child[self
::NAME
] === 'name' ) {
1881 $bits['name'] = new self( $children, $i );
1882 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1883 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1885 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1887 } elseif ( $child[self
::NAME
] === 'value' ) {
1888 $bits['value'] = new self( $children, $i );
1892 if ( !isset( $bits['name'] ) ) {
1893 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1895 if ( !isset( $bits['index'] ) ) {
1896 $bits['index'] = '';
1902 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1903 * All values in the resulting array are PPNodes. Inner and close are optional.
1905 * @throws MWException
1908 public function splitExt() {
1909 return self
::splitRawExt( $this->rawChildren
);
1913 * Like splitExt() but for a raw child array. For internal use only.
1915 public static function splitRawExt( array $children ) {
1917 foreach ( $children as $i => $child ) {
1918 if ( !is_array( $child ) ) {
1921 switch ( $child[self
::NAME
] ) {
1923 $bits['name'] = new self( $children, $i );
1926 $bits['attr'] = new self( $children, $i );
1929 $bits['inner'] = new self( $children, $i );
1932 $bits['close'] = new self( $children, $i );
1936 if ( !isset( $bits['name'] ) ) {
1937 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1943 * Split an "<h>" node
1945 * @throws MWException
1948 public function splitHeading() {
1949 if ( $this->name
!== 'h' ) {
1950 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1952 return self
::splitRawHeading( $this->rawChildren
);
1956 * Like splitHeading() but for a raw child array. For internal use only.
1958 public static function splitRawHeading( array $children ) {
1960 foreach ( $children as $i => $child ) {
1961 if ( !is_array( $child ) ) {
1964 if ( $child[self
::NAME
] === '@i' ) {
1965 $bits['i'] = $child[self
::CHILDREN
][0];
1966 } elseif ( $child[self
::NAME
] === '@level' ) {
1967 $bits['level'] = $child[self
::CHILDREN
][0];
1970 if ( !isset( $bits['i'] ) ) {
1971 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1977 * Split a "<template>" or "<tplarg>" node
1979 * @throws MWException
1982 public function splitTemplate() {
1983 return self
::splitRawTemplate( $this->rawChildren
);
1987 * Like splitTemplate() but for a raw child array. For internal use only.
1989 public static function splitRawTemplate( array $children ) {
1991 $bits = [ 'lineStart' => '' ];
1992 foreach ( $children as $i => $child ) {
1993 if ( !is_array( $child ) ) {
1996 switch ( $child[self
::NAME
] ) {
1998 $bits['title'] = new self( $children, $i );
2001 $parts[] = new self( $children, $i );
2004 $bits['lineStart'] = '1';
2008 if ( !isset( $bits['title'] ) ) {
2009 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
2011 $bits['parts'] = new PPNode_Hash_Array( $parts );
2019 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2020 class PPNode_Hash_Text
implements PPNode
{
2021 // @codingStandardsIgnoreEnd
2024 private $store, $index;
2027 * Construct an object using the data from $store[$index]. The rest of the
2028 * store array can be accessed via getNextSibling().
2030 * @param array $store
2031 * @param integer $index
2033 public function __construct( array $store, $index ) {
2034 $this->value
= $store[$index];
2035 if ( !is_scalar( $this->value
) ) {
2036 throw new MWException( __CLASS__
. ' given object instead of string' );
2038 $this->store
= $store;
2039 $this->index
= $index;
2042 public function __toString() {
2043 return htmlspecialchars( $this->value
);
2046 public function getNextSibling() {
2047 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2050 public function getChildren() {
2054 public function getFirstChild() {
2058 public function getChildrenOfType( $name ) {
2062 public function getLength() {
2066 public function item( $i ) {
2070 public function getName() {
2074 public function splitArg() {
2075 throw new MWException( __METHOD__
. ': not supported' );
2078 public function splitExt() {
2079 throw new MWException( __METHOD__
. ': not supported' );
2082 public function splitHeading() {
2083 throw new MWException( __METHOD__
. ': not supported' );
2090 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2091 class PPNode_Hash_Array
implements PPNode
{
2092 // @codingStandardsIgnoreEnd
2096 public function __construct( $value ) {
2097 $this->value
= $value;
2100 public function __toString() {
2101 return var_export( $this, true );
2104 public function getLength() {
2105 return count( $this->value
);
2108 public function item( $i ) {
2109 return $this->value
[$i];
2112 public function getName() {
2116 public function getNextSibling() {
2120 public function getChildren() {
2124 public function getFirstChild() {
2128 public function getChildrenOfType( $name ) {
2132 public function splitArg() {
2133 throw new MWException( __METHOD__
. ': not supported' );
2136 public function splitExt() {
2137 throw new MWException( __METHOD__
. ': not supported' );
2140 public function splitHeading() {
2141 throw new MWException( __METHOD__
. ': not supported' );
2148 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2149 class PPNode_Hash_Attr
implements PPNode
{
2150 // @codingStandardsIgnoreEnd
2152 public $name, $value;
2153 private $store, $index;
2156 * Construct an object using the data from $store[$index]. The rest of the
2157 * store array can be accessed via getNextSibling().
2159 * @param array $store
2160 * @param integer $index
2162 public function __construct( array $store, $index ) {
2163 $descriptor = $store[$index];
2164 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2165 throw new MWException( __METHOD__
.': invalid name in attribute descriptor' );
2167 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2168 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2169 $this->store
= $store;
2170 $this->index
= $index;
2173 public function __toString() {
2174 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2177 public function getName() {
2181 public function getNextSibling() {
2182 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2185 public function getChildren() {
2189 public function getFirstChild() {
2193 public function getChildrenOfType( $name ) {
2197 public function getLength() {
2201 public function item( $i ) {
2205 public function splitArg() {
2206 throw new MWException( __METHOD__
. ': not supported' );
2209 public function splitExt() {
2210 throw new MWException( __METHOD__
. ': not supported' );
2213 public function splitHeading() {
2214 throw new MWException( __METHOD__
. ': not supported' );