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 * @codingStandardsIgnoreStart
31 class Preprocessor_Hash
implements Preprocessor
{
32 // @codingStandardsIgnoreEnd
39 const CACHE_VERSION
= 1;
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 wfProfileIn( __METHOD__
);
118 global $wgMemc, $wgPreprocessorCacheThreshold;
120 $cacheable = $wgPreprocessorCacheThreshold !== false
121 && strlen( $text ) > $wgPreprocessorCacheThreshold;
124 wfProfileIn( __METHOD__
. '-cacheable' );
126 $cacheKey = wfMemcKey( 'preprocess-hash', md5( $text ), $flags );
127 $cacheValue = $wgMemc->get( $cacheKey );
129 $version = substr( $cacheValue, 0, 8 );
130 if ( intval( $version ) == self
::CACHE_VERSION
) {
131 $hash = unserialize( substr( $cacheValue, 8 ) );
133 wfDebugLog( "Preprocessor",
134 "Loaded preprocessor hash from memcached (key $cacheKey)" );
135 wfProfileOut( __METHOD__
. '-cacheable' );
136 wfProfileOut( __METHOD__
);
140 wfProfileIn( __METHOD__
. '-cache-miss' );
155 'names' => array( 2 => null ),
161 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
163 $xmlishElements = $this->parser
->getStripList();
164 $enableOnlyinclude = false;
165 if ( $forInclusion ) {
166 $ignoredTags = array( 'includeonly', '/includeonly' );
167 $ignoredElements = array( 'noinclude' );
168 $xmlishElements[] = 'noinclude';
169 if ( strpos( $text, '<onlyinclude>' ) !== false
170 && strpos( $text, '</onlyinclude>' ) !== false
172 $enableOnlyinclude = true;
175 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
176 $ignoredElements = array( 'includeonly' );
177 $xmlishElements[] = 'includeonly';
179 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
181 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
182 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
184 $stack = new PPDStack_Hash
;
186 $searchBase = "[{<\n";
187 // For fast reverse searches
188 $revText = strrev( $text );
189 $lengthText = strlen( $text );
191 // Input pointer, starts out pointing to a pseudo-newline before the start
193 // Current accumulator
194 $accum =& $stack->getAccum();
195 // True to find equals signs in arguments
197 // True to take notice of pipe characters
200 // True if $i is inside a possible heading
202 // True if there are no more greater-than (>) signs right of $i
204 // True to ignore all input up to the next <onlyinclude>
205 $findOnlyinclude = $enableOnlyinclude;
206 // Do a line-start run without outputting an LF character
207 $fakeLineStart = true;
212 if ( $findOnlyinclude ) {
213 // Ignore all input up to the next <onlyinclude>
214 $startPos = strpos( $text, '<onlyinclude>', $i );
215 if ( $startPos === false ) {
216 // Ignored section runs to the end
217 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
220 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
221 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
223 $findOnlyinclude = false;
226 if ( $fakeLineStart ) {
227 $found = 'line-start';
230 # Find next opening brace, closing brace or pipe
231 $search = $searchBase;
232 if ( $stack->top
=== false ) {
233 $currentClosing = '';
235 $currentClosing = $stack->top
->close
;
236 $search .= $currentClosing;
242 // First equals will be for the template
246 # Output literal section, advance input counter
247 $literalLength = strcspn( $text, $search, $i );
248 if ( $literalLength > 0 ) {
249 $accum->addLiteral( substr( $text, $i, $literalLength ) );
250 $i +
= $literalLength;
252 if ( $i >= $lengthText ) {
253 if ( $currentClosing == "\n" ) {
254 // Do a past-the-end run to finish off the heading
262 $curChar = $text[$i];
263 if ( $curChar == '|' ) {
265 } elseif ( $curChar == '=' ) {
267 } elseif ( $curChar == '<' ) {
269 } elseif ( $curChar == "\n" ) {
273 $found = 'line-start';
275 } elseif ( $curChar == $currentClosing ) {
277 } elseif ( isset( $rules[$curChar] ) ) {
279 $rule = $rules[$curChar];
281 # Some versions of PHP have a strcspn which stops on null characters
282 # Ignore and continue
289 if ( $found == 'angle' ) {
291 // Handle </onlyinclude>
292 if ( $enableOnlyinclude
293 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
295 $findOnlyinclude = true;
299 // Determine element name
300 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
301 // Element name missing or not listed
302 $accum->addLiteral( '<' );
307 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
309 // To avoid leaving blank lines, when a sequence of
310 // space-separated comments is both preceded and followed by
311 // a newline (ignoring spaces), then
312 // trim leading and trailing spaces and the trailing newline.
315 $endPos = strpos( $text, '-->', $i +
4 );
316 if ( $endPos === false ) {
317 // Unclosed comment in input, runs to end
318 $inner = substr( $text, $i );
319 $accum->addNodeWithText( 'comment', $inner );
322 // Search backwards for leading whitespace
323 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
325 // Search forwards for trailing whitespace
326 // $wsEnd will be the position of the last space (or the '>' if there's none)
327 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
329 // Keep looking forward as long as we're finding more
331 $comments = array( array( $wsStart, $wsEnd ) );
332 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
333 $c = strpos( $text, '-->', $wsEnd +
4 );
334 if ( $c === false ) {
337 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
338 $comments[] = array( $wsEnd +
1, $c );
342 // Eat the line if possible
343 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
344 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
345 // it's a possible beneficial b/c break.
346 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
347 && substr( $text, $wsEnd +
1, 1 ) == "\n"
349 // Remove leading whitespace from the end of the accumulator
350 // Sanity check first though
351 $wsLength = $i - $wsStart;
353 && $accum->lastNode
instanceof PPNode_Hash_Text
354 && strspn( $accum->lastNode
->value
, " \t", -$wsLength ) === $wsLength
356 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
359 // Dump all but the last comment to the accumulator
360 foreach ( $comments as $j => $com ) {
362 $endPos = $com[1] +
1;
363 if ( $j == ( count( $comments ) - 1 ) ) {
366 $inner = substr( $text, $startPos, $endPos - $startPos );
367 $accum->addNodeWithText( 'comment', $inner );
370 // Do a line-start run next time to look for headings after the comment
371 $fakeLineStart = true;
373 // No line to eat, just take the comment itself
379 $part = $stack->top
->getCurrentPart();
380 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
381 $part->visualEnd
= $wsStart;
383 // Else comments abutting, no change in visual end
384 $part->commentEnd
= $endPos;
387 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
388 $accum->addNodeWithText( 'comment', $inner );
393 $lowerName = strtolower( $name );
394 $attrStart = $i +
strlen( $name ) +
1;
397 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
398 if ( $tagEndPos === false ) {
399 // Infinite backtrack
400 // Disable tag search to prevent worst-case O(N^2) performance
402 $accum->addLiteral( '<' );
407 // Handle ignored tags
408 if ( in_array( $lowerName, $ignoredTags ) ) {
409 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
415 if ( $text[$tagEndPos - 1] == '/' ) {
417 $attrEnd = $tagEndPos - 1;
422 $attrEnd = $tagEndPos;
424 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
425 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
427 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
428 $i = $matches[0][1] +
strlen( $matches[0][0] );
429 $close = $matches[0][0];
431 // No end tag -- let it run out to the end of the text.
432 $inner = substr( $text, $tagEndPos +
1 );
437 // <includeonly> and <noinclude> just become <ignore> tags
438 if ( in_array( $lowerName, $ignoredElements ) ) {
439 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
443 if ( $attrEnd <= $attrStart ) {
446 // Note that the attr element contains the whitespace between name and attribute,
447 // this is necessary for precise reconstruction during pre-save transform.
448 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
451 $extNode = new PPNode_Hash_Tree( 'ext' );
452 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
453 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
454 if ( $inner !== null ) {
455 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
457 if ( $close !== null ) {
458 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
460 $accum->addNode( $extNode );
461 } elseif ( $found == 'line-start' ) {
462 // Is this the start of a heading?
463 // Line break belongs before the heading element in any case
464 if ( $fakeLineStart ) {
465 $fakeLineStart = false;
467 $accum->addLiteral( $curChar );
471 $count = strspn( $text, '=', $i, 6 );
472 if ( $count == 1 && $findEquals ) {
473 // DWIM: This looks kind of like a name/value separator.
474 // Let's let the equals handler have it and break the potential
475 // heading. This is heuristic, but AFAICT the methods for
476 // completely correct disambiguation are very complex.
477 } elseif ( $count > 0 ) {
481 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
484 $stack->push( $piece );
485 $accum =& $stack->getAccum();
486 extract( $stack->getFlags() );
489 } elseif ( $found == 'line-end' ) {
490 $piece = $stack->top
;
491 // A heading must be open, otherwise \n wouldn't have been in the search list
492 assert( '$piece->open == "\n"' );
493 $part = $piece->getCurrentPart();
494 // Search back through the input to see if it has a proper close.
495 // Do this using the reversed string since the other solutions
496 // (end anchor, etc.) are inefficient.
497 $wsLength = strspn( $revText, " \t", $lengthText - $i );
498 $searchStart = $i - $wsLength;
499 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
500 // Comment found at line end
501 // Search for equals signs before the comment
502 $searchStart = $part->visualEnd
;
503 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
505 $count = $piece->count
;
506 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
507 if ( $equalsLength > 0 ) {
508 if ( $searchStart - $equalsLength == $piece->startPos
) {
509 // This is just a single string of equals signs on its own line
510 // Replicate the doHeadings behavior /={count}(.+)={count}/
511 // First find out how many equals signs there really are (don't stop at 6)
512 $count = $equalsLength;
516 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
519 $count = min( $equalsLength, $count );
522 // Normal match, output <h>
523 $element = new PPNode_Hash_Tree( 'possible-h' );
524 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
525 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
526 $element->lastChild
->nextSibling
= $accum->firstNode
;
527 $element->lastChild
= $accum->lastNode
;
529 // Single equals sign on its own line, count=0
533 // No match, no <h>, just pass down the inner text
538 $accum =& $stack->getAccum();
539 extract( $stack->getFlags() );
541 // Append the result to the enclosing accumulator
542 if ( $element instanceof PPNode
) {
543 $accum->addNode( $element );
545 $accum->addAccum( $element );
547 // Note that we do NOT increment the input pointer.
548 // This is because the closing linebreak could be the opening linebreak of
549 // another heading. Infinite loops are avoided because the next iteration MUST
550 // hit the heading open case above, which unconditionally increments the
552 } elseif ( $found == 'open' ) {
553 # count opening brace characters
554 $count = strspn( $text, $curChar, $i );
556 # we need to add to stack only if opening brace count is enough for one of the rules
557 if ( $count >= $rule['min'] ) {
558 # Add it to the stack
561 'close' => $rule['end'],
563 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
566 $stack->push( $piece );
567 $accum =& $stack->getAccum();
568 extract( $stack->getFlags() );
570 # Add literal brace(s)
571 $accum->addLiteral( str_repeat( $curChar, $count ) );
574 } elseif ( $found == 'close' ) {
575 $piece = $stack->top
;
576 # lets check if there are enough characters for closing brace
577 $maxCount = $piece->count
;
578 $count = strspn( $text, $curChar, $i, $maxCount );
580 # check for maximum matching characters (if there are 5 closing
581 # characters, we will probably need only 3 - depending on the rules)
582 $rule = $rules[$piece->open
];
583 if ( $count > $rule['max'] ) {
584 # The specified maximum exists in the callback array, unless the caller
586 $matchingCount = $rule['max'];
588 # Count is less than the maximum
589 # Skip any gaps in the callback array to find the true largest match
590 # Need to use array_key_exists not isset because the callback can be null
591 $matchingCount = $count;
592 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
597 if ( $matchingCount <= 0 ) {
598 # No matching element found in callback array
599 # Output a literal closing brace and continue
600 $accum->addLiteral( str_repeat( $curChar, $count ) );
604 $name = $rule['names'][$matchingCount];
605 if ( $name === null ) {
606 // No element, just literal text
607 $element = $piece->breakSyntax( $matchingCount );
608 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
611 # Note: $parts is already XML, does not need to be encoded further
612 $parts = $piece->parts
;
613 $titleAccum = $parts[0]->out
;
616 $element = new PPNode_Hash_Tree( $name );
618 # The invocation is at the start of the line if lineStart is set in
619 # the stack, and all opening brackets are used up.
620 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
621 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
623 $titleNode = new PPNode_Hash_Tree( 'title' );
624 $titleNode->firstChild
= $titleAccum->firstNode
;
625 $titleNode->lastChild
= $titleAccum->lastNode
;
626 $element->addChild( $titleNode );
628 foreach ( $parts as $part ) {
629 if ( isset( $part->eqpos
) ) {
632 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
633 if ( $node === $part->eqpos
) {
640 wfProfileOut( __METHOD__
. '-cache-miss' );
641 wfProfileOut( __METHOD__
. '-cacheable' );
643 wfProfileOut( __METHOD__
);
644 throw new MWException( __METHOD__
. ': eqpos not found' );
646 if ( $node->name
!== 'equals' ) {
648 wfProfileOut( __METHOD__
. '-cache-miss' );
649 wfProfileOut( __METHOD__
. '-cacheable' );
651 wfProfileOut( __METHOD__
);
652 throw new MWException( __METHOD__
. ': eqpos is not equals' );
656 // Construct name node
657 $nameNode = new PPNode_Hash_Tree( 'name' );
658 if ( $lastNode !== false ) {
659 $lastNode->nextSibling
= false;
660 $nameNode->firstChild
= $part->out
->firstNode
;
661 $nameNode->lastChild
= $lastNode;
664 // Construct value node
665 $valueNode = new PPNode_Hash_Tree( 'value' );
666 if ( $equalsNode->nextSibling
!== false ) {
667 $valueNode->firstChild
= $equalsNode->nextSibling
;
668 $valueNode->lastChild
= $part->out
->lastNode
;
670 $partNode = new PPNode_Hash_Tree( 'part' );
671 $partNode->addChild( $nameNode );
672 $partNode->addChild( $equalsNode->firstChild
);
673 $partNode->addChild( $valueNode );
674 $element->addChild( $partNode );
676 $partNode = new PPNode_Hash_Tree( 'part' );
677 $nameNode = new PPNode_Hash_Tree( 'name' );
678 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
679 $valueNode = new PPNode_Hash_Tree( 'value' );
680 $valueNode->firstChild
= $part->out
->firstNode
;
681 $valueNode->lastChild
= $part->out
->lastNode
;
682 $partNode->addChild( $nameNode );
683 $partNode->addChild( $valueNode );
684 $element->addChild( $partNode );
689 # Advance input pointer
690 $i +
= $matchingCount;
694 $accum =& $stack->getAccum();
696 # Re-add the old stack element if it still has unmatched opening characters remaining
697 if ( $matchingCount < $piece->count
) {
698 $piece->parts
= array( new PPDPart_Hash
);
699 $piece->count
-= $matchingCount;
700 # do we still qualify for any callback with remaining count?
701 $min = $rules[$piece->open
]['min'];
702 if ( $piece->count
>= $min ) {
703 $stack->push( $piece );
704 $accum =& $stack->getAccum();
706 $accum->addLiteral( str_repeat( $piece->open
, $piece->count
) );
710 extract( $stack->getFlags() );
712 # Add XML element to the enclosing accumulator
713 if ( $element instanceof PPNode
) {
714 $accum->addNode( $element );
716 $accum->addAccum( $element );
718 } elseif ( $found == 'pipe' ) {
719 $findEquals = true; // shortcut for getFlags()
721 $accum =& $stack->getAccum();
723 } elseif ( $found == 'equals' ) {
724 $findEquals = false; // shortcut for getFlags()
725 $accum->addNodeWithText( 'equals', '=' );
726 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
731 # Output any remaining unclosed brackets
732 foreach ( $stack->stack
as $piece ) {
733 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
736 # Enable top-level headings
737 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
738 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
743 $rootNode = new PPNode_Hash_Tree( 'root' );
744 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
745 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
749 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
750 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
751 wfProfileOut( __METHOD__
. '-cache-miss' );
752 wfProfileOut( __METHOD__
. '-cacheable' );
753 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
756 wfProfileOut( __METHOD__
);
762 * Stack class to help Preprocessor::preprocessToObj()
764 * @codingStandardsIgnoreStart
766 class PPDStack_Hash
extends PPDStack
{
767 // @codingStandardsIgnoreEnd
769 public function __construct() {
770 $this->elementClass
= 'PPDStackElement_Hash';
771 parent
::__construct();
772 $this->rootAccum
= new PPDAccum_Hash
;
778 * @codingStandardsIgnoreStart
780 class PPDStackElement_Hash
extends PPDStackElement
{
781 // @codingStandardsIgnoreENd
783 public function __construct( $data = array() ) {
784 $this->partClass
= 'PPDPart_Hash';
785 parent
::__construct( $data );
789 * Get the accumulator that would result if the close is not found.
791 * @param int|bool $openingCount
792 * @return PPDAccum_Hash
794 public function breakSyntax( $openingCount = false ) {
795 if ( $this->open
== "\n" ) {
796 $accum = $this->parts
[0]->out
;
798 if ( $openingCount === false ) {
799 $openingCount = $this->count
;
801 $accum = new PPDAccum_Hash
;
802 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
804 foreach ( $this->parts
as $part ) {
808 $accum->addLiteral( '|' );
810 $accum->addAccum( $part->out
);
819 * @codingStandardsIgnoreStart
821 class PPDPart_Hash
extends PPDPart
{
822 // @codingStandardsIgnoreEnd
824 public function __construct( $out = '' ) {
825 $accum = new PPDAccum_Hash
;
827 $accum->addLiteral( $out );
829 parent
::__construct( $accum );
835 * @codingStandardsIgnoreStart
837 class PPDAccum_Hash
{
838 // @codingStandardsIgnoreEnd
840 public $firstNode, $lastNode;
842 public function __construct() {
843 $this->firstNode
= $this->lastNode
= false;
847 * Append a string literal
850 public function addLiteral( $s ) {
851 if ( $this->lastNode
=== false ) {
852 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
853 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
854 $this->lastNode
->value
.= $s;
856 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
857 $this->lastNode
= $this->lastNode
->nextSibling
;
863 * @param PPNode $node
865 public function addNode( PPNode
$node ) {
866 if ( $this->lastNode
=== false ) {
867 $this->firstNode
= $this->lastNode
= $node;
869 $this->lastNode
->nextSibling
= $node;
870 $this->lastNode
= $node;
875 * Append a tree node with text contents
876 * @param string $name
877 * @param string $value
879 public function addNodeWithText( $name, $value ) {
880 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
881 $this->addNode( $node );
885 * Append a PPDAccum_Hash
886 * Takes over ownership of the nodes in the source argument. These nodes may
887 * subsequently be modified, especially nextSibling.
888 * @param PPDAccum_Hash $accum
890 public function addAccum( $accum ) {
891 if ( $accum->lastNode
=== false ) {
893 } elseif ( $this->lastNode
=== false ) {
894 $this->firstNode
= $accum->firstNode
;
895 $this->lastNode
= $accum->lastNode
;
897 $this->lastNode
->nextSibling
= $accum->firstNode
;
898 $this->lastNode
= $accum->lastNode
;
904 * An expansion frame, used as a context to expand the result of preprocessToObj()
906 * @codingStandardsIgnoreStart
908 class PPFrame_Hash
implements PPFrame
{
909 // @codingStandardsIgnoreEnd
919 public $preprocessor;
928 * Hashtable listing templates which are disallowed for expansion in this frame,
929 * having been encountered previously in parent frames.
931 public $loopCheckHash;
934 * Recursion depth of this frame, top = 0
935 * Note that this is NOT the same as expansion depth in expand()
939 private $volatile = false;
945 protected $childExpansionCache;
948 * Construct a new preprocessor frame.
949 * @param Preprocessor $preprocessor The parent preprocessor
951 public function __construct( $preprocessor ) {
952 $this->preprocessor
= $preprocessor;
953 $this->parser
= $preprocessor->parser
;
954 $this->title
= $this->parser
->mTitle
;
955 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
956 $this->loopCheckHash
= array();
958 $this->childExpansionCache
= array();
962 * Create a new child frame
963 * $args is optionally a multi-root PPNode or array containing the template arguments
965 * @param array|bool|PPNode_Hash_Array $args
966 * @param Title|bool $title
967 * @param int $indexOffset
968 * @throws MWException
969 * @return PPTemplateFrame_Hash
971 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
972 $namedArgs = array();
973 $numberedArgs = array();
974 if ( $title === false ) {
975 $title = $this->title
;
977 if ( $args !== false ) {
978 if ( $args instanceof PPNode_Hash_Array
) {
979 $args = $args->value
;
980 } elseif ( !is_array( $args ) ) {
981 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
983 foreach ( $args as $arg ) {
984 $bits = $arg->splitArg();
985 if ( $bits['index'] !== '' ) {
986 // Numbered parameter
987 $index = $bits['index'] - $indexOffset;
988 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
989 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
991 $numberedArgs[$index] = $bits['value'];
992 unset( $namedArgs[$index] );
995 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
996 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
997 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
999 $namedArgs[$name] = $bits['value'];
1000 unset( $numberedArgs[$name] );
1004 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1008 * @throws MWException
1009 * @param string|int $key
1010 * @param string|PPNode $root
1014 public function cachedExpand( $key, $root, $flags = 0 ) {
1015 // we don't have a parent, so we don't have a cache
1016 return $this->expand( $root, $flags );
1020 * @throws MWException
1021 * @param string|PPNode $root
1025 public function expand( $root, $flags = 0 ) {
1026 static $expansionDepth = 0;
1027 if ( is_string( $root ) ) {
1031 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1032 $this->parser
->limitationWarn( 'node-count-exceeded',
1033 $this->parser
->mPPNodeCount
,
1034 $this->parser
->mOptions
->getMaxPPNodeCount()
1036 return '<span class="error">Node-count limit exceeded</span>';
1038 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1039 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1041 $this->parser
->mOptions
->getMaxPPExpandDepth()
1043 return '<span class="error">Expansion depth limit exceeded</span>';
1046 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1047 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1050 $outStack = array( '', '' );
1051 $iteratorStack = array( false, $root );
1052 $indexStack = array( 0, 0 );
1054 while ( count( $iteratorStack ) > 1 ) {
1055 $level = count( $outStack ) - 1;
1056 $iteratorNode =& $iteratorStack[$level];
1057 $out =& $outStack[$level];
1058 $index =& $indexStack[$level];
1060 if ( is_array( $iteratorNode ) ) {
1061 if ( $index >= count( $iteratorNode ) ) {
1062 // All done with this iterator
1063 $iteratorStack[$level] = false;
1064 $contextNode = false;
1066 $contextNode = $iteratorNode[$index];
1069 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
1070 if ( $index >= $iteratorNode->getLength() ) {
1071 // All done with this iterator
1072 $iteratorStack[$level] = false;
1073 $contextNode = false;
1075 $contextNode = $iteratorNode->item( $index );
1079 // Copy to $contextNode and then delete from iterator stack,
1080 // because this is not an iterator but we do have to execute it once
1081 $contextNode = $iteratorStack[$level];
1082 $iteratorStack[$level] = false;
1085 $newIterator = false;
1087 if ( $contextNode === false ) {
1089 } elseif ( is_string( $contextNode ) ) {
1090 $out .= $contextNode;
1091 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
1092 $newIterator = $contextNode;
1093 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
1095 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
1096 $out .= $contextNode->value
;
1097 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1098 if ( $contextNode->name
== 'template' ) {
1099 # Double-brace expansion
1100 $bits = $contextNode->splitTemplate();
1101 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1102 $newIterator = $this->virtualBracketedImplode(
1108 $ret = $this->parser
->braceSubstitution( $bits, $this );
1109 if ( isset( $ret['object'] ) ) {
1110 $newIterator = $ret['object'];
1112 $out .= $ret['text'];
1115 } elseif ( $contextNode->name
== 'tplarg' ) {
1116 # Triple-brace expansion
1117 $bits = $contextNode->splitTemplate();
1118 if ( $flags & PPFrame
::NO_ARGS
) {
1119 $newIterator = $this->virtualBracketedImplode(
1125 $ret = $this->parser
->argSubstitution( $bits, $this );
1126 if ( isset( $ret['object'] ) ) {
1127 $newIterator = $ret['object'];
1129 $out .= $ret['text'];
1132 } elseif ( $contextNode->name
== 'comment' ) {
1133 # HTML-style comment
1134 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1135 if ( $this->parser
->ot
['html']
1136 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1137 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1140 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1141 # Add a strip marker in PST mode so that pstPass2() can
1142 # run some old-fashioned regexes on the result.
1143 # Not in RECOVER_COMMENTS mode (extractSections) though.
1144 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1146 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1147 $out .= $contextNode->firstChild
->value
;
1149 } elseif ( $contextNode->name
== 'ignore' ) {
1150 # Output suppression used by <includeonly> etc.
1151 # OT_WIKI will only respect <ignore> in substed templates.
1152 # The other output types respect it unless NO_IGNORE is set.
1153 # extractSections() sets NO_IGNORE and so never respects it.
1154 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1155 ||
( $flags & PPFrame
::NO_IGNORE
)
1157 $out .= $contextNode->firstChild
->value
;
1161 } elseif ( $contextNode->name
== 'ext' ) {
1163 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1164 if ( $flags & PPFrame
::NO_TAGS
) {
1165 $s = '<' . $bits['name']->firstChild
->value
;
1166 if ( $bits['attr'] ) {
1167 $s .= $bits['attr']->firstChild
->value
;
1169 if ( $bits['inner'] ) {
1170 $s .= '>' . $bits['inner']->firstChild
->value
;
1171 if ( $bits['close'] ) {
1172 $s .= $bits['close']->firstChild
->value
;
1179 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1181 } elseif ( $contextNode->name
== 'h' ) {
1183 if ( $this->parser
->ot
['html'] ) {
1184 # Expand immediately and insert heading index marker
1186 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1187 $s .= $this->expand( $node, $flags );
1190 $bits = $contextNode->splitHeading();
1191 $titleText = $this->title
->getPrefixedDBkey();
1192 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1193 $serial = count( $this->parser
->mHeadings
) - 1;
1194 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1195 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1196 $this->parser
->mStripState
->addGeneral( $marker, '' );
1199 # Expand in virtual stack
1200 $newIterator = $contextNode->getChildren();
1203 # Generic recursive expansion
1204 $newIterator = $contextNode->getChildren();
1207 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1210 if ( $newIterator !== false ) {
1212 $iteratorStack[] = $newIterator;
1214 } elseif ( $iteratorStack[$level] === false ) {
1215 // Return accumulated value to parent
1216 // With tail recursion
1217 while ( $iteratorStack[$level] === false && $level > 0 ) {
1218 $outStack[$level - 1] .= $out;
1219 array_pop( $outStack );
1220 array_pop( $iteratorStack );
1221 array_pop( $indexStack );
1227 return $outStack[0];
1231 * @param string $sep
1233 * @param string|PPNode $args,...
1236 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1237 $args = array_slice( func_get_args(), 2 );
1241 foreach ( $args as $root ) {
1242 if ( $root instanceof PPNode_Hash_Array
) {
1243 $root = $root->value
;
1245 if ( !is_array( $root ) ) {
1246 $root = array( $root );
1248 foreach ( $root as $node ) {
1254 $s .= $this->expand( $node, $flags );
1261 * Implode with no flags specified
1262 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1263 * @param string $sep
1264 * @param string|PPNode $args,...
1267 public function implode( $sep /*, ... */ ) {
1268 $args = array_slice( func_get_args(), 1 );
1272 foreach ( $args as $root ) {
1273 if ( $root instanceof PPNode_Hash_Array
) {
1274 $root = $root->value
;
1276 if ( !is_array( $root ) ) {
1277 $root = array( $root );
1279 foreach ( $root as $node ) {
1285 $s .= $this->expand( $node );
1292 * Makes an object that, when expand()ed, will be the same as one obtained
1295 * @param string $sep
1296 * @param string|PPNode $args,...
1297 * @return PPNode_Hash_Array
1299 public function virtualImplode( $sep /*, ... */ ) {
1300 $args = array_slice( func_get_args(), 1 );
1304 foreach ( $args as $root ) {
1305 if ( $root instanceof PPNode_Hash_Array
) {
1306 $root = $root->value
;
1308 if ( !is_array( $root ) ) {
1309 $root = array( $root );
1311 foreach ( $root as $node ) {
1320 return new PPNode_Hash_Array( $out );
1324 * Virtual implode with brackets
1326 * @param string $start
1327 * @param string $sep
1328 * @param string $end
1329 * @param string|PPNode $args,...
1330 * @return PPNode_Hash_Array
1332 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1333 $args = array_slice( func_get_args(), 3 );
1334 $out = array( $start );
1337 foreach ( $args as $root ) {
1338 if ( $root instanceof PPNode_Hash_Array
) {
1339 $root = $root->value
;
1341 if ( !is_array( $root ) ) {
1342 $root = array( $root );
1344 foreach ( $root as $node ) {
1354 return new PPNode_Hash_Array( $out );
1357 public function __toString() {
1362 * @param bool $level
1363 * @return array|bool|string
1365 public function getPDBK( $level = false ) {
1366 if ( $level === false ) {
1367 return $this->title
->getPrefixedDBkey();
1369 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1376 public function getArguments() {
1383 public function getNumberedArguments() {
1390 public function getNamedArguments() {
1395 * Returns true if there are no arguments in this frame
1399 public function isEmpty() {
1404 * @param string $name
1407 public function getArgument( $name ) {
1412 * Returns true if the infinite loop check is OK, false if a loop is detected
1414 * @param Title $title
1418 public function loopCheck( $title ) {
1419 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1423 * Return true if the frame is a template frame
1427 public function isTemplate() {
1432 * Get a title of frame
1436 public function getTitle() {
1437 return $this->title
;
1441 * Set the volatile flag
1445 public function setVolatile( $flag = true ) {
1446 $this->volatile
= $flag;
1450 * Get the volatile flag
1454 public function isVolatile() {
1455 return $this->volatile
;
1463 public function setTTL( $ttl ) {
1464 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1474 public function getTTL() {
1480 * Expansion frame with template arguments
1482 * @codingStandardsIgnoreStart
1484 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1485 // @codingStandardsIgnoreEnd
1487 public $numberedArgs, $namedArgs, $parent;
1488 public $numberedExpansionCache, $namedExpansionCache;
1491 * @param Preprocessor $preprocessor
1492 * @param bool|PPFrame $parent
1493 * @param array $numberedArgs
1494 * @param array $namedArgs
1495 * @param bool|Title $title
1497 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1498 $namedArgs = array(), $title = false
1500 parent
::__construct( $preprocessor );
1502 $this->parent
= $parent;
1503 $this->numberedArgs
= $numberedArgs;
1504 $this->namedArgs
= $namedArgs;
1505 $this->title
= $title;
1506 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1507 $this->titleCache
= $parent->titleCache
;
1508 $this->titleCache
[] = $pdbk;
1509 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1510 if ( $pdbk !== false ) {
1511 $this->loopCheckHash
[$pdbk] = true;
1513 $this->depth
= $parent->depth +
1;
1514 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1517 public function __toString() {
1520 $args = $this->numberedArgs +
$this->namedArgs
;
1521 foreach ( $args as $name => $value ) {
1527 $s .= "\"$name\":\"" .
1528 str_replace( '"', '\\"', $value->__toString() ) . '"';
1535 * @throws MWException
1536 * @param string|int $key
1537 * @param string|PPNode $root
1541 public function cachedExpand( $key, $root, $flags = 0 ) {
1542 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1543 return $this->parent
->childExpansionCache
[$key];
1545 $retval = $this->expand( $root, $flags );
1546 if ( !$this->isVolatile() ) {
1547 $this->parent
->childExpansionCache
[$key] = $retval;
1553 * Returns true if there are no arguments in this frame
1557 public function isEmpty() {
1558 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1564 public function getArguments() {
1565 $arguments = array();
1566 foreach ( array_merge(
1567 array_keys( $this->numberedArgs
),
1568 array_keys( $this->namedArgs
) ) as $key ) {
1569 $arguments[$key] = $this->getArgument( $key );
1577 public function getNumberedArguments() {
1578 $arguments = array();
1579 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1580 $arguments[$key] = $this->getArgument( $key );
1588 public function getNamedArguments() {
1589 $arguments = array();
1590 foreach ( array_keys( $this->namedArgs
) as $key ) {
1591 $arguments[$key] = $this->getArgument( $key );
1598 * @return array|bool
1600 public function getNumberedArgument( $index ) {
1601 if ( !isset( $this->numberedArgs
[$index] ) ) {
1604 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1605 # No trimming for unnamed arguments
1606 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1607 $this->numberedArgs
[$index],
1608 PPFrame
::STRIP_COMMENTS
1611 return $this->numberedExpansionCache
[$index];
1615 * @param string $name
1618 public function getNamedArgument( $name ) {
1619 if ( !isset( $this->namedArgs
[$name] ) ) {
1622 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1623 # Trim named arguments post-expand, for backwards compatibility
1624 $this->namedExpansionCache
[$name] = trim(
1625 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1627 return $this->namedExpansionCache
[$name];
1631 * @param string $name
1632 * @return array|bool
1634 public function getArgument( $name ) {
1635 $text = $this->getNumberedArgument( $name );
1636 if ( $text === false ) {
1637 $text = $this->getNamedArgument( $name );
1643 * Return true if the frame is a template frame
1647 public function isTemplate() {
1651 public function setVolatile( $flag = true ) {
1652 parent
::setVolatile( $flag );
1653 $this->parent
->setVolatile( $flag );
1656 public function setTTL( $ttl ) {
1657 parent
::setTTL( $ttl );
1658 $this->parent
->setTTL( $ttl );
1663 * Expansion frame with custom arguments
1665 * @codingStandardsIgnoreStart
1667 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1668 // @codingStandardsIgnoreEnd
1672 public function __construct( $preprocessor, $args ) {
1673 parent
::__construct( $preprocessor );
1674 $this->args
= $args;
1677 public function __toString() {
1680 foreach ( $this->args
as $name => $value ) {
1686 $s .= "\"$name\":\"" .
1687 str_replace( '"', '\\"', $value->__toString() ) . '"';
1696 public function isEmpty() {
1697 return !count( $this->args
);
1704 public function getArgument( $index ) {
1705 if ( !isset( $this->args
[$index] ) ) {
1708 return $this->args
[$index];
1711 public function getArguments() {
1718 * @codingStandardsIgnoreStart
1720 class PPNode_Hash_Tree
implements PPNode
{
1721 // @codingStandardsIgnoreEnd
1723 public $name, $firstChild, $lastChild, $nextSibling;
1725 public function __construct( $name ) {
1726 $this->name
= $name;
1727 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1730 public function __toString() {
1733 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1734 if ( $node instanceof PPNode_Hash_Attr
) {
1735 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1737 $inner .= $node->__toString();
1740 if ( $inner === '' ) {
1741 return "<{$this->name}$attribs/>";
1743 return "<{$this->name}$attribs>$inner</{$this->name}>";
1748 * @param string $name
1749 * @param string $text
1750 * @return PPNode_Hash_Tree
1752 public static function newWithText( $name, $text ) {
1753 $obj = new self( $name );
1754 $obj->addChild( new PPNode_Hash_Text( $text ) );
1758 public function addChild( $node ) {
1759 if ( $this->lastChild
=== false ) {
1760 $this->firstChild
= $this->lastChild
= $node;
1762 $this->lastChild
->nextSibling
= $node;
1763 $this->lastChild
= $node;
1768 * @return PPNode_Hash_Array
1770 public function getChildren() {
1771 $children = array();
1772 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1773 $children[] = $child;
1775 return new PPNode_Hash_Array( $children );
1778 public function getFirstChild() {
1779 return $this->firstChild
;
1782 public function getNextSibling() {
1783 return $this->nextSibling
;
1786 public function getChildrenOfType( $name ) {
1787 $children = array();
1788 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1789 if ( isset( $child->name
) && $child->name
=== $name ) {
1790 $children[] = $child;
1799 public function getLength() {
1807 public function item( $i ) {
1814 public function getName() {
1819 * Split a "<part>" node into an associative array containing:
1820 * - name PPNode name
1821 * - index String index
1822 * - value PPNode value
1824 * @throws MWException
1827 public function splitArg() {
1829 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1830 if ( !isset( $child->name
) ) {
1833 if ( $child->name
=== 'name' ) {
1834 $bits['name'] = $child;
1835 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1836 && $child->firstChild
->name
=== 'index'
1838 $bits['index'] = $child->firstChild
->value
;
1840 } elseif ( $child->name
=== 'value' ) {
1841 $bits['value'] = $child;
1845 if ( !isset( $bits['name'] ) ) {
1846 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1848 if ( !isset( $bits['index'] ) ) {
1849 $bits['index'] = '';
1855 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1856 * All values in the resulting array are PPNodes. Inner and close are optional.
1858 * @throws MWException
1861 public function splitExt() {
1863 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1864 if ( !isset( $child->name
) ) {
1867 if ( $child->name
== 'name' ) {
1868 $bits['name'] = $child;
1869 } elseif ( $child->name
== 'attr' ) {
1870 $bits['attr'] = $child;
1871 } elseif ( $child->name
== 'inner' ) {
1872 $bits['inner'] = $child;
1873 } elseif ( $child->name
== 'close' ) {
1874 $bits['close'] = $child;
1877 if ( !isset( $bits['name'] ) ) {
1878 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1884 * Split an "<h>" node
1886 * @throws MWException
1889 public function splitHeading() {
1890 if ( $this->name
!== 'h' ) {
1891 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1894 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1895 if ( !isset( $child->name
) ) {
1898 if ( $child->name
== 'i' ) {
1899 $bits['i'] = $child->value
;
1900 } elseif ( $child->name
== 'level' ) {
1901 $bits['level'] = $child->value
;
1904 if ( !isset( $bits['i'] ) ) {
1905 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1911 * Split a "<template>" or "<tplarg>" node
1913 * @throws MWException
1916 public function splitTemplate() {
1918 $bits = array( 'lineStart' => '' );
1919 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1920 if ( !isset( $child->name
) ) {
1923 if ( $child->name
== 'title' ) {
1924 $bits['title'] = $child;
1926 if ( $child->name
== 'part' ) {
1929 if ( $child->name
== 'lineStart' ) {
1930 $bits['lineStart'] = '1';
1933 if ( !isset( $bits['title'] ) ) {
1934 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1936 $bits['parts'] = new PPNode_Hash_Array( $parts );
1943 * @codingStandardsIgnoreStart
1945 class PPNode_Hash_Text
implements PPNode
{
1946 // @codingStandardsIgnoreEnd
1948 public $value, $nextSibling;
1950 public function __construct( $value ) {
1951 if ( is_object( $value ) ) {
1952 throw new MWException( __CLASS__
. ' given object instead of string' );
1954 $this->value
= $value;
1957 public function __toString() {
1958 return htmlspecialchars( $this->value
);
1961 public function getNextSibling() {
1962 return $this->nextSibling
;
1965 public function getChildren() {
1969 public function getFirstChild() {
1973 public function getChildrenOfType( $name ) {
1977 public function getLength() {
1981 public function item( $i ) {
1985 public function getName() {
1989 public function splitArg() {
1990 throw new MWException( __METHOD__
. ': not supported' );
1993 public function splitExt() {
1994 throw new MWException( __METHOD__
. ': not supported' );
1997 public function splitHeading() {
1998 throw new MWException( __METHOD__
. ': not supported' );
2004 * @codingStandardsIgnoreStart
2006 class PPNode_Hash_Array
implements PPNode
{
2007 // @codingStandardsIgnoreEnd
2009 public $value, $nextSibling;
2011 public function __construct( $value ) {
2012 $this->value
= $value;
2015 public function __toString() {
2016 return var_export( $this, true );
2019 public function getLength() {
2020 return count( $this->value
);
2023 public function item( $i ) {
2024 return $this->value
[$i];
2027 public function getName() {
2031 public function getNextSibling() {
2032 return $this->nextSibling
;
2035 public function getChildren() {
2039 public function getFirstChild() {
2043 public function getChildrenOfType( $name ) {
2047 public function splitArg() {
2048 throw new MWException( __METHOD__
. ': not supported' );
2051 public function splitExt() {
2052 throw new MWException( __METHOD__
. ': not supported' );
2055 public function splitHeading() {
2056 throw new MWException( __METHOD__
. ': not supported' );
2062 * @codingStandardsIgnoreStart
2064 class PPNode_Hash_Attr
implements PPNode
{
2065 // @codingStandardsIgnoreEnd
2067 public $name, $value, $nextSibling;
2069 public function __construct( $name, $value ) {
2070 $this->name
= $name;
2071 $this->value
= $value;
2074 public function __toString() {
2075 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
2078 public function getName() {
2082 public function getNextSibling() {
2083 return $this->nextSibling
;
2086 public function getChildren() {
2090 public function getFirstChild() {
2094 public function getChildrenOfType( $name ) {
2098 public function getLength() {
2102 public function item( $i ) {
2106 public function splitArg() {
2107 throw new MWException( __METHOD__
. ': not supported' );
2110 public function splitExt() {
2111 throw new MWException( __METHOD__
. ': not supported' );
2114 public function splitHeading() {
2115 throw new MWException( __METHOD__
. ': not supported' );