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 $stackFlags = $stack->getFlags();
501 if ( isset( $stackFlags['findEquals'] ) ) {
502 $findEquals = $stackFlags['findEquals'];
504 if ( isset( $stackFlags['findPipe'] ) ) {
505 $findPipe = $stackFlags['findPipe'];
507 if ( isset( $stackFlags['inHeading'] ) ) {
508 $inHeading = $stackFlags['inHeading'];
512 } elseif ( $found == 'line-end' ) {
513 $piece = $stack->top
;
514 // A heading must be open, otherwise \n wouldn't have been in the search list
515 assert( $piece->open
=== "\n" );
516 $part = $piece->getCurrentPart();
517 // Search back through the input to see if it has a proper close.
518 // Do this using the reversed string since the other solutions
519 // (end anchor, etc.) are inefficient.
520 $wsLength = strspn( $revText, " \t", $lengthText - $i );
521 $searchStart = $i - $wsLength;
522 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
523 // Comment found at line end
524 // Search for equals signs before the comment
525 $searchStart = $part->visualEnd
;
526 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
528 $count = $piece->count
;
529 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
530 if ( $equalsLength > 0 ) {
531 if ( $searchStart - $equalsLength == $piece->startPos
) {
532 // This is just a single string of equals signs on its own line
533 // Replicate the doHeadings behavior /={count}(.+)={count}/
534 // First find out how many equals signs there really are (don't stop at 6)
535 $count = $equalsLength;
539 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
542 $count = min( $equalsLength, $count );
545 // Normal match, output <h>
546 $element = [ [ 'possible-h',
549 [ '@level', [ $count ] ],
550 [ '@i', [ $headingIndex++
] ]
556 // Single equals sign on its own line, count=0
560 // No match, no <h>, just pass down the inner text
565 $accum =& $stack->getAccum();
566 $stackFlags = $stack->getFlags();
567 if ( isset( $stackFlags['findEquals'] ) ) {
568 $findEquals = $stackFlags['findEquals'];
570 if ( isset( $stackFlags['findPipe'] ) ) {
571 $findPipe = $stackFlags['findPipe'];
573 if ( isset( $stackFlags['inHeading'] ) ) {
574 $inHeading = $stackFlags['inHeading'];
577 // Append the result to the enclosing accumulator
578 array_splice( $accum, count( $accum ), 0, $element );
580 // Note that we do NOT increment the input pointer.
581 // This is because the closing linebreak could be the opening linebreak of
582 // another heading. Infinite loops are avoided because the next iteration MUST
583 // hit the heading open case above, which unconditionally increments the
585 } elseif ( $found == 'open' ) {
586 # count opening brace characters
587 $curLen = strlen( $curChar );
588 $count = ( $curLen > 1 ) ?
589 # allow the final character to repeat
590 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
591 strspn( $text, $curChar, $i );
593 # we need to add to stack only if opening brace count is enough for one of the rules
594 if ( $count >= $rule['min'] ) {
595 # Add it to the stack
598 'close' => $rule['end'],
600 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
603 $stack->push( $piece );
604 $accum =& $stack->getAccum();
605 $stackFlags = $stack->getFlags();
606 if ( isset( $stackFlags['findEquals'] ) ) {
607 $findEquals = $stackFlags['findEquals'];
609 if ( isset( $stackFlags['findPipe'] ) ) {
610 $findPipe = $stackFlags['findPipe'];
612 if ( isset( $stackFlags['inHeading'] ) ) {
613 $inHeading = $stackFlags['inHeading'];
616 # Add literal brace(s)
617 self
::addLiteral( $accum, str_repeat( $curChar, $count ) );
620 } elseif ( $found == 'close' ) {
621 $piece = $stack->top
;
622 # lets check if there are enough characters for closing brace
623 $maxCount = $piece->count
;
624 if ( $piece->close
=== '}-' && $curChar === '}' ) {
625 $maxCount--; # don't try to match closing '-' as a '}'
627 $curLen = strlen( $curChar );
628 $count = ( $curLen > 1 ) ?
$curLen :
629 strspn( $text, $curChar, $i, $maxCount );
631 # check for maximum matching characters (if there are 5 closing
632 # characters, we will probably need only 3 - depending on the rules)
633 $rule = $this->rules
[$piece->open
];
634 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
635 # tweak for -{..{{ }}..}-
636 $rule = $this->rules
['{'];
638 if ( $count > $rule['max'] ) {
639 # The specified maximum exists in the callback array, unless the caller
641 $matchingCount = $rule['max'];
643 # Count is less than the maximum
644 # Skip any gaps in the callback array to find the true largest match
645 # Need to use array_key_exists not isset because the callback can be null
646 $matchingCount = $count;
647 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
652 if ( $matchingCount <= 0 ) {
653 # No matching element found in callback array
654 # Output a literal closing brace and continue
655 $endText = substr( $text, $i, $count );
656 self
::addLiteral( $accum, $endText );
660 $name = $rule['names'][$matchingCount];
661 if ( $name === null ) {
662 // No element, just literal text
663 $endText = substr( $text, $i, $matchingCount );
664 $element = $piece->breakSyntax( $matchingCount );
665 self
::addLiteral( $element, $endText );
668 $parts = $piece->parts
;
669 $titleAccum = $parts[0]->out
;
674 # The invocation is at the start of the line if lineStart is set in
675 # the stack, and all opening brackets are used up.
676 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
677 $children[] = [ '@lineStart', [ 1 ] ];
679 $titleNode = [ 'title', $titleAccum ];
680 $children[] = $titleNode;
682 foreach ( $parts as $part ) {
683 if ( isset( $part->eqpos
) ) {
684 $equalsNode = $part->out
[$part->eqpos
];
685 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
686 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
687 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
688 $children[] = $partNode;
690 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
691 $valueNode = [ 'value', $part->out
];
692 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
693 $children[] = $partNode;
696 $element = [ [ $name, $children ] ];
699 # Advance input pointer
700 $i +
= $matchingCount;
704 $accum =& $stack->getAccum();
706 # Re-add the old stack element if it still has unmatched opening characters remaining
707 if ( $matchingCount < $piece->count
) {
708 $piece->parts
= [ new PPDPart_Hash
];
709 $piece->count
-= $matchingCount;
710 # do we still qualify for any callback with remaining count?
711 $min = $this->rules
[$piece->open
]['min'];
712 if ( $piece->count
>= $min ) {
713 $stack->push( $piece );
714 $accum =& $stack->getAccum();
716 $s = substr( $piece->open
, 0, -1 );
718 substr( $piece->open
, -1 ),
719 $piece->count
- strlen( $s )
721 self
::addLiteral( $accum, $s );
725 $stackFlags = $stack->getFlags();
726 if ( isset( $stackFlags['findEquals'] ) ) {
727 $findEquals = $stackFlags['findEquals'];
729 if ( isset( $stackFlags['findPipe'] ) ) {
730 $findPipe = $stackFlags['findPipe'];
732 if ( isset( $stackFlags['inHeading'] ) ) {
733 $inHeading = $stackFlags['inHeading'];
736 # Add XML element to the enclosing accumulator
737 array_splice( $accum, count( $accum ), 0, $element );
738 } elseif ( $found == 'pipe' ) {
739 $findEquals = true; // shortcut for getFlags()
741 $accum =& $stack->getAccum();
743 } elseif ( $found == 'equals' ) {
744 $findEquals = false; // shortcut for getFlags()
745 $accum[] = [ 'equals', [ '=' ] ];
746 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
748 } elseif ( $found == 'dash' ) {
749 self
::addLiteral( $accum, '-' );
754 # Output any remaining unclosed brackets
755 foreach ( $stack->stack
as $piece ) {
756 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
759 # Enable top-level headings
760 foreach ( $stack->rootAccum
as &$node ) {
761 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
762 $node[PPNode_Hash_Tree
::NAME
] = 'h';
766 $rootStore = [ [ 'root', $stack->rootAccum
] ];
767 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
770 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
771 if ( $tree !== false ) {
772 $this->cacheSetTree( $text, $flags, $tree );
778 private static function addLiteral( array &$accum, $text ) {
779 $n = count( $accum );
780 if ( $n && is_string( $accum[$n - 1] ) ) {
781 $accum[$n - 1] .= $text;
789 * Stack class to help Preprocessor::preprocessToObj()
792 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
793 class PPDStack_Hash
extends PPDStack
{
794 // @codingStandardsIgnoreEnd
796 public function __construct() {
797 $this->elementClass
= 'PPDStackElement_Hash';
798 parent
::__construct();
799 $this->rootAccum
= [];
806 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
807 class PPDStackElement_Hash
extends PPDStackElement
{
808 // @codingStandardsIgnoreEnd
810 public function __construct( $data = [] ) {
811 $this->partClass
= 'PPDPart_Hash';
812 parent
::__construct( $data );
816 * Get the accumulator that would result if the close is not found.
818 * @param int|bool $openingCount
821 public function breakSyntax( $openingCount = false ) {
822 if ( $this->open
== "\n" ) {
823 $accum = $this->parts
[0]->out
;
825 if ( $openingCount === false ) {
826 $openingCount = $this->count
;
828 $s = substr( $this->open
, 0, -1 );
830 substr( $this->open
, -1 ),
831 $openingCount - strlen( $s )
836 foreach ( $this->parts
as $part ) {
839 } elseif ( is_string( $accum[$lastIndex] ) ) {
840 $accum[$lastIndex] .= '|';
842 $accum[++
$lastIndex] = '|';
844 foreach ( $part->out
as $node ) {
845 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
846 $accum[$lastIndex] .= $node;
848 $accum[++
$lastIndex] = $node;
860 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
861 class PPDPart_Hash
extends PPDPart
{
862 // @codingStandardsIgnoreEnd
864 public function __construct( $out = '' ) {
870 parent
::__construct( $accum );
875 * An expansion frame, used as a context to expand the result of preprocessToObj()
878 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
879 class PPFrame_Hash
implements PPFrame
{
880 // @codingStandardsIgnoreEnd
890 public $preprocessor;
899 * Hashtable listing templates which are disallowed for expansion in this frame,
900 * having been encountered previously in parent frames.
902 public $loopCheckHash;
905 * Recursion depth of this frame, top = 0
906 * Note that this is NOT the same as expansion depth in expand()
910 private $volatile = false;
916 protected $childExpansionCache;
919 * Construct a new preprocessor frame.
920 * @param Preprocessor $preprocessor The parent preprocessor
922 public function __construct( $preprocessor ) {
923 $this->preprocessor
= $preprocessor;
924 $this->parser
= $preprocessor->parser
;
925 $this->title
= $this->parser
->mTitle
;
926 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
927 $this->loopCheckHash
= [];
929 $this->childExpansionCache
= [];
933 * Create a new child frame
934 * $args is optionally a multi-root PPNode or array containing the template arguments
936 * @param array|bool|PPNode_Hash_Array $args
937 * @param Title|bool $title
938 * @param int $indexOffset
939 * @throws MWException
940 * @return PPTemplateFrame_Hash
942 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
945 if ( $title === false ) {
946 $title = $this->title
;
948 if ( $args !== false ) {
949 if ( $args instanceof PPNode_Hash_Array
) {
950 $args = $args->value
;
951 } elseif ( !is_array( $args ) ) {
952 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
954 foreach ( $args as $arg ) {
955 $bits = $arg->splitArg();
956 if ( $bits['index'] !== '' ) {
957 // Numbered parameter
958 $index = $bits['index'] - $indexOffset;
959 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
960 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
961 wfEscapeWikiText( $this->title
),
962 wfEscapeWikiText( $title ),
963 wfEscapeWikiText( $index ) )->text() );
964 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
966 $numberedArgs[$index] = $bits['value'];
967 unset( $namedArgs[$index] );
970 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
971 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
972 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
973 wfEscapeWikiText( $this->title
),
974 wfEscapeWikiText( $title ),
975 wfEscapeWikiText( $name ) )->text() );
976 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
978 $namedArgs[$name] = $bits['value'];
979 unset( $numberedArgs[$name] );
983 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
987 * @throws MWException
988 * @param string|int $key
989 * @param string|PPNode $root
993 public function cachedExpand( $key, $root, $flags = 0 ) {
994 // we don't have a parent, so we don't have a cache
995 return $this->expand( $root, $flags );
999 * @throws MWException
1000 * @param string|PPNode $root
1004 public function expand( $root, $flags = 0 ) {
1005 static $expansionDepth = 0;
1006 if ( is_string( $root ) ) {
1010 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1011 $this->parser
->limitationWarn( 'node-count-exceeded',
1012 $this->parser
->mPPNodeCount
,
1013 $this->parser
->mOptions
->getMaxPPNodeCount()
1015 return '<span class="error">Node-count limit exceeded</span>';
1017 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1018 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1020 $this->parser
->mOptions
->getMaxPPExpandDepth()
1022 return '<span class="error">Expansion depth limit exceeded</span>';
1025 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1026 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1029 $outStack = [ '', '' ];
1030 $iteratorStack = [ false, $root ];
1031 $indexStack = [ 0, 0 ];
1033 while ( count( $iteratorStack ) > 1 ) {
1034 $level = count( $outStack ) - 1;
1035 $iteratorNode =& $iteratorStack[$level];
1036 $out =& $outStack[$level];
1037 $index =& $indexStack[$level];
1039 if ( is_array( $iteratorNode ) ) {
1040 if ( $index >= count( $iteratorNode ) ) {
1041 // All done with this iterator
1042 $iteratorStack[$level] = false;
1043 $contextNode = false;
1045 $contextNode = $iteratorNode[$index];
1048 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1049 if ( $index >= $iteratorNode->getLength() ) {
1050 // All done with this iterator
1051 $iteratorStack[$level] = false;
1052 $contextNode = false;
1054 $contextNode = $iteratorNode->item( $index );
1058 // Copy to $contextNode and then delete from iterator stack,
1059 // because this is not an iterator but we do have to execute it once
1060 $contextNode = $iteratorStack[$level];
1061 $iteratorStack[$level] = false;
1064 $newIterator = false;
1065 $contextName = false;
1066 $contextChildren = false;
1068 if ( $contextNode === false ) {
1070 } elseif ( is_string( $contextNode ) ) {
1071 $out .= $contextNode;
1072 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1073 $newIterator = $contextNode;
1074 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1076 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1077 $out .= $contextNode->value
;
1078 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1079 $contextName = $contextNode->name
;
1080 $contextChildren = $contextNode->getRawChildren();
1081 } elseif ( is_array( $contextNode ) ) {
1082 // Node descriptor array
1083 if ( count( $contextNode ) !== 2 ) {
1084 throw new MWException( __METHOD__
.
1085 ': found an array where a node descriptor should be' );
1087 list( $contextName, $contextChildren ) = $contextNode;
1089 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1092 // Handle node descriptor array or tree object
1093 if ( $contextName === false ) {
1094 // Not a node, already handled above
1095 } elseif ( $contextName[0] === '@' ) {
1096 // Attribute: no output
1097 } elseif ( $contextName === 'template' ) {
1098 # Double-brace expansion
1099 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1100 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1101 $newIterator = $this->virtualBracketedImplode(
1107 $ret = $this->parser
->braceSubstitution( $bits, $this );
1108 if ( isset( $ret['object'] ) ) {
1109 $newIterator = $ret['object'];
1111 $out .= $ret['text'];
1114 } elseif ( $contextName === 'tplarg' ) {
1115 # Triple-brace expansion
1116 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1117 if ( $flags & PPFrame
::NO_ARGS
) {
1118 $newIterator = $this->virtualBracketedImplode(
1124 $ret = $this->parser
->argSubstitution( $bits, $this );
1125 if ( isset( $ret['object'] ) ) {
1126 $newIterator = $ret['object'];
1128 $out .= $ret['text'];
1131 } elseif ( $contextName === 'comment' ) {
1132 # HTML-style comment
1133 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1134 # Not in RECOVER_COMMENTS mode (msgnw) though.
1135 if ( ( $this->parser
->ot
['html']
1136 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1137 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1138 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1141 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1142 # Add a strip marker in PST mode so that pstPass2() can
1143 # run some old-fashioned regexes on the result.
1144 # Not in RECOVER_COMMENTS mode (extractSections) though.
1145 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1147 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1148 $out .= $contextChildren[0];
1150 } elseif ( $contextName === 'ignore' ) {
1151 # Output suppression used by <includeonly> etc.
1152 # OT_WIKI will only respect <ignore> in substed templates.
1153 # The other output types respect it unless NO_IGNORE is set.
1154 # extractSections() sets NO_IGNORE and so never respects it.
1155 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1156 ||
( $flags & PPFrame
::NO_IGNORE
)
1158 $out .= $contextChildren[0];
1162 } elseif ( $contextName === 'ext' ) {
1164 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1165 [ 'attr' => null, 'inner' => null, 'close' => null ];
1166 if ( $flags & PPFrame
::NO_TAGS
) {
1167 $s = '<' . $bits['name']->getFirstChild()->value
;
1168 if ( $bits['attr'] ) {
1169 $s .= $bits['attr']->getFirstChild()->value
;
1171 if ( $bits['inner'] ) {
1172 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1173 if ( $bits['close'] ) {
1174 $s .= $bits['close']->getFirstChild()->value
;
1181 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1183 } elseif ( $contextName === 'h' ) {
1185 if ( $this->parser
->ot
['html'] ) {
1186 # Expand immediately and insert heading index marker
1187 $s = $this->expand( $contextChildren, $flags );
1188 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1189 $titleText = $this->title
->getPrefixedDBkey();
1190 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1191 $serial = count( $this->parser
->mHeadings
) - 1;
1192 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1193 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1194 $this->parser
->mStripState
->addGeneral( $marker, '' );
1197 # Expand in virtual stack
1198 $newIterator = $contextChildren;
1201 # Generic recursive expansion
1202 $newIterator = $contextChildren;
1205 if ( $newIterator !== false ) {
1207 $iteratorStack[] = $newIterator;
1209 } elseif ( $iteratorStack[$level] === false ) {
1210 // Return accumulated value to parent
1211 // With tail recursion
1212 while ( $iteratorStack[$level] === false && $level > 0 ) {
1213 $outStack[$level - 1] .= $out;
1214 array_pop( $outStack );
1215 array_pop( $iteratorStack );
1216 array_pop( $indexStack );
1222 return $outStack[0];
1226 * @param string $sep
1228 * @param string|PPNode $args,...
1231 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1232 $args = array_slice( func_get_args(), 2 );
1236 foreach ( $args as $root ) {
1237 if ( $root instanceof PPNode_Hash_Array
) {
1238 $root = $root->value
;
1240 if ( !is_array( $root ) ) {
1243 foreach ( $root as $node ) {
1249 $s .= $this->expand( $node, $flags );
1256 * Implode with no flags specified
1257 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1258 * @param string $sep
1259 * @param string|PPNode $args,...
1262 public function implode( $sep /*, ... */ ) {
1263 $args = array_slice( func_get_args(), 1 );
1267 foreach ( $args as $root ) {
1268 if ( $root instanceof PPNode_Hash_Array
) {
1269 $root = $root->value
;
1271 if ( !is_array( $root ) ) {
1274 foreach ( $root as $node ) {
1280 $s .= $this->expand( $node );
1287 * Makes an object that, when expand()ed, will be the same as one obtained
1290 * @param string $sep
1291 * @param string|PPNode $args,...
1292 * @return PPNode_Hash_Array
1294 public function virtualImplode( $sep /*, ... */ ) {
1295 $args = array_slice( func_get_args(), 1 );
1299 foreach ( $args as $root ) {
1300 if ( $root instanceof PPNode_Hash_Array
) {
1301 $root = $root->value
;
1303 if ( !is_array( $root ) ) {
1306 foreach ( $root as $node ) {
1315 return new PPNode_Hash_Array( $out );
1319 * Virtual implode with brackets
1321 * @param string $start
1322 * @param string $sep
1323 * @param string $end
1324 * @param string|PPNode $args,...
1325 * @return PPNode_Hash_Array
1327 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1328 $args = array_slice( func_get_args(), 3 );
1332 foreach ( $args as $root ) {
1333 if ( $root instanceof PPNode_Hash_Array
) {
1334 $root = $root->value
;
1336 if ( !is_array( $root ) ) {
1339 foreach ( $root as $node ) {
1349 return new PPNode_Hash_Array( $out );
1352 public function __toString() {
1357 * @param bool $level
1358 * @return array|bool|string
1360 public function getPDBK( $level = false ) {
1361 if ( $level === false ) {
1362 return $this->title
->getPrefixedDBkey();
1364 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1371 public function getArguments() {
1378 public function getNumberedArguments() {
1385 public function getNamedArguments() {
1390 * Returns true if there are no arguments in this frame
1394 public function isEmpty() {
1399 * @param int|string $name
1400 * @return bool Always false in this implementation.
1402 public function getArgument( $name ) {
1407 * Returns true if the infinite loop check is OK, false if a loop is detected
1409 * @param Title $title
1413 public function loopCheck( $title ) {
1414 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1418 * Return true if the frame is a template frame
1422 public function isTemplate() {
1427 * Get a title of frame
1431 public function getTitle() {
1432 return $this->title
;
1436 * Set the volatile flag
1440 public function setVolatile( $flag = true ) {
1441 $this->volatile
= $flag;
1445 * Get the volatile flag
1449 public function isVolatile() {
1450 return $this->volatile
;
1458 public function setTTL( $ttl ) {
1459 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1469 public function getTTL() {
1475 * Expansion frame with template arguments
1478 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1479 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1480 // @codingStandardsIgnoreEnd
1482 public $numberedArgs, $namedArgs, $parent;
1483 public $numberedExpansionCache, $namedExpansionCache;
1486 * @param Preprocessor $preprocessor
1487 * @param bool|PPFrame $parent
1488 * @param array $numberedArgs
1489 * @param array $namedArgs
1490 * @param bool|Title $title
1492 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1493 $namedArgs = [], $title = false
1495 parent
::__construct( $preprocessor );
1497 $this->parent
= $parent;
1498 $this->numberedArgs
= $numberedArgs;
1499 $this->namedArgs
= $namedArgs;
1500 $this->title
= $title;
1501 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1502 $this->titleCache
= $parent->titleCache
;
1503 $this->titleCache
[] = $pdbk;
1504 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1505 if ( $pdbk !== false ) {
1506 $this->loopCheckHash
[$pdbk] = true;
1508 $this->depth
= $parent->depth +
1;
1509 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1512 public function __toString() {
1515 $args = $this->numberedArgs +
$this->namedArgs
;
1516 foreach ( $args as $name => $value ) {
1522 $s .= "\"$name\":\"" .
1523 str_replace( '"', '\\"', $value->__toString() ) . '"';
1530 * @throws MWException
1531 * @param string|int $key
1532 * @param string|PPNode $root
1536 public function cachedExpand( $key, $root, $flags = 0 ) {
1537 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1538 return $this->parent
->childExpansionCache
[$key];
1540 $retval = $this->expand( $root, $flags );
1541 if ( !$this->isVolatile() ) {
1542 $this->parent
->childExpansionCache
[$key] = $retval;
1548 * Returns true if there are no arguments in this frame
1552 public function isEmpty() {
1553 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1559 public function getArguments() {
1561 foreach ( array_merge(
1562 array_keys( $this->numberedArgs
),
1563 array_keys( $this->namedArgs
) ) as $key ) {
1564 $arguments[$key] = $this->getArgument( $key );
1572 public function getNumberedArguments() {
1574 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1575 $arguments[$key] = $this->getArgument( $key );
1583 public function getNamedArguments() {
1585 foreach ( array_keys( $this->namedArgs
) as $key ) {
1586 $arguments[$key] = $this->getArgument( $key );
1593 * @return string|bool
1595 public function getNumberedArgument( $index ) {
1596 if ( !isset( $this->numberedArgs
[$index] ) ) {
1599 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1600 # No trimming for unnamed arguments
1601 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1602 $this->numberedArgs
[$index],
1603 PPFrame
::STRIP_COMMENTS
1606 return $this->numberedExpansionCache
[$index];
1610 * @param string $name
1611 * @return string|bool
1613 public function getNamedArgument( $name ) {
1614 if ( !isset( $this->namedArgs
[$name] ) ) {
1617 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1618 # Trim named arguments post-expand, for backwards compatibility
1619 $this->namedExpansionCache
[$name] = trim(
1620 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1622 return $this->namedExpansionCache
[$name];
1626 * @param int|string $name
1627 * @return string|bool
1629 public function getArgument( $name ) {
1630 $text = $this->getNumberedArgument( $name );
1631 if ( $text === false ) {
1632 $text = $this->getNamedArgument( $name );
1638 * Return true if the frame is a template frame
1642 public function isTemplate() {
1646 public function setVolatile( $flag = true ) {
1647 parent
::setVolatile( $flag );
1648 $this->parent
->setVolatile( $flag );
1651 public function setTTL( $ttl ) {
1652 parent
::setTTL( $ttl );
1653 $this->parent
->setTTL( $ttl );
1658 * Expansion frame with custom arguments
1661 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1662 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1663 // @codingStandardsIgnoreEnd
1667 public function __construct( $preprocessor, $args ) {
1668 parent
::__construct( $preprocessor );
1669 $this->args
= $args;
1672 public function __toString() {
1675 foreach ( $this->args
as $name => $value ) {
1681 $s .= "\"$name\":\"" .
1682 str_replace( '"', '\\"', $value->__toString() ) . '"';
1691 public function isEmpty() {
1692 return !count( $this->args
);
1696 * @param int|string $index
1697 * @return string|bool
1699 public function getArgument( $index ) {
1700 if ( !isset( $this->args
[$index] ) ) {
1703 return $this->args
[$index];
1706 public function getArguments() {
1714 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1715 class PPNode_Hash_Tree
implements PPNode
{
1716 // @codingStandardsIgnoreEnd
1721 * The store array for children of this node. It is "raw" in the sense that
1722 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1725 private $rawChildren;
1728 * The store array for the siblings of this node, including this node itself.
1733 * The index into $this->store which contains the descriptor of this node.
1738 * The offset of the name within descriptors, used in some places for
1744 * The offset of the child list within descriptors, used in some places for
1750 * Construct an object using the data from $store[$index]. The rest of the
1751 * store array can be accessed via getNextSibling().
1753 * @param array $store
1756 public function __construct( array $store, $index ) {
1757 $this->store
= $store;
1758 $this->index
= $index;
1759 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1763 * Construct an appropriate PPNode_Hash_* object with a class that depends
1764 * on what is at the relevant store index.
1766 * @param array $store
1768 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1770 public static function factory( array $store, $index ) {
1771 if ( !isset( $store[$index] ) ) {
1775 $descriptor = $store[$index];
1776 if ( is_string( $descriptor ) ) {
1777 $class = 'PPNode_Hash_Text';
1778 } elseif ( is_array( $descriptor ) ) {
1779 if ( $descriptor[self
::NAME
][0] === '@' ) {
1780 $class = 'PPNode_Hash_Attr';
1782 $class = 'PPNode_Hash_Tree';
1785 throw new MWException( __METHOD__
.': invalid node descriptor' );
1787 return new $class( $store, $index );
1791 * Convert a node to XML, for debugging
1793 public function __toString() {
1796 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1797 if ( $node instanceof PPNode_Hash_Attr
) {
1798 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1800 $inner .= $node->__toString();
1803 if ( $inner === '' ) {
1804 return "<{$this->name}$attribs/>";
1806 return "<{$this->name}$attribs>$inner</{$this->name}>";
1811 * @return PPNode_Hash_Array
1813 public function getChildren() {
1815 foreach ( $this->rawChildren
as $i => $child ) {
1816 $children[] = self
::factory( $this->rawChildren
, $i );
1818 return new PPNode_Hash_Array( $children );
1822 * Get the first child, or false if there is none. Note that this will
1823 * return a temporary proxy object: different instances will be returned
1824 * if this is called more than once on the same node.
1826 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1828 public function getFirstChild() {
1829 if ( !isset( $this->rawChildren
[0] ) ) {
1832 return self
::factory( $this->rawChildren
, 0 );
1837 * Get the next sibling, or false if there is none. Note that this will
1838 * return a temporary proxy object: different instances will be returned
1839 * if this is called more than once on the same node.
1841 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|bool
1843 public function getNextSibling() {
1844 return self
::factory( $this->store
, $this->index +
1 );
1848 * Get an array of the children with a given node name
1850 * @param string $name
1851 * @return PPNode_Hash_Array
1853 public function getChildrenOfType( $name ) {
1855 foreach ( $this->rawChildren
as $i => $child ) {
1856 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1857 $children[] = self
::factory( $this->rawChildren
, $i );
1860 return new PPNode_Hash_Array( $children );
1864 * Get the raw child array. For internal use.
1867 public function getRawChildren() {
1868 return $this->rawChildren
;
1874 public function getLength() {
1882 public function item( $i ) {
1889 public function getName() {
1894 * Split a "<part>" node into an associative array containing:
1895 * - name PPNode name
1896 * - index String index
1897 * - value PPNode value
1899 * @throws MWException
1902 public function splitArg() {
1903 return self
::splitRawArg( $this->rawChildren
);
1907 * Like splitArg() but for a raw child array. For internal use only.
1908 * @param array $children
1911 public static function splitRawArg( array $children ) {
1913 foreach ( $children as $i => $child ) {
1914 if ( !is_array( $child ) ) {
1917 if ( $child[self
::NAME
] === 'name' ) {
1918 $bits['name'] = new self( $children, $i );
1919 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1920 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1922 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1924 } elseif ( $child[self
::NAME
] === 'value' ) {
1925 $bits['value'] = new self( $children, $i );
1929 if ( !isset( $bits['name'] ) ) {
1930 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1932 if ( !isset( $bits['index'] ) ) {
1933 $bits['index'] = '';
1939 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1940 * All values in the resulting array are PPNodes. Inner and close are optional.
1942 * @throws MWException
1945 public function splitExt() {
1946 return self
::splitRawExt( $this->rawChildren
);
1950 * Like splitExt() but for a raw child array. For internal use only.
1951 * @param array $children
1954 public static function splitRawExt( array $children ) {
1956 foreach ( $children as $i => $child ) {
1957 if ( !is_array( $child ) ) {
1960 switch ( $child[self
::NAME
] ) {
1962 $bits['name'] = new self( $children, $i );
1965 $bits['attr'] = new self( $children, $i );
1968 $bits['inner'] = new self( $children, $i );
1971 $bits['close'] = new self( $children, $i );
1975 if ( !isset( $bits['name'] ) ) {
1976 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1982 * Split an "<h>" node
1984 * @throws MWException
1987 public function splitHeading() {
1988 if ( $this->name
!== 'h' ) {
1989 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1991 return self
::splitRawHeading( $this->rawChildren
);
1995 * Like splitHeading() but for a raw child array. For internal use only.
1996 * @param array $children
1999 public static function splitRawHeading( array $children ) {
2001 foreach ( $children as $i => $child ) {
2002 if ( !is_array( $child ) ) {
2005 if ( $child[self
::NAME
] === '@i' ) {
2006 $bits['i'] = $child[self
::CHILDREN
][0];
2007 } elseif ( $child[self
::NAME
] === '@level' ) {
2008 $bits['level'] = $child[self
::CHILDREN
][0];
2011 if ( !isset( $bits['i'] ) ) {
2012 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2018 * Split a "<template>" or "<tplarg>" node
2020 * @throws MWException
2023 public function splitTemplate() {
2024 return self
::splitRawTemplate( $this->rawChildren
);
2028 * Like splitTemplate() but for a raw child array. For internal use only.
2029 * @param array $children
2032 public static function splitRawTemplate( array $children ) {
2034 $bits = [ 'lineStart' => '' ];
2035 foreach ( $children as $i => $child ) {
2036 if ( !is_array( $child ) ) {
2039 switch ( $child[self
::NAME
] ) {
2041 $bits['title'] = new self( $children, $i );
2044 $parts[] = new self( $children, $i );
2047 $bits['lineStart'] = '1';
2051 if ( !isset( $bits['title'] ) ) {
2052 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
2054 $bits['parts'] = new PPNode_Hash_Array( $parts );
2062 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2063 class PPNode_Hash_Text
implements PPNode
{
2064 // @codingStandardsIgnoreEnd
2067 private $store, $index;
2070 * Construct an object using the data from $store[$index]. The rest of the
2071 * store array can be accessed via getNextSibling().
2073 * @param array $store
2076 public function __construct( array $store, $index ) {
2077 $this->value
= $store[$index];
2078 if ( !is_scalar( $this->value
) ) {
2079 throw new MWException( __CLASS__
. ' given object instead of string' );
2081 $this->store
= $store;
2082 $this->index
= $index;
2085 public function __toString() {
2086 return htmlspecialchars( $this->value
);
2089 public function getNextSibling() {
2090 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2093 public function getChildren() {
2097 public function getFirstChild() {
2101 public function getChildrenOfType( $name ) {
2105 public function getLength() {
2109 public function item( $i ) {
2113 public function getName() {
2117 public function splitArg() {
2118 throw new MWException( __METHOD__
. ': not supported' );
2121 public function splitExt() {
2122 throw new MWException( __METHOD__
. ': not supported' );
2125 public function splitHeading() {
2126 throw new MWException( __METHOD__
. ': not supported' );
2133 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2134 class PPNode_Hash_Array
implements PPNode
{
2135 // @codingStandardsIgnoreEnd
2139 public function __construct( $value ) {
2140 $this->value
= $value;
2143 public function __toString() {
2144 return var_export( $this, true );
2147 public function getLength() {
2148 return count( $this->value
);
2151 public function item( $i ) {
2152 return $this->value
[$i];
2155 public function getName() {
2159 public function getNextSibling() {
2163 public function getChildren() {
2167 public function getFirstChild() {
2171 public function getChildrenOfType( $name ) {
2175 public function splitArg() {
2176 throw new MWException( __METHOD__
. ': not supported' );
2179 public function splitExt() {
2180 throw new MWException( __METHOD__
. ': not supported' );
2183 public function splitHeading() {
2184 throw new MWException( __METHOD__
. ': not supported' );
2191 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2192 class PPNode_Hash_Attr
implements PPNode
{
2193 // @codingStandardsIgnoreEnd
2195 public $name, $value;
2196 private $store, $index;
2199 * Construct an object using the data from $store[$index]. The rest of the
2200 * store array can be accessed via getNextSibling().
2202 * @param array $store
2205 public function __construct( array $store, $index ) {
2206 $descriptor = $store[$index];
2207 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2208 throw new MWException( __METHOD__
.': invalid name in attribute descriptor' );
2210 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2211 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2212 $this->store
= $store;
2213 $this->index
= $index;
2216 public function __toString() {
2217 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2220 public function getName() {
2224 public function getNextSibling() {
2225 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2228 public function getChildren() {
2232 public function getFirstChild() {
2236 public function getChildrenOfType( $name ) {
2240 public function getLength() {
2244 public function item( $i ) {
2248 public function splitArg() {
2249 throw new MWException( __METHOD__
. ': not supported' );
2252 public function splitExt() {
2253 throw new MWException( __METHOD__
. ': not supported' );
2256 public function splitHeading() {
2257 throw new MWException( __METHOD__
. ': not supported' );