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 wfProfileIn( __METHOD__
);
57 'names' => array( 2 => null ),
63 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
65 $xmlishElements = $this->parser
->getStripList();
66 $enableOnlyinclude = false;
67 if ( $forInclusion ) {
68 $ignoredTags = array( 'includeonly', '/includeonly' );
69 $ignoredElements = array( 'noinclude' );
70 $xmlishElements[] = 'noinclude';
71 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
72 $enableOnlyinclude = true;
75 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
76 $ignoredElements = array( 'includeonly' );
77 $xmlishElements[] = 'includeonly';
79 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
81 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
82 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
84 $stack = new PPDStack_Hash
;
86 $searchBase = "[{<\n";
87 $revText = strrev( $text ); // For fast reverse searches
89 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
90 $accum =& $stack->getAccum(); # Current accumulator
91 $findEquals = false; # True to find equals signs in arguments
92 $findPipe = false; # True to take notice of pipe characters
94 $inHeading = false; # True if $i is inside a possible heading
95 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
96 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
97 $fakeLineStart = true; # Do a line-start run without outputting an LF character
102 if ( $findOnlyinclude ) {
103 // Ignore all input up to the next <onlyinclude>
104 $startPos = strpos( $text, '<onlyinclude>', $i );
105 if ( $startPos === false ) {
106 // Ignored section runs to the end
107 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
110 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
111 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
113 $findOnlyinclude = false;
116 if ( $fakeLineStart ) {
117 $found = 'line-start';
120 # Find next opening brace, closing brace or pipe
121 $search = $searchBase;
122 if ( $stack->top
=== false ) {
123 $currentClosing = '';
125 $currentClosing = $stack->top
->close
;
126 $search .= $currentClosing;
132 // First equals will be for the template
136 # Output literal section, advance input counter
137 $literalLength = strcspn( $text, $search, $i );
138 if ( $literalLength > 0 ) {
139 $accum->addLiteral( substr( $text, $i, $literalLength ) );
140 $i +
= $literalLength;
142 if ( $i >= strlen( $text ) ) {
143 if ( $currentClosing == "\n" ) {
144 // Do a past-the-end run to finish off the heading
152 $curChar = $text[$i];
153 if ( $curChar == '|' ) {
155 } elseif ( $curChar == '=' ) {
157 } elseif ( $curChar == '<' ) {
159 } elseif ( $curChar == "\n" ) {
163 $found = 'line-start';
165 } elseif ( $curChar == $currentClosing ) {
167 } elseif ( isset( $rules[$curChar] ) ) {
169 $rule = $rules[$curChar];
171 # Some versions of PHP have a strcspn which stops on null characters
172 # Ignore and continue
179 if ( $found == 'angle' ) {
181 // Handle </onlyinclude>
182 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
183 $findOnlyinclude = true;
187 // Determine element name
188 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
189 // Element name missing or not listed
190 $accum->addLiteral( '<' );
195 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
196 // To avoid leaving blank lines, when a comment is both preceded
197 // and followed by a newline (ignoring spaces), trim leading and
198 // trailing spaces and one of the newlines.
201 $endPos = strpos( $text, '-->', $i +
4 );
202 if ( $endPos === false ) {
203 // Unclosed comment in input, runs to end
204 $inner = substr( $text, $i );
205 $accum->addNodeWithText( 'comment', $inner );
206 $i = strlen( $text );
208 // Search backwards for leading whitespace
209 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
210 // Search forwards for trailing whitespace
211 // $wsEnd will be the position of the last space
212 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
213 // Eat the line if possible
214 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
215 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
216 // it's a possible beneficial b/c break.
217 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
218 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
220 $startPos = $wsStart;
221 $endPos = $wsEnd +
1;
222 // Remove leading whitespace from the end of the accumulator
223 // Sanity check first though
224 $wsLength = $i - $wsStart;
226 && $accum->lastNode
instanceof PPNode_Hash_Text
227 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
229 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
231 // Do a line-start run next time to look for headings after the comment
232 $fakeLineStart = true;
234 // No line to eat, just take the comment itself
240 $part = $stack->top
->getCurrentPart();
241 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
242 // Comments abutting, no change in visual end
243 $part->commentEnd
= $wsEnd;
245 $part->visualEnd
= $wsStart;
246 $part->commentEnd
= $endPos;
250 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
251 $accum->addNodeWithText( 'comment', $inner );
256 $lowerName = strtolower( $name );
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( $lowerName, $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( $lowerName, $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()
623 class PPDStack_Hash
extends PPDStack
{
624 function __construct() {
625 $this->elementClass
= 'PPDStackElement_Hash';
626 parent
::__construct();
627 $this->rootAccum
= new PPDAccum_Hash
;
634 class PPDStackElement_Hash
extends PPDStackElement
{
635 function __construct( $data = array() ) {
636 $this->partClass
= 'PPDPart_Hash';
637 parent
::__construct( $data );
641 * Get the accumulator that would result if the close is not found.
643 function breakSyntax( $openingCount = false ) {
644 if ( $this->open
== "\n" ) {
645 $accum = $this->parts
[0]->out
;
647 if ( $openingCount === false ) {
648 $openingCount = $this->count
;
650 $accum = new PPDAccum_Hash
;
651 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
653 foreach ( $this->parts
as $part ) {
657 $accum->addLiteral( '|' );
659 $accum->addAccum( $part->out
);
669 class PPDPart_Hash
extends PPDPart
{
670 function __construct( $out = '' ) {
671 $accum = new PPDAccum_Hash
;
673 $accum->addLiteral( $out );
675 parent
::__construct( $accum );
682 class PPDAccum_Hash
{
683 var $firstNode, $lastNode;
685 function __construct() {
686 $this->firstNode
= $this->lastNode
= false;
690 * Append a string literal
692 function addLiteral( $s ) {
693 if ( $this->lastNode
=== false ) {
694 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
695 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
696 $this->lastNode
->value
.= $s;
698 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
699 $this->lastNode
= $this->lastNode
->nextSibling
;
706 function addNode( PPNode
$node ) {
707 if ( $this->lastNode
=== false ) {
708 $this->firstNode
= $this->lastNode
= $node;
710 $this->lastNode
->nextSibling
= $node;
711 $this->lastNode
= $node;
716 * Append a tree node with text contents
718 function addNodeWithText( $name, $value ) {
719 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
720 $this->addNode( $node );
724 * Append a PPAccum_Hash
725 * Takes over ownership of the nodes in the source argument. These nodes may
726 * subsequently be modified, especially nextSibling.
728 function addAccum( $accum ) {
729 if ( $accum->lastNode
=== false ) {
731 } elseif ( $this->lastNode
=== false ) {
732 $this->firstNode
= $accum->firstNode
;
733 $this->lastNode
= $accum->lastNode
;
735 $this->lastNode
->nextSibling
= $accum->firstNode
;
736 $this->lastNode
= $accum->lastNode
;
742 * An expansion frame, used as a context to expand the result of preprocessToObj()
745 class PPFrame_Hash
implements PPFrame
{
746 var $preprocessor, $parser, $title;
750 * Hashtable listing templates which are disallowed for expansion in this frame,
751 * having been encountered previously in parent frames.
756 * Recursion depth of this frame, top = 0
762 * Construct a new preprocessor frame.
763 * @param Preprocessor $preprocessor The parent preprocessor
765 function __construct( $preprocessor ) {
766 $this->preprocessor
= $preprocessor;
767 $this->parser
= $preprocessor->parser
;
768 $this->title
= $this->parser
->mTitle
;
769 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
770 $this->loopCheckHash
= array();
775 * Create a new child frame
776 * $args is optionally a multi-root PPNode or array containing the template arguments
778 function newChild( $args = false, $title = false ) {
779 $namedArgs = array();
780 $numberedArgs = array();
781 if ( $title === false ) {
782 $title = $this->title
;
784 if ( $args !== false ) {
786 if ( $args instanceof PPNode_Hash_Array
) {
787 $args = $args->value
;
788 } elseif ( !is_array( $args ) ) {
789 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
791 foreach ( $args as $arg ) {
792 $bits = $arg->splitArg();
793 if ( $bits['index'] !== '' ) {
794 // Numbered parameter
795 $numberedArgs[$bits['index']] = $bits['value'];
796 unset( $namedArgs[$bits['index']] );
799 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
800 $namedArgs[$name] = $bits['value'];
801 unset( $numberedArgs[$name] );
805 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
808 function expand( $root, $flags = 0 ) {
809 if ( is_string( $root ) ) {
813 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
815 return '<span class="error">Node-count limit exceeded</span>';
817 if ( $this->depth
> $this->parser
->mOptions
->mMaxPPExpandDepth
) {
818 return '<span class="error">Expansion depth limit exceeded</span>';
822 $outStack = array( '', '' );
823 $iteratorStack = array( false, $root );
824 $indexStack = array( 0, 0 );
826 while ( count( $iteratorStack ) > 1 ) {
827 $level = count( $outStack ) - 1;
828 $iteratorNode =& $iteratorStack[ $level ];
829 $out =& $outStack[$level];
830 $index =& $indexStack[$level];
832 if ( is_array( $iteratorNode ) ) {
833 if ( $index >= count( $iteratorNode ) ) {
834 // All done with this iterator
835 $iteratorStack[$level] = false;
836 $contextNode = false;
838 $contextNode = $iteratorNode[$index];
841 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
842 if ( $index >= $iteratorNode->getLength() ) {
843 // All done with this iterator
844 $iteratorStack[$level] = false;
845 $contextNode = false;
847 $contextNode = $iteratorNode->item( $index );
851 // Copy to $contextNode and then delete from iterator stack,
852 // because this is not an iterator but we do have to execute it once
853 $contextNode = $iteratorStack[$level];
854 $iteratorStack[$level] = false;
857 $newIterator = false;
859 if ( $contextNode === false ) {
861 } elseif ( is_string( $contextNode ) ) {
862 $out .= $contextNode;
863 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
864 $newIterator = $contextNode;
865 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
867 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
868 $out .= $contextNode->value
;
869 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
870 if ( $contextNode->name
== 'template' ) {
871 # Double-brace expansion
872 $bits = $contextNode->splitTemplate();
873 if ( $flags & self
::NO_TEMPLATES
) {
874 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
876 $ret = $this->parser
->braceSubstitution( $bits, $this );
877 if ( isset( $ret['object'] ) ) {
878 $newIterator = $ret['object'];
880 $out .= $ret['text'];
883 } elseif ( $contextNode->name
== 'tplarg' ) {
884 # Triple-brace expansion
885 $bits = $contextNode->splitTemplate();
886 if ( $flags & self
::NO_ARGS
) {
887 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
889 $ret = $this->parser
->argSubstitution( $bits, $this );
890 if ( isset( $ret['object'] ) ) {
891 $newIterator = $ret['object'];
893 $out .= $ret['text'];
896 } elseif ( $contextNode->name
== 'comment' ) {
898 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
899 if ( $this->parser
->ot
['html']
900 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
901 ||
( $flags & self
::STRIP_COMMENTS
) )
905 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
906 # Not in RECOVER_COMMENTS mode (extractSections) though
907 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
908 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
910 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
912 $out .= $contextNode->firstChild
->value
;
914 } elseif ( $contextNode->name
== 'ignore' ) {
915 # Output suppression used by <includeonly> etc.
916 # OT_WIKI will only respect <ignore> in substed templates.
917 # The other output types respect it unless NO_IGNORE is set.
918 # extractSections() sets NO_IGNORE and so never respects it.
919 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
920 $out .= $contextNode->firstChild
->value
;
924 } elseif ( $contextNode->name
== 'ext' ) {
926 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
927 $out .= $this->parser
->extensionSubstitution( $bits, $this );
928 } elseif ( $contextNode->name
== 'h' ) {
930 if ( $this->parser
->ot
['html'] ) {
931 # Expand immediately and insert heading index marker
933 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
934 $s .= $this->expand( $node, $flags );
937 $bits = $contextNode->splitHeading();
938 $titleText = $this->title
->getPrefixedDBkey();
939 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
940 $serial = count( $this->parser
->mHeadings
) - 1;
941 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
942 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
943 $this->parser
->mStripState
->general
->setPair( $marker, '' );
946 # Expand in virtual stack
947 $newIterator = $contextNode->getChildren();
950 # Generic recursive expansion
951 $newIterator = $contextNode->getChildren();
954 throw new MWException( __METHOD__
.': Invalid parameter type' );
957 if ( $newIterator !== false ) {
959 $iteratorStack[] = $newIterator;
961 } elseif ( $iteratorStack[$level] === false ) {
962 // Return accumulated value to parent
963 // With tail recursion
964 while ( $iteratorStack[$level] === false && $level > 0 ) {
965 $outStack[$level - 1] .= $out;
966 array_pop( $outStack );
967 array_pop( $iteratorStack );
968 array_pop( $indexStack );
977 function implodeWithFlags( $sep, $flags /*, ... */ ) {
978 $args = array_slice( func_get_args(), 2 );
982 foreach ( $args as $root ) {
983 if ( $root instanceof PPNode_Hash_Array
) {
984 $root = $root->value
;
986 if ( !is_array( $root ) ) {
987 $root = array( $root );
989 foreach ( $root as $node ) {
995 $s .= $this->expand( $node, $flags );
1002 * Implode with no flags specified
1003 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1005 function implode( $sep /*, ... */ ) {
1006 $args = array_slice( func_get_args(), 1 );
1010 foreach ( $args as $root ) {
1011 if ( $root instanceof PPNode_Hash_Array
) {
1012 $root = $root->value
;
1014 if ( !is_array( $root ) ) {
1015 $root = array( $root );
1017 foreach ( $root as $node ) {
1023 $s .= $this->expand( $node );
1030 * Makes an object that, when expand()ed, will be the same as one obtained
1033 function virtualImplode( $sep /*, ... */ ) {
1034 $args = array_slice( func_get_args(), 1 );
1038 foreach ( $args as $root ) {
1039 if ( $root instanceof PPNode_Hash_Array
) {
1040 $root = $root->value
;
1042 if ( !is_array( $root ) ) {
1043 $root = array( $root );
1045 foreach ( $root as $node ) {
1054 return new PPNode_Hash_Array( $out );
1058 * Virtual implode with brackets
1060 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1061 $args = array_slice( func_get_args(), 3 );
1062 $out = array( $start );
1065 foreach ( $args as $root ) {
1066 if ( $root instanceof PPNode_Hash_Array
) {
1067 $root = $root->value
;
1069 if ( !is_array( $root ) ) {
1070 $root = array( $root );
1072 foreach ( $root as $node ) {
1082 return new PPNode_Hash_Array( $out );
1085 function __toString() {
1089 function getPDBK( $level = false ) {
1090 if ( $level === false ) {
1091 return $this->title
->getPrefixedDBkey();
1093 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1098 * Returns true if there are no arguments in this frame
1100 function isEmpty() {
1104 function getArgument( $name ) {
1109 * Returns true if the infinite loop check is OK, false if a loop is detected
1111 function loopCheck( $title ) {
1112 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1116 * Return true if the frame is a template frame
1118 function isTemplate() {
1124 * Expansion frame with template arguments
1127 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1128 var $numberedArgs, $namedArgs, $parent;
1129 var $numberedExpansionCache, $namedExpansionCache;
1131 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1132 $this->preprocessor
= $preprocessor;
1133 $this->parser
= $preprocessor->parser
;
1134 $this->parent
= $parent;
1135 $this->numberedArgs
= $numberedArgs;
1136 $this->namedArgs
= $namedArgs;
1137 $this->title
= $title;
1138 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1139 $this->titleCache
= $parent->titleCache
;
1140 $this->titleCache
[] = $pdbk;
1141 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1142 if ( $pdbk !== false ) {
1143 $this->loopCheckHash
[$pdbk] = true;
1145 $this->depth
= $parent->depth +
1;
1146 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1149 function __toString() {
1152 $args = $this->numberedArgs +
$this->namedArgs
;
1153 foreach ( $args as $name => $value ) {
1159 $s .= "\"$name\":\"" .
1160 str_replace( '"', '\\"', $value->__toString() ) . '"';
1166 * Returns true if there are no arguments in this frame
1168 function isEmpty() {
1169 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1172 function getNumberedArgument( $index ) {
1173 if ( !isset( $this->numberedArgs
[$index] ) ) {
1176 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1177 # No trimming for unnamed arguments
1178 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1180 return $this->numberedExpansionCache
[$index];
1183 function getNamedArgument( $name ) {
1184 if ( !isset( $this->namedArgs
[$name] ) ) {
1187 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1188 # Trim named arguments post-expand, for backwards compatibility
1189 $this->namedExpansionCache
[$name] = trim(
1190 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1192 return $this->namedExpansionCache
[$name];
1195 function getArgument( $name ) {
1196 $text = $this->getNumberedArgument( $name );
1197 if ( $text === false ) {
1198 $text = $this->getNamedArgument( $name );
1204 * Return true if the frame is a template frame
1206 function isTemplate() {
1214 class PPNode_Hash_Tree
implements PPNode
{
1215 var $name, $firstChild, $lastChild, $nextSibling;
1217 function __construct( $name ) {
1218 $this->name
= $name;
1219 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1222 function __toString() {
1225 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1226 if ( $node instanceof PPNode_Hash_Attr
) {
1227 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1229 $inner .= $node->__toString();
1232 if ( $inner === '' ) {
1233 return "<{$this->name}$attribs/>";
1235 return "<{$this->name}$attribs>$inner</{$this->name}>";
1239 static function newWithText( $name, $text ) {
1240 $obj = new self( $name );
1241 $obj->addChild( new PPNode_Hash_Text( $text ) );
1245 function addChild( $node ) {
1246 if ( $this->lastChild
=== false ) {
1247 $this->firstChild
= $this->lastChild
= $node;
1249 $this->lastChild
->nextSibling
= $node;
1250 $this->lastChild
= $node;
1254 function getChildren() {
1255 $children = array();
1256 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1257 $children[] = $child;
1259 return new PPNode_Hash_Array( $children );
1262 function getFirstChild() {
1263 return $this->firstChild
;
1266 function getNextSibling() {
1267 return $this->nextSibling
;
1270 function getChildrenOfType( $name ) {
1271 $children = array();
1272 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1273 if ( isset( $child->name
) && $child->name
=== $name ) {
1274 $children[] = $name;
1280 function getLength() { return false; }
1281 function item( $i ) { return false; }
1283 function getName() {
1288 * Split a <part> node into an associative array containing:
1290 * index String index
1291 * value PPNode value
1293 function splitArg() {
1295 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1296 if ( !isset( $child->name
) ) {
1299 if ( $child->name
=== 'name' ) {
1300 $bits['name'] = $child;
1301 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1302 && $child->firstChild
->name
=== 'index' )
1304 $bits['index'] = $child->firstChild
->value
;
1306 } elseif ( $child->name
=== 'value' ) {
1307 $bits['value'] = $child;
1311 if ( !isset( $bits['name'] ) ) {
1312 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1314 if ( !isset( $bits['index'] ) ) {
1315 $bits['index'] = '';
1321 * Split an <ext> node into an associative array containing name, attr, inner and close
1322 * All values in the resulting array are PPNodes. Inner and close are optional.
1324 function splitExt() {
1326 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1327 if ( !isset( $child->name
) ) {
1330 if ( $child->name
== 'name' ) {
1331 $bits['name'] = $child;
1332 } elseif ( $child->name
== 'attr' ) {
1333 $bits['attr'] = $child;
1334 } elseif ( $child->name
== 'inner' ) {
1335 $bits['inner'] = $child;
1336 } elseif ( $child->name
== 'close' ) {
1337 $bits['close'] = $child;
1340 if ( !isset( $bits['name'] ) ) {
1341 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1349 function splitHeading() {
1350 if ( $this->name
!== 'h' ) {
1351 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1354 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1355 if ( !isset( $child->name
) ) {
1358 if ( $child->name
== 'i' ) {
1359 $bits['i'] = $child->value
;
1360 } elseif ( $child->name
== 'level' ) {
1361 $bits['level'] = $child->value
;
1364 if ( !isset( $bits['i'] ) ) {
1365 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1371 * Split a <template> or <tplarg> node
1373 function splitTemplate() {
1375 $bits = array( 'lineStart' => '' );
1376 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1377 if ( !isset( $child->name
) ) {
1380 if ( $child->name
== 'title' ) {
1381 $bits['title'] = $child;
1383 if ( $child->name
== 'part' ) {
1386 if ( $child->name
== 'lineStart' ) {
1387 $bits['lineStart'] = '1';
1390 if ( !isset( $bits['title'] ) ) {
1391 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1393 $bits['parts'] = new PPNode_Hash_Array( $parts );
1401 class PPNode_Hash_Text
implements PPNode
{
1402 var $value, $nextSibling;
1404 function __construct( $value ) {
1405 if ( is_object( $value ) ) {
1406 throw new MWException( __CLASS__
. ' given object instead of string' );
1408 $this->value
= $value;
1411 function __toString() {
1412 return htmlspecialchars( $this->value
);
1415 function getNextSibling() {
1416 return $this->nextSibling
;
1419 function getChildren() { return false; }
1420 function getFirstChild() { return false; }
1421 function getChildrenOfType( $name ) { return false; }
1422 function getLength() { return false; }
1423 function item( $i ) { return false; }
1424 function getName() { return '#text'; }
1425 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1426 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1427 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1433 class PPNode_Hash_Array
implements PPNode
{
1434 var $value, $nextSibling;
1436 function __construct( $value ) {
1437 $this->value
= $value;
1440 function __toString() {
1441 return var_export( $this, true );
1444 function getLength() {
1445 return count( $this->value
);
1448 function item( $i ) {
1449 return $this->value
[$i];
1452 function getName() { return '#nodelist'; }
1454 function getNextSibling() {
1455 return $this->nextSibling
;
1458 function getChildren() { return false; }
1459 function getFirstChild() { return false; }
1460 function getChildrenOfType( $name ) { return false; }
1461 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1462 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1463 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1469 class PPNode_Hash_Attr
implements PPNode
{
1470 var $name, $value, $nextSibling;
1472 function __construct( $name, $value ) {
1473 $this->name
= $name;
1474 $this->value
= $value;
1477 function __toString() {
1478 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1481 function getName() {
1485 function getNextSibling() {
1486 return $this->nextSibling
;
1489 function getChildren() { return false; }
1490 function getFirstChild() { return false; }
1491 function getChildrenOfType( $name ) { return false; }
1492 function getLength() { return false; }
1493 function item( $i ) { return false; }
1494 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1495 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1496 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }