4 * Differences from DOM schema:
5 * * attribute nodes are children
6 * * <h> nodes that aren't at the top are replaced with <possible-h>
9 class Preprocessor_Hash
implements Preprocessor
{
12 function __construct( $parser ) {
13 $this->parser
= $parser;
17 return new PPFrame_Hash( $this );
21 * Preprocess some wikitext and return the document tree.
22 * This is the ghost of Parser::replace_variables().
24 * @param string $text The text to parse
25 * @param integer flags Bitwise combination of:
26 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
27 * included. Default is to assume a direct page view.
29 * The generated DOM tree must depend only on the input text and the flags.
30 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
32 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
33 * change in the DOM tree for a given text, must be passed through the section identifier
34 * in the section edit link and thus back to extractSections().
36 * The output of this function is currently only cached in process memory, but a persistent
37 * cache may be implemented at a later date which takes further advantage of these strict
38 * dependency requirements.
42 function preprocessToObj( $text, $flags = 0 ) {
43 wfDebug( __METHOD__
."\n" . $text . "\n" );
44 wfProfileIn( __METHOD__
);
58 'names' => array( 2 => null ),
64 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
66 $xmlishElements = $this->parser
->getStripList();
67 $enableOnlyinclude = false;
68 if ( $forInclusion ) {
69 $ignoredTags = array( 'includeonly', '/includeonly' );
70 $ignoredElements = array( 'noinclude' );
71 $xmlishElements[] = 'noinclude';
72 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
73 $enableOnlyinclude = true;
76 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
77 $ignoredElements = array( 'includeonly' );
78 $xmlishElements[] = 'includeonly';
80 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
82 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
83 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
85 $stack = new PPDStack_Hash
;
87 $searchBase = "[{<\n";
88 $revText = strrev( $text ); // For fast reverse searches
90 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
91 $accum =& $stack->getAccum(); # Current accumulator
92 $findEquals = false; # True to find equals signs in arguments
93 $findPipe = false; # True to take notice of pipe characters
95 $inHeading = false; # True if $i is inside a possible heading
96 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
97 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
98 $fakeLineStart = true; # Do a line-start run without outputting an LF character
103 if ( $findOnlyinclude ) {
104 // Ignore all input up to the next <onlyinclude>
105 $startPos = strpos( $text, '<onlyinclude>', $i );
106 if ( $startPos === false ) {
107 // Ignored section runs to the end
108 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
111 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
112 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
114 $findOnlyinclude = false;
117 if ( $fakeLineStart ) {
118 $found = 'line-start';
121 # Find next opening brace, closing brace or pipe
122 $search = $searchBase;
123 if ( $stack->top
=== false ) {
124 $currentClosing = '';
126 $currentClosing = $stack->top
->close
;
127 $search .= $currentClosing;
133 // First equals will be for the template
137 # Output literal section, advance input counter
138 $literalLength = strcspn( $text, $search, $i );
139 if ( $literalLength > 0 ) {
140 $accum->addLiteral( substr( $text, $i, $literalLength ) );
141 $i +
= $literalLength;
143 if ( $i >= strlen( $text ) ) {
144 if ( $currentClosing == "\n" ) {
145 // Do a past-the-end run to finish off the heading
153 $curChar = $text[$i];
154 if ( $curChar == '|' ) {
156 } elseif ( $curChar == '=' ) {
158 } elseif ( $curChar == '<' ) {
160 } elseif ( $curChar == "\n" ) {
164 $found = 'line-start';
166 } elseif ( $curChar == $currentClosing ) {
168 } elseif ( isset( $rules[$curChar] ) ) {
170 $rule = $rules[$curChar];
172 # Some versions of PHP have a strcspn which stops on null characters
173 # Ignore and continue
180 if ( $found == 'angle' ) {
182 // Handle </onlyinclude>
183 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
184 $findOnlyinclude = true;
188 // Determine element name
189 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
190 // Element name missing or not listed
191 $accum->addLiteral( '<' );
196 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
197 // To avoid leaving blank lines, when a comment is both preceded
198 // and followed by a newline (ignoring spaces), trim leading and
199 // trailing spaces and one of the newlines.
202 $endPos = strpos( $text, '-->', $i +
4 );
203 if ( $endPos === false ) {
204 // Unclosed comment in input, runs to end
205 $inner = substr( $text, $i );
206 $accum->addNodeWithText( 'comment', $inner );
207 $i = strlen( $text );
209 // Search backwards for leading whitespace
210 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
211 // Search forwards for trailing whitespace
212 // $wsEnd will be the position of the last space
213 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
214 // Eat the line if possible
215 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
216 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
217 // it's a possible beneficial b/c break.
218 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
219 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
221 $startPos = $wsStart;
222 $endPos = $wsEnd +
1;
223 // Remove leading whitespace from the end of the accumulator
224 // Sanity check first though
225 $wsLength = $i - $wsStart;
227 && $accum->lastNode
instanceof PPNode_Hash_Text
228 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
230 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
232 // Do a line-start run next time to look for headings after the comment
233 $fakeLineStart = true;
235 // No line to eat, just take the comment itself
241 $part = $stack->top
->getCurrentPart();
242 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
243 // Comments abutting, no change in visual end
244 $part->commentEnd
= $wsEnd;
246 $part->visualEnd
= $wsStart;
247 $part->commentEnd
= $endPos;
251 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
252 $accum->addNodeWithText( 'comment', $inner );
257 $attrStart = $i +
strlen( $name ) +
1;
260 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
261 if ( $tagEndPos === false ) {
262 // Infinite backtrack
263 // Disable tag search to prevent worst-case O(N^2) performance
265 $accum->addLiteral( '<' );
270 // Handle ignored tags
271 if ( in_array( $name, $ignoredTags ) ) {
272 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
278 if ( $text[$tagEndPos-1] == '/' ) {
280 $attrEnd = $tagEndPos - 1;
285 $attrEnd = $tagEndPos;
287 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
288 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
289 $i = $matches[0][1] +
strlen( $matches[0][0] );
290 $close = $matches[0][0];
292 // No end tag -- let it run out to the end of the text.
293 $inner = substr( $text, $tagEndPos +
1 );
294 $i = strlen( $text );
298 // <includeonly> and <noinclude> just become <ignore> tags
299 if ( in_array( $name, $ignoredElements ) ) {
300 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
304 if ( $attrEnd <= $attrStart ) {
307 // Note that the attr element contains the whitespace between name and attribute,
308 // this is necessary for precise reconstruction during pre-save transform.
309 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
312 $extNode = new PPNode_Hash_Tree( 'ext' );
313 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
314 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
315 if ( $inner !== null ) {
316 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
318 if ( $close !== null ) {
319 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
321 $accum->addNode( $extNode );
324 elseif ( $found == 'line-start' ) {
325 // Is this the start of a heading?
326 // Line break belongs before the heading element in any case
327 if ( $fakeLineStart ) {
328 $fakeLineStart = false;
330 $accum->addLiteral( $curChar );
334 $count = strspn( $text, '=', $i, 6 );
335 if ( $count == 1 && $findEquals ) {
336 // DWIM: This looks kind of like a name/value separator
337 // Let's let the equals handler have it and break the potential heading
338 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
339 } elseif ( $count > 0 ) {
343 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
346 $stack->push( $piece );
347 $accum =& $stack->getAccum();
348 extract( $stack->getFlags() );
353 elseif ( $found == 'line-end' ) {
354 $piece = $stack->top
;
355 // A heading must be open, otherwise \n wouldn't have been in the search list
356 assert( $piece->open
== "\n" );
357 $part = $piece->getCurrentPart();
358 // Search back through the input to see if it has a proper close
359 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
360 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
361 $searchStart = $i - $wsLength;
362 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
363 // Comment found at line end
364 // Search for equals signs before the comment
365 $searchStart = $part->visualEnd
;
366 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
368 $count = $piece->count
;
369 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
370 if ( $equalsLength > 0 ) {
371 if ( $i - $equalsLength == $piece->startPos
) {
372 // This is just a single string of equals signs on its own line
373 // Replicate the doHeadings behaviour /={count}(.+)={count}/
374 // First find out how many equals signs there really are (don't stop at 6)
375 $count = $equalsLength;
379 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
382 $count = min( $equalsLength, $count );
385 // Normal match, output <h>
386 $element = new PPNode_Hash_Tree( 'possible-h' );
387 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
388 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
389 $element->lastChild
->nextSibling
= $accum->firstNode
;
390 $element->lastChild
= $accum->lastNode
;
392 // Single equals sign on its own line, count=0
396 // No match, no <h>, just pass down the inner text
401 $accum =& $stack->getAccum();
402 extract( $stack->getFlags() );
404 // Append the result to the enclosing accumulator
405 if ( $element instanceof PPNode
) {
406 $accum->addNode( $element );
408 $accum->addAccum( $element );
410 // Note that we do NOT increment the input pointer.
411 // This is because the closing linebreak could be the opening linebreak of
412 // another heading. Infinite loops are avoided because the next iteration MUST
413 // hit the heading open case above, which unconditionally increments the
417 elseif ( $found == 'open' ) {
418 # count opening brace characters
419 $count = strspn( $text, $curChar, $i );
421 # we need to add to stack only if opening brace count is enough for one of the rules
422 if ( $count >= $rule['min'] ) {
423 # Add it to the stack
426 'close' => $rule['end'],
428 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
431 $stack->push( $piece );
432 $accum =& $stack->getAccum();
433 extract( $stack->getFlags() );
435 # Add literal brace(s)
436 $accum->addLiteral( str_repeat( $curChar, $count ) );
441 elseif ( $found == 'close' ) {
442 $piece = $stack->top
;
443 # lets check if there are enough characters for closing brace
444 $maxCount = $piece->count
;
445 $count = strspn( $text, $curChar, $i, $maxCount );
447 # check for maximum matching characters (if there are 5 closing
448 # characters, we will probably need only 3 - depending on the rules)
450 $rule = $rules[$piece->open
];
451 if ( $count > $rule['max'] ) {
452 # The specified maximum exists in the callback array, unless the caller
454 $matchingCount = $rule['max'];
456 # Count is less than the maximum
457 # Skip any gaps in the callback array to find the true largest match
458 # Need to use array_key_exists not isset because the callback can be null
459 $matchingCount = $count;
460 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
465 if ($matchingCount <= 0) {
466 # No matching element found in callback array
467 # Output a literal closing brace and continue
468 $accum->addLiteral( str_repeat( $curChar, $count ) );
472 $name = $rule['names'][$matchingCount];
473 if ( $name === null ) {
474 // No element, just literal text
475 $element = $piece->breakSyntax( $matchingCount );
476 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
479 # Note: $parts is already XML, does not need to be encoded further
480 $parts = $piece->parts
;
481 $titleAccum = $parts[0]->out
;
484 $element = new PPNode_Hash_Tree( $name );
486 # The invocation is at the start of the line if lineStart is set in
487 # the stack, and all opening brackets are used up.
488 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
489 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
491 $titleNode = new PPNode_Hash_Tree( 'title' );
492 $titleNode->firstChild
= $titleAccum->firstNode
;
493 $titleNode->lastChild
= $titleAccum->lastNode
;
494 $element->addChild( $titleNode );
496 foreach ( $parts as $partIndex => $part ) {
497 if ( isset( $part->eqpos
) ) {
500 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
501 if ( $node === $part->eqpos
) {
507 throw new MWException( __METHOD__
. ': eqpos not found' );
509 if ( $node->name
!== 'equals' ) {
510 throw new MWException( __METHOD__
.': eqpos is not equals' );
514 // Construct name node
515 $nameNode = new PPNode_Hash_Tree( 'name' );
516 if ( $lastNode !== false ) {
517 $lastNode->nextSibling
= false;
518 $nameNode->firstChild
= $part->out
->firstNode
;
519 $nameNode->lastChild
= $lastNode;
522 // Construct value node
523 $valueNode = new PPNode_Hash_Tree( 'value' );
524 if ( $equalsNode->nextSibling
!== false ) {
525 $valueNode->firstChild
= $equalsNode->nextSibling
;
526 $valueNode->lastChild
= $part->out
->lastNode
;
528 $partNode = new PPNode_Hash_Tree( 'part' );
529 $partNode->addChild( $nameNode );
530 $partNode->addChild( $equalsNode->firstChild
);
531 $partNode->addChild( $valueNode );
532 $element->addChild( $partNode );
534 $partNode = new PPNode_Hash_Tree( 'part' );
535 $nameNode = new PPNode_Hash_Tree( 'name' );
536 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
537 $valueNode = new PPNode_Hash_Tree( 'value' );
538 $valueNode->firstChild
= $part->out
->firstNode
;
539 $valueNode->lastChild
= $part->out
->lastNode
;
540 $partNode->addChild( $nameNode );
541 $partNode->addChild( $valueNode );
542 $element->addChild( $partNode );
547 # Advance input pointer
548 $i +
= $matchingCount;
552 $accum =& $stack->getAccum();
554 # Re-add the old stack element if it still has unmatched opening characters remaining
555 if ($matchingCount < $piece->count
) {
556 $piece->parts
= array( new PPDPart_Hash
);
557 $piece->count
-= $matchingCount;
558 # do we still qualify for any callback with remaining count?
559 $names = $rules[$piece->open
]['names'];
561 $enclosingAccum =& $accum;
562 while ( $piece->count
) {
563 if ( array_key_exists( $piece->count
, $names ) ) {
564 $stack->push( $piece );
565 $accum =& $stack->getAccum();
571 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
574 extract( $stack->getFlags() );
576 # Add XML element to the enclosing accumulator
577 if ( $element instanceof PPNode
) {
578 $accum->addNode( $element );
580 $accum->addAccum( $element );
584 elseif ( $found == 'pipe' ) {
585 $findEquals = true; // shortcut for getFlags()
587 $accum =& $stack->getAccum();
591 elseif ( $found == 'equals' ) {
592 $findEquals = false; // shortcut for getFlags()
593 $accum->addNodeWithText( 'equals', '=' );
594 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
599 # Output any remaining unclosed brackets
600 foreach ( $stack->stack
as $piece ) {
601 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
604 # Enable top-level headings
605 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
606 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
611 $rootNode = new PPNode_Hash_Tree( 'root' );
612 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
613 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
614 wfProfileOut( __METHOD__
);
620 * Stack class to help Preprocessor::preprocessToObj()
622 class PPDStack_Hash
extends PPDStack
{
623 function __construct() {
624 $this->elementClass
= 'PPDStackElement_Hash';
625 parent
::__construct();
626 $this->rootAccum
= new PPDAccum_Hash
;
630 class PPDStackElement_Hash
extends PPDStackElement
{
631 function __construct( $data = array() ) {
632 $this->partClass
= 'PPDPart_Hash';
633 parent
::__construct( $data );
637 * Get the accumulator that would result if the close is not found.
639 function breakSyntax( $openingCount = false ) {
640 if ( $this->open
== "\n" ) {
641 $accum = $this->parts
[0]->out
;
643 if ( $openingCount === false ) {
644 $openingCount = $this->count
;
646 $accum = new PPDAccum_Hash
;
647 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
649 foreach ( $this->parts
as $part ) {
653 $accum->addLiteral( '|' );
655 $accum->addAccum( $part->out
);
662 class PPDPart_Hash
extends PPDPart
{
663 function __construct( $out = '' ) {
664 $accum = new PPDAccum_Hash
;
666 $accum->addLiteral( $out );
668 parent
::__construct( $accum );
672 class PPDAccum_Hash
{
673 var $firstNode, $lastNode;
675 function __construct() {
676 $this->firstNode
= $this->lastNode
= false;
680 * Append a string literal
682 function addLiteral( $s ) {
683 if ( $this->lastNode
=== false ) {
684 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
685 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
686 $this->lastNode
->value
.= $s;
688 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
689 $this->lastNode
= $this->lastNode
->nextSibling
;
696 function addNode( PPNode
$node ) {
697 if ( $this->lastNode
=== false ) {
698 $this->firstNode
= $this->lastNode
= $node;
700 $this->lastNode
->nextSibling
= $node;
701 $this->lastNode
= $node;
706 * Append a tree node with text contents
708 function addNodeWithText( $name, $value ) {
709 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
710 $this->addNode( $node );
714 * Append a PPAccum_Hash
715 * Takes over ownership of the nodes in the source argument. These nodes may
716 * subsequently be modified, especially nextSibling.
718 function addAccum( $accum ) {
719 if ( $accum->lastNode
=== false ) {
721 } elseif ( $this->lastNode
=== false ) {
722 $this->firstNode
= $accum->firstNode
;
723 $this->lastNode
= $accum->lastNode
;
725 $this->lastNode
->nextSibling
= $accum->firstNode
;
726 $this->lastNode
= $accum->lastNode
;
732 * An expansion frame, used as a context to expand the result of preprocessToObj()
734 class PPFrame_Hash
implements PPFrame
{
735 var $preprocessor, $parser, $title;
739 * Hashtable listing templates which are disallowed for expansion in this frame,
740 * having been encountered previously in parent frames.
745 * Recursion depth of this frame, top = 0
751 * Construct a new preprocessor frame.
752 * @param Preprocessor $preprocessor The parent preprocessor
754 function __construct( $preprocessor ) {
755 $this->preprocessor
= $preprocessor;
756 $this->parser
= $preprocessor->parser
;
757 $this->title
= $this->parser
->mTitle
;
758 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
759 $this->loopCheckHash
= array();
764 * Create a new child frame
765 * $args is optionally a multi-root PPNode or array containing the template arguments
767 function newChild( $args = false, $title = false ) {
768 $namedArgs = array();
769 $numberedArgs = array();
770 if ( $title === false ) {
771 $title = $this->title
;
773 if ( $args !== false ) {
775 if ( $args instanceof PPNode_Hash_Array
) {
776 $args = $args->value
;
777 } elseif ( !is_array( $args ) ) {
778 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
780 foreach ( $args as $arg ) {
781 $bits = $arg->splitArg();
782 if ( $bits['index'] !== '' ) {
783 // Numbered parameter
784 $numberedArgs[$bits['index']] = $bits['value'];
785 unset( $namedArgs[$bits['index']] );
788 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
789 $namedArgs[$name] = $bits['value'];
790 unset( $numberedArgs[$name] );
794 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
797 function expand( $root, $flags = 0 ) {
798 if ( is_string( $root ) ) {
802 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
804 return '<span class="error">Node-count limit exceeded</span>';
807 $outStack = array( '', '' );
808 $iteratorStack = array( false, $root );
809 $indexStack = array( 0, 0 );
811 while ( count( $iteratorStack ) > 1 ) {
812 $level = count( $outStack ) - 1;
813 $iteratorNode =& $iteratorStack[ $level ];
814 $out =& $outStack[$level];
815 $index =& $indexStack[$level];
817 if ( is_array( $iteratorNode ) ) {
818 if ( $index >= count( $iteratorNode ) ) {
819 // All done with this iterator
820 $iteratorStack[$level] = false;
821 $contextNode = false;
823 $contextNode = $iteratorNode[$index];
826 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
827 if ( $index >= $iteratorNode->getLength() ) {
828 // All done with this iterator
829 $iteratorStack[$level] = false;
830 $contextNode = false;
832 $contextNode = $iteratorNode->item( $index );
836 // Copy to $contextNode and then delete from iterator stack,
837 // because this is not an iterator but we do have to execute it once
838 $contextNode = $iteratorStack[$level];
839 $iteratorStack[$level] = false;
842 $newIterator = false;
844 if ( $contextNode === false ) {
846 } elseif ( is_string( $contextNode ) ) {
847 $out .= $contextNode;
848 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
849 $newIterator = $contextNode;
850 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
852 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
853 $out .= $contextNode->value
;
854 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
855 if ( $contextNode->name
== 'template' ) {
856 # Double-brace expansion
857 $bits = $contextNode->splitTemplate();
858 if ( $flags & self
::NO_TEMPLATES
) {
859 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
861 $ret = $this->parser
->braceSubstitution( $bits, $this );
862 if ( isset( $ret['object'] ) ) {
863 $newIterator = $ret['object'];
865 $out .= $ret['text'];
868 } elseif ( $contextNode->name
== 'tplarg' ) {
869 # Triple-brace expansion
870 $bits = $contextNode->splitTemplate();
871 if ( $flags & self
::NO_ARGS
) {
872 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
874 $ret = $this->parser
->argSubstitution( $bits, $this );
875 if ( isset( $ret['object'] ) ) {
876 $newIterator = $ret['object'];
878 $out .= $ret['text'];
881 } elseif ( $contextNode->name
== 'comment' ) {
883 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
884 if ( $this->parser
->ot
['html']
885 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
886 ||
( $flags & self
::STRIP_COMMENTS
) )
890 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
891 # Not in RECOVER_COMMENTS mode (extractSections) though
892 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
893 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
895 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
897 $out .= $contextNode->firstChild
->value
;
899 } elseif ( $contextNode->name
== 'ignore' ) {
900 # Output suppression used by <includeonly> etc.
901 # OT_WIKI will only respect <ignore> in substed templates.
902 # The other output types respect it unless NO_IGNORE is set.
903 # extractSections() sets NO_IGNORE and so never respects it.
904 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
905 $out .= $contextNode->firstChild
->value
;
909 } elseif ( $contextNode->name
== 'ext' ) {
911 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
912 $out .= $this->parser
->extensionSubstitution( $bits, $this );
913 } elseif ( $contextNode->name
== 'h' ) {
915 if ( $this->parser
->ot
['html'] ) {
916 # Expand immediately and insert heading index marker
918 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
919 $s .= $this->expand( $node, $flags );
922 $bits = $contextNode->splitHeading();
923 $titleText = $this->title
->getPrefixedDBkey();
924 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
925 $serial = count( $this->parser
->mHeadings
) - 1;
926 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
927 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
928 $this->parser
->mStripState
->general
->setPair( $marker, '' );
931 # Expand in virtual stack
932 $newIterator = $contextNode->getChildren();
935 # Generic recursive expansion
936 $newIterator = $contextNode->getChildren();
939 throw new MWException( __METHOD__
.': Invalid parameter type' );
942 if ( $newIterator !== false ) {
944 $iteratorStack[] = $newIterator;
946 } elseif ( $iteratorStack[$level] === false ) {
947 // Return accumulated value to parent
948 // With tail recursion
949 while ( $iteratorStack[$level] === false && $level > 0 ) {
950 $outStack[$level - 1] .= $out;
951 array_pop( $outStack );
952 array_pop( $iteratorStack );
953 array_pop( $indexStack );
961 function implodeWithFlags( $sep, $flags /*, ... */ ) {
962 $args = array_slice( func_get_args(), 2 );
966 foreach ( $args as $root ) {
967 if ( $root instanceof PPNode_Hash_Array
) {
968 $root = $root->value
;
970 if ( !is_array( $root ) ) {
971 $root = array( $root );
973 foreach ( $root as $node ) {
979 $s .= $this->expand( $node, $flags );
986 * Implode with no flags specified
987 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
989 function implode( $sep /*, ... */ ) {
990 $args = array_slice( func_get_args(), 1 );
994 foreach ( $args as $root ) {
995 if ( $root instanceof PPNode_Hash_Array
) {
996 $root = $root->value
;
998 if ( !is_array( $root ) ) {
999 $root = array( $root );
1001 foreach ( $root as $node ) {
1007 $s .= $this->expand( $node );
1014 * Makes an object that, when expand()ed, will be the same as one obtained
1017 function virtualImplode( $sep /*, ... */ ) {
1018 $args = array_slice( func_get_args(), 1 );
1022 foreach ( $args as $root ) {
1023 if ( $root instanceof PPNode_Hash_Array
) {
1024 $root = $root->value
;
1026 if ( !is_array( $root ) ) {
1027 $root = array( $root );
1029 foreach ( $root as $node ) {
1038 return new PPNode_Hash_Array( $out );
1042 * Virtual implode with brackets
1044 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1045 $args = array_slice( func_get_args(), 3 );
1046 $out = array( $start );
1049 foreach ( $args as $root ) {
1050 if ( $root instanceof PPNode_Hash_Array
) {
1051 $root = $root->value
;
1053 if ( !is_array( $root ) ) {
1054 $root = array( $root );
1056 foreach ( $root as $node ) {
1066 return new PPNode_Hash_Array( $out );
1069 function __toString() {
1073 function getPDBK( $level = false ) {
1074 if ( $level === false ) {
1075 return $this->title
->getPrefixedDBkey();
1077 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1082 * Returns true if there are no arguments in this frame
1084 function isEmpty() {
1088 function getArgument( $name ) {
1093 * Returns true if the infinite loop check is OK, false if a loop is detected
1095 function loopCheck( $title ) {
1096 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1100 * Return true if the frame is a template frame
1102 function isTemplate() {
1108 * Expansion frame with template arguments
1110 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1111 var $numberedArgs, $namedArgs, $parent;
1112 var $numberedExpansionCache, $namedExpansionCache;
1114 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1115 $this->preprocessor
= $preprocessor;
1116 $this->parser
= $preprocessor->parser
;
1117 $this->parent
= $parent;
1118 $this->numberedArgs
= $numberedArgs;
1119 $this->namedArgs
= $namedArgs;
1120 $this->title
= $title;
1121 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1122 $this->titleCache
= $parent->titleCache
;
1123 $this->titleCache
[] = $pdbk;
1124 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1125 if ( $pdbk !== false ) {
1126 $this->loopCheckHash
[$pdbk] = true;
1128 $this->depth
= $parent->depth +
1;
1129 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1132 function __toString() {
1135 $args = $this->numberedArgs +
$this->namedArgs
;
1136 foreach ( $args as $name => $value ) {
1142 $s .= "\"$name\":\"" .
1143 str_replace( '"', '\\"', $value->__toString() ) . '"';
1149 * Returns true if there are no arguments in this frame
1151 function isEmpty() {
1152 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1155 function getNumberedArgument( $index ) {
1156 if ( !isset( $this->numberedArgs
[$index] ) ) {
1159 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1160 # No trimming for unnamed arguments
1161 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1163 return $this->numberedExpansionCache
[$index];
1166 function getNamedArgument( $name ) {
1167 if ( !isset( $this->namedArgs
[$name] ) ) {
1170 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1171 # Trim named arguments post-expand, for backwards compatibility
1172 $this->namedExpansionCache
[$name] = trim(
1173 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1175 return $this->namedExpansionCache
[$name];
1178 function getArgument( $name ) {
1179 $text = $this->getNumberedArgument( $name );
1180 if ( $text === false ) {
1181 $text = $this->getNamedArgument( $name );
1187 * Return true if the frame is a template frame
1189 function isTemplate() {
1194 class PPNode_Hash_Tree
implements PPNode
{
1195 var $name, $firstChild, $lastChild, $nextSibling;
1197 function __construct( $name ) {
1198 $this->name
= $name;
1199 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1202 function __toString() {
1205 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1206 if ( $node instanceof PPNode_Hash_Attr
) {
1207 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1209 $inner .= $node->__toString();
1212 if ( $inner === '' ) {
1213 return "<{$this->name}$attribs/>";
1215 return "<{$this->name}$attribs>$inner</{$this->name}>";
1219 function newWithText( $name, $text ) {
1220 $obj = new self( $name );
1221 $obj->addChild( new PPNode_Hash_Text( $text ) );
1225 function addChild( $node ) {
1226 if ( $this->lastChild
=== false ) {
1227 $this->firstChild
= $this->lastChild
= $node;
1229 $this->lastChild
->nextSibling
= $node;
1230 $this->lastChild
= $node;
1234 function getChildren() {
1235 $children = array();
1236 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1237 $children[] = $child;
1239 return new PPNode_Hash_Array( $children );
1242 function getFirstChild() {
1243 return $this->firstChild
;
1246 function getNextSibling() {
1247 return $this->nextSibling
;
1250 function getChildrenOfType( $name ) {
1251 $children = array();
1252 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1253 if ( isset( $child->name
) && $child->name
=== $name ) {
1254 $children[] = $name;
1260 function getLength() { return false; }
1261 function item( $i ) { return false; }
1263 function getName() {
1268 * Split a <part> node into an associative array containing:
1270 * index String index
1271 * value PPNode value
1273 function splitArg() {
1275 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1276 if ( !isset( $child->name
) ) {
1279 if ( $child->name
=== 'name' ) {
1280 $bits['name'] = $child;
1281 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1282 && $child->firstChild
->name
=== 'index' )
1284 $bits['index'] = $child->firstChild
->value
;
1286 } elseif ( $child->name
=== 'value' ) {
1287 $bits['value'] = $child;
1291 if ( !isset( $bits['name'] ) ) {
1292 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1294 if ( !isset( $bits['index'] ) ) {
1295 $bits['index'] = '';
1301 * Split an <ext> node into an associative array containing name, attr, inner and close
1302 * All values in the resulting array are PPNodes. Inner and close are optional.
1304 function splitExt() {
1306 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1307 if ( !isset( $child->name
) ) {
1310 if ( $child->name
== 'name' ) {
1311 $bits['name'] = $child;
1312 } elseif ( $child->name
== 'attr' ) {
1313 $bits['attr'] = $child;
1314 } elseif ( $child->name
== 'inner' ) {
1315 $bits['inner'] = $child;
1316 } elseif ( $child->name
== 'close' ) {
1317 $bits['close'] = $child;
1320 if ( !isset( $bits['name'] ) ) {
1321 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1329 function splitHeading() {
1330 if ( $this->name
!== 'h' ) {
1331 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1334 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1335 if ( !isset( $child->name
) ) {
1338 if ( $child->name
== 'i' ) {
1339 $bits['i'] = $child->value
;
1340 } elseif ( $child->name
== 'level' ) {
1341 $bits['level'] = $child->value
;
1344 if ( !isset( $bits['i'] ) ) {
1345 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1351 * Split a <template> or <tplarg> node
1353 function splitTemplate() {
1354 wfDebug( 'Template: ' . var_export( $this, true ) );
1356 $bits = array( 'lineStart' => '' );
1357 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1358 wfDebug( 'Child: ' . var_export( $child, true ) );
1359 if ( !isset( $child->name
) ) {
1362 if ( $child->name
== 'title' ) {
1363 $bits['title'] = $child;
1365 if ( $child->name
== 'part' ) {
1368 if ( $child->name
== 'lineStart' ) {
1369 $bits['lineStart'] = '1';
1372 if ( !isset( $bits['title'] ) ) {
1373 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1375 $bits['parts'] = new PPNode_Hash_Array( $parts );
1380 class PPNode_Hash_Text
implements PPNode
{
1381 var $value, $nextSibling;
1383 function __construct( $value ) {
1384 if ( is_object( $value ) ) {
1385 throw new MWException( __CLASS__
. ' given object instead of string' );
1387 $this->value
= $value;
1390 function __toString() {
1391 return htmlspecialchars( $this->value
);
1394 function getNextSibling() {
1395 return $this->nextSibling
;
1398 function getChildren() { return false; }
1399 function getFirstChild() { return false; }
1400 function getChildrenOfType( $name ) { return false; }
1401 function getLength() { return false; }
1402 function item( $i ) { return false; }
1403 function getName() { return '#text'; }
1404 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1405 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1406 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1409 class PPNode_Hash_Array
implements PPNode
{
1410 var $value, $nextSibling;
1412 function __construct( $value ) {
1413 $this->value
= $value;
1416 function __toString() {
1417 return var_export( $this, true );
1420 function getLength() {
1421 return count( $this->value
);
1424 function item( $i ) {
1425 return $this->value
[$i];
1428 function getName() { return '#nodelist'; }
1430 function getNextSibling() {
1431 return $this->nextSibling
;
1434 function getChildren() { return false; }
1435 function getFirstChild() { return false; }
1436 function getChildrenOfType( $name ) { return false; }
1437 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1438 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1439 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1442 class PPNode_Hash_Attr
implements PPNode
{
1443 var $name, $value, $nextSibling;
1445 function __construct( $name, $value ) {
1446 $this->name
= $name;
1447 $this->value
= $value;
1450 function __toString() {
1451 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1454 function getName() {
1458 function getNextSibling() {
1459 return $this->nextSibling
;
1462 function getChildren() { return false; }
1463 function getFirstChild() { return false; }
1464 function getChildrenOfType( $name ) { return false; }
1465 function getLength() { return false; }
1466 function item( $i ) { return false; }
1467 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1468 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1469 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }