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 $lowerName = strtolower( $name );
258 $attrStart = $i +
strlen( $name ) +
1;
261 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
262 if ( $tagEndPos === false ) {
263 // Infinite backtrack
264 // Disable tag search to prevent worst-case O(N^2) performance
266 $accum->addLiteral( '<' );
271 // Handle ignored tags
272 if ( in_array( $lowerName, $ignoredTags ) ) {
273 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
279 if ( $text[$tagEndPos-1] == '/' ) {
281 $attrEnd = $tagEndPos - 1;
286 $attrEnd = $tagEndPos;
288 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
289 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
290 $i = $matches[0][1] +
strlen( $matches[0][0] );
291 $close = $matches[0][0];
293 // No end tag -- let it run out to the end of the text.
294 $inner = substr( $text, $tagEndPos +
1 );
295 $i = strlen( $text );
299 // <includeonly> and <noinclude> just become <ignore> tags
300 if ( in_array( $lowerName, $ignoredElements ) ) {
301 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
305 if ( $attrEnd <= $attrStart ) {
308 // Note that the attr element contains the whitespace between name and attribute,
309 // this is necessary for precise reconstruction during pre-save transform.
310 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
313 $extNode = new PPNode_Hash_Tree( 'ext' );
314 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
315 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
316 if ( $inner !== null ) {
317 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
319 if ( $close !== null ) {
320 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
322 $accum->addNode( $extNode );
325 elseif ( $found == 'line-start' ) {
326 // Is this the start of a heading?
327 // Line break belongs before the heading element in any case
328 if ( $fakeLineStart ) {
329 $fakeLineStart = false;
331 $accum->addLiteral( $curChar );
335 $count = strspn( $text, '=', $i, 6 );
336 if ( $count == 1 && $findEquals ) {
337 // DWIM: This looks kind of like a name/value separator
338 // Let's let the equals handler have it and break the potential heading
339 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
340 } elseif ( $count > 0 ) {
344 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
347 $stack->push( $piece );
348 $accum =& $stack->getAccum();
349 extract( $stack->getFlags() );
354 elseif ( $found == 'line-end' ) {
355 $piece = $stack->top
;
356 // A heading must be open, otherwise \n wouldn't have been in the search list
357 assert( $piece->open
== "\n" );
358 $part = $piece->getCurrentPart();
359 // Search back through the input to see if it has a proper close
360 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
361 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
362 $searchStart = $i - $wsLength;
363 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
364 // Comment found at line end
365 // Search for equals signs before the comment
366 $searchStart = $part->visualEnd
;
367 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
369 $count = $piece->count
;
370 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
371 if ( $equalsLength > 0 ) {
372 if ( $i - $equalsLength == $piece->startPos
) {
373 // This is just a single string of equals signs on its own line
374 // Replicate the doHeadings behaviour /={count}(.+)={count}/
375 // First find out how many equals signs there really are (don't stop at 6)
376 $count = $equalsLength;
380 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
383 $count = min( $equalsLength, $count );
386 // Normal match, output <h>
387 $element = new PPNode_Hash_Tree( 'possible-h' );
388 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
389 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
390 $element->lastChild
->nextSibling
= $accum->firstNode
;
391 $element->lastChild
= $accum->lastNode
;
393 // Single equals sign on its own line, count=0
397 // No match, no <h>, just pass down the inner text
402 $accum =& $stack->getAccum();
403 extract( $stack->getFlags() );
405 // Append the result to the enclosing accumulator
406 if ( $element instanceof PPNode
) {
407 $accum->addNode( $element );
409 $accum->addAccum( $element );
411 // Note that we do NOT increment the input pointer.
412 // This is because the closing linebreak could be the opening linebreak of
413 // another heading. Infinite loops are avoided because the next iteration MUST
414 // hit the heading open case above, which unconditionally increments the
418 elseif ( $found == 'open' ) {
419 # count opening brace characters
420 $count = strspn( $text, $curChar, $i );
422 # we need to add to stack only if opening brace count is enough for one of the rules
423 if ( $count >= $rule['min'] ) {
424 # Add it to the stack
427 'close' => $rule['end'],
429 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
432 $stack->push( $piece );
433 $accum =& $stack->getAccum();
434 extract( $stack->getFlags() );
436 # Add literal brace(s)
437 $accum->addLiteral( str_repeat( $curChar, $count ) );
442 elseif ( $found == 'close' ) {
443 $piece = $stack->top
;
444 # lets check if there are enough characters for closing brace
445 $maxCount = $piece->count
;
446 $count = strspn( $text, $curChar, $i, $maxCount );
448 # check for maximum matching characters (if there are 5 closing
449 # characters, we will probably need only 3 - depending on the rules)
451 $rule = $rules[$piece->open
];
452 if ( $count > $rule['max'] ) {
453 # The specified maximum exists in the callback array, unless the caller
455 $matchingCount = $rule['max'];
457 # Count is less than the maximum
458 # Skip any gaps in the callback array to find the true largest match
459 # Need to use array_key_exists not isset because the callback can be null
460 $matchingCount = $count;
461 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
466 if ($matchingCount <= 0) {
467 # No matching element found in callback array
468 # Output a literal closing brace and continue
469 $accum->addLiteral( str_repeat( $curChar, $count ) );
473 $name = $rule['names'][$matchingCount];
474 if ( $name === null ) {
475 // No element, just literal text
476 $element = $piece->breakSyntax( $matchingCount );
477 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
480 # Note: $parts is already XML, does not need to be encoded further
481 $parts = $piece->parts
;
482 $titleAccum = $parts[0]->out
;
485 $element = new PPNode_Hash_Tree( $name );
487 # The invocation is at the start of the line if lineStart is set in
488 # the stack, and all opening brackets are used up.
489 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
490 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
492 $titleNode = new PPNode_Hash_Tree( 'title' );
493 $titleNode->firstChild
= $titleAccum->firstNode
;
494 $titleNode->lastChild
= $titleAccum->lastNode
;
495 $element->addChild( $titleNode );
497 foreach ( $parts as $partIndex => $part ) {
498 if ( isset( $part->eqpos
) ) {
501 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
502 if ( $node === $part->eqpos
) {
508 throw new MWException( __METHOD__
. ': eqpos not found' );
510 if ( $node->name
!== 'equals' ) {
511 throw new MWException( __METHOD__
.': eqpos is not equals' );
515 // Construct name node
516 $nameNode = new PPNode_Hash_Tree( 'name' );
517 if ( $lastNode !== false ) {
518 $lastNode->nextSibling
= false;
519 $nameNode->firstChild
= $part->out
->firstNode
;
520 $nameNode->lastChild
= $lastNode;
523 // Construct value node
524 $valueNode = new PPNode_Hash_Tree( 'value' );
525 if ( $equalsNode->nextSibling
!== false ) {
526 $valueNode->firstChild
= $equalsNode->nextSibling
;
527 $valueNode->lastChild
= $part->out
->lastNode
;
529 $partNode = new PPNode_Hash_Tree( 'part' );
530 $partNode->addChild( $nameNode );
531 $partNode->addChild( $equalsNode->firstChild
);
532 $partNode->addChild( $valueNode );
533 $element->addChild( $partNode );
535 $partNode = new PPNode_Hash_Tree( 'part' );
536 $nameNode = new PPNode_Hash_Tree( 'name' );
537 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
538 $valueNode = new PPNode_Hash_Tree( 'value' );
539 $valueNode->firstChild
= $part->out
->firstNode
;
540 $valueNode->lastChild
= $part->out
->lastNode
;
541 $partNode->addChild( $nameNode );
542 $partNode->addChild( $valueNode );
543 $element->addChild( $partNode );
548 # Advance input pointer
549 $i +
= $matchingCount;
553 $accum =& $stack->getAccum();
555 # Re-add the old stack element if it still has unmatched opening characters remaining
556 if ($matchingCount < $piece->count
) {
557 $piece->parts
= array( new PPDPart_Hash
);
558 $piece->count
-= $matchingCount;
559 # do we still qualify for any callback with remaining count?
560 $names = $rules[$piece->open
]['names'];
562 $enclosingAccum =& $accum;
563 while ( $piece->count
) {
564 if ( array_key_exists( $piece->count
, $names ) ) {
565 $stack->push( $piece );
566 $accum =& $stack->getAccum();
572 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
575 extract( $stack->getFlags() );
577 # Add XML element to the enclosing accumulator
578 if ( $element instanceof PPNode
) {
579 $accum->addNode( $element );
581 $accum->addAccum( $element );
585 elseif ( $found == 'pipe' ) {
586 $findEquals = true; // shortcut for getFlags()
588 $accum =& $stack->getAccum();
592 elseif ( $found == 'equals' ) {
593 $findEquals = false; // shortcut for getFlags()
594 $accum->addNodeWithText( 'equals', '=' );
595 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
600 # Output any remaining unclosed brackets
601 foreach ( $stack->stack
as $piece ) {
602 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
605 # Enable top-level headings
606 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
607 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
612 $rootNode = new PPNode_Hash_Tree( 'root' );
613 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
614 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
615 wfProfileOut( __METHOD__
);
621 * 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
;
631 class PPDStackElement_Hash
extends PPDStackElement
{
632 function __construct( $data = array() ) {
633 $this->partClass
= 'PPDPart_Hash';
634 parent
::__construct( $data );
638 * Get the accumulator that would result if the close is not found.
640 function breakSyntax( $openingCount = false ) {
641 if ( $this->open
== "\n" ) {
642 $accum = $this->parts
[0]->out
;
644 if ( $openingCount === false ) {
645 $openingCount = $this->count
;
647 $accum = new PPDAccum_Hash
;
648 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
650 foreach ( $this->parts
as $part ) {
654 $accum->addLiteral( '|' );
656 $accum->addAccum( $part->out
);
663 class PPDPart_Hash
extends PPDPart
{
664 function __construct( $out = '' ) {
665 $accum = new PPDAccum_Hash
;
667 $accum->addLiteral( $out );
669 parent
::__construct( $accum );
673 class PPDAccum_Hash
{
674 var $firstNode, $lastNode;
676 function __construct() {
677 $this->firstNode
= $this->lastNode
= false;
681 * Append a string literal
683 function addLiteral( $s ) {
684 if ( $this->lastNode
=== false ) {
685 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
686 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
687 $this->lastNode
->value
.= $s;
689 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
690 $this->lastNode
= $this->lastNode
->nextSibling
;
697 function addNode( PPNode
$node ) {
698 if ( $this->lastNode
=== false ) {
699 $this->firstNode
= $this->lastNode
= $node;
701 $this->lastNode
->nextSibling
= $node;
702 $this->lastNode
= $node;
707 * Append a tree node with text contents
709 function addNodeWithText( $name, $value ) {
710 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
711 $this->addNode( $node );
715 * Append a PPAccum_Hash
716 * Takes over ownership of the nodes in the source argument. These nodes may
717 * subsequently be modified, especially nextSibling.
719 function addAccum( $accum ) {
720 if ( $accum->lastNode
=== false ) {
722 } elseif ( $this->lastNode
=== false ) {
723 $this->firstNode
= $accum->firstNode
;
724 $this->lastNode
= $accum->lastNode
;
726 $this->lastNode
->nextSibling
= $accum->firstNode
;
727 $this->lastNode
= $accum->lastNode
;
733 * An expansion frame, used as a context to expand the result of preprocessToObj()
735 class PPFrame_Hash
implements PPFrame
{
736 var $preprocessor, $parser, $title;
740 * Hashtable listing templates which are disallowed for expansion in this frame,
741 * having been encountered previously in parent frames.
746 * Recursion depth of this frame, top = 0
752 * Construct a new preprocessor frame.
753 * @param Preprocessor $preprocessor The parent preprocessor
755 function __construct( $preprocessor ) {
756 $this->preprocessor
= $preprocessor;
757 $this->parser
= $preprocessor->parser
;
758 $this->title
= $this->parser
->mTitle
;
759 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
760 $this->loopCheckHash
= array();
765 * Create a new child frame
766 * $args is optionally a multi-root PPNode or array containing the template arguments
768 function newChild( $args = false, $title = false ) {
769 $namedArgs = array();
770 $numberedArgs = array();
771 if ( $title === false ) {
772 $title = $this->title
;
774 if ( $args !== false ) {
776 if ( $args instanceof PPNode_Hash_Array
) {
777 $args = $args->value
;
778 } elseif ( !is_array( $args ) ) {
779 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
781 foreach ( $args as $arg ) {
782 $bits = $arg->splitArg();
783 if ( $bits['index'] !== '' ) {
784 // Numbered parameter
785 $numberedArgs[$bits['index']] = $bits['value'];
786 unset( $namedArgs[$bits['index']] );
789 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
790 $namedArgs[$name] = $bits['value'];
791 unset( $numberedArgs[$name] );
795 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
798 function expand( $root, $flags = 0 ) {
799 if ( is_string( $root ) ) {
803 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
805 return '<span class="error">Node-count limit exceeded</span>';
808 $outStack = array( '', '' );
809 $iteratorStack = array( false, $root );
810 $indexStack = array( 0, 0 );
812 while ( count( $iteratorStack ) > 1 ) {
813 $level = count( $outStack ) - 1;
814 $iteratorNode =& $iteratorStack[ $level ];
815 $out =& $outStack[$level];
816 $index =& $indexStack[$level];
818 if ( is_array( $iteratorNode ) ) {
819 if ( $index >= count( $iteratorNode ) ) {
820 // All done with this iterator
821 $iteratorStack[$level] = false;
822 $contextNode = false;
824 $contextNode = $iteratorNode[$index];
827 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
828 if ( $index >= $iteratorNode->getLength() ) {
829 // All done with this iterator
830 $iteratorStack[$level] = false;
831 $contextNode = false;
833 $contextNode = $iteratorNode->item( $index );
837 // Copy to $contextNode and then delete from iterator stack,
838 // because this is not an iterator but we do have to execute it once
839 $contextNode = $iteratorStack[$level];
840 $iteratorStack[$level] = false;
843 $newIterator = false;
845 if ( $contextNode === false ) {
847 } elseif ( is_string( $contextNode ) ) {
848 $out .= $contextNode;
849 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
850 $newIterator = $contextNode;
851 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
853 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
854 $out .= $contextNode->value
;
855 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
856 if ( $contextNode->name
== 'template' ) {
857 # Double-brace expansion
858 $bits = $contextNode->splitTemplate();
859 if ( $flags & self
::NO_TEMPLATES
) {
860 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
862 $ret = $this->parser
->braceSubstitution( $bits, $this );
863 if ( isset( $ret['object'] ) ) {
864 $newIterator = $ret['object'];
866 $out .= $ret['text'];
869 } elseif ( $contextNode->name
== 'tplarg' ) {
870 # Triple-brace expansion
871 $bits = $contextNode->splitTemplate();
872 if ( $flags & self
::NO_ARGS
) {
873 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
875 $ret = $this->parser
->argSubstitution( $bits, $this );
876 if ( isset( $ret['object'] ) ) {
877 $newIterator = $ret['object'];
879 $out .= $ret['text'];
882 } elseif ( $contextNode->name
== 'comment' ) {
884 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
885 if ( $this->parser
->ot
['html']
886 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
887 ||
( $flags & self
::STRIP_COMMENTS
) )
891 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
892 # Not in RECOVER_COMMENTS mode (extractSections) though
893 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
894 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
896 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
898 $out .= $contextNode->firstChild
->value
;
900 } elseif ( $contextNode->name
== 'ignore' ) {
901 # Output suppression used by <includeonly> etc.
902 # OT_WIKI will only respect <ignore> in substed templates.
903 # The other output types respect it unless NO_IGNORE is set.
904 # extractSections() sets NO_IGNORE and so never respects it.
905 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
906 $out .= $contextNode->firstChild
->value
;
910 } elseif ( $contextNode->name
== 'ext' ) {
912 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
913 $out .= $this->parser
->extensionSubstitution( $bits, $this );
914 } elseif ( $contextNode->name
== 'h' ) {
916 if ( $this->parser
->ot
['html'] ) {
917 # Expand immediately and insert heading index marker
919 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
920 $s .= $this->expand( $node, $flags );
923 $bits = $contextNode->splitHeading();
924 $titleText = $this->title
->getPrefixedDBkey();
925 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
926 $serial = count( $this->parser
->mHeadings
) - 1;
927 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
928 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
929 $this->parser
->mStripState
->general
->setPair( $marker, '' );
932 # Expand in virtual stack
933 $newIterator = $contextNode->getChildren();
936 # Generic recursive expansion
937 $newIterator = $contextNode->getChildren();
940 throw new MWException( __METHOD__
.': Invalid parameter type' );
943 if ( $newIterator !== false ) {
945 $iteratorStack[] = $newIterator;
947 } elseif ( $iteratorStack[$level] === false ) {
948 // Return accumulated value to parent
949 // With tail recursion
950 while ( $iteratorStack[$level] === false && $level > 0 ) {
951 $outStack[$level - 1] .= $out;
952 array_pop( $outStack );
953 array_pop( $iteratorStack );
954 array_pop( $indexStack );
962 function implodeWithFlags( $sep, $flags /*, ... */ ) {
963 $args = array_slice( func_get_args(), 2 );
967 foreach ( $args as $root ) {
968 if ( $root instanceof PPNode_Hash_Array
) {
969 $root = $root->value
;
971 if ( !is_array( $root ) ) {
972 $root = array( $root );
974 foreach ( $root as $node ) {
980 $s .= $this->expand( $node, $flags );
987 * Implode with no flags specified
988 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
990 function implode( $sep /*, ... */ ) {
991 $args = array_slice( func_get_args(), 1 );
995 foreach ( $args as $root ) {
996 if ( $root instanceof PPNode_Hash_Array
) {
997 $root = $root->value
;
999 if ( !is_array( $root ) ) {
1000 $root = array( $root );
1002 foreach ( $root as $node ) {
1008 $s .= $this->expand( $node );
1015 * Makes an object that, when expand()ed, will be the same as one obtained
1018 function virtualImplode( $sep /*, ... */ ) {
1019 $args = array_slice( func_get_args(), 1 );
1023 foreach ( $args as $root ) {
1024 if ( $root instanceof PPNode_Hash_Array
) {
1025 $root = $root->value
;
1027 if ( !is_array( $root ) ) {
1028 $root = array( $root );
1030 foreach ( $root as $node ) {
1039 return new PPNode_Hash_Array( $out );
1043 * Virtual implode with brackets
1045 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1046 $args = array_slice( func_get_args(), 3 );
1047 $out = array( $start );
1050 foreach ( $args as $root ) {
1051 if ( $root instanceof PPNode_Hash_Array
) {
1052 $root = $root->value
;
1054 if ( !is_array( $root ) ) {
1055 $root = array( $root );
1057 foreach ( $root as $node ) {
1067 return new PPNode_Hash_Array( $out );
1070 function __toString() {
1074 function getPDBK( $level = false ) {
1075 if ( $level === false ) {
1076 return $this->title
->getPrefixedDBkey();
1078 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1083 * Returns true if there are no arguments in this frame
1085 function isEmpty() {
1089 function getArgument( $name ) {
1094 * Returns true if the infinite loop check is OK, false if a loop is detected
1096 function loopCheck( $title ) {
1097 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1101 * Return true if the frame is a template frame
1103 function isTemplate() {
1109 * Expansion frame with template arguments
1111 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1112 var $numberedArgs, $namedArgs, $parent;
1113 var $numberedExpansionCache, $namedExpansionCache;
1115 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1116 $this->preprocessor
= $preprocessor;
1117 $this->parser
= $preprocessor->parser
;
1118 $this->parent
= $parent;
1119 $this->numberedArgs
= $numberedArgs;
1120 $this->namedArgs
= $namedArgs;
1121 $this->title
= $title;
1122 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1123 $this->titleCache
= $parent->titleCache
;
1124 $this->titleCache
[] = $pdbk;
1125 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1126 if ( $pdbk !== false ) {
1127 $this->loopCheckHash
[$pdbk] = true;
1129 $this->depth
= $parent->depth +
1;
1130 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1133 function __toString() {
1136 $args = $this->numberedArgs +
$this->namedArgs
;
1137 foreach ( $args as $name => $value ) {
1143 $s .= "\"$name\":\"" .
1144 str_replace( '"', '\\"', $value->__toString() ) . '"';
1150 * Returns true if there are no arguments in this frame
1152 function isEmpty() {
1153 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1156 function getNumberedArgument( $index ) {
1157 if ( !isset( $this->numberedArgs
[$index] ) ) {
1160 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1161 # No trimming for unnamed arguments
1162 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1164 return $this->numberedExpansionCache
[$index];
1167 function getNamedArgument( $name ) {
1168 if ( !isset( $this->namedArgs
[$name] ) ) {
1171 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1172 # Trim named arguments post-expand, for backwards compatibility
1173 $this->namedExpansionCache
[$name] = trim(
1174 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1176 return $this->namedExpansionCache
[$name];
1179 function getArgument( $name ) {
1180 $text = $this->getNumberedArgument( $name );
1181 if ( $text === false ) {
1182 $text = $this->getNamedArgument( $name );
1188 * Return true if the frame is a template frame
1190 function isTemplate() {
1195 class PPNode_Hash_Tree
implements PPNode
{
1196 var $name, $firstChild, $lastChild, $nextSibling;
1198 function __construct( $name ) {
1199 $this->name
= $name;
1200 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1203 function __toString() {
1206 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1207 if ( $node instanceof PPNode_Hash_Attr
) {
1208 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1210 $inner .= $node->__toString();
1213 if ( $inner === '' ) {
1214 return "<{$this->name}$attribs/>";
1216 return "<{$this->name}$attribs>$inner</{$this->name}>";
1220 function newWithText( $name, $text ) {
1221 $obj = new self( $name );
1222 $obj->addChild( new PPNode_Hash_Text( $text ) );
1226 function addChild( $node ) {
1227 if ( $this->lastChild
=== false ) {
1228 $this->firstChild
= $this->lastChild
= $node;
1230 $this->lastChild
->nextSibling
= $node;
1231 $this->lastChild
= $node;
1235 function getChildren() {
1236 $children = array();
1237 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1238 $children[] = $child;
1240 return new PPNode_Hash_Array( $children );
1243 function getFirstChild() {
1244 return $this->firstChild
;
1247 function getNextSibling() {
1248 return $this->nextSibling
;
1251 function getChildrenOfType( $name ) {
1252 $children = array();
1253 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1254 if ( isset( $child->name
) && $child->name
=== $name ) {
1255 $children[] = $name;
1261 function getLength() { return false; }
1262 function item( $i ) { return false; }
1264 function getName() {
1269 * Split a <part> node into an associative array containing:
1271 * index String index
1272 * value PPNode value
1274 function splitArg() {
1276 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1277 if ( !isset( $child->name
) ) {
1280 if ( $child->name
=== 'name' ) {
1281 $bits['name'] = $child;
1282 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1283 && $child->firstChild
->name
=== 'index' )
1285 $bits['index'] = $child->firstChild
->value
;
1287 } elseif ( $child->name
=== 'value' ) {
1288 $bits['value'] = $child;
1292 if ( !isset( $bits['name'] ) ) {
1293 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1295 if ( !isset( $bits['index'] ) ) {
1296 $bits['index'] = '';
1302 * Split an <ext> node into an associative array containing name, attr, inner and close
1303 * All values in the resulting array are PPNodes. Inner and close are optional.
1305 function splitExt() {
1307 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1308 if ( !isset( $child->name
) ) {
1311 if ( $child->name
== 'name' ) {
1312 $bits['name'] = $child;
1313 } elseif ( $child->name
== 'attr' ) {
1314 $bits['attr'] = $child;
1315 } elseif ( $child->name
== 'inner' ) {
1316 $bits['inner'] = $child;
1317 } elseif ( $child->name
== 'close' ) {
1318 $bits['close'] = $child;
1321 if ( !isset( $bits['name'] ) ) {
1322 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1330 function splitHeading() {
1331 if ( $this->name
!== 'h' ) {
1332 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1335 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1336 if ( !isset( $child->name
) ) {
1339 if ( $child->name
== 'i' ) {
1340 $bits['i'] = $child->value
;
1341 } elseif ( $child->name
== 'level' ) {
1342 $bits['level'] = $child->value
;
1345 if ( !isset( $bits['i'] ) ) {
1346 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1352 * Split a <template> or <tplarg> node
1354 function splitTemplate() {
1355 wfDebug( 'Template: ' . var_export( $this, true ) );
1357 $bits = array( 'lineStart' => '' );
1358 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1359 wfDebug( 'Child: ' . var_export( $child, true ) );
1360 if ( !isset( $child->name
) ) {
1363 if ( $child->name
== 'title' ) {
1364 $bits['title'] = $child;
1366 if ( $child->name
== 'part' ) {
1369 if ( $child->name
== 'lineStart' ) {
1370 $bits['lineStart'] = '1';
1373 if ( !isset( $bits['title'] ) ) {
1374 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1376 $bits['parts'] = new PPNode_Hash_Array( $parts );
1381 class PPNode_Hash_Text
implements PPNode
{
1382 var $value, $nextSibling;
1384 function __construct( $value ) {
1385 if ( is_object( $value ) ) {
1386 throw new MWException( __CLASS__
. ' given object instead of string' );
1388 $this->value
= $value;
1391 function __toString() {
1392 return htmlspecialchars( $this->value
);
1395 function getNextSibling() {
1396 return $this->nextSibling
;
1399 function getChildren() { return false; }
1400 function getFirstChild() { return false; }
1401 function getChildrenOfType( $name ) { return false; }
1402 function getLength() { return false; }
1403 function item( $i ) { return false; }
1404 function getName() { return '#text'; }
1405 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1406 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1407 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1410 class PPNode_Hash_Array
implements PPNode
{
1411 var $value, $nextSibling;
1413 function __construct( $value ) {
1414 $this->value
= $value;
1417 function __toString() {
1418 return var_export( $this, true );
1421 function getLength() {
1422 return count( $this->value
);
1425 function item( $i ) {
1426 return $this->value
[$i];
1429 function getName() { return '#nodelist'; }
1431 function getNextSibling() {
1432 return $this->nextSibling
;
1435 function getChildren() { return false; }
1436 function getFirstChild() { return false; }
1437 function getChildrenOfType( $name ) { return false; }
1438 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1439 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1440 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1443 class PPNode_Hash_Attr
implements PPNode
{
1444 var $name, $value, $nextSibling;
1446 function __construct( $name, $value ) {
1447 $this->name
= $name;
1448 $this->value
= $value;
1451 function __toString() {
1452 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1455 function getName() {
1459 function getNextSibling() {
1460 return $this->nextSibling
;
1463 function getChildren() { return false; }
1464 function getFirstChild() { return false; }
1465 function getChildrenOfType( $name ) { return false; }
1466 function getLength() { return false; }
1467 function item( $i ) { return false; }
1468 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1469 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1470 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }