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 );
20 function newCustomFrame( $args ) {
21 return new PPCustomFrame_Hash( $this, $args );
25 * Preprocess some wikitext and return the document tree.
26 * This is the ghost of Parser::replace_variables().
28 * @param string $text The text to parse
29 * @param integer flags Bitwise combination of:
30 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
31 * included. Default is to assume a direct page view.
33 * The generated DOM tree must depend only on the input text and the flags.
34 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
36 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
37 * change in the DOM tree for a given text, must be passed through the section identifier
38 * in the section edit link and thus back to extractSections().
40 * The output of this function is currently only cached in process memory, but a persistent
41 * cache may be implemented at a later date which takes further advantage of these strict
42 * dependency requirements.
46 function preprocessToObj( $text, $flags = 0 ) {
47 wfProfileIn( __METHOD__
);
61 'names' => array( 2 => null ),
67 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
69 $xmlishElements = $this->parser
->getStripList();
70 $enableOnlyinclude = false;
71 if ( $forInclusion ) {
72 $ignoredTags = array( 'includeonly', '/includeonly' );
73 $ignoredElements = array( 'noinclude' );
74 $xmlishElements[] = 'noinclude';
75 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
76 $enableOnlyinclude = true;
79 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
80 $ignoredElements = array( 'includeonly' );
81 $xmlishElements[] = 'includeonly';
83 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
85 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
86 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
88 $stack = new PPDStack_Hash
;
90 $searchBase = "[{<\n";
91 $revText = strrev( $text ); // For fast reverse searches
93 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
94 $accum =& $stack->getAccum(); # Current accumulator
95 $findEquals = false; # True to find equals signs in arguments
96 $findPipe = false; # True to take notice of pipe characters
98 $inHeading = false; # True if $i is inside a possible heading
99 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
100 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
101 $fakeLineStart = true; # Do a line-start run without outputting an LF character
106 if ( $findOnlyinclude ) {
107 // Ignore all input up to the next <onlyinclude>
108 $startPos = strpos( $text, '<onlyinclude>', $i );
109 if ( $startPos === false ) {
110 // Ignored section runs to the end
111 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
114 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
115 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
117 $findOnlyinclude = false;
120 if ( $fakeLineStart ) {
121 $found = 'line-start';
124 # Find next opening brace, closing brace or pipe
125 $search = $searchBase;
126 if ( $stack->top
=== false ) {
127 $currentClosing = '';
129 $currentClosing = $stack->top
->close
;
130 $search .= $currentClosing;
136 // First equals will be for the template
140 # Output literal section, advance input counter
141 $literalLength = strcspn( $text, $search, $i );
142 if ( $literalLength > 0 ) {
143 $accum->addLiteral( substr( $text, $i, $literalLength ) );
144 $i +
= $literalLength;
146 if ( $i >= strlen( $text ) ) {
147 if ( $currentClosing == "\n" ) {
148 // Do a past-the-end run to finish off the heading
156 $curChar = $text[$i];
157 if ( $curChar == '|' ) {
159 } elseif ( $curChar == '=' ) {
161 } elseif ( $curChar == '<' ) {
163 } elseif ( $curChar == "\n" ) {
167 $found = 'line-start';
169 } elseif ( $curChar == $currentClosing ) {
171 } elseif ( isset( $rules[$curChar] ) ) {
173 $rule = $rules[$curChar];
175 # Some versions of PHP have a strcspn which stops on null characters
176 # Ignore and continue
183 if ( $found == 'angle' ) {
185 // Handle </onlyinclude>
186 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
187 $findOnlyinclude = true;
191 // Determine element name
192 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
193 // Element name missing or not listed
194 $accum->addLiteral( '<' );
199 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
200 // To avoid leaving blank lines, when a comment is both preceded
201 // and followed by a newline (ignoring spaces), trim leading and
202 // trailing spaces and one of the newlines.
205 $endPos = strpos( $text, '-->', $i +
4 );
206 if ( $endPos === false ) {
207 // Unclosed comment in input, runs to end
208 $inner = substr( $text, $i );
209 $accum->addNodeWithText( 'comment', $inner );
210 $i = strlen( $text );
212 // Search backwards for leading whitespace
213 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
214 // Search forwards for trailing whitespace
215 // $wsEnd will be the position of the last space
216 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
217 // Eat the line if possible
218 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
219 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
220 // it's a possible beneficial b/c break.
221 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
222 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
224 $startPos = $wsStart;
225 $endPos = $wsEnd +
1;
226 // Remove leading whitespace from the end of the accumulator
227 // Sanity check first though
228 $wsLength = $i - $wsStart;
230 && $accum->lastNode
instanceof PPNode_Hash_Text
231 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
233 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
235 // Do a line-start run next time to look for headings after the comment
236 $fakeLineStart = true;
238 // No line to eat, just take the comment itself
244 $part = $stack->top
->getCurrentPart();
245 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
246 // Comments abutting, no change in visual end
247 $part->commentEnd
= $wsEnd;
249 $part->visualEnd
= $wsStart;
250 $part->commentEnd
= $endPos;
254 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
255 $accum->addNodeWithText( 'comment', $inner );
260 $lowerName = strtolower( $name );
261 $attrStart = $i +
strlen( $name ) +
1;
264 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
265 if ( $tagEndPos === false ) {
266 // Infinite backtrack
267 // Disable tag search to prevent worst-case O(N^2) performance
269 $accum->addLiteral( '<' );
274 // Handle ignored tags
275 if ( in_array( $lowerName, $ignoredTags ) ) {
276 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
282 if ( $text[$tagEndPos-1] == '/' ) {
284 $attrEnd = $tagEndPos - 1;
289 $attrEnd = $tagEndPos;
291 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
292 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
293 $i = $matches[0][1] +
strlen( $matches[0][0] );
294 $close = $matches[0][0];
296 // No end tag -- let it run out to the end of the text.
297 $inner = substr( $text, $tagEndPos +
1 );
298 $i = strlen( $text );
302 // <includeonly> and <noinclude> just become <ignore> tags
303 if ( in_array( $lowerName, $ignoredElements ) ) {
304 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
308 if ( $attrEnd <= $attrStart ) {
311 // Note that the attr element contains the whitespace between name and attribute,
312 // this is necessary for precise reconstruction during pre-save transform.
313 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
316 $extNode = new PPNode_Hash_Tree( 'ext' );
317 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
318 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
319 if ( $inner !== null ) {
320 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
322 if ( $close !== null ) {
323 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
325 $accum->addNode( $extNode );
328 elseif ( $found == 'line-start' ) {
329 // Is this the start of a heading?
330 // Line break belongs before the heading element in any case
331 if ( $fakeLineStart ) {
332 $fakeLineStart = false;
334 $accum->addLiteral( $curChar );
338 $count = strspn( $text, '=', $i, 6 );
339 if ( $count == 1 && $findEquals ) {
340 // DWIM: This looks kind of like a name/value separator
341 // Let's let the equals handler have it and break the potential heading
342 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
343 } elseif ( $count > 0 ) {
347 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
350 $stack->push( $piece );
351 $accum =& $stack->getAccum();
352 extract( $stack->getFlags() );
357 elseif ( $found == 'line-end' ) {
358 $piece = $stack->top
;
359 // A heading must be open, otherwise \n wouldn't have been in the search list
360 assert( $piece->open
== "\n" );
361 $part = $piece->getCurrentPart();
362 // Search back through the input to see if it has a proper close
363 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
364 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
365 $searchStart = $i - $wsLength;
366 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
367 // Comment found at line end
368 // Search for equals signs before the comment
369 $searchStart = $part->visualEnd
;
370 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
372 $count = $piece->count
;
373 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
374 if ( $equalsLength > 0 ) {
375 if ( $i - $equalsLength == $piece->startPos
) {
376 // This is just a single string of equals signs on its own line
377 // Replicate the doHeadings behaviour /={count}(.+)={count}/
378 // First find out how many equals signs there really are (don't stop at 6)
379 $count = $equalsLength;
383 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
386 $count = min( $equalsLength, $count );
389 // Normal match, output <h>
390 $element = new PPNode_Hash_Tree( 'possible-h' );
391 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
392 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
393 $element->lastChild
->nextSibling
= $accum->firstNode
;
394 $element->lastChild
= $accum->lastNode
;
396 // Single equals sign on its own line, count=0
400 // No match, no <h>, just pass down the inner text
405 $accum =& $stack->getAccum();
406 extract( $stack->getFlags() );
408 // Append the result to the enclosing accumulator
409 if ( $element instanceof PPNode
) {
410 $accum->addNode( $element );
412 $accum->addAccum( $element );
414 // Note that we do NOT increment the input pointer.
415 // This is because the closing linebreak could be the opening linebreak of
416 // another heading. Infinite loops are avoided because the next iteration MUST
417 // hit the heading open case above, which unconditionally increments the
421 elseif ( $found == 'open' ) {
422 # count opening brace characters
423 $count = strspn( $text, $curChar, $i );
425 # we need to add to stack only if opening brace count is enough for one of the rules
426 if ( $count >= $rule['min'] ) {
427 # Add it to the stack
430 'close' => $rule['end'],
432 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
435 $stack->push( $piece );
436 $accum =& $stack->getAccum();
437 extract( $stack->getFlags() );
439 # Add literal brace(s)
440 $accum->addLiteral( str_repeat( $curChar, $count ) );
445 elseif ( $found == 'close' ) {
446 $piece = $stack->top
;
447 # lets check if there are enough characters for closing brace
448 $maxCount = $piece->count
;
449 $count = strspn( $text, $curChar, $i, $maxCount );
451 # check for maximum matching characters (if there are 5 closing
452 # characters, we will probably need only 3 - depending on the rules)
454 $rule = $rules[$piece->open
];
455 if ( $count > $rule['max'] ) {
456 # The specified maximum exists in the callback array, unless the caller
458 $matchingCount = $rule['max'];
460 # Count is less than the maximum
461 # Skip any gaps in the callback array to find the true largest match
462 # Need to use array_key_exists not isset because the callback can be null
463 $matchingCount = $count;
464 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
469 if ($matchingCount <= 0) {
470 # No matching element found in callback array
471 # Output a literal closing brace and continue
472 $accum->addLiteral( str_repeat( $curChar, $count ) );
476 $name = $rule['names'][$matchingCount];
477 if ( $name === null ) {
478 // No element, just literal text
479 $element = $piece->breakSyntax( $matchingCount );
480 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
483 # Note: $parts is already XML, does not need to be encoded further
484 $parts = $piece->parts
;
485 $titleAccum = $parts[0]->out
;
488 $element = new PPNode_Hash_Tree( $name );
490 # The invocation is at the start of the line if lineStart is set in
491 # the stack, and all opening brackets are used up.
492 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
493 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
495 $titleNode = new PPNode_Hash_Tree( 'title' );
496 $titleNode->firstChild
= $titleAccum->firstNode
;
497 $titleNode->lastChild
= $titleAccum->lastNode
;
498 $element->addChild( $titleNode );
500 foreach ( $parts as $partIndex => $part ) {
501 if ( isset( $part->eqpos
) ) {
504 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
505 if ( $node === $part->eqpos
) {
511 throw new MWException( __METHOD__
. ': eqpos not found' );
513 if ( $node->name
!== 'equals' ) {
514 throw new MWException( __METHOD__
.': eqpos is not equals' );
518 // Construct name node
519 $nameNode = new PPNode_Hash_Tree( 'name' );
520 if ( $lastNode !== false ) {
521 $lastNode->nextSibling
= false;
522 $nameNode->firstChild
= $part->out
->firstNode
;
523 $nameNode->lastChild
= $lastNode;
526 // Construct value node
527 $valueNode = new PPNode_Hash_Tree( 'value' );
528 if ( $equalsNode->nextSibling
!== false ) {
529 $valueNode->firstChild
= $equalsNode->nextSibling
;
530 $valueNode->lastChild
= $part->out
->lastNode
;
532 $partNode = new PPNode_Hash_Tree( 'part' );
533 $partNode->addChild( $nameNode );
534 $partNode->addChild( $equalsNode->firstChild
);
535 $partNode->addChild( $valueNode );
536 $element->addChild( $partNode );
538 $partNode = new PPNode_Hash_Tree( 'part' );
539 $nameNode = new PPNode_Hash_Tree( 'name' );
540 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
541 $valueNode = new PPNode_Hash_Tree( 'value' );
542 $valueNode->firstChild
= $part->out
->firstNode
;
543 $valueNode->lastChild
= $part->out
->lastNode
;
544 $partNode->addChild( $nameNode );
545 $partNode->addChild( $valueNode );
546 $element->addChild( $partNode );
551 # Advance input pointer
552 $i +
= $matchingCount;
556 $accum =& $stack->getAccum();
558 # Re-add the old stack element if it still has unmatched opening characters remaining
559 if ($matchingCount < $piece->count
) {
560 $piece->parts
= array( new PPDPart_Hash
);
561 $piece->count
-= $matchingCount;
562 # do we still qualify for any callback with remaining count?
563 $names = $rules[$piece->open
]['names'];
565 $enclosingAccum =& $accum;
566 while ( $piece->count
) {
567 if ( array_key_exists( $piece->count
, $names ) ) {
568 $stack->push( $piece );
569 $accum =& $stack->getAccum();
575 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
578 extract( $stack->getFlags() );
580 # Add XML element to the enclosing accumulator
581 if ( $element instanceof PPNode
) {
582 $accum->addNode( $element );
584 $accum->addAccum( $element );
588 elseif ( $found == 'pipe' ) {
589 $findEquals = true; // shortcut for getFlags()
591 $accum =& $stack->getAccum();
595 elseif ( $found == 'equals' ) {
596 $findEquals = false; // shortcut for getFlags()
597 $accum->addNodeWithText( 'equals', '=' );
598 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
603 # Output any remaining unclosed brackets
604 foreach ( $stack->stack
as $piece ) {
605 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
608 # Enable top-level headings
609 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
610 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
615 $rootNode = new PPNode_Hash_Tree( 'root' );
616 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
617 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
618 wfProfileOut( __METHOD__
);
624 * Stack class to help Preprocessor::preprocessToObj()
627 class PPDStack_Hash
extends PPDStack
{
628 function __construct() {
629 $this->elementClass
= 'PPDStackElement_Hash';
630 parent
::__construct();
631 $this->rootAccum
= new PPDAccum_Hash
;
638 class PPDStackElement_Hash
extends PPDStackElement
{
639 function __construct( $data = array() ) {
640 $this->partClass
= 'PPDPart_Hash';
641 parent
::__construct( $data );
645 * Get the accumulator that would result if the close is not found.
647 function breakSyntax( $openingCount = false ) {
648 if ( $this->open
== "\n" ) {
649 $accum = $this->parts
[0]->out
;
651 if ( $openingCount === false ) {
652 $openingCount = $this->count
;
654 $accum = new PPDAccum_Hash
;
655 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
657 foreach ( $this->parts
as $part ) {
661 $accum->addLiteral( '|' );
663 $accum->addAccum( $part->out
);
673 class PPDPart_Hash
extends PPDPart
{
674 function __construct( $out = '' ) {
675 $accum = new PPDAccum_Hash
;
677 $accum->addLiteral( $out );
679 parent
::__construct( $accum );
686 class PPDAccum_Hash
{
687 var $firstNode, $lastNode;
689 function __construct() {
690 $this->firstNode
= $this->lastNode
= false;
694 * Append a string literal
696 function addLiteral( $s ) {
697 if ( $this->lastNode
=== false ) {
698 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
699 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
700 $this->lastNode
->value
.= $s;
702 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
703 $this->lastNode
= $this->lastNode
->nextSibling
;
710 function addNode( PPNode
$node ) {
711 if ( $this->lastNode
=== false ) {
712 $this->firstNode
= $this->lastNode
= $node;
714 $this->lastNode
->nextSibling
= $node;
715 $this->lastNode
= $node;
720 * Append a tree node with text contents
722 function addNodeWithText( $name, $value ) {
723 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
724 $this->addNode( $node );
728 * Append a PPAccum_Hash
729 * Takes over ownership of the nodes in the source argument. These nodes may
730 * subsequently be modified, especially nextSibling.
732 function addAccum( $accum ) {
733 if ( $accum->lastNode
=== false ) {
735 } elseif ( $this->lastNode
=== false ) {
736 $this->firstNode
= $accum->firstNode
;
737 $this->lastNode
= $accum->lastNode
;
739 $this->lastNode
->nextSibling
= $accum->firstNode
;
740 $this->lastNode
= $accum->lastNode
;
746 * An expansion frame, used as a context to expand the result of preprocessToObj()
749 class PPFrame_Hash
implements PPFrame
{
750 var $preprocessor, $parser, $title;
754 * Hashtable listing templates which are disallowed for expansion in this frame,
755 * having been encountered previously in parent frames.
760 * Recursion depth of this frame, top = 0
766 * Construct a new preprocessor frame.
767 * @param Preprocessor $preprocessor The parent preprocessor
769 function __construct( $preprocessor ) {
770 $this->preprocessor
= $preprocessor;
771 $this->parser
= $preprocessor->parser
;
772 $this->title
= $this->parser
->mTitle
;
773 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
774 $this->loopCheckHash
= array();
779 * Create a new child frame
780 * $args is optionally a multi-root PPNode or array containing the template arguments
782 function newChild( $args = false, $title = false ) {
783 $namedArgs = array();
784 $numberedArgs = array();
785 if ( $title === false ) {
786 $title = $this->title
;
788 if ( $args !== false ) {
790 if ( $args instanceof PPNode_Hash_Array
) {
791 $args = $args->value
;
792 } elseif ( !is_array( $args ) ) {
793 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
795 foreach ( $args as $arg ) {
796 $bits = $arg->splitArg();
797 if ( $bits['index'] !== '' ) {
798 // Numbered parameter
799 $numberedArgs[$bits['index']] = $bits['value'];
800 unset( $namedArgs[$bits['index']] );
803 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
804 $namedArgs[$name] = $bits['value'];
805 unset( $numberedArgs[$name] );
809 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
812 function expand( $root, $flags = 0 ) {
813 if ( is_string( $root ) ) {
817 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
819 return '<span class="error">Node-count limit exceeded</span>';
821 if ( $this->depth
> $this->parser
->mOptions
->mMaxPPExpandDepth
) {
822 return '<span class="error">Expansion depth limit exceeded</span>';
826 $outStack = array( '', '' );
827 $iteratorStack = array( false, $root );
828 $indexStack = array( 0, 0 );
830 while ( count( $iteratorStack ) > 1 ) {
831 $level = count( $outStack ) - 1;
832 $iteratorNode =& $iteratorStack[ $level ];
833 $out =& $outStack[$level];
834 $index =& $indexStack[$level];
836 if ( is_array( $iteratorNode ) ) {
837 if ( $index >= count( $iteratorNode ) ) {
838 // All done with this iterator
839 $iteratorStack[$level] = false;
840 $contextNode = false;
842 $contextNode = $iteratorNode[$index];
845 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
846 if ( $index >= $iteratorNode->getLength() ) {
847 // All done with this iterator
848 $iteratorStack[$level] = false;
849 $contextNode = false;
851 $contextNode = $iteratorNode->item( $index );
855 // Copy to $contextNode and then delete from iterator stack,
856 // because this is not an iterator but we do have to execute it once
857 $contextNode = $iteratorStack[$level];
858 $iteratorStack[$level] = false;
861 $newIterator = false;
863 if ( $contextNode === false ) {
865 } elseif ( is_string( $contextNode ) ) {
866 $out .= $contextNode;
867 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
868 $newIterator = $contextNode;
869 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
871 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
872 $out .= $contextNode->value
;
873 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
874 if ( $contextNode->name
== 'template' ) {
875 # Double-brace expansion
876 $bits = $contextNode->splitTemplate();
877 if ( $flags & self
::NO_TEMPLATES
) {
878 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
880 $ret = $this->parser
->braceSubstitution( $bits, $this );
881 if ( isset( $ret['object'] ) ) {
882 $newIterator = $ret['object'];
884 $out .= $ret['text'];
887 } elseif ( $contextNode->name
== 'tplarg' ) {
888 # Triple-brace expansion
889 $bits = $contextNode->splitTemplate();
890 if ( $flags & self
::NO_ARGS
) {
891 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
893 $ret = $this->parser
->argSubstitution( $bits, $this );
894 if ( isset( $ret['object'] ) ) {
895 $newIterator = $ret['object'];
897 $out .= $ret['text'];
900 } elseif ( $contextNode->name
== 'comment' ) {
902 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
903 if ( $this->parser
->ot
['html']
904 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
905 ||
( $flags & self
::STRIP_COMMENTS
) )
909 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
910 # Not in RECOVER_COMMENTS mode (extractSections) though
911 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
912 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
914 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
916 $out .= $contextNode->firstChild
->value
;
918 } elseif ( $contextNode->name
== 'ignore' ) {
919 # Output suppression used by <includeonly> etc.
920 # OT_WIKI will only respect <ignore> in substed templates.
921 # The other output types respect it unless NO_IGNORE is set.
922 # extractSections() sets NO_IGNORE and so never respects it.
923 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
924 $out .= $contextNode->firstChild
->value
;
928 } elseif ( $contextNode->name
== 'ext' ) {
930 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
931 $out .= $this->parser
->extensionSubstitution( $bits, $this );
932 } elseif ( $contextNode->name
== 'h' ) {
934 if ( $this->parser
->ot
['html'] ) {
935 # Expand immediately and insert heading index marker
937 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
938 $s .= $this->expand( $node, $flags );
941 $bits = $contextNode->splitHeading();
942 $titleText = $this->title
->getPrefixedDBkey();
943 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
944 $serial = count( $this->parser
->mHeadings
) - 1;
945 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
946 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
947 $this->parser
->mStripState
->general
->setPair( $marker, '' );
950 # Expand in virtual stack
951 $newIterator = $contextNode->getChildren();
954 # Generic recursive expansion
955 $newIterator = $contextNode->getChildren();
958 throw new MWException( __METHOD__
.': Invalid parameter type' );
961 if ( $newIterator !== false ) {
963 $iteratorStack[] = $newIterator;
965 } elseif ( $iteratorStack[$level] === false ) {
966 // Return accumulated value to parent
967 // With tail recursion
968 while ( $iteratorStack[$level] === false && $level > 0 ) {
969 $outStack[$level - 1] .= $out;
970 array_pop( $outStack );
971 array_pop( $iteratorStack );
972 array_pop( $indexStack );
981 function implodeWithFlags( $sep, $flags /*, ... */ ) {
982 $args = array_slice( func_get_args(), 2 );
986 foreach ( $args as $root ) {
987 if ( $root instanceof PPNode_Hash_Array
) {
988 $root = $root->value
;
990 if ( !is_array( $root ) ) {
991 $root = array( $root );
993 foreach ( $root as $node ) {
999 $s .= $this->expand( $node, $flags );
1006 * Implode with no flags specified
1007 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1009 function implode( $sep /*, ... */ ) {
1010 $args = array_slice( func_get_args(), 1 );
1014 foreach ( $args as $root ) {
1015 if ( $root instanceof PPNode_Hash_Array
) {
1016 $root = $root->value
;
1018 if ( !is_array( $root ) ) {
1019 $root = array( $root );
1021 foreach ( $root as $node ) {
1027 $s .= $this->expand( $node );
1034 * Makes an object that, when expand()ed, will be the same as one obtained
1037 function virtualImplode( $sep /*, ... */ ) {
1038 $args = array_slice( func_get_args(), 1 );
1042 foreach ( $args as $root ) {
1043 if ( $root instanceof PPNode_Hash_Array
) {
1044 $root = $root->value
;
1046 if ( !is_array( $root ) ) {
1047 $root = array( $root );
1049 foreach ( $root as $node ) {
1058 return new PPNode_Hash_Array( $out );
1062 * Virtual implode with brackets
1064 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1065 $args = array_slice( func_get_args(), 3 );
1066 $out = array( $start );
1069 foreach ( $args as $root ) {
1070 if ( $root instanceof PPNode_Hash_Array
) {
1071 $root = $root->value
;
1073 if ( !is_array( $root ) ) {
1074 $root = array( $root );
1076 foreach ( $root as $node ) {
1086 return new PPNode_Hash_Array( $out );
1089 function __toString() {
1093 function getPDBK( $level = false ) {
1094 if ( $level === false ) {
1095 return $this->title
->getPrefixedDBkey();
1097 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1102 * Returns true if there are no arguments in this frame
1104 function isEmpty() {
1108 function getArgument( $name ) {
1113 * Returns true if the infinite loop check is OK, false if a loop is detected
1115 function loopCheck( $title ) {
1116 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1120 * Return true if the frame is a template frame
1122 function isTemplate() {
1128 * Expansion frame with template arguments
1131 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1132 var $numberedArgs, $namedArgs, $parent;
1133 var $numberedExpansionCache, $namedExpansionCache;
1135 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1136 $this->preprocessor
= $preprocessor;
1137 $this->parser
= $preprocessor->parser
;
1138 $this->parent
= $parent;
1139 $this->numberedArgs
= $numberedArgs;
1140 $this->namedArgs
= $namedArgs;
1141 $this->title
= $title;
1142 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1143 $this->titleCache
= $parent->titleCache
;
1144 $this->titleCache
[] = $pdbk;
1145 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1146 if ( $pdbk !== false ) {
1147 $this->loopCheckHash
[$pdbk] = true;
1149 $this->depth
= $parent->depth +
1;
1150 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1153 function __toString() {
1156 $args = $this->numberedArgs +
$this->namedArgs
;
1157 foreach ( $args as $name => $value ) {
1163 $s .= "\"$name\":\"" .
1164 str_replace( '"', '\\"', $value->__toString() ) . '"';
1170 * Returns true if there are no arguments in this frame
1172 function isEmpty() {
1173 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1176 function getArguments() {
1177 $arguments = array();
1178 foreach ( array_merge(
1179 array_keys($this->numberedArgs
),
1180 array_keys($this->namedArgs
)) as $key ) {
1181 $arguments[$key] = $this->getArgument($key);
1186 function getNumberedArguments() {
1187 $arguments = array();
1188 foreach ( array_keys($this->numberedArgs
) as $key ) {
1189 $arguments[$key] = $this->getArgument($key);
1194 function getNamedArguments() {
1195 $arguments = array();
1196 foreach ( array_keys($this->namedArgs
) as $key ) {
1197 $arguments[$key] = $this->getArgument($key);
1202 function getNumberedArgument( $index ) {
1203 if ( !isset( $this->numberedArgs
[$index] ) ) {
1206 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1207 # No trimming for unnamed arguments
1208 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1210 return $this->numberedExpansionCache
[$index];
1213 function getNamedArgument( $name ) {
1214 if ( !isset( $this->namedArgs
[$name] ) ) {
1217 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1218 # Trim named arguments post-expand, for backwards compatibility
1219 $this->namedExpansionCache
[$name] = trim(
1220 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1222 return $this->namedExpansionCache
[$name];
1225 function getArgument( $name ) {
1226 $text = $this->getNumberedArgument( $name );
1227 if ( $text === false ) {
1228 $text = $this->getNamedArgument( $name );
1234 * Return true if the frame is a template frame
1236 function isTemplate() {
1242 * Expansion frame with custom arguments
1245 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1248 function __construct( $preprocessor, $args ) {
1249 $this->preprocessor
= $preprocessor;
1250 $this->parser
= $preprocessor->parser
;
1251 $this->args
= $args;
1254 function __toString() {
1257 foreach ( $this->args
as $name => $value ) {
1263 $s .= "\"$name\":\"" .
1264 str_replace( '"', '\\"', $value->__toString() ) . '"';
1270 function isEmpty() {
1271 return !count( $this->args
);
1274 function getArgument( $index ) {
1275 return $this->args
[$index];
1282 class PPNode_Hash_Tree
implements PPNode
{
1283 var $name, $firstChild, $lastChild, $nextSibling;
1285 function __construct( $name ) {
1286 $this->name
= $name;
1287 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1290 function __toString() {
1293 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1294 if ( $node instanceof PPNode_Hash_Attr
) {
1295 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1297 $inner .= $node->__toString();
1300 if ( $inner === '' ) {
1301 return "<{$this->name}$attribs/>";
1303 return "<{$this->name}$attribs>$inner</{$this->name}>";
1307 static function newWithText( $name, $text ) {
1308 $obj = new self( $name );
1309 $obj->addChild( new PPNode_Hash_Text( $text ) );
1313 function addChild( $node ) {
1314 if ( $this->lastChild
=== false ) {
1315 $this->firstChild
= $this->lastChild
= $node;
1317 $this->lastChild
->nextSibling
= $node;
1318 $this->lastChild
= $node;
1322 function getChildren() {
1323 $children = array();
1324 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1325 $children[] = $child;
1327 return new PPNode_Hash_Array( $children );
1330 function getFirstChild() {
1331 return $this->firstChild
;
1334 function getNextSibling() {
1335 return $this->nextSibling
;
1338 function getChildrenOfType( $name ) {
1339 $children = array();
1340 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1341 if ( isset( $child->name
) && $child->name
=== $name ) {
1342 $children[] = $name;
1348 function getLength() { return false; }
1349 function item( $i ) { return false; }
1351 function getName() {
1356 * Split a <part> node into an associative array containing:
1358 * index String index
1359 * value PPNode value
1361 function splitArg() {
1363 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1364 if ( !isset( $child->name
) ) {
1367 if ( $child->name
=== 'name' ) {
1368 $bits['name'] = $child;
1369 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1370 && $child->firstChild
->name
=== 'index' )
1372 $bits['index'] = $child->firstChild
->value
;
1374 } elseif ( $child->name
=== 'value' ) {
1375 $bits['value'] = $child;
1379 if ( !isset( $bits['name'] ) ) {
1380 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1382 if ( !isset( $bits['index'] ) ) {
1383 $bits['index'] = '';
1389 * Split an <ext> node into an associative array containing name, attr, inner and close
1390 * All values in the resulting array are PPNodes. Inner and close are optional.
1392 function splitExt() {
1394 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1395 if ( !isset( $child->name
) ) {
1398 if ( $child->name
== 'name' ) {
1399 $bits['name'] = $child;
1400 } elseif ( $child->name
== 'attr' ) {
1401 $bits['attr'] = $child;
1402 } elseif ( $child->name
== 'inner' ) {
1403 $bits['inner'] = $child;
1404 } elseif ( $child->name
== 'close' ) {
1405 $bits['close'] = $child;
1408 if ( !isset( $bits['name'] ) ) {
1409 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1417 function splitHeading() {
1418 if ( $this->name
!== 'h' ) {
1419 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1422 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1423 if ( !isset( $child->name
) ) {
1426 if ( $child->name
== 'i' ) {
1427 $bits['i'] = $child->value
;
1428 } elseif ( $child->name
== 'level' ) {
1429 $bits['level'] = $child->value
;
1432 if ( !isset( $bits['i'] ) ) {
1433 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1439 * Split a <template> or <tplarg> node
1441 function splitTemplate() {
1443 $bits = array( 'lineStart' => '' );
1444 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1445 if ( !isset( $child->name
) ) {
1448 if ( $child->name
== 'title' ) {
1449 $bits['title'] = $child;
1451 if ( $child->name
== 'part' ) {
1454 if ( $child->name
== 'lineStart' ) {
1455 $bits['lineStart'] = '1';
1458 if ( !isset( $bits['title'] ) ) {
1459 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1461 $bits['parts'] = new PPNode_Hash_Array( $parts );
1469 class PPNode_Hash_Text
implements PPNode
{
1470 var $value, $nextSibling;
1472 function __construct( $value ) {
1473 if ( is_object( $value ) ) {
1474 throw new MWException( __CLASS__
. ' given object instead of string' );
1476 $this->value
= $value;
1479 function __toString() {
1480 return htmlspecialchars( $this->value
);
1483 function getNextSibling() {
1484 return $this->nextSibling
;
1487 function getChildren() { return false; }
1488 function getFirstChild() { return false; }
1489 function getChildrenOfType( $name ) { return false; }
1490 function getLength() { return false; }
1491 function item( $i ) { return false; }
1492 function getName() { return '#text'; }
1493 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1494 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1495 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1501 class PPNode_Hash_Array
implements PPNode
{
1502 var $value, $nextSibling;
1504 function __construct( $value ) {
1505 $this->value
= $value;
1508 function __toString() {
1509 return var_export( $this, true );
1512 function getLength() {
1513 return count( $this->value
);
1516 function item( $i ) {
1517 return $this->value
[$i];
1520 function getName() { return '#nodelist'; }
1522 function getNextSibling() {
1523 return $this->nextSibling
;
1526 function getChildren() { return false; }
1527 function getFirstChild() { return false; }
1528 function getChildrenOfType( $name ) { return false; }
1529 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1530 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1531 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1537 class PPNode_Hash_Attr
implements PPNode
{
1538 var $name, $value, $nextSibling;
1540 function __construct( $name, $value ) {
1541 $this->name
= $name;
1542 $this->value
= $value;
1545 function __toString() {
1546 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1549 function getName() {
1553 function getNextSibling() {
1554 return $this->nextSibling
;
1557 function getChildren() { return false; }
1558 function getFirstChild() { return false; }
1559 function getChildrenOfType( $name ) { return false; }
1560 function getLength() { return false; }
1561 function item( $i ) { return false; }
1562 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1563 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1564 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }