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 bug 4899.
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 $currentClosing = $stack->top
->close
;
212 $search .= $currentClosing;
218 // First equals will be for the template
222 # Output literal section, advance input counter
223 $literalLength = strcspn( $text, $search, $i );
224 if ( $literalLength > 0 ) {
225 self
::addLiteral( $accum, substr( $text, $i, $literalLength ) );
226 $i +
= $literalLength;
228 if ( $i >= $lengthText ) {
229 if ( $currentClosing == "\n" ) {
230 // Do a past-the-end run to finish off the heading
238 $curChar = $curTwoChar = $text[$i];
239 if ( ( $i +
1 ) < $lengthText ) {
240 $curTwoChar .= $text[$i +
1];
242 if ( $curChar == '|' ) {
244 } elseif ( $curChar == '=' ) {
246 } elseif ( $curChar == '<' ) {
248 } elseif ( $curChar == "\n" ) {
252 $found = 'line-start';
254 } elseif ( $curTwoChar == $currentClosing ) {
256 $curChar = $curTwoChar;
257 } elseif ( $curChar == $currentClosing ) {
259 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
260 $curChar = $curTwoChar;
262 $rule = $this->rules
[$curChar];
263 } elseif ( isset( $this->rules
[$curChar] ) ) {
265 $rule = $this->rules
[$curChar];
266 } elseif ( $curChar == '-' ) {
269 # Some versions of PHP have a strcspn which stops on null characters
270 # Ignore and continue
277 if ( $found == 'angle' ) {
279 // Handle </onlyinclude>
280 if ( $enableOnlyinclude
281 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
283 $findOnlyinclude = true;
287 // Determine element name
288 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
289 // Element name missing or not listed
290 self
::addLiteral( $accum, '<' );
295 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
297 // To avoid leaving blank lines, when a sequence of
298 // space-separated comments is both preceded and followed by
299 // a newline (ignoring spaces), then
300 // trim leading and trailing spaces and the trailing newline.
303 $endPos = strpos( $text, '-->', $i +
4 );
304 if ( $endPos === false ) {
305 // Unclosed comment in input, runs to end
306 $inner = substr( $text, $i );
307 $accum[] = [ 'comment', [ $inner ] ];
310 // Search backwards for leading whitespace
311 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
313 // Search forwards for trailing whitespace
314 // $wsEnd will be the position of the last space (or the '>' if there's none)
315 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
317 // Keep looking forward as long as we're finding more
319 $comments = [ [ $wsStart, $wsEnd ] ];
320 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
321 $c = strpos( $text, '-->', $wsEnd +
4 );
322 if ( $c === false ) {
325 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
326 $comments[] = [ $wsEnd +
1, $c ];
330 // Eat the line if possible
331 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
332 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
333 // it's a possible beneficial b/c break.
334 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
335 && substr( $text, $wsEnd +
1, 1 ) == "\n"
337 // Remove leading whitespace from the end of the accumulator
338 $wsLength = $i - $wsStart;
339 $endIndex = count( $accum ) - 1;
344 && is_string( $accum[$endIndex] )
345 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
347 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
350 // Dump all but the last comment to the accumulator
351 foreach ( $comments as $j => $com ) {
353 $endPos = $com[1] +
1;
354 if ( $j == ( count( $comments ) - 1 ) ) {
357 $inner = substr( $text, $startPos, $endPos - $startPos );
358 $accum[] = [ 'comment', [ $inner ] ];
361 // Do a line-start run next time to look for headings after the comment
362 $fakeLineStart = true;
364 // No line to eat, just take the comment itself
370 $part = $stack->top
->getCurrentPart();
371 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
372 $part->visualEnd
= $wsStart;
374 // Else comments abutting, no change in visual end
375 $part->commentEnd
= $endPos;
378 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
379 $accum[] = [ 'comment', [ $inner ] ];
384 $lowerName = strtolower( $name );
385 $attrStart = $i +
strlen( $name ) +
1;
388 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
389 if ( $tagEndPos === false ) {
390 // Infinite backtrack
391 // Disable tag search to prevent worst-case O(N^2) performance
393 self
::addLiteral( $accum, '<' );
398 // Handle ignored tags
399 if ( in_array( $lowerName, $ignoredTags ) ) {
400 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i +
1 ) ] ];
406 if ( $text[$tagEndPos - 1] == '/' ) {
408 $attrEnd = $tagEndPos - 1;
413 $attrEnd = $tagEndPos;
416 !isset( $noMoreClosingTag[$name] ) &&
417 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
418 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
420 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
421 $i = $matches[0][1] +
strlen( $matches[0][0] );
422 $close = $matches[0][0];
425 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
426 // Let it run out to the end of the text.
427 $inner = substr( $text, $tagEndPos +
1 );
431 // Don't match the tag, treat opening tag as literal and resume parsing.
433 self
::addLiteral( $accum,
434 substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
435 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
436 $noMoreClosingTag[$name] = true;
441 // <includeonly> and <noinclude> just become <ignore> tags
442 if ( in_array( $lowerName, $ignoredElements ) ) {
443 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
447 if ( $attrEnd <= $attrStart ) {
450 // Note that the attr element contains the whitespace between name and attribute,
451 // this is necessary for precise reconstruction during pre-save transform.
452 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
456 [ 'name', [ $name ] ],
457 [ 'attr', [ $attr ] ] ];
458 if ( $inner !== null ) {
459 $children[] = [ 'inner', [ $inner ] ];
461 if ( $close !== null ) {
462 $children[] = [ 'close', [ $close ] ];
464 $accum[] = [ 'ext', $children ];
465 } elseif ( $found == 'line-start' ) {
466 // Is this the start of a heading?
467 // Line break belongs before the heading element in any case
468 if ( $fakeLineStart ) {
469 $fakeLineStart = false;
471 self
::addLiteral( $accum, $curChar );
475 $count = strspn( $text, '=', $i, 6 );
476 if ( $count == 1 && $findEquals ) {
477 // DWIM: This looks kind of like a name/value separator.
478 // Let's let the equals handler have it and break the potential
479 // heading. This is heuristic, but AFAICT the methods for
480 // completely correct disambiguation are very complex.
481 } elseif ( $count > 0 ) {
485 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
488 $stack->push( $piece );
489 $accum =& $stack->getAccum();
490 extract( $stack->getFlags() );
493 } elseif ( $found == 'line-end' ) {
494 $piece = $stack->top
;
495 // A heading must be open, otherwise \n wouldn't have been in the search list
496 assert( $piece->open
=== "\n" );
497 $part = $piece->getCurrentPart();
498 // Search back through the input to see if it has a proper close.
499 // Do this using the reversed string since the other solutions
500 // (end anchor, etc.) are inefficient.
501 $wsLength = strspn( $revText, " \t", $lengthText - $i );
502 $searchStart = $i - $wsLength;
503 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
504 // Comment found at line end
505 // Search for equals signs before the comment
506 $searchStart = $part->visualEnd
;
507 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
509 $count = $piece->count
;
510 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
511 if ( $equalsLength > 0 ) {
512 if ( $searchStart - $equalsLength == $piece->startPos
) {
513 // This is just a single string of equals signs on its own line
514 // Replicate the doHeadings behavior /={count}(.+)={count}/
515 // First find out how many equals signs there really are (don't stop at 6)
516 $count = $equalsLength;
520 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
523 $count = min( $equalsLength, $count );
526 // Normal match, output <h>
527 $element = [ [ 'possible-h',
530 [ '@level', [ $count ] ],
531 [ '@i', [ $headingIndex++
] ]
537 // Single equals sign on its own line, count=0
541 // No match, no <h>, just pass down the inner text
546 $accum =& $stack->getAccum();
547 extract( $stack->getFlags() );
549 // Append the result to the enclosing accumulator
550 array_splice( $accum, count( $accum ), 0, $element );
552 // Note that we do NOT increment the input pointer.
553 // This is because the closing linebreak could be the opening linebreak of
554 // another heading. Infinite loops are avoided because the next iteration MUST
555 // hit the heading open case above, which unconditionally increments the
557 } elseif ( $found == 'open' ) {
558 # count opening brace characters
559 $curLen = strlen( $curChar );
560 $count = ( $curLen > 1 ) ?
1 : strspn( $text, $curChar, $i );
562 # we need to add to stack only if opening brace count is enough for one of the rules
563 if ( $count >= $rule['min'] ) {
564 # Add it to the stack
567 'close' => $rule['end'],
569 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
572 $stack->push( $piece );
573 $accum =& $stack->getAccum();
574 extract( $stack->getFlags() );
576 # Add literal brace(s)
577 self
::addLiteral( $accum, str_repeat( $curChar, $count ) );
579 $i +
= $curLen * $count;
580 } elseif ( $found == 'close' ) {
581 $piece = $stack->top
;
582 # lets check if there are enough characters for closing brace
583 $maxCount = $piece->count
;
584 $curLen = strlen( $curChar );
585 $count = ( $curLen > 1 ) ?
1 : strspn( $text, $curChar, $i, $maxCount );
587 # check for maximum matching characters (if there are 5 closing
588 # characters, we will probably need only 3 - depending on the rules)
589 $rule = $this->rules
[$piece->open
];
590 if ( $count > $rule['max'] ) {
591 # The specified maximum exists in the callback array, unless the caller
593 $matchingCount = $rule['max'];
595 # Count is less than the maximum
596 # Skip any gaps in the callback array to find the true largest match
597 # Need to use array_key_exists not isset because the callback can be null
598 $matchingCount = $count;
599 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
604 if ( $matchingCount <= 0 ) {
605 # No matching element found in callback array
606 # Output a literal closing brace and continue
607 self
::addLiteral( $accum, str_repeat( $curChar, $count ) );
608 $i +
= $curLen * $count;
611 $name = $rule['names'][$matchingCount];
612 if ( $name === null ) {
613 // No element, just literal text
614 $element = $piece->breakSyntax( $matchingCount );
615 self
::addLiteral( $element, str_repeat( $rule['end'], $matchingCount ) );
618 $parts = $piece->parts
;
619 $titleAccum = $parts[0]->out
;
624 # The invocation is at the start of the line if lineStart is set in
625 # the stack, and all opening brackets are used up.
626 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
627 $children[] = [ '@lineStart', [ 1 ] ];
629 $titleNode = [ 'title', $titleAccum ];
630 $children[] = $titleNode;
632 foreach ( $parts as $part ) {
633 if ( isset( $part->eqpos
) ) {
634 $equalsNode = $part->out
[$part->eqpos
];
635 $nameNode = [ 'name', array_slice( $part->out
, 0, $part->eqpos
) ];
636 $valueNode = [ 'value', array_slice( $part->out
, $part->eqpos +
1 ) ];
637 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
638 $children[] = $partNode;
640 $nameNode = [ 'name', [ [ '@index', [ $argIndex++
] ] ] ];
641 $valueNode = [ 'value', $part->out
];
642 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
643 $children[] = $partNode;
646 $element = [ [ $name, $children ] ];
649 # Advance input pointer
650 $i +
= $curLen * $matchingCount;
654 $accum =& $stack->getAccum();
656 # Re-add the old stack element if it still has unmatched opening characters remaining
657 if ( $matchingCount < $piece->count
) {
658 $piece->parts
= [ new PPDPart_Hash
];
659 $piece->count
-= $matchingCount;
660 # do we still qualify for any callback with remaining count?
661 $min = $this->rules
[$piece->open
]['min'];
662 if ( $piece->count
>= $min ) {
663 $stack->push( $piece );
664 $accum =& $stack->getAccum();
666 self
::addLiteral( $accum, str_repeat( $piece->open
, $piece->count
) );
670 extract( $stack->getFlags() );
672 # Add XML element to the enclosing accumulator
673 array_splice( $accum, count( $accum ), 0, $element );
674 } elseif ( $found == 'pipe' ) {
675 $findEquals = true; // shortcut for getFlags()
677 $accum =& $stack->getAccum();
679 } elseif ( $found == 'equals' ) {
680 $findEquals = false; // shortcut for getFlags()
681 $accum[] = [ 'equals', [ '=' ] ];
682 $stack->getCurrentPart()->eqpos
= count( $accum ) - 1;
684 } elseif ( $found == 'dash' ) {
685 self
::addLiteral( $accum, '-' );
690 # Output any remaining unclosed brackets
691 foreach ( $stack->stack
as $piece ) {
692 array_splice( $stack->rootAccum
, count( $stack->rootAccum
), 0, $piece->breakSyntax() );
695 # Enable top-level headings
696 foreach ( $stack->rootAccum
as &$node ) {
697 if ( is_array( $node ) && $node[PPNode_Hash_Tree
::NAME
] === 'possible-h' ) {
698 $node[PPNode_Hash_Tree
::NAME
] = 'h';
702 $rootStore = [ [ 'root', $stack->rootAccum
] ];
703 $rootNode = new PPNode_Hash_Tree( $rootStore, 0 );
706 $tree = json_encode( $rootStore, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
707 if ( $tree !== false ) {
708 $this->cacheSetTree( $text, $flags, $tree );
714 private static function addLiteral( array &$accum, $text ) {
715 $n = count( $accum );
716 if ( $n && is_string( $accum[$n - 1] ) ) {
717 $accum[$n - 1] .= $text;
725 * Stack class to help Preprocessor::preprocessToObj()
728 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
729 class PPDStack_Hash
extends PPDStack
{
730 // @codingStandardsIgnoreEnd
732 public function __construct() {
733 $this->elementClass
= 'PPDStackElement_Hash';
734 parent
::__construct();
735 $this->rootAccum
= [];
742 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
743 class PPDStackElement_Hash
extends PPDStackElement
{
744 // @codingStandardsIgnoreEnd
746 public function __construct( $data = [] ) {
747 $this->partClass
= 'PPDPart_Hash';
748 parent
::__construct( $data );
752 * Get the accumulator that would result if the close is not found.
754 * @param int|bool $openingCount
757 public function breakSyntax( $openingCount = false ) {
758 if ( $this->open
== "\n" ) {
759 $accum = $this->parts
[0]->out
;
761 if ( $openingCount === false ) {
762 $openingCount = $this->count
;
764 $accum = [ str_repeat( $this->open
, $openingCount ) ];
767 foreach ( $this->parts
as $part ) {
770 } elseif ( is_string( $accum[$lastIndex] ) ) {
771 $accum[$lastIndex] .= '|';
773 $accum[++
$lastIndex] = '|';
775 foreach ( $part->out
as $node ) {
776 if ( is_string( $node ) && is_string( $accum[$lastIndex] ) ) {
777 $accum[$lastIndex] .= $node;
779 $accum[++
$lastIndex] = $node;
791 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
792 class PPDPart_Hash
extends PPDPart
{
793 // @codingStandardsIgnoreEnd
795 public function __construct( $out = '' ) {
801 parent
::__construct( $accum );
806 * An expansion frame, used as a context to expand the result of preprocessToObj()
809 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
810 class PPFrame_Hash
implements PPFrame
{
811 // @codingStandardsIgnoreEnd
821 public $preprocessor;
830 * Hashtable listing templates which are disallowed for expansion in this frame,
831 * having been encountered previously in parent frames.
833 public $loopCheckHash;
836 * Recursion depth of this frame, top = 0
837 * Note that this is NOT the same as expansion depth in expand()
841 private $volatile = false;
847 protected $childExpansionCache;
850 * Construct a new preprocessor frame.
851 * @param Preprocessor $preprocessor The parent preprocessor
853 public function __construct( $preprocessor ) {
854 $this->preprocessor
= $preprocessor;
855 $this->parser
= $preprocessor->parser
;
856 $this->title
= $this->parser
->mTitle
;
857 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
858 $this->loopCheckHash
= [];
860 $this->childExpansionCache
= [];
864 * Create a new child frame
865 * $args is optionally a multi-root PPNode or array containing the template arguments
867 * @param array|bool|PPNode_Hash_Array $args
868 * @param Title|bool $title
869 * @param int $indexOffset
870 * @throws MWException
871 * @return PPTemplateFrame_Hash
873 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
876 if ( $title === false ) {
877 $title = $this->title
;
879 if ( $args !== false ) {
880 if ( $args instanceof PPNode_Hash_Array
) {
881 $args = $args->value
;
882 } elseif ( !is_array( $args ) ) {
883 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
885 foreach ( $args as $arg ) {
886 $bits = $arg->splitArg();
887 if ( $bits['index'] !== '' ) {
888 // Numbered parameter
889 $index = $bits['index'] - $indexOffset;
890 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
891 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
892 wfEscapeWikiText( $this->title
),
893 wfEscapeWikiText( $title ),
894 wfEscapeWikiText( $index ) )->text() );
895 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
897 $numberedArgs[$index] = $bits['value'];
898 unset( $namedArgs[$index] );
901 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
902 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
903 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
904 wfEscapeWikiText( $this->title
),
905 wfEscapeWikiText( $title ),
906 wfEscapeWikiText( $name ) )->text() );
907 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
909 $namedArgs[$name] = $bits['value'];
910 unset( $numberedArgs[$name] );
914 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
918 * @throws MWException
919 * @param string|int $key
920 * @param string|PPNode $root
924 public function cachedExpand( $key, $root, $flags = 0 ) {
925 // we don't have a parent, so we don't have a cache
926 return $this->expand( $root, $flags );
930 * @throws MWException
931 * @param string|PPNode $root
935 public function expand( $root, $flags = 0 ) {
936 static $expansionDepth = 0;
937 if ( is_string( $root ) ) {
941 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
942 $this->parser
->limitationWarn( 'node-count-exceeded',
943 $this->parser
->mPPNodeCount
,
944 $this->parser
->mOptions
->getMaxPPNodeCount()
946 return '<span class="error">Node-count limit exceeded</span>';
948 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
949 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
951 $this->parser
->mOptions
->getMaxPPExpandDepth()
953 return '<span class="error">Expansion depth limit exceeded</span>';
956 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
957 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
960 $outStack = [ '', '' ];
961 $iteratorStack = [ false, $root ];
962 $indexStack = [ 0, 0 ];
964 while ( count( $iteratorStack ) > 1 ) {
965 $level = count( $outStack ) - 1;
966 $iteratorNode =& $iteratorStack[$level];
967 $out =& $outStack[$level];
968 $index =& $indexStack[$level];
970 if ( is_array( $iteratorNode ) ) {
971 if ( $index >= count( $iteratorNode ) ) {
972 // All done with this iterator
973 $iteratorStack[$level] = false;
974 $contextNode = false;
976 $contextNode = $iteratorNode[$index];
979 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
980 if ( $index >= $iteratorNode->getLength() ) {
981 // All done with this iterator
982 $iteratorStack[$level] = false;
983 $contextNode = false;
985 $contextNode = $iteratorNode->item( $index );
989 // Copy to $contextNode and then delete from iterator stack,
990 // because this is not an iterator but we do have to execute it once
991 $contextNode = $iteratorStack[$level];
992 $iteratorStack[$level] = false;
995 $newIterator = false;
996 $contextName = false;
997 $contextChildren = false;
999 if ( $contextNode === false ) {
1001 } elseif ( is_string( $contextNode ) ) {
1002 $out .= $contextNode;
1003 } elseif ( $contextNode instanceof PPNode_Hash_Array
) {
1004 $newIterator = $contextNode;
1005 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1007 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1008 $out .= $contextNode->value
;
1009 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1010 $contextName = $contextNode->name
;
1011 $contextChildren = $contextNode->getRawChildren();
1012 } elseif ( is_array( $contextNode ) ) {
1013 // Node descriptor array
1014 if ( count( $contextNode ) !== 2 ) {
1015 throw new MWException( __METHOD__
.
1016 ': found an array where a node descriptor should be' );
1018 list( $contextName, $contextChildren ) = $contextNode;
1020 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1023 // Handle node descriptor array or tree object
1024 if ( $contextName === false ) {
1025 // Not a node, already handled above
1026 } elseif ( $contextName[0] === '@' ) {
1027 // Attribute: no output
1028 } elseif ( $contextName === 'template' ) {
1029 # Double-brace expansion
1030 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1031 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1032 $newIterator = $this->virtualBracketedImplode(
1038 $ret = $this->parser
->braceSubstitution( $bits, $this );
1039 if ( isset( $ret['object'] ) ) {
1040 $newIterator = $ret['object'];
1042 $out .= $ret['text'];
1045 } elseif ( $contextName === 'tplarg' ) {
1046 # Triple-brace expansion
1047 $bits = PPNode_Hash_Tree
::splitRawTemplate( $contextChildren );
1048 if ( $flags & PPFrame
::NO_ARGS
) {
1049 $newIterator = $this->virtualBracketedImplode(
1055 $ret = $this->parser
->argSubstitution( $bits, $this );
1056 if ( isset( $ret['object'] ) ) {
1057 $newIterator = $ret['object'];
1059 $out .= $ret['text'];
1062 } elseif ( $contextName === 'comment' ) {
1063 # HTML-style comment
1064 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1065 # Not in RECOVER_COMMENTS mode (msgnw) though.
1066 if ( ( $this->parser
->ot
['html']
1067 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1068 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1069 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1072 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1073 # Add a strip marker in PST mode so that pstPass2() can
1074 # run some old-fashioned regexes on the result.
1075 # Not in RECOVER_COMMENTS mode (extractSections) though.
1076 $out .= $this->parser
->insertStripItem( $contextChildren[0] );
1078 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1079 $out .= $contextChildren[0];
1081 } elseif ( $contextName === 'ignore' ) {
1082 # Output suppression used by <includeonly> etc.
1083 # OT_WIKI will only respect <ignore> in substed templates.
1084 # The other output types respect it unless NO_IGNORE is set.
1085 # extractSections() sets NO_IGNORE and so never respects it.
1086 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1087 ||
( $flags & PPFrame
::NO_IGNORE
)
1089 $out .= $contextChildren[0];
1093 } elseif ( $contextName === 'ext' ) {
1095 $bits = PPNode_Hash_Tree
::splitRawExt( $contextChildren ) +
1096 [ 'attr' => null, 'inner' => null, 'close' => null ];
1097 if ( $flags & PPFrame
::NO_TAGS
) {
1098 $s = '<' . $bits['name']->getFirstChild()->value
;
1099 if ( $bits['attr'] ) {
1100 $s .= $bits['attr']->getFirstChild()->value
;
1102 if ( $bits['inner'] ) {
1103 $s .= '>' . $bits['inner']->getFirstChild()->value
;
1104 if ( $bits['close'] ) {
1105 $s .= $bits['close']->getFirstChild()->value
;
1112 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1114 } elseif ( $contextName === 'h' ) {
1116 if ( $this->parser
->ot
['html'] ) {
1117 # Expand immediately and insert heading index marker
1118 $s = $this->expand( $contextChildren, $flags );
1119 $bits = PPNode_Hash_Tree
::splitRawHeading( $contextChildren );
1120 $titleText = $this->title
->getPrefixedDBkey();
1121 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1122 $serial = count( $this->parser
->mHeadings
) - 1;
1123 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1124 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1125 $this->parser
->mStripState
->addGeneral( $marker, '' );
1128 # Expand in virtual stack
1129 $newIterator = $contextChildren;
1132 # Generic recursive expansion
1133 $newIterator = $contextChildren;
1136 if ( $newIterator !== false ) {
1138 $iteratorStack[] = $newIterator;
1140 } elseif ( $iteratorStack[$level] === false ) {
1141 // Return accumulated value to parent
1142 // With tail recursion
1143 while ( $iteratorStack[$level] === false && $level > 0 ) {
1144 $outStack[$level - 1] .= $out;
1145 array_pop( $outStack );
1146 array_pop( $iteratorStack );
1147 array_pop( $indexStack );
1153 return $outStack[0];
1157 * @param string $sep
1159 * @param string|PPNode $args,...
1162 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1163 $args = array_slice( func_get_args(), 2 );
1167 foreach ( $args as $root ) {
1168 if ( $root instanceof PPNode_Hash_Array
) {
1169 $root = $root->value
;
1171 if ( !is_array( $root ) ) {
1174 foreach ( $root as $node ) {
1180 $s .= $this->expand( $node, $flags );
1187 * Implode with no flags specified
1188 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1189 * @param string $sep
1190 * @param string|PPNode $args,...
1193 public function implode( $sep /*, ... */ ) {
1194 $args = array_slice( func_get_args(), 1 );
1198 foreach ( $args as $root ) {
1199 if ( $root instanceof PPNode_Hash_Array
) {
1200 $root = $root->value
;
1202 if ( !is_array( $root ) ) {
1205 foreach ( $root as $node ) {
1211 $s .= $this->expand( $node );
1218 * Makes an object that, when expand()ed, will be the same as one obtained
1221 * @param string $sep
1222 * @param string|PPNode $args,...
1223 * @return PPNode_Hash_Array
1225 public function virtualImplode( $sep /*, ... */ ) {
1226 $args = array_slice( func_get_args(), 1 );
1230 foreach ( $args as $root ) {
1231 if ( $root instanceof PPNode_Hash_Array
) {
1232 $root = $root->value
;
1234 if ( !is_array( $root ) ) {
1237 foreach ( $root as $node ) {
1246 return new PPNode_Hash_Array( $out );
1250 * Virtual implode with brackets
1252 * @param string $start
1253 * @param string $sep
1254 * @param string $end
1255 * @param string|PPNode $args,...
1256 * @return PPNode_Hash_Array
1258 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1259 $args = array_slice( func_get_args(), 3 );
1263 foreach ( $args as $root ) {
1264 if ( $root instanceof PPNode_Hash_Array
) {
1265 $root = $root->value
;
1267 if ( !is_array( $root ) ) {
1270 foreach ( $root as $node ) {
1280 return new PPNode_Hash_Array( $out );
1283 public function __toString() {
1288 * @param bool $level
1289 * @return array|bool|string
1291 public function getPDBK( $level = false ) {
1292 if ( $level === false ) {
1293 return $this->title
->getPrefixedDBkey();
1295 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1302 public function getArguments() {
1309 public function getNumberedArguments() {
1316 public function getNamedArguments() {
1321 * Returns true if there are no arguments in this frame
1325 public function isEmpty() {
1330 * @param int|string $name
1331 * @return bool Always false in this implementation.
1333 public function getArgument( $name ) {
1338 * Returns true if the infinite loop check is OK, false if a loop is detected
1340 * @param Title $title
1344 public function loopCheck( $title ) {
1345 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1349 * Return true if the frame is a template frame
1353 public function isTemplate() {
1358 * Get a title of frame
1362 public function getTitle() {
1363 return $this->title
;
1367 * Set the volatile flag
1371 public function setVolatile( $flag = true ) {
1372 $this->volatile
= $flag;
1376 * Get the volatile flag
1380 public function isVolatile() {
1381 return $this->volatile
;
1389 public function setTTL( $ttl ) {
1390 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1400 public function getTTL() {
1406 * Expansion frame with template arguments
1409 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1410 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1411 // @codingStandardsIgnoreEnd
1413 public $numberedArgs, $namedArgs, $parent;
1414 public $numberedExpansionCache, $namedExpansionCache;
1417 * @param Preprocessor $preprocessor
1418 * @param bool|PPFrame $parent
1419 * @param array $numberedArgs
1420 * @param array $namedArgs
1421 * @param bool|Title $title
1423 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1424 $namedArgs = [], $title = false
1426 parent
::__construct( $preprocessor );
1428 $this->parent
= $parent;
1429 $this->numberedArgs
= $numberedArgs;
1430 $this->namedArgs
= $namedArgs;
1431 $this->title
= $title;
1432 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1433 $this->titleCache
= $parent->titleCache
;
1434 $this->titleCache
[] = $pdbk;
1435 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1436 if ( $pdbk !== false ) {
1437 $this->loopCheckHash
[$pdbk] = true;
1439 $this->depth
= $parent->depth +
1;
1440 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1443 public function __toString() {
1446 $args = $this->numberedArgs +
$this->namedArgs
;
1447 foreach ( $args as $name => $value ) {
1453 $s .= "\"$name\":\"" .
1454 str_replace( '"', '\\"', $value->__toString() ) . '"';
1461 * @throws MWException
1462 * @param string|int $key
1463 * @param string|PPNode $root
1467 public function cachedExpand( $key, $root, $flags = 0 ) {
1468 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1469 return $this->parent
->childExpansionCache
[$key];
1471 $retval = $this->expand( $root, $flags );
1472 if ( !$this->isVolatile() ) {
1473 $this->parent
->childExpansionCache
[$key] = $retval;
1479 * Returns true if there are no arguments in this frame
1483 public function isEmpty() {
1484 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1490 public function getArguments() {
1492 foreach ( array_merge(
1493 array_keys( $this->numberedArgs
),
1494 array_keys( $this->namedArgs
) ) as $key ) {
1495 $arguments[$key] = $this->getArgument( $key );
1503 public function getNumberedArguments() {
1505 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1506 $arguments[$key] = $this->getArgument( $key );
1514 public function getNamedArguments() {
1516 foreach ( array_keys( $this->namedArgs
) as $key ) {
1517 $arguments[$key] = $this->getArgument( $key );
1524 * @return string|bool
1526 public function getNumberedArgument( $index ) {
1527 if ( !isset( $this->numberedArgs
[$index] ) ) {
1530 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1531 # No trimming for unnamed arguments
1532 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1533 $this->numberedArgs
[$index],
1534 PPFrame
::STRIP_COMMENTS
1537 return $this->numberedExpansionCache
[$index];
1541 * @param string $name
1542 * @return string|bool
1544 public function getNamedArgument( $name ) {
1545 if ( !isset( $this->namedArgs
[$name] ) ) {
1548 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1549 # Trim named arguments post-expand, for backwards compatibility
1550 $this->namedExpansionCache
[$name] = trim(
1551 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1553 return $this->namedExpansionCache
[$name];
1557 * @param int|string $name
1558 * @return string|bool
1560 public function getArgument( $name ) {
1561 $text = $this->getNumberedArgument( $name );
1562 if ( $text === false ) {
1563 $text = $this->getNamedArgument( $name );
1569 * Return true if the frame is a template frame
1573 public function isTemplate() {
1577 public function setVolatile( $flag = true ) {
1578 parent
::setVolatile( $flag );
1579 $this->parent
->setVolatile( $flag );
1582 public function setTTL( $ttl ) {
1583 parent
::setTTL( $ttl );
1584 $this->parent
->setTTL( $ttl );
1589 * Expansion frame with custom arguments
1592 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1593 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1594 // @codingStandardsIgnoreEnd
1598 public function __construct( $preprocessor, $args ) {
1599 parent
::__construct( $preprocessor );
1600 $this->args
= $args;
1603 public function __toString() {
1606 foreach ( $this->args
as $name => $value ) {
1612 $s .= "\"$name\":\"" .
1613 str_replace( '"', '\\"', $value->__toString() ) . '"';
1622 public function isEmpty() {
1623 return !count( $this->args
);
1627 * @param int|string $index
1628 * @return string|bool
1630 public function getArgument( $index ) {
1631 if ( !isset( $this->args
[$index] ) ) {
1634 return $this->args
[$index];
1637 public function getArguments() {
1645 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1646 class PPNode_Hash_Tree
implements PPNode
{
1647 // @codingStandardsIgnoreEnd
1652 * The store array for children of this node. It is "raw" in the sense that
1653 * nodes are two-element arrays ("descriptors") rather than PPNode_Hash_*
1656 private $rawChildren;
1659 * The store array for the siblings of this node, including this node itself.
1664 * The index into $this->store which contains the descriptor of this node.
1669 * The offset of the name within descriptors, used in some places for
1675 * The offset of the child list within descriptors, used in some places for
1681 * Construct an object using the data from $store[$index]. The rest of the
1682 * store array can be accessed via getNextSibling().
1684 * @param array $store
1685 * @param integer $index
1687 public function __construct( array $store, $index ) {
1688 $this->store
= $store;
1689 $this->index
= $index;
1690 list( $this->name
, $this->rawChildren
) = $this->store
[$index];
1694 * Construct an appropriate PPNode_Hash_* object with a class that depends
1695 * on what is at the relevant store index.
1697 * @param array $store
1698 * @param integer $index
1699 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text
1701 public static function factory( array $store, $index ) {
1702 if ( !isset( $store[$index] ) ) {
1706 $descriptor = $store[$index];
1707 if ( is_string( $descriptor ) ) {
1708 $class = 'PPNode_Hash_Text';
1709 } elseif ( is_array( $descriptor ) ) {
1710 if ( $descriptor[self
::NAME
][0] === '@' ) {
1711 $class = 'PPNode_Hash_Attr';
1713 $class = 'PPNode_Hash_Tree';
1716 throw new MWException( __METHOD__
.': invalid node descriptor' );
1718 return new $class( $store, $index );
1722 * Convert a node to XML, for debugging
1724 public function __toString() {
1727 for ( $node = $this->getFirstChild(); $node; $node = $node->getNextSibling() ) {
1728 if ( $node instanceof PPNode_Hash_Attr
) {
1729 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1731 $inner .= $node->__toString();
1734 if ( $inner === '' ) {
1735 return "<{$this->name}$attribs/>";
1737 return "<{$this->name}$attribs>$inner</{$this->name}>";
1742 * @return PPNode_Hash_Array
1744 public function getChildren() {
1746 foreach ( $this->rawChildren
as $i => $child ) {
1747 $children[] = self
::factory( $this->rawChildren
, $i );
1749 return new PPNode_Hash_Array( $children );
1753 * Get the first child, or false if there is none. Note that this will
1754 * return a temporary proxy object: different instances will be returned
1755 * if this is called more than once on the same node.
1757 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|boolean
1759 public function getFirstChild() {
1760 if ( !isset( $this->rawChildren
[0] ) ) {
1763 return self
::factory( $this->rawChildren
, 0 );
1768 * Get the next sibling, or false if there is none. Note that this will
1769 * return a temporary proxy object: different instances will be returned
1770 * if this is called more than once on the same node.
1772 * @return PPNode_Hash_Tree|PPNode_Hash_Attr|PPNode_Hash_Text|boolean
1774 public function getNextSibling() {
1775 return self
::factory( $this->store
, $this->index +
1 );
1779 * Get an array of the children with a given node name
1781 * @param string $name
1782 * @return PPNode_Hash_Array
1784 public function getChildrenOfType( $name ) {
1786 foreach ( $this->rawChildren
as $i => $child ) {
1787 if ( is_array( $child ) && $child[self
::NAME
] === $name ) {
1788 $children[] = self
::factory( $this->rawChildren
, $i );
1791 return new PPNode_Hash_Array( $children );
1795 * Get the raw child array. For internal use.
1798 public function getRawChildren() {
1799 return $this->rawChildren
;
1805 public function getLength() {
1813 public function item( $i ) {
1820 public function getName() {
1825 * Split a "<part>" node into an associative array containing:
1826 * - name PPNode name
1827 * - index String index
1828 * - value PPNode value
1830 * @throws MWException
1833 public function splitArg() {
1834 return self
::splitRawArg( $this->rawChildren
);
1838 * Like splitArg() but for a raw child array. For internal use only.
1840 public static function splitRawArg( array $children ) {
1842 foreach ( $children as $i => $child ) {
1843 if ( !is_array( $child ) ) {
1846 if ( $child[self
::NAME
] === 'name' ) {
1847 $bits['name'] = new self( $children, $i );
1848 if ( isset( $child[self
::CHILDREN
][0][self
::NAME
] )
1849 && $child[self
::CHILDREN
][0][self
::NAME
] === '@index'
1851 $bits['index'] = $child[self
::CHILDREN
][0][self
::CHILDREN
][0];
1853 } elseif ( $child[self
::NAME
] === 'value' ) {
1854 $bits['value'] = new self( $children, $i );
1858 if ( !isset( $bits['name'] ) ) {
1859 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1861 if ( !isset( $bits['index'] ) ) {
1862 $bits['index'] = '';
1868 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1869 * All values in the resulting array are PPNodes. Inner and close are optional.
1871 * @throws MWException
1874 public function splitExt() {
1875 return self
::splitRawExt( $this->rawChildren
);
1879 * Like splitExt() but for a raw child array. For internal use only.
1881 public static function splitRawExt( array $children ) {
1883 foreach ( $children as $i => $child ) {
1884 if ( !is_array( $child ) ) {
1887 switch ( $child[self
::NAME
] ) {
1889 $bits['name'] = new self( $children, $i );
1892 $bits['attr'] = new self( $children, $i );
1895 $bits['inner'] = new self( $children, $i );
1898 $bits['close'] = new self( $children, $i );
1902 if ( !isset( $bits['name'] ) ) {
1903 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1909 * Split an "<h>" node
1911 * @throws MWException
1914 public function splitHeading() {
1915 if ( $this->name
!== 'h' ) {
1916 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1918 return self
::splitRawHeading( $this->rawChildren
);
1922 * Like splitHeading() but for a raw child array. For internal use only.
1924 public static function splitRawHeading( array $children ) {
1926 foreach ( $children as $i => $child ) {
1927 if ( !is_array( $child ) ) {
1930 if ( $child[self
::NAME
] === '@i' ) {
1931 $bits['i'] = $child[self
::CHILDREN
][0];
1932 } elseif ( $child[self
::NAME
] === '@level' ) {
1933 $bits['level'] = $child[self
::CHILDREN
][0];
1936 if ( !isset( $bits['i'] ) ) {
1937 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1943 * Split a "<template>" or "<tplarg>" node
1945 * @throws MWException
1948 public function splitTemplate() {
1949 return self
::splitRawTemplate( $this->rawChildren
);
1953 * Like splitTemplate() but for a raw child array. For internal use only.
1955 public static function splitRawTemplate( array $children ) {
1957 $bits = [ 'lineStart' => '' ];
1958 foreach ( $children as $i => $child ) {
1959 if ( !is_array( $child ) ) {
1962 switch ( $child[self
::NAME
] ) {
1964 $bits['title'] = new self( $children, $i );
1967 $parts[] = new self( $children, $i );
1970 $bits['lineStart'] = '1';
1974 if ( !isset( $bits['title'] ) ) {
1975 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1977 $bits['parts'] = new PPNode_Hash_Array( $parts );
1985 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1986 class PPNode_Hash_Text
implements PPNode
{
1987 // @codingStandardsIgnoreEnd
1990 private $store, $index;
1993 * Construct an object using the data from $store[$index]. The rest of the
1994 * store array can be accessed via getNextSibling().
1996 * @param array $store
1997 * @param integer $index
1999 public function __construct( array $store, $index ) {
2000 $this->value
= $store[$index];
2001 if ( !is_scalar( $this->value
) ) {
2002 throw new MWException( __CLASS__
. ' given object instead of string' );
2004 $this->store
= $store;
2005 $this->index
= $index;
2008 public function __toString() {
2009 return htmlspecialchars( $this->value
);
2012 public function getNextSibling() {
2013 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2016 public function getChildren() {
2020 public function getFirstChild() {
2024 public function getChildrenOfType( $name ) {
2028 public function getLength() {
2032 public function item( $i ) {
2036 public function getName() {
2040 public function splitArg() {
2041 throw new MWException( __METHOD__
. ': not supported' );
2044 public function splitExt() {
2045 throw new MWException( __METHOD__
. ': not supported' );
2048 public function splitHeading() {
2049 throw new MWException( __METHOD__
. ': not supported' );
2056 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2057 class PPNode_Hash_Array
implements PPNode
{
2058 // @codingStandardsIgnoreEnd
2062 public function __construct( $value ) {
2063 $this->value
= $value;
2066 public function __toString() {
2067 return var_export( $this, true );
2070 public function getLength() {
2071 return count( $this->value
);
2074 public function item( $i ) {
2075 return $this->value
[$i];
2078 public function getName() {
2082 public function getNextSibling() {
2086 public function getChildren() {
2090 public function getFirstChild() {
2094 public function getChildrenOfType( $name ) {
2098 public function splitArg() {
2099 throw new MWException( __METHOD__
. ': not supported' );
2102 public function splitExt() {
2103 throw new MWException( __METHOD__
. ': not supported' );
2106 public function splitHeading() {
2107 throw new MWException( __METHOD__
. ': not supported' );
2114 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2115 class PPNode_Hash_Attr
implements PPNode
{
2116 // @codingStandardsIgnoreEnd
2118 public $name, $value;
2119 private $store, $index;
2122 * Construct an object using the data from $store[$index]. The rest of the
2123 * store array can be accessed via getNextSibling().
2125 * @param array $store
2126 * @param integer $index
2128 public function __construct( array $store, $index ) {
2129 $descriptor = $store[$index];
2130 if ( $descriptor[PPNode_Hash_Tree
::NAME
][0] !== '@' ) {
2131 throw new MWException( __METHOD__
.': invalid name in attribute descriptor' );
2133 $this->name
= substr( $descriptor[PPNode_Hash_Tree
::NAME
], 1 );
2134 $this->value
= $descriptor[PPNode_Hash_Tree
::CHILDREN
][0];
2135 $this->store
= $store;
2136 $this->index
= $index;
2139 public function __toString() {
2140 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2143 public function getName() {
2147 public function getNextSibling() {
2148 return PPNode_Hash_Tree
::factory( $this->store
, $this->index +
1 );
2151 public function getChildren() {
2155 public function getFirstChild() {
2159 public function getChildrenOfType( $name ) {
2163 public function getLength() {
2167 public function item( $i ) {
2171 public function splitArg() {
2172 throw new MWException( __METHOD__
. ': not supported' );
2175 public function splitExt() {
2176 throw new MWException( __METHOD__
. ': not supported' );
2179 public function splitHeading() {
2180 throw new MWException( __METHOD__
. ': not supported' );