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>';
807 if ( $depth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
808 return '<span class="error">Expansion depth limit exceeded</span>';
812 $outStack = array( '', '' );
813 $iteratorStack = array( false, $root );
814 $indexStack = array( 0, 0 );
816 while ( count( $iteratorStack ) > 1 ) {
817 $level = count( $outStack ) - 1;
818 $iteratorNode =& $iteratorStack[ $level ];
819 $out =& $outStack[$level];
820 $index =& $indexStack[$level];
822 if ( is_array( $iteratorNode ) ) {
823 if ( $index >= count( $iteratorNode ) ) {
824 // All done with this iterator
825 $iteratorStack[$level] = false;
826 $contextNode = false;
828 $contextNode = $iteratorNode[$index];
831 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
832 if ( $index >= $iteratorNode->getLength() ) {
833 // All done with this iterator
834 $iteratorStack[$level] = false;
835 $contextNode = false;
837 $contextNode = $iteratorNode->item( $index );
841 // Copy to $contextNode and then delete from iterator stack,
842 // because this is not an iterator but we do have to execute it once
843 $contextNode = $iteratorStack[$level];
844 $iteratorStack[$level] = false;
847 $newIterator = false;
849 if ( $contextNode === false ) {
851 } elseif ( is_string( $contextNode ) ) {
852 $out .= $contextNode;
853 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
854 $newIterator = $contextNode;
855 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
857 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
858 $out .= $contextNode->value
;
859 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
860 if ( $contextNode->name
== 'template' ) {
861 # Double-brace expansion
862 $bits = $contextNode->splitTemplate();
863 if ( $flags & self
::NO_TEMPLATES
) {
864 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
866 $ret = $this->parser
->braceSubstitution( $bits, $this );
867 if ( isset( $ret['object'] ) ) {
868 $newIterator = $ret['object'];
870 $out .= $ret['text'];
873 } elseif ( $contextNode->name
== 'tplarg' ) {
874 # Triple-brace expansion
875 $bits = $contextNode->splitTemplate();
876 if ( $flags & self
::NO_ARGS
) {
877 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
879 $ret = $this->parser
->argSubstitution( $bits, $this );
880 if ( isset( $ret['object'] ) ) {
881 $newIterator = $ret['object'];
883 $out .= $ret['text'];
886 } elseif ( $contextNode->name
== 'comment' ) {
888 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
889 if ( $this->parser
->ot
['html']
890 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
891 ||
( $flags & self
::STRIP_COMMENTS
) )
895 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
896 # Not in RECOVER_COMMENTS mode (extractSections) though
897 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
898 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
900 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
902 $out .= $contextNode->firstChild
->value
;
904 } elseif ( $contextNode->name
== 'ignore' ) {
905 # Output suppression used by <includeonly> etc.
906 # OT_WIKI will only respect <ignore> in substed templates.
907 # The other output types respect it unless NO_IGNORE is set.
908 # extractSections() sets NO_IGNORE and so never respects it.
909 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
910 $out .= $contextNode->firstChild
->value
;
914 } elseif ( $contextNode->name
== 'ext' ) {
916 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
917 $out .= $this->parser
->extensionSubstitution( $bits, $this );
918 } elseif ( $contextNode->name
== 'h' ) {
920 if ( $this->parser
->ot
['html'] ) {
921 # Expand immediately and insert heading index marker
923 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
924 $s .= $this->expand( $node, $flags );
927 $bits = $contextNode->splitHeading();
928 $titleText = $this->title
->getPrefixedDBkey();
929 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
930 $serial = count( $this->parser
->mHeadings
) - 1;
931 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
932 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
933 $this->parser
->mStripState
->general
->setPair( $marker, '' );
936 # Expand in virtual stack
937 $newIterator = $contextNode->getChildren();
940 # Generic recursive expansion
941 $newIterator = $contextNode->getChildren();
944 throw new MWException( __METHOD__
.': Invalid parameter type' );
947 if ( $newIterator !== false ) {
949 $iteratorStack[] = $newIterator;
951 } elseif ( $iteratorStack[$level] === false ) {
952 // Return accumulated value to parent
953 // With tail recursion
954 while ( $iteratorStack[$level] === false && $level > 0 ) {
955 $outStack[$level - 1] .= $out;
956 array_pop( $outStack );
957 array_pop( $iteratorStack );
958 array_pop( $indexStack );
967 function implodeWithFlags( $sep, $flags /*, ... */ ) {
968 $args = array_slice( func_get_args(), 2 );
972 foreach ( $args as $root ) {
973 if ( $root instanceof PPNode_Hash_Array
) {
974 $root = $root->value
;
976 if ( !is_array( $root ) ) {
977 $root = array( $root );
979 foreach ( $root as $node ) {
985 $s .= $this->expand( $node, $flags );
992 * Implode with no flags specified
993 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
995 function implode( $sep /*, ... */ ) {
996 $args = array_slice( func_get_args(), 1 );
1000 foreach ( $args as $root ) {
1001 if ( $root instanceof PPNode_Hash_Array
) {
1002 $root = $root->value
;
1004 if ( !is_array( $root ) ) {
1005 $root = array( $root );
1007 foreach ( $root as $node ) {
1013 $s .= $this->expand( $node );
1020 * Makes an object that, when expand()ed, will be the same as one obtained
1023 function virtualImplode( $sep /*, ... */ ) {
1024 $args = array_slice( func_get_args(), 1 );
1028 foreach ( $args as $root ) {
1029 if ( $root instanceof PPNode_Hash_Array
) {
1030 $root = $root->value
;
1032 if ( !is_array( $root ) ) {
1033 $root = array( $root );
1035 foreach ( $root as $node ) {
1044 return new PPNode_Hash_Array( $out );
1048 * Virtual implode with brackets
1050 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1051 $args = array_slice( func_get_args(), 3 );
1052 $out = array( $start );
1055 foreach ( $args as $root ) {
1056 if ( $root instanceof PPNode_Hash_Array
) {
1057 $root = $root->value
;
1059 if ( !is_array( $root ) ) {
1060 $root = array( $root );
1062 foreach ( $root as $node ) {
1072 return new PPNode_Hash_Array( $out );
1075 function __toString() {
1079 function getPDBK( $level = false ) {
1080 if ( $level === false ) {
1081 return $this->title
->getPrefixedDBkey();
1083 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1088 * Returns true if there are no arguments in this frame
1090 function isEmpty() {
1094 function getArgument( $name ) {
1099 * Returns true if the infinite loop check is OK, false if a loop is detected
1101 function loopCheck( $title ) {
1102 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1106 * Return true if the frame is a template frame
1108 function isTemplate() {
1114 * Expansion frame with template arguments
1116 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1117 var $numberedArgs, $namedArgs, $parent;
1118 var $numberedExpansionCache, $namedExpansionCache;
1120 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1121 $this->preprocessor
= $preprocessor;
1122 $this->parser
= $preprocessor->parser
;
1123 $this->parent
= $parent;
1124 $this->numberedArgs
= $numberedArgs;
1125 $this->namedArgs
= $namedArgs;
1126 $this->title
= $title;
1127 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1128 $this->titleCache
= $parent->titleCache
;
1129 $this->titleCache
[] = $pdbk;
1130 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1131 if ( $pdbk !== false ) {
1132 $this->loopCheckHash
[$pdbk] = true;
1134 $this->depth
= $parent->depth +
1;
1135 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1138 function __toString() {
1141 $args = $this->numberedArgs +
$this->namedArgs
;
1142 foreach ( $args as $name => $value ) {
1148 $s .= "\"$name\":\"" .
1149 str_replace( '"', '\\"', $value->__toString() ) . '"';
1155 * Returns true if there are no arguments in this frame
1157 function isEmpty() {
1158 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1161 function getNumberedArgument( $index ) {
1162 if ( !isset( $this->numberedArgs
[$index] ) ) {
1165 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1166 # No trimming for unnamed arguments
1167 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1169 return $this->numberedExpansionCache
[$index];
1172 function getNamedArgument( $name ) {
1173 if ( !isset( $this->namedArgs
[$name] ) ) {
1176 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1177 # Trim named arguments post-expand, for backwards compatibility
1178 $this->namedExpansionCache
[$name] = trim(
1179 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1181 return $this->namedExpansionCache
[$name];
1184 function getArgument( $name ) {
1185 $text = $this->getNumberedArgument( $name );
1186 if ( $text === false ) {
1187 $text = $this->getNamedArgument( $name );
1193 * Return true if the frame is a template frame
1195 function isTemplate() {
1200 class PPNode_Hash_Tree
implements PPNode
{
1201 var $name, $firstChild, $lastChild, $nextSibling;
1203 function __construct( $name ) {
1204 $this->name
= $name;
1205 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1208 function __toString() {
1211 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1212 if ( $node instanceof PPNode_Hash_Attr
) {
1213 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1215 $inner .= $node->__toString();
1218 if ( $inner === '' ) {
1219 return "<{$this->name}$attribs/>";
1221 return "<{$this->name}$attribs>$inner</{$this->name}>";
1225 function newWithText( $name, $text ) {
1226 $obj = new self( $name );
1227 $obj->addChild( new PPNode_Hash_Text( $text ) );
1231 function addChild( $node ) {
1232 if ( $this->lastChild
=== false ) {
1233 $this->firstChild
= $this->lastChild
= $node;
1235 $this->lastChild
->nextSibling
= $node;
1236 $this->lastChild
= $node;
1240 function getChildren() {
1241 $children = array();
1242 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1243 $children[] = $child;
1245 return new PPNode_Hash_Array( $children );
1248 function getFirstChild() {
1249 return $this->firstChild
;
1252 function getNextSibling() {
1253 return $this->nextSibling
;
1256 function getChildrenOfType( $name ) {
1257 $children = array();
1258 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1259 if ( isset( $child->name
) && $child->name
=== $name ) {
1260 $children[] = $name;
1266 function getLength() { return false; }
1267 function item( $i ) { return false; }
1269 function getName() {
1274 * Split a <part> node into an associative array containing:
1276 * index String index
1277 * value PPNode value
1279 function splitArg() {
1281 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1282 if ( !isset( $child->name
) ) {
1285 if ( $child->name
=== 'name' ) {
1286 $bits['name'] = $child;
1287 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1288 && $child->firstChild
->name
=== 'index' )
1290 $bits['index'] = $child->firstChild
->value
;
1292 } elseif ( $child->name
=== 'value' ) {
1293 $bits['value'] = $child;
1297 if ( !isset( $bits['name'] ) ) {
1298 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1300 if ( !isset( $bits['index'] ) ) {
1301 $bits['index'] = '';
1307 * Split an <ext> node into an associative array containing name, attr, inner and close
1308 * All values in the resulting array are PPNodes. Inner and close are optional.
1310 function splitExt() {
1312 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1313 if ( !isset( $child->name
) ) {
1316 if ( $child->name
== 'name' ) {
1317 $bits['name'] = $child;
1318 } elseif ( $child->name
== 'attr' ) {
1319 $bits['attr'] = $child;
1320 } elseif ( $child->name
== 'inner' ) {
1321 $bits['inner'] = $child;
1322 } elseif ( $child->name
== 'close' ) {
1323 $bits['close'] = $child;
1326 if ( !isset( $bits['name'] ) ) {
1327 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1335 function splitHeading() {
1336 if ( $this->name
!== 'h' ) {
1337 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1340 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1341 if ( !isset( $child->name
) ) {
1344 if ( $child->name
== 'i' ) {
1345 $bits['i'] = $child->value
;
1346 } elseif ( $child->name
== 'level' ) {
1347 $bits['level'] = $child->value
;
1350 if ( !isset( $bits['i'] ) ) {
1351 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1357 * Split a <template> or <tplarg> node
1359 function splitTemplate() {
1360 wfDebug( 'Template: ' . var_export( $this, true ) );
1362 $bits = array( 'lineStart' => '' );
1363 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1364 wfDebug( 'Child: ' . var_export( $child, true ) );
1365 if ( !isset( $child->name
) ) {
1368 if ( $child->name
== 'title' ) {
1369 $bits['title'] = $child;
1371 if ( $child->name
== 'part' ) {
1374 if ( $child->name
== 'lineStart' ) {
1375 $bits['lineStart'] = '1';
1378 if ( !isset( $bits['title'] ) ) {
1379 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1381 $bits['parts'] = new PPNode_Hash_Array( $parts );
1386 class PPNode_Hash_Text
implements PPNode
{
1387 var $value, $nextSibling;
1389 function __construct( $value ) {
1390 if ( is_object( $value ) ) {
1391 throw new MWException( __CLASS__
. ' given object instead of string' );
1393 $this->value
= $value;
1396 function __toString() {
1397 return htmlspecialchars( $this->value
);
1400 function getNextSibling() {
1401 return $this->nextSibling
;
1404 function getChildren() { return false; }
1405 function getFirstChild() { return false; }
1406 function getChildrenOfType( $name ) { return false; }
1407 function getLength() { return false; }
1408 function item( $i ) { return false; }
1409 function getName() { return '#text'; }
1410 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1411 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1412 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1415 class PPNode_Hash_Array
implements PPNode
{
1416 var $value, $nextSibling;
1418 function __construct( $value ) {
1419 $this->value
= $value;
1422 function __toString() {
1423 return var_export( $this, true );
1426 function getLength() {
1427 return count( $this->value
);
1430 function item( $i ) {
1431 return $this->value
[$i];
1434 function getName() { return '#nodelist'; }
1436 function getNextSibling() {
1437 return $this->nextSibling
;
1440 function getChildren() { return false; }
1441 function getFirstChild() { return false; }
1442 function getChildrenOfType( $name ) { return false; }
1443 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1444 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1445 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1448 class PPNode_Hash_Attr
implements PPNode
{
1449 var $name, $value, $nextSibling;
1451 function __construct( $name, $value ) {
1452 $this->name
= $name;
1453 $this->value
= $value;
1456 function __toString() {
1457 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1460 function getName() {
1464 function getNextSibling() {
1465 return $this->nextSibling
;
1468 function getChildren() { return false; }
1469 function getFirstChild() { return false; }
1470 function getChildrenOfType( $name ) { return false; }
1471 function getLength() { return false; }
1472 function item( $i ) { return false; }
1473 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1474 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1475 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }