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>
30 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
31 class Preprocessor_Hash
extends Preprocessor
{
32 // @codingStandardsIgnoreEnd
39 const CACHE_PREFIX
= 'preprocess-hash';
41 public function __construct( $parser ) {
42 $this->parser
= $parser;
46 * @return PPFrame_Hash
48 public function newFrame() {
49 return new PPFrame_Hash( $this );
54 * @return PPCustomFrame_Hash
56 public function newCustomFrame( $args ) {
57 return new PPCustomFrame_Hash( $this, $args );
61 * @param array $values
62 * @return PPNode_Hash_Array
64 public function newPartNodeArray( $values ) {
67 foreach ( $values as $k => $val ) {
68 $partNode = new PPNode_Hash_Tree( 'part' );
69 $nameNode = new PPNode_Hash_Tree( 'name' );
72 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
73 $partNode->addChild( $nameNode );
75 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
76 $partNode->addChild( $nameNode );
77 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
80 $valueNode = new PPNode_Hash_Tree( 'value' );
81 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
82 $partNode->addChild( $valueNode );
87 $node = new PPNode_Hash_Array( $list );
92 * Preprocess some wikitext and return the document tree.
93 * This is the ghost of Parser::replace_variables().
95 * @param string $text The text to parse
96 * @param int $flags Bitwise combination of:
97 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
98 * included. Default is to assume a direct page view.
100 * The generated DOM tree must depend only on the input text and the flags.
101 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
103 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
104 * change in the DOM tree for a given text, must be passed through the section identifier
105 * in the section edit link and thus back to extractSections().
107 * The output of this function is currently only cached in process memory, but a persistent
108 * cache may be implemented at a later date which takes further advantage of these strict
109 * dependency requirements.
111 * @throws MWException
112 * @return PPNode_Hash_Tree
114 public function preprocessToObj( $text, $flags = 0 ) {
115 $tree = $this->cacheGetTree( $text, $flags );
116 if ( $tree !== false ) {
117 return unserialize( $tree );
120 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
122 $xmlishElements = $this->parser
->getStripList();
123 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
124 $enableOnlyinclude = false;
125 if ( $forInclusion ) {
126 $ignoredTags = [ 'includeonly', '/includeonly' ];
127 $ignoredElements = [ 'noinclude' ];
128 $xmlishElements[] = 'noinclude';
129 if ( strpos( $text, '<onlyinclude>' ) !== false
130 && strpos( $text, '</onlyinclude>' ) !== false
132 $enableOnlyinclude = true;
135 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
136 $ignoredElements = [ 'includeonly' ];
137 $xmlishElements[] = 'includeonly';
139 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
141 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
142 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
144 $stack = new PPDStack_Hash
;
146 $searchBase = "[{<\n";
147 // For fast reverse searches
148 $revText = strrev( $text );
149 $lengthText = strlen( $text );
151 // Input pointer, starts out pointing to a pseudo-newline before the start
153 // Current accumulator
154 $accum =& $stack->getAccum();
155 // True to find equals signs in arguments
157 // True to take notice of pipe characters
160 // True if $i is inside a possible heading
162 // True if there are no more greater-than (>) signs right of $i
164 // Map of tag name => true if there are no more closing tags of given type right of $i
165 $noMoreClosingTag = [];
166 // True to ignore all input up to the next <onlyinclude>
167 $findOnlyinclude = $enableOnlyinclude;
168 // Do a line-start run without outputting an LF character
169 $fakeLineStart = true;
172 // $this->memCheck();
174 if ( $findOnlyinclude ) {
175 // Ignore all input up to the next <onlyinclude>
176 $startPos = strpos( $text, '<onlyinclude>', $i );
177 if ( $startPos === false ) {
178 // Ignored section runs to the end
179 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
182 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
183 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
185 $findOnlyinclude = false;
188 if ( $fakeLineStart ) {
189 $found = 'line-start';
192 # Find next opening brace, closing brace or pipe
193 $search = $searchBase;
194 if ( $stack->top
=== false ) {
195 $currentClosing = '';
197 $currentClosing = $stack->top
->close
;
198 $search .= $currentClosing;
204 // First equals will be for the template
208 # Output literal section, advance input counter
209 $literalLength = strcspn( $text, $search, $i );
210 if ( $literalLength > 0 ) {
211 $accum->addLiteral( substr( $text, $i, $literalLength ) );
212 $i +
= $literalLength;
214 if ( $i >= $lengthText ) {
215 if ( $currentClosing == "\n" ) {
216 // Do a past-the-end run to finish off the heading
224 $curChar = $text[$i];
225 if ( $curChar == '|' ) {
227 } elseif ( $curChar == '=' ) {
229 } elseif ( $curChar == '<' ) {
231 } elseif ( $curChar == "\n" ) {
235 $found = 'line-start';
237 } elseif ( $curChar == $currentClosing ) {
239 } elseif ( isset( $this->rules
[$curChar] ) ) {
241 $rule = $this->rules
[$curChar];
243 # Some versions of PHP have a strcspn which stops on null characters
244 # Ignore and continue
251 if ( $found == 'angle' ) {
253 // Handle </onlyinclude>
254 if ( $enableOnlyinclude
255 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
257 $findOnlyinclude = true;
261 // Determine element name
262 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
263 // Element name missing or not listed
264 $accum->addLiteral( '<' );
269 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
271 // To avoid leaving blank lines, when a sequence of
272 // space-separated comments is both preceded and followed by
273 // a newline (ignoring spaces), then
274 // trim leading and trailing spaces and the trailing newline.
277 $endPos = strpos( $text, '-->', $i +
4 );
278 if ( $endPos === false ) {
279 // Unclosed comment in input, runs to end
280 $inner = substr( $text, $i );
281 $accum->addNodeWithText( 'comment', $inner );
284 // Search backwards for leading whitespace
285 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
287 // Search forwards for trailing whitespace
288 // $wsEnd will be the position of the last space (or the '>' if there's none)
289 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
291 // Keep looking forward as long as we're finding more
293 $comments = [ [ $wsStart, $wsEnd ] ];
294 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
295 $c = strpos( $text, '-->', $wsEnd +
4 );
296 if ( $c === false ) {
299 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
300 $comments[] = [ $wsEnd +
1, $c ];
304 // Eat the line if possible
305 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
306 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
307 // it's a possible beneficial b/c break.
308 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
309 && substr( $text, $wsEnd +
1, 1 ) == "\n"
311 // Remove leading whitespace from the end of the accumulator
312 // Sanity check first though
313 $wsLength = $i - $wsStart;
315 && $accum->lastNode
instanceof PPNode_Hash_Text
316 && strspn( $accum->lastNode
->value
, " \t", -$wsLength ) === $wsLength
318 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
321 // Dump all but the last comment to the accumulator
322 foreach ( $comments as $j => $com ) {
324 $endPos = $com[1] +
1;
325 if ( $j == ( count( $comments ) - 1 ) ) {
328 $inner = substr( $text, $startPos, $endPos - $startPos );
329 $accum->addNodeWithText( 'comment', $inner );
332 // Do a line-start run next time to look for headings after the comment
333 $fakeLineStart = true;
335 // No line to eat, just take the comment itself
341 $part = $stack->top
->getCurrentPart();
342 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
343 $part->visualEnd
= $wsStart;
345 // Else comments abutting, no change in visual end
346 $part->commentEnd
= $endPos;
349 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
350 $accum->addNodeWithText( 'comment', $inner );
355 $lowerName = strtolower( $name );
356 $attrStart = $i +
strlen( $name ) +
1;
359 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
360 if ( $tagEndPos === false ) {
361 // Infinite backtrack
362 // Disable tag search to prevent worst-case O(N^2) performance
364 $accum->addLiteral( '<' );
369 // Handle ignored tags
370 if ( in_array( $lowerName, $ignoredTags ) ) {
371 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
377 if ( $text[$tagEndPos - 1] == '/' ) {
379 $attrEnd = $tagEndPos - 1;
384 $attrEnd = $tagEndPos;
387 !isset( $noMoreClosingTag[$name] ) &&
388 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
389 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
391 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
392 $i = $matches[0][1] +
strlen( $matches[0][0] );
393 $close = $matches[0][0];
396 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
397 // Let it run out to the end of the text.
398 $inner = substr( $text, $tagEndPos +
1 );
402 // Don't match the tag, treat opening tag as literal and resume parsing.
404 $accum->addLiteral( substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
405 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
406 $noMoreClosingTag[$name] = true;
411 // <includeonly> and <noinclude> just become <ignore> tags
412 if ( in_array( $lowerName, $ignoredElements ) ) {
413 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
417 if ( $attrEnd <= $attrStart ) {
420 // Note that the attr element contains the whitespace between name and attribute,
421 // this is necessary for precise reconstruction during pre-save transform.
422 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
425 $extNode = new PPNode_Hash_Tree( 'ext' );
426 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
427 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
428 if ( $inner !== null ) {
429 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
431 if ( $close !== null ) {
432 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
434 $accum->addNode( $extNode );
435 } elseif ( $found == 'line-start' ) {
436 // Is this the start of a heading?
437 // Line break belongs before the heading element in any case
438 if ( $fakeLineStart ) {
439 $fakeLineStart = false;
441 $accum->addLiteral( $curChar );
445 $count = strspn( $text, '=', $i, 6 );
446 if ( $count == 1 && $findEquals ) {
447 // DWIM: This looks kind of like a name/value separator.
448 // Let's let the equals handler have it and break the potential
449 // heading. This is heuristic, but AFAICT the methods for
450 // completely correct disambiguation are very complex.
451 } elseif ( $count > 0 ) {
455 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
458 $stack->push( $piece );
459 $accum =& $stack->getAccum();
460 extract( $stack->getFlags() );
463 } elseif ( $found == 'line-end' ) {
464 $piece = $stack->top
;
465 // A heading must be open, otherwise \n wouldn't have been in the search list
466 assert( '$piece->open == "\n"' );
467 $part = $piece->getCurrentPart();
468 // Search back through the input to see if it has a proper close.
469 // Do this using the reversed string since the other solutions
470 // (end anchor, etc.) are inefficient.
471 $wsLength = strspn( $revText, " \t", $lengthText - $i );
472 $searchStart = $i - $wsLength;
473 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
474 // Comment found at line end
475 // Search for equals signs before the comment
476 $searchStart = $part->visualEnd
;
477 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
479 $count = $piece->count
;
480 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
481 if ( $equalsLength > 0 ) {
482 if ( $searchStart - $equalsLength == $piece->startPos
) {
483 // This is just a single string of equals signs on its own line
484 // Replicate the doHeadings behavior /={count}(.+)={count}/
485 // First find out how many equals signs there really are (don't stop at 6)
486 $count = $equalsLength;
490 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
493 $count = min( $equalsLength, $count );
496 // Normal match, output <h>
497 $element = new PPNode_Hash_Tree( 'possible-h' );
498 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
499 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
500 $element->lastChild
->nextSibling
= $accum->firstNode
;
501 $element->lastChild
= $accum->lastNode
;
503 // Single equals sign on its own line, count=0
507 // No match, no <h>, just pass down the inner text
512 $accum =& $stack->getAccum();
513 extract( $stack->getFlags() );
515 // Append the result to the enclosing accumulator
516 if ( $element instanceof PPNode
) {
517 $accum->addNode( $element );
519 $accum->addAccum( $element );
521 // Note that we do NOT increment the input pointer.
522 // This is because the closing linebreak could be the opening linebreak of
523 // another heading. Infinite loops are avoided because the next iteration MUST
524 // hit the heading open case above, which unconditionally increments the
526 } elseif ( $found == 'open' ) {
527 # count opening brace characters
528 $count = strspn( $text, $curChar, $i );
530 # we need to add to stack only if opening brace count is enough for one of the rules
531 if ( $count >= $rule['min'] ) {
532 # Add it to the stack
535 'close' => $rule['end'],
537 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
540 $stack->push( $piece );
541 $accum =& $stack->getAccum();
542 extract( $stack->getFlags() );
544 # Add literal brace(s)
545 $accum->addLiteral( str_repeat( $curChar, $count ) );
548 } elseif ( $found == 'close' ) {
549 $piece = $stack->top
;
550 # lets check if there are enough characters for closing brace
551 $maxCount = $piece->count
;
552 $count = strspn( $text, $curChar, $i, $maxCount );
554 # check for maximum matching characters (if there are 5 closing
555 # characters, we will probably need only 3 - depending on the rules)
556 $rule = $this->rules
[$piece->open
];
557 if ( $count > $rule['max'] ) {
558 # The specified maximum exists in the callback array, unless the caller
560 $matchingCount = $rule['max'];
562 # Count is less than the maximum
563 # Skip any gaps in the callback array to find the true largest match
564 # Need to use array_key_exists not isset because the callback can be null
565 $matchingCount = $count;
566 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
571 if ( $matchingCount <= 0 ) {
572 # No matching element found in callback array
573 # Output a literal closing brace and continue
574 $accum->addLiteral( str_repeat( $curChar, $count ) );
578 $name = $rule['names'][$matchingCount];
579 if ( $name === null ) {
580 // No element, just literal text
581 $element = $piece->breakSyntax( $matchingCount );
582 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
585 # Note: $parts is already XML, does not need to be encoded further
586 $parts = $piece->parts
;
587 $titleAccum = $parts[0]->out
;
590 $element = new PPNode_Hash_Tree( $name );
592 # The invocation is at the start of the line if lineStart is set in
593 # the stack, and all opening brackets are used up.
594 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
595 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
597 $titleNode = new PPNode_Hash_Tree( 'title' );
598 $titleNode->firstChild
= $titleAccum->firstNode
;
599 $titleNode->lastChild
= $titleAccum->lastNode
;
600 $element->addChild( $titleNode );
602 foreach ( $parts as $part ) {
603 if ( isset( $part->eqpos
) ) {
606 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
607 if ( $node === $part->eqpos
) {
613 // if ( $cacheable ) { ... }
614 throw new MWException( __METHOD__
. ': eqpos not found' );
616 if ( $node->name
!== 'equals' ) {
617 // if ( $cacheable ) { ... }
618 throw new MWException( __METHOD__
. ': eqpos is not equals' );
622 // Construct name node
623 $nameNode = new PPNode_Hash_Tree( 'name' );
624 if ( $lastNode !== false ) {
625 $lastNode->nextSibling
= false;
626 $nameNode->firstChild
= $part->out
->firstNode
;
627 $nameNode->lastChild
= $lastNode;
630 // Construct value node
631 $valueNode = new PPNode_Hash_Tree( 'value' );
632 if ( $equalsNode->nextSibling
!== false ) {
633 $valueNode->firstChild
= $equalsNode->nextSibling
;
634 $valueNode->lastChild
= $part->out
->lastNode
;
636 $partNode = new PPNode_Hash_Tree( 'part' );
637 $partNode->addChild( $nameNode );
638 $partNode->addChild( $equalsNode->firstChild
);
639 $partNode->addChild( $valueNode );
640 $element->addChild( $partNode );
642 $partNode = new PPNode_Hash_Tree( 'part' );
643 $nameNode = new PPNode_Hash_Tree( 'name' );
644 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
645 $valueNode = new PPNode_Hash_Tree( 'value' );
646 $valueNode->firstChild
= $part->out
->firstNode
;
647 $valueNode->lastChild
= $part->out
->lastNode
;
648 $partNode->addChild( $nameNode );
649 $partNode->addChild( $valueNode );
650 $element->addChild( $partNode );
655 # Advance input pointer
656 $i +
= $matchingCount;
660 $accum =& $stack->getAccum();
662 # Re-add the old stack element if it still has unmatched opening characters remaining
663 if ( $matchingCount < $piece->count
) {
664 $piece->parts
= [ new PPDPart_Hash
];
665 $piece->count
-= $matchingCount;
666 # do we still qualify for any callback with remaining count?
667 $min = $this->rules
[$piece->open
]['min'];
668 if ( $piece->count
>= $min ) {
669 $stack->push( $piece );
670 $accum =& $stack->getAccum();
672 $accum->addLiteral( str_repeat( $piece->open
, $piece->count
) );
676 extract( $stack->getFlags() );
678 # Add XML element to the enclosing accumulator
679 if ( $element instanceof PPNode
) {
680 $accum->addNode( $element );
682 $accum->addAccum( $element );
684 } elseif ( $found == 'pipe' ) {
685 $findEquals = true; // shortcut for getFlags()
687 $accum =& $stack->getAccum();
689 } elseif ( $found == 'equals' ) {
690 $findEquals = false; // shortcut for getFlags()
691 $accum->addNodeWithText( 'equals', '=' );
692 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
697 # Output any remaining unclosed brackets
698 foreach ( $stack->stack
as $piece ) {
699 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
702 # Enable top-level headings
703 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
704 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
709 $rootNode = new PPNode_Hash_Tree( 'root' );
710 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
711 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
714 $this->cacheSetTree( $text, $flags, serialize( $rootNode ) );
721 * Stack class to help Preprocessor::preprocessToObj()
724 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
725 class PPDStack_Hash
extends PPDStack
{
726 // @codingStandardsIgnoreEnd
728 public function __construct() {
729 $this->elementClass
= 'PPDStackElement_Hash';
730 parent
::__construct();
731 $this->rootAccum
= new PPDAccum_Hash
;
738 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
739 class PPDStackElement_Hash
extends PPDStackElement
{
740 // @codingStandardsIgnoreEnd
742 public function __construct( $data = [] ) {
743 $this->partClass
= 'PPDPart_Hash';
744 parent
::__construct( $data );
748 * Get the accumulator that would result if the close is not found.
750 * @param int|bool $openingCount
751 * @return PPDAccum_Hash
753 public function breakSyntax( $openingCount = false ) {
754 if ( $this->open
== "\n" ) {
755 $accum = $this->parts
[0]->out
;
757 if ( $openingCount === false ) {
758 $openingCount = $this->count
;
760 $accum = new PPDAccum_Hash
;
761 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
763 foreach ( $this->parts
as $part ) {
767 $accum->addLiteral( '|' );
769 $accum->addAccum( $part->out
);
779 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
780 class PPDPart_Hash
extends PPDPart
{
781 // @codingStandardsIgnoreEnd
783 public function __construct( $out = '' ) {
784 $accum = new PPDAccum_Hash
;
786 $accum->addLiteral( $out );
788 parent
::__construct( $accum );
795 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
796 class PPDAccum_Hash
{
797 // @codingStandardsIgnoreEnd
799 public $firstNode, $lastNode;
801 public function __construct() {
802 $this->firstNode
= $this->lastNode
= false;
806 * Append a string literal
809 public function addLiteral( $s ) {
810 if ( $this->lastNode
=== false ) {
811 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
812 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
813 $this->lastNode
->value
.= $s;
815 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
816 $this->lastNode
= $this->lastNode
->nextSibling
;
822 * @param PPNode $node
824 public function addNode( PPNode
$node ) {
825 if ( $this->lastNode
=== false ) {
826 $this->firstNode
= $this->lastNode
= $node;
828 $this->lastNode
->nextSibling
= $node;
829 $this->lastNode
= $node;
834 * Append a tree node with text contents
835 * @param string $name
836 * @param string $value
838 public function addNodeWithText( $name, $value ) {
839 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
840 $this->addNode( $node );
844 * Append a PPDAccum_Hash
845 * Takes over ownership of the nodes in the source argument. These nodes may
846 * subsequently be modified, especially nextSibling.
847 * @param PPDAccum_Hash $accum
849 public function addAccum( $accum ) {
850 if ( $accum->lastNode
=== false ) {
852 } elseif ( $this->lastNode
=== false ) {
853 $this->firstNode
= $accum->firstNode
;
854 $this->lastNode
= $accum->lastNode
;
856 $this->lastNode
->nextSibling
= $accum->firstNode
;
857 $this->lastNode
= $accum->lastNode
;
863 * An expansion frame, used as a context to expand the result of preprocessToObj()
866 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
867 class PPFrame_Hash
implements PPFrame
{
868 // @codingStandardsIgnoreEnd
878 public $preprocessor;
887 * Hashtable listing templates which are disallowed for expansion in this frame,
888 * having been encountered previously in parent frames.
890 public $loopCheckHash;
893 * Recursion depth of this frame, top = 0
894 * Note that this is NOT the same as expansion depth in expand()
898 private $volatile = false;
904 protected $childExpansionCache;
907 * Construct a new preprocessor frame.
908 * @param Preprocessor $preprocessor The parent preprocessor
910 public function __construct( $preprocessor ) {
911 $this->preprocessor
= $preprocessor;
912 $this->parser
= $preprocessor->parser
;
913 $this->title
= $this->parser
->mTitle
;
914 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
915 $this->loopCheckHash
= [];
917 $this->childExpansionCache
= [];
921 * Create a new child frame
922 * $args is optionally a multi-root PPNode or array containing the template arguments
924 * @param array|bool|PPNode_Hash_Array $args
925 * @param Title|bool $title
926 * @param int $indexOffset
927 * @throws MWException
928 * @return PPTemplateFrame_Hash
930 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
933 if ( $title === false ) {
934 $title = $this->title
;
936 if ( $args !== false ) {
937 if ( $args instanceof PPNode_Hash_Array
) {
938 $args = $args->value
;
939 } elseif ( !is_array( $args ) ) {
940 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
942 foreach ( $args as $arg ) {
943 $bits = $arg->splitArg();
944 if ( $bits['index'] !== '' ) {
945 // Numbered parameter
946 $index = $bits['index'] - $indexOffset;
947 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
948 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
949 wfEscapeWikiText( $this->title
),
950 wfEscapeWikiText( $title ),
951 wfEscapeWikiText( $index ) )->text() );
952 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
954 $numberedArgs[$index] = $bits['value'];
955 unset( $namedArgs[$index] );
958 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
959 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
960 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
961 wfEscapeWikiText( $this->title
),
962 wfEscapeWikiText( $title ),
963 wfEscapeWikiText( $name ) )->text() );
964 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
966 $namedArgs[$name] = $bits['value'];
967 unset( $numberedArgs[$name] );
971 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
975 * @throws MWException
976 * @param string|int $key
977 * @param string|PPNode $root
981 public function cachedExpand( $key, $root, $flags = 0 ) {
982 // we don't have a parent, so we don't have a cache
983 return $this->expand( $root, $flags );
987 * @throws MWException
988 * @param string|PPNode $root
992 public function expand( $root, $flags = 0 ) {
993 static $expansionDepth = 0;
994 if ( is_string( $root ) ) {
998 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
999 $this->parser
->limitationWarn( 'node-count-exceeded',
1000 $this->parser
->mPPNodeCount
,
1001 $this->parser
->mOptions
->getMaxPPNodeCount()
1003 return '<span class="error">Node-count limit exceeded</span>';
1005 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1006 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1008 $this->parser
->mOptions
->getMaxPPExpandDepth()
1010 return '<span class="error">Expansion depth limit exceeded</span>';
1013 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1014 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1017 $outStack = [ '', '' ];
1018 $iteratorStack = [ false, $root ];
1019 $indexStack = [ 0, 0 ];
1021 while ( count( $iteratorStack ) > 1 ) {
1022 $level = count( $outStack ) - 1;
1023 $iteratorNode =& $iteratorStack[$level];
1024 $out =& $outStack[$level];
1025 $index =& $indexStack[$level];
1027 if ( is_array( $iteratorNode ) ) {
1028 if ( $index >= count( $iteratorNode ) ) {
1029 // All done with this iterator
1030 $iteratorStack[$level] = false;
1031 $contextNode = false;
1033 $contextNode = $iteratorNode[$index];
1036 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1037 if ( $index >= $iteratorNode->getLength() ) {
1038 // All done with this iterator
1039 $iteratorStack[$level] = false;
1040 $contextNode = false;
1042 $contextNode = $iteratorNode->item( $index );
1046 // Copy to $contextNode and then delete from iterator stack,
1047 // because this is not an iterator but we do have to execute it once
1048 $contextNode = $iteratorStack[$level];
1049 $iteratorStack[$level] = false;
1052 $newIterator = false;
1054 if ( $contextNode === false ) {
1056 } elseif ( is_string( $contextNode ) ) {
1057 $out .= $contextNode;
1058 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
1059 $newIterator = $contextNode;
1060 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1062 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1063 $out .= $contextNode->value
;
1064 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1065 if ( $contextNode->name
== 'template' ) {
1066 # Double-brace expansion
1067 $bits = $contextNode->splitTemplate();
1068 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1069 $newIterator = $this->virtualBracketedImplode(
1075 $ret = $this->parser
->braceSubstitution( $bits, $this );
1076 if ( isset( $ret['object'] ) ) {
1077 $newIterator = $ret['object'];
1079 $out .= $ret['text'];
1082 } elseif ( $contextNode->name
== 'tplarg' ) {
1083 # Triple-brace expansion
1084 $bits = $contextNode->splitTemplate();
1085 if ( $flags & PPFrame
::NO_ARGS
) {
1086 $newIterator = $this->virtualBracketedImplode(
1092 $ret = $this->parser
->argSubstitution( $bits, $this );
1093 if ( isset( $ret['object'] ) ) {
1094 $newIterator = $ret['object'];
1096 $out .= $ret['text'];
1099 } elseif ( $contextNode->name
== 'comment' ) {
1100 # HTML-style comment
1101 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1102 # Not in RECOVER_COMMENTS mode (msgnw) though.
1103 if ( ( $this->parser
->ot
['html']
1104 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1105 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1106 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1109 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1110 # Add a strip marker in PST mode so that pstPass2() can
1111 # run some old-fashioned regexes on the result.
1112 # Not in RECOVER_COMMENTS mode (extractSections) though.
1113 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1115 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1116 $out .= $contextNode->firstChild
->value
;
1118 } elseif ( $contextNode->name
== 'ignore' ) {
1119 # Output suppression used by <includeonly> etc.
1120 # OT_WIKI will only respect <ignore> in substed templates.
1121 # The other output types respect it unless NO_IGNORE is set.
1122 # extractSections() sets NO_IGNORE and so never respects it.
1123 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1124 ||
( $flags & PPFrame
::NO_IGNORE
)
1126 $out .= $contextNode->firstChild
->value
;
1130 } elseif ( $contextNode->name
== 'ext' ) {
1132 $bits = $contextNode->splitExt() +
[ 'attr' => null, 'inner' => null, 'close' => null ];
1133 if ( $flags & PPFrame
::NO_TAGS
) {
1134 $s = '<' . $bits['name']->firstChild
->value
;
1135 if ( $bits['attr'] ) {
1136 $s .= $bits['attr']->firstChild
->value
;
1138 if ( $bits['inner'] ) {
1139 $s .= '>' . $bits['inner']->firstChild
->value
;
1140 if ( $bits['close'] ) {
1141 $s .= $bits['close']->firstChild
->value
;
1148 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1150 } elseif ( $contextNode->name
== 'h' ) {
1152 if ( $this->parser
->ot
['html'] ) {
1153 # Expand immediately and insert heading index marker
1155 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1156 $s .= $this->expand( $node, $flags );
1159 $bits = $contextNode->splitHeading();
1160 $titleText = $this->title
->getPrefixedDBkey();
1161 $this->parser
->mHeadings
[] = [ $titleText, $bits['i'] ];
1162 $serial = count( $this->parser
->mHeadings
) - 1;
1163 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1164 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1165 $this->parser
->mStripState
->addGeneral( $marker, '' );
1168 # Expand in virtual stack
1169 $newIterator = $contextNode->getChildren();
1172 # Generic recursive expansion
1173 $newIterator = $contextNode->getChildren();
1176 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1179 if ( $newIterator !== false ) {
1181 $iteratorStack[] = $newIterator;
1183 } elseif ( $iteratorStack[$level] === false ) {
1184 // Return accumulated value to parent
1185 // With tail recursion
1186 while ( $iteratorStack[$level] === false && $level > 0 ) {
1187 $outStack[$level - 1] .= $out;
1188 array_pop( $outStack );
1189 array_pop( $iteratorStack );
1190 array_pop( $indexStack );
1196 return $outStack[0];
1200 * @param string $sep
1202 * @param string|PPNode $args,...
1205 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1206 $args = array_slice( func_get_args(), 2 );
1210 foreach ( $args as $root ) {
1211 if ( $root instanceof PPNode_Hash_Array
) {
1212 $root = $root->value
;
1214 if ( !is_array( $root ) ) {
1217 foreach ( $root as $node ) {
1223 $s .= $this->expand( $node, $flags );
1230 * Implode with no flags specified
1231 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1232 * @param string $sep
1233 * @param string|PPNode $args,...
1236 public function implode( $sep /*, ... */ ) {
1237 $args = array_slice( func_get_args(), 1 );
1241 foreach ( $args as $root ) {
1242 if ( $root instanceof PPNode_Hash_Array
) {
1243 $root = $root->value
;
1245 if ( !is_array( $root ) ) {
1248 foreach ( $root as $node ) {
1254 $s .= $this->expand( $node );
1261 * Makes an object that, when expand()ed, will be the same as one obtained
1264 * @param string $sep
1265 * @param string|PPNode $args,...
1266 * @return PPNode_Hash_Array
1268 public function virtualImplode( $sep /*, ... */ ) {
1269 $args = array_slice( func_get_args(), 1 );
1273 foreach ( $args as $root ) {
1274 if ( $root instanceof PPNode_Hash_Array
) {
1275 $root = $root->value
;
1277 if ( !is_array( $root ) ) {
1280 foreach ( $root as $node ) {
1289 return new PPNode_Hash_Array( $out );
1293 * Virtual implode with brackets
1295 * @param string $start
1296 * @param string $sep
1297 * @param string $end
1298 * @param string|PPNode $args,...
1299 * @return PPNode_Hash_Array
1301 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1302 $args = array_slice( func_get_args(), 3 );
1306 foreach ( $args as $root ) {
1307 if ( $root instanceof PPNode_Hash_Array
) {
1308 $root = $root->value
;
1310 if ( !is_array( $root ) ) {
1313 foreach ( $root as $node ) {
1323 return new PPNode_Hash_Array( $out );
1326 public function __toString() {
1331 * @param bool $level
1332 * @return array|bool|string
1334 public function getPDBK( $level = false ) {
1335 if ( $level === false ) {
1336 return $this->title
->getPrefixedDBkey();
1338 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1345 public function getArguments() {
1352 public function getNumberedArguments() {
1359 public function getNamedArguments() {
1364 * Returns true if there are no arguments in this frame
1368 public function isEmpty() {
1373 * @param int|string $name
1374 * @return bool Always false in this implementation.
1376 public function getArgument( $name ) {
1381 * Returns true if the infinite loop check is OK, false if a loop is detected
1383 * @param Title $title
1387 public function loopCheck( $title ) {
1388 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1392 * Return true if the frame is a template frame
1396 public function isTemplate() {
1401 * Get a title of frame
1405 public function getTitle() {
1406 return $this->title
;
1410 * Set the volatile flag
1414 public function setVolatile( $flag = true ) {
1415 $this->volatile
= $flag;
1419 * Get the volatile flag
1423 public function isVolatile() {
1424 return $this->volatile
;
1432 public function setTTL( $ttl ) {
1433 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1443 public function getTTL() {
1449 * Expansion frame with template arguments
1452 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1453 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1454 // @codingStandardsIgnoreEnd
1456 public $numberedArgs, $namedArgs, $parent;
1457 public $numberedExpansionCache, $namedExpansionCache;
1460 * @param Preprocessor $preprocessor
1461 * @param bool|PPFrame $parent
1462 * @param array $numberedArgs
1463 * @param array $namedArgs
1464 * @param bool|Title $title
1466 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1467 $namedArgs = [], $title = false
1469 parent
::__construct( $preprocessor );
1471 $this->parent
= $parent;
1472 $this->numberedArgs
= $numberedArgs;
1473 $this->namedArgs
= $namedArgs;
1474 $this->title
= $title;
1475 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1476 $this->titleCache
= $parent->titleCache
;
1477 $this->titleCache
[] = $pdbk;
1478 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1479 if ( $pdbk !== false ) {
1480 $this->loopCheckHash
[$pdbk] = true;
1482 $this->depth
= $parent->depth +
1;
1483 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1486 public function __toString() {
1489 $args = $this->numberedArgs +
$this->namedArgs
;
1490 foreach ( $args as $name => $value ) {
1496 $s .= "\"$name\":\"" .
1497 str_replace( '"', '\\"', $value->__toString() ) . '"';
1504 * @throws MWException
1505 * @param string|int $key
1506 * @param string|PPNode $root
1510 public function cachedExpand( $key, $root, $flags = 0 ) {
1511 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1512 return $this->parent
->childExpansionCache
[$key];
1514 $retval = $this->expand( $root, $flags );
1515 if ( !$this->isVolatile() ) {
1516 $this->parent
->childExpansionCache
[$key] = $retval;
1522 * Returns true if there are no arguments in this frame
1526 public function isEmpty() {
1527 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1533 public function getArguments() {
1535 foreach ( array_merge(
1536 array_keys( $this->numberedArgs
),
1537 array_keys( $this->namedArgs
) ) as $key ) {
1538 $arguments[$key] = $this->getArgument( $key );
1546 public function getNumberedArguments() {
1548 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1549 $arguments[$key] = $this->getArgument( $key );
1557 public function getNamedArguments() {
1559 foreach ( array_keys( $this->namedArgs
) as $key ) {
1560 $arguments[$key] = $this->getArgument( $key );
1567 * @return string|bool
1569 public function getNumberedArgument( $index ) {
1570 if ( !isset( $this->numberedArgs
[$index] ) ) {
1573 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1574 # No trimming for unnamed arguments
1575 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1576 $this->numberedArgs
[$index],
1577 PPFrame
::STRIP_COMMENTS
1580 return $this->numberedExpansionCache
[$index];
1584 * @param string $name
1585 * @return string|bool
1587 public function getNamedArgument( $name ) {
1588 if ( !isset( $this->namedArgs
[$name] ) ) {
1591 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1592 # Trim named arguments post-expand, for backwards compatibility
1593 $this->namedExpansionCache
[$name] = trim(
1594 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1596 return $this->namedExpansionCache
[$name];
1600 * @param int|string $name
1601 * @return string|bool
1603 public function getArgument( $name ) {
1604 $text = $this->getNumberedArgument( $name );
1605 if ( $text === false ) {
1606 $text = $this->getNamedArgument( $name );
1612 * Return true if the frame is a template frame
1616 public function isTemplate() {
1620 public function setVolatile( $flag = true ) {
1621 parent
::setVolatile( $flag );
1622 $this->parent
->setVolatile( $flag );
1625 public function setTTL( $ttl ) {
1626 parent
::setTTL( $ttl );
1627 $this->parent
->setTTL( $ttl );
1632 * Expansion frame with custom arguments
1635 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1636 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1637 // @codingStandardsIgnoreEnd
1641 public function __construct( $preprocessor, $args ) {
1642 parent
::__construct( $preprocessor );
1643 $this->args
= $args;
1646 public function __toString() {
1649 foreach ( $this->args
as $name => $value ) {
1655 $s .= "\"$name\":\"" .
1656 str_replace( '"', '\\"', $value->__toString() ) . '"';
1665 public function isEmpty() {
1666 return !count( $this->args
);
1670 * @param int|string $index
1671 * @return string|bool
1673 public function getArgument( $index ) {
1674 if ( !isset( $this->args
[$index] ) ) {
1677 return $this->args
[$index];
1680 public function getArguments() {
1688 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1689 class PPNode_Hash_Tree
implements PPNode
{
1690 // @codingStandardsIgnoreEnd
1692 public $name, $firstChild, $lastChild, $nextSibling;
1694 public function __construct( $name ) {
1695 $this->name
= $name;
1696 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1699 public function __toString() {
1702 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1703 if ( $node instanceof PPNode_Hash_Attr
) {
1704 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1706 $inner .= $node->__toString();
1709 if ( $inner === '' ) {
1710 return "<{$this->name}$attribs/>";
1712 return "<{$this->name}$attribs>$inner</{$this->name}>";
1717 * @param string $name
1718 * @param string $text
1719 * @return PPNode_Hash_Tree
1721 public static function newWithText( $name, $text ) {
1722 $obj = new self( $name );
1723 $obj->addChild( new PPNode_Hash_Text( $text ) );
1727 public function addChild( $node ) {
1728 if ( $this->lastChild
=== false ) {
1729 $this->firstChild
= $this->lastChild
= $node;
1731 $this->lastChild
->nextSibling
= $node;
1732 $this->lastChild
= $node;
1737 * @return PPNode_Hash_Array
1739 public function getChildren() {
1741 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1742 $children[] = $child;
1744 return new PPNode_Hash_Array( $children );
1747 public function getFirstChild() {
1748 return $this->firstChild
;
1751 public function getNextSibling() {
1752 return $this->nextSibling
;
1755 public function getChildrenOfType( $name ) {
1757 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1758 if ( isset( $child->name
) && $child->name
=== $name ) {
1759 $children[] = $child;
1762 return new PPNode_Hash_Array( $children );
1768 public function getLength() {
1776 public function item( $i ) {
1783 public function getName() {
1788 * Split a "<part>" node into an associative array containing:
1789 * - name PPNode name
1790 * - index String index
1791 * - value PPNode value
1793 * @throws MWException
1796 public function splitArg() {
1798 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1799 if ( !isset( $child->name
) ) {
1802 if ( $child->name
=== 'name' ) {
1803 $bits['name'] = $child;
1804 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1805 && $child->firstChild
->name
=== 'index'
1807 $bits['index'] = $child->firstChild
->value
;
1809 } elseif ( $child->name
=== 'value' ) {
1810 $bits['value'] = $child;
1814 if ( !isset( $bits['name'] ) ) {
1815 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1817 if ( !isset( $bits['index'] ) ) {
1818 $bits['index'] = '';
1824 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1825 * All values in the resulting array are PPNodes. Inner and close are optional.
1827 * @throws MWException
1830 public function splitExt() {
1832 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1833 if ( !isset( $child->name
) ) {
1836 if ( $child->name
== 'name' ) {
1837 $bits['name'] = $child;
1838 } elseif ( $child->name
== 'attr' ) {
1839 $bits['attr'] = $child;
1840 } elseif ( $child->name
== 'inner' ) {
1841 $bits['inner'] = $child;
1842 } elseif ( $child->name
== 'close' ) {
1843 $bits['close'] = $child;
1846 if ( !isset( $bits['name'] ) ) {
1847 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1853 * Split an "<h>" node
1855 * @throws MWException
1858 public function splitHeading() {
1859 if ( $this->name
!== 'h' ) {
1860 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1863 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1864 if ( !isset( $child->name
) ) {
1867 if ( $child->name
== 'i' ) {
1868 $bits['i'] = $child->value
;
1869 } elseif ( $child->name
== 'level' ) {
1870 $bits['level'] = $child->value
;
1873 if ( !isset( $bits['i'] ) ) {
1874 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1880 * Split a "<template>" or "<tplarg>" node
1882 * @throws MWException
1885 public function splitTemplate() {
1887 $bits = [ 'lineStart' => '' ];
1888 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1889 if ( !isset( $child->name
) ) {
1892 if ( $child->name
== 'title' ) {
1893 $bits['title'] = $child;
1895 if ( $child->name
== 'part' ) {
1898 if ( $child->name
== 'lineStart' ) {
1899 $bits['lineStart'] = '1';
1902 if ( !isset( $bits['title'] ) ) {
1903 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1905 $bits['parts'] = new PPNode_Hash_Array( $parts );
1913 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1914 class PPNode_Hash_Text
implements PPNode
{
1915 // @codingStandardsIgnoreEnd
1917 public $value, $nextSibling;
1919 public function __construct( $value ) {
1920 if ( is_object( $value ) ) {
1921 throw new MWException( __CLASS__
. ' given object instead of string' );
1923 $this->value
= $value;
1926 public function __toString() {
1927 return htmlspecialchars( $this->value
);
1930 public function getNextSibling() {
1931 return $this->nextSibling
;
1934 public function getChildren() {
1938 public function getFirstChild() {
1942 public function getChildrenOfType( $name ) {
1946 public function getLength() {
1950 public function item( $i ) {
1954 public function getName() {
1958 public function splitArg() {
1959 throw new MWException( __METHOD__
. ': not supported' );
1962 public function splitExt() {
1963 throw new MWException( __METHOD__
. ': not supported' );
1966 public function splitHeading() {
1967 throw new MWException( __METHOD__
. ': not supported' );
1974 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1975 class PPNode_Hash_Array
implements PPNode
{
1976 // @codingStandardsIgnoreEnd
1978 public $value, $nextSibling;
1980 public function __construct( $value ) {
1981 $this->value
= $value;
1984 public function __toString() {
1985 return var_export( $this, true );
1988 public function getLength() {
1989 return count( $this->value
);
1992 public function item( $i ) {
1993 return $this->value
[$i];
1996 public function getName() {
2000 public function getNextSibling() {
2001 return $this->nextSibling
;
2004 public function getChildren() {
2008 public function getFirstChild() {
2012 public function getChildrenOfType( $name ) {
2016 public function splitArg() {
2017 throw new MWException( __METHOD__
. ': not supported' );
2020 public function splitExt() {
2021 throw new MWException( __METHOD__
. ': not supported' );
2024 public function splitHeading() {
2025 throw new MWException( __METHOD__
. ': not supported' );
2032 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2033 class PPNode_Hash_Attr
implements PPNode
{
2034 // @codingStandardsIgnoreEnd
2036 public $name, $value, $nextSibling;
2038 public function __construct( $name, $value ) {
2039 $this->name
= $name;
2040 $this->value
= $value;
2043 public function __toString() {
2044 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2047 public function getName() {
2051 public function getNextSibling() {
2052 return $this->nextSibling
;
2055 public function getChildren() {
2059 public function getFirstChild() {
2063 public function getChildrenOfType( $name ) {
2067 public function getLength() {
2071 public function item( $i ) {
2075 public function splitArg() {
2076 throw new MWException( __METHOD__
. ': not supported' );
2079 public function splitExt() {
2080 throw new MWException( __METHOD__
. ': not supported' );
2083 public function splitHeading() {
2084 throw new MWException( __METHOD__
. ': not supported' );