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__
);
50 $cacheKey = wfMemckey( 'preprocessor-hash', md5( $text ), $flags );
52 if ( $obj = $wgMemc->get( $cacheKey ) ) {
53 wfDebugLog( "Preprocessor", "Got preprocessor_hash output from cache" );
54 wfProfileOut( __METHOD__
);
70 'names' => array( 2 => null ),
76 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
78 $xmlishElements = $this->parser
->getStripList();
79 $enableOnlyinclude = false;
80 if ( $forInclusion ) {
81 $ignoredTags = array( 'includeonly', '/includeonly' );
82 $ignoredElements = array( 'noinclude' );
83 $xmlishElements[] = 'noinclude';
84 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
85 $enableOnlyinclude = true;
88 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
89 $ignoredElements = array( 'includeonly' );
90 $xmlishElements[] = 'includeonly';
92 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
94 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
95 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
97 $stack = new PPDStack_Hash
;
99 $searchBase = "[{<\n";
100 $revText = strrev( $text ); // For fast reverse searches
102 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
103 $accum =& $stack->getAccum(); # Current accumulator
104 $findEquals = false; # True to find equals signs in arguments
105 $findPipe = false; # True to take notice of pipe characters
107 $inHeading = false; # True if $i is inside a possible heading
108 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
109 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
110 $fakeLineStart = true; # Do a line-start run without outputting an LF character
115 if ( $findOnlyinclude ) {
116 // Ignore all input up to the next <onlyinclude>
117 $startPos = strpos( $text, '<onlyinclude>', $i );
118 if ( $startPos === false ) {
119 // Ignored section runs to the end
120 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
123 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
124 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
126 $findOnlyinclude = false;
129 if ( $fakeLineStart ) {
130 $found = 'line-start';
133 # Find next opening brace, closing brace or pipe
134 $search = $searchBase;
135 if ( $stack->top
=== false ) {
136 $currentClosing = '';
138 $currentClosing = $stack->top
->close
;
139 $search .= $currentClosing;
145 // First equals will be for the template
149 # Output literal section, advance input counter
150 $literalLength = strcspn( $text, $search, $i );
151 if ( $literalLength > 0 ) {
152 $accum->addLiteral( substr( $text, $i, $literalLength ) );
153 $i +
= $literalLength;
155 if ( $i >= strlen( $text ) ) {
156 if ( $currentClosing == "\n" ) {
157 // Do a past-the-end run to finish off the heading
165 $curChar = $text[$i];
166 if ( $curChar == '|' ) {
168 } elseif ( $curChar == '=' ) {
170 } elseif ( $curChar == '<' ) {
172 } elseif ( $curChar == "\n" ) {
176 $found = 'line-start';
178 } elseif ( $curChar == $currentClosing ) {
180 } elseif ( isset( $rules[$curChar] ) ) {
182 $rule = $rules[$curChar];
184 # Some versions of PHP have a strcspn which stops on null characters
185 # Ignore and continue
192 if ( $found == 'angle' ) {
194 // Handle </onlyinclude>
195 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
196 $findOnlyinclude = true;
200 // Determine element name
201 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
202 // Element name missing or not listed
203 $accum->addLiteral( '<' );
208 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
209 // To avoid leaving blank lines, when a comment is both preceded
210 // and followed by a newline (ignoring spaces), trim leading and
211 // trailing spaces and one of the newlines.
214 $endPos = strpos( $text, '-->', $i +
4 );
215 if ( $endPos === false ) {
216 // Unclosed comment in input, runs to end
217 $inner = substr( $text, $i );
218 $accum->addNodeWithText( 'comment', $inner );
219 $i = strlen( $text );
221 // Search backwards for leading whitespace
222 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
223 // Search forwards for trailing whitespace
224 // $wsEnd will be the position of the last space
225 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
226 // Eat the line if possible
227 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
228 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
229 // it's a possible beneficial b/c break.
230 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
231 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
233 $startPos = $wsStart;
234 $endPos = $wsEnd +
1;
235 // Remove leading whitespace from the end of the accumulator
236 // Sanity check first though
237 $wsLength = $i - $wsStart;
239 && $accum->lastNode
instanceof PPNode_Hash_Text
240 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
242 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
244 // Do a line-start run next time to look for headings after the comment
245 $fakeLineStart = true;
247 // No line to eat, just take the comment itself
253 $part = $stack->top
->getCurrentPart();
254 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
255 // Comments abutting, no change in visual end
256 $part->commentEnd
= $wsEnd;
258 $part->visualEnd
= $wsStart;
259 $part->commentEnd
= $endPos;
263 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
264 $accum->addNodeWithText( 'comment', $inner );
269 $lowerName = strtolower( $name );
270 $attrStart = $i +
strlen( $name ) +
1;
273 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
274 if ( $tagEndPos === false ) {
275 // Infinite backtrack
276 // Disable tag search to prevent worst-case O(N^2) performance
278 $accum->addLiteral( '<' );
283 // Handle ignored tags
284 if ( in_array( $lowerName, $ignoredTags ) ) {
285 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
291 if ( $text[$tagEndPos-1] == '/' ) {
293 $attrEnd = $tagEndPos - 1;
298 $attrEnd = $tagEndPos;
300 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
301 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
303 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
304 $i = $matches[0][1] +
strlen( $matches[0][0] );
305 $close = $matches[0][0];
307 // No end tag -- let it run out to the end of the text.
308 $inner = substr( $text, $tagEndPos +
1 );
309 $i = strlen( $text );
313 // <includeonly> and <noinclude> just become <ignore> tags
314 if ( in_array( $lowerName, $ignoredElements ) ) {
315 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
319 if ( $attrEnd <= $attrStart ) {
322 // Note that the attr element contains the whitespace between name and attribute,
323 // this is necessary for precise reconstruction during pre-save transform.
324 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
327 $extNode = new PPNode_Hash_Tree( 'ext' );
328 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
329 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
330 if ( $inner !== null ) {
331 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
333 if ( $close !== null ) {
334 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
336 $accum->addNode( $extNode );
339 elseif ( $found == 'line-start' ) {
340 // Is this the start of a heading?
341 // Line break belongs before the heading element in any case
342 if ( $fakeLineStart ) {
343 $fakeLineStart = false;
345 $accum->addLiteral( $curChar );
349 $count = strspn( $text, '=', $i, 6 );
350 if ( $count == 1 && $findEquals ) {
351 // DWIM: This looks kind of like a name/value separator
352 // Let's let the equals handler have it and break the potential heading
353 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
354 } elseif ( $count > 0 ) {
358 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
361 $stack->push( $piece );
362 $accum =& $stack->getAccum();
363 extract( $stack->getFlags() );
368 elseif ( $found == 'line-end' ) {
369 $piece = $stack->top
;
370 // A heading must be open, otherwise \n wouldn't have been in the search list
371 assert( $piece->open
== "\n" );
372 $part = $piece->getCurrentPart();
373 // Search back through the input to see if it has a proper close
374 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
375 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
376 $searchStart = $i - $wsLength;
377 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
378 // Comment found at line end
379 // Search for equals signs before the comment
380 $searchStart = $part->visualEnd
;
381 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
383 $count = $piece->count
;
384 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
385 if ( $equalsLength > 0 ) {
386 if ( $i - $equalsLength == $piece->startPos
) {
387 // This is just a single string of equals signs on its own line
388 // Replicate the doHeadings behaviour /={count}(.+)={count}/
389 // First find out how many equals signs there really are (don't stop at 6)
390 $count = $equalsLength;
394 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
397 $count = min( $equalsLength, $count );
400 // Normal match, output <h>
401 $element = new PPNode_Hash_Tree( 'possible-h' );
402 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
403 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
404 $element->lastChild
->nextSibling
= $accum->firstNode
;
405 $element->lastChild
= $accum->lastNode
;
407 // Single equals sign on its own line, count=0
411 // No match, no <h>, just pass down the inner text
416 $accum =& $stack->getAccum();
417 extract( $stack->getFlags() );
419 // Append the result to the enclosing accumulator
420 if ( $element instanceof PPNode
) {
421 $accum->addNode( $element );
423 $accum->addAccum( $element );
425 // Note that we do NOT increment the input pointer.
426 // This is because the closing linebreak could be the opening linebreak of
427 // another heading. Infinite loops are avoided because the next iteration MUST
428 // hit the heading open case above, which unconditionally increments the
432 elseif ( $found == 'open' ) {
433 # count opening brace characters
434 $count = strspn( $text, $curChar, $i );
436 # we need to add to stack only if opening brace count is enough for one of the rules
437 if ( $count >= $rule['min'] ) {
438 # Add it to the stack
441 'close' => $rule['end'],
443 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
446 $stack->push( $piece );
447 $accum =& $stack->getAccum();
448 extract( $stack->getFlags() );
450 # Add literal brace(s)
451 $accum->addLiteral( str_repeat( $curChar, $count ) );
456 elseif ( $found == 'close' ) {
457 $piece = $stack->top
;
458 # lets check if there are enough characters for closing brace
459 $maxCount = $piece->count
;
460 $count = strspn( $text, $curChar, $i, $maxCount );
462 # check for maximum matching characters (if there are 5 closing
463 # characters, we will probably need only 3 - depending on the rules)
465 $rule = $rules[$piece->open
];
466 if ( $count > $rule['max'] ) {
467 # The specified maximum exists in the callback array, unless the caller
469 $matchingCount = $rule['max'];
471 # Count is less than the maximum
472 # Skip any gaps in the callback array to find the true largest match
473 # Need to use array_key_exists not isset because the callback can be null
474 $matchingCount = $count;
475 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
480 if ($matchingCount <= 0) {
481 # No matching element found in callback array
482 # Output a literal closing brace and continue
483 $accum->addLiteral( str_repeat( $curChar, $count ) );
487 $name = $rule['names'][$matchingCount];
488 if ( $name === null ) {
489 // No element, just literal text
490 $element = $piece->breakSyntax( $matchingCount );
491 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
494 # Note: $parts is already XML, does not need to be encoded further
495 $parts = $piece->parts
;
496 $titleAccum = $parts[0]->out
;
499 $element = new PPNode_Hash_Tree( $name );
501 # The invocation is at the start of the line if lineStart is set in
502 # the stack, and all opening brackets are used up.
503 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
504 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
506 $titleNode = new PPNode_Hash_Tree( 'title' );
507 $titleNode->firstChild
= $titleAccum->firstNode
;
508 $titleNode->lastChild
= $titleAccum->lastNode
;
509 $element->addChild( $titleNode );
511 foreach ( $parts as $partIndex => $part ) {
512 if ( isset( $part->eqpos
) ) {
515 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
516 if ( $node === $part->eqpos
) {
522 throw new MWException( __METHOD__
. ': eqpos not found' );
524 if ( $node->name
!== 'equals' ) {
525 throw new MWException( __METHOD__
.': eqpos is not equals' );
529 // Construct name node
530 $nameNode = new PPNode_Hash_Tree( 'name' );
531 if ( $lastNode !== false ) {
532 $lastNode->nextSibling
= false;
533 $nameNode->firstChild
= $part->out
->firstNode
;
534 $nameNode->lastChild
= $lastNode;
537 // Construct value node
538 $valueNode = new PPNode_Hash_Tree( 'value' );
539 if ( $equalsNode->nextSibling
!== false ) {
540 $valueNode->firstChild
= $equalsNode->nextSibling
;
541 $valueNode->lastChild
= $part->out
->lastNode
;
543 $partNode = new PPNode_Hash_Tree( 'part' );
544 $partNode->addChild( $nameNode );
545 $partNode->addChild( $equalsNode->firstChild
);
546 $partNode->addChild( $valueNode );
547 $element->addChild( $partNode );
549 $partNode = new PPNode_Hash_Tree( 'part' );
550 $nameNode = new PPNode_Hash_Tree( 'name' );
551 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
552 $valueNode = new PPNode_Hash_Tree( 'value' );
553 $valueNode->firstChild
= $part->out
->firstNode
;
554 $valueNode->lastChild
= $part->out
->lastNode
;
555 $partNode->addChild( $nameNode );
556 $partNode->addChild( $valueNode );
557 $element->addChild( $partNode );
562 # Advance input pointer
563 $i +
= $matchingCount;
567 $accum =& $stack->getAccum();
569 # Re-add the old stack element if it still has unmatched opening characters remaining
570 if ($matchingCount < $piece->count
) {
571 $piece->parts
= array( new PPDPart_Hash
);
572 $piece->count
-= $matchingCount;
573 # do we still qualify for any callback with remaining count?
574 $names = $rules[$piece->open
]['names'];
576 $enclosingAccum =& $accum;
577 while ( $piece->count
) {
578 if ( array_key_exists( $piece->count
, $names ) ) {
579 $stack->push( $piece );
580 $accum =& $stack->getAccum();
586 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
589 extract( $stack->getFlags() );
591 # Add XML element to the enclosing accumulator
592 if ( $element instanceof PPNode
) {
593 $accum->addNode( $element );
595 $accum->addAccum( $element );
599 elseif ( $found == 'pipe' ) {
600 $findEquals = true; // shortcut for getFlags()
602 $accum =& $stack->getAccum();
606 elseif ( $found == 'equals' ) {
607 $findEquals = false; // shortcut for getFlags()
608 $accum->addNodeWithText( 'equals', '=' );
609 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
614 # Output any remaining unclosed brackets
615 foreach ( $stack->stack
as $piece ) {
616 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
619 # Enable top-level headings
620 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
621 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
626 $rootNode = new PPNode_Hash_Tree( 'root' );
627 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
628 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
629 wfProfileOut( __METHOD__
);
631 $wgMemc->set( $cacheKey, $rootNode, 86400 );
638 * Stack class to help Preprocessor::preprocessToObj()
641 class PPDStack_Hash
extends PPDStack
{
642 function __construct() {
643 $this->elementClass
= 'PPDStackElement_Hash';
644 parent
::__construct();
645 $this->rootAccum
= new PPDAccum_Hash
;
652 class PPDStackElement_Hash
extends PPDStackElement
{
653 function __construct( $data = array() ) {
654 $this->partClass
= 'PPDPart_Hash';
655 parent
::__construct( $data );
659 * Get the accumulator that would result if the close is not found.
661 function breakSyntax( $openingCount = false ) {
662 if ( $this->open
== "\n" ) {
663 $accum = $this->parts
[0]->out
;
665 if ( $openingCount === false ) {
666 $openingCount = $this->count
;
668 $accum = new PPDAccum_Hash
;
669 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
671 foreach ( $this->parts
as $part ) {
675 $accum->addLiteral( '|' );
677 $accum->addAccum( $part->out
);
687 class PPDPart_Hash
extends PPDPart
{
688 function __construct( $out = '' ) {
689 $accum = new PPDAccum_Hash
;
691 $accum->addLiteral( $out );
693 parent
::__construct( $accum );
700 class PPDAccum_Hash
{
701 var $firstNode, $lastNode;
703 function __construct() {
704 $this->firstNode
= $this->lastNode
= false;
708 * Append a string literal
710 function addLiteral( $s ) {
711 if ( $this->lastNode
=== false ) {
712 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
713 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
714 $this->lastNode
->value
.= $s;
716 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
717 $this->lastNode
= $this->lastNode
->nextSibling
;
724 function addNode( PPNode
$node ) {
725 if ( $this->lastNode
=== false ) {
726 $this->firstNode
= $this->lastNode
= $node;
728 $this->lastNode
->nextSibling
= $node;
729 $this->lastNode
= $node;
734 * Append a tree node with text contents
736 function addNodeWithText( $name, $value ) {
737 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
738 $this->addNode( $node );
742 * Append a PPAccum_Hash
743 * Takes over ownership of the nodes in the source argument. These nodes may
744 * subsequently be modified, especially nextSibling.
746 function addAccum( $accum ) {
747 if ( $accum->lastNode
=== false ) {
749 } elseif ( $this->lastNode
=== false ) {
750 $this->firstNode
= $accum->firstNode
;
751 $this->lastNode
= $accum->lastNode
;
753 $this->lastNode
->nextSibling
= $accum->firstNode
;
754 $this->lastNode
= $accum->lastNode
;
760 * An expansion frame, used as a context to expand the result of preprocessToObj()
763 class PPFrame_Hash
implements PPFrame
{
764 var $preprocessor, $parser, $title;
768 * Hashtable listing templates which are disallowed for expansion in this frame,
769 * having been encountered previously in parent frames.
774 * Recursion depth of this frame, top = 0
775 * Note that this is NOT the same as expansion depth in expand()
781 * Construct a new preprocessor frame.
782 * @param Preprocessor $preprocessor The parent preprocessor
784 function __construct( $preprocessor ) {
785 $this->preprocessor
= $preprocessor;
786 $this->parser
= $preprocessor->parser
;
787 $this->title
= $this->parser
->mTitle
;
788 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
789 $this->loopCheckHash
= array();
794 * Create a new child frame
795 * $args is optionally a multi-root PPNode or array containing the template arguments
797 function newChild( $args = false, $title = false ) {
798 $namedArgs = array();
799 $numberedArgs = array();
800 if ( $title === false ) {
801 $title = $this->title
;
803 if ( $args !== false ) {
805 if ( $args instanceof PPNode_Hash_Array
) {
806 $args = $args->value
;
807 } elseif ( !is_array( $args ) ) {
808 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
810 foreach ( $args as $arg ) {
811 $bits = $arg->splitArg();
812 if ( $bits['index'] !== '' ) {
813 // Numbered parameter
814 $numberedArgs[$bits['index']] = $bits['value'];
815 unset( $namedArgs[$bits['index']] );
818 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
819 $namedArgs[$name] = $bits['value'];
820 unset( $numberedArgs[$name] );
824 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
827 function expand( $root, $flags = 0 ) {
828 static $expansionDepth = 0;
829 if ( is_string( $root ) ) {
833 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
835 return '<span class="error">Node-count limit exceeded</span>';
837 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
838 return '<span class="error">Expansion depth limit exceeded</span>';
842 $outStack = array( '', '' );
843 $iteratorStack = array( false, $root );
844 $indexStack = array( 0, 0 );
846 while ( count( $iteratorStack ) > 1 ) {
847 $level = count( $outStack ) - 1;
848 $iteratorNode =& $iteratorStack[ $level ];
849 $out =& $outStack[$level];
850 $index =& $indexStack[$level];
852 if ( is_array( $iteratorNode ) ) {
853 if ( $index >= count( $iteratorNode ) ) {
854 // All done with this iterator
855 $iteratorStack[$level] = false;
856 $contextNode = false;
858 $contextNode = $iteratorNode[$index];
861 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
862 if ( $index >= $iteratorNode->getLength() ) {
863 // All done with this iterator
864 $iteratorStack[$level] = false;
865 $contextNode = false;
867 $contextNode = $iteratorNode->item( $index );
871 // Copy to $contextNode and then delete from iterator stack,
872 // because this is not an iterator but we do have to execute it once
873 $contextNode = $iteratorStack[$level];
874 $iteratorStack[$level] = false;
877 $newIterator = false;
879 if ( $contextNode === false ) {
881 } elseif ( is_string( $contextNode ) ) {
882 $out .= $contextNode;
883 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
884 $newIterator = $contextNode;
885 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
887 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
888 $out .= $contextNode->value
;
889 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
890 if ( $contextNode->name
== 'template' ) {
891 # Double-brace expansion
892 $bits = $contextNode->splitTemplate();
893 if ( $flags & self
::NO_TEMPLATES
) {
894 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
896 $ret = $this->parser
->braceSubstitution( $bits, $this );
897 if ( isset( $ret['object'] ) ) {
898 $newIterator = $ret['object'];
900 $out .= $ret['text'];
903 } elseif ( $contextNode->name
== 'tplarg' ) {
904 # Triple-brace expansion
905 $bits = $contextNode->splitTemplate();
906 if ( $flags & self
::NO_ARGS
) {
907 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
909 $ret = $this->parser
->argSubstitution( $bits, $this );
910 if ( isset( $ret['object'] ) ) {
911 $newIterator = $ret['object'];
913 $out .= $ret['text'];
916 } elseif ( $contextNode->name
== 'comment' ) {
918 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
919 if ( $this->parser
->ot
['html']
920 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
921 ||
( $flags & self
::STRIP_COMMENTS
) )
925 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
926 # Not in RECOVER_COMMENTS mode (extractSections) though
927 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
928 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
930 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
932 $out .= $contextNode->firstChild
->value
;
934 } elseif ( $contextNode->name
== 'ignore' ) {
935 # Output suppression used by <includeonly> etc.
936 # OT_WIKI will only respect <ignore> in substed templates.
937 # The other output types respect it unless NO_IGNORE is set.
938 # extractSections() sets NO_IGNORE and so never respects it.
939 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
940 $out .= $contextNode->firstChild
->value
;
944 } elseif ( $contextNode->name
== 'ext' ) {
946 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
947 $out .= $this->parser
->extensionSubstitution( $bits, $this );
948 } elseif ( $contextNode->name
== 'h' ) {
950 if ( $this->parser
->ot
['html'] ) {
951 # Expand immediately and insert heading index marker
953 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
954 $s .= $this->expand( $node, $flags );
957 $bits = $contextNode->splitHeading();
958 $titleText = $this->title
->getPrefixedDBkey();
959 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
960 $serial = count( $this->parser
->mHeadings
) - 1;
961 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
962 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
963 $this->parser
->mStripState
->general
->setPair( $marker, '' );
966 # Expand in virtual stack
967 $newIterator = $contextNode->getChildren();
970 # Generic recursive expansion
971 $newIterator = $contextNode->getChildren();
974 throw new MWException( __METHOD__
.': Invalid parameter type' );
977 if ( $newIterator !== false ) {
979 $iteratorStack[] = $newIterator;
981 } elseif ( $iteratorStack[$level] === false ) {
982 // Return accumulated value to parent
983 // With tail recursion
984 while ( $iteratorStack[$level] === false && $level > 0 ) {
985 $outStack[$level - 1] .= $out;
986 array_pop( $outStack );
987 array_pop( $iteratorStack );
988 array_pop( $indexStack );
997 function implodeWithFlags( $sep, $flags /*, ... */ ) {
998 $args = array_slice( func_get_args(), 2 );
1002 foreach ( $args as $root ) {
1003 if ( $root instanceof PPNode_Hash_Array
) {
1004 $root = $root->value
;
1006 if ( !is_array( $root ) ) {
1007 $root = array( $root );
1009 foreach ( $root as $node ) {
1015 $s .= $this->expand( $node, $flags );
1022 * Implode with no flags specified
1023 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1025 function implode( $sep /*, ... */ ) {
1026 $args = array_slice( func_get_args(), 1 );
1030 foreach ( $args as $root ) {
1031 if ( $root instanceof PPNode_Hash_Array
) {
1032 $root = $root->value
;
1034 if ( !is_array( $root ) ) {
1035 $root = array( $root );
1037 foreach ( $root as $node ) {
1043 $s .= $this->expand( $node );
1050 * Makes an object that, when expand()ed, will be the same as one obtained
1053 function virtualImplode( $sep /*, ... */ ) {
1054 $args = array_slice( func_get_args(), 1 );
1058 foreach ( $args as $root ) {
1059 if ( $root instanceof PPNode_Hash_Array
) {
1060 $root = $root->value
;
1062 if ( !is_array( $root ) ) {
1063 $root = array( $root );
1065 foreach ( $root as $node ) {
1074 return new PPNode_Hash_Array( $out );
1078 * Virtual implode with brackets
1080 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1081 $args = array_slice( func_get_args(), 3 );
1082 $out = array( $start );
1085 foreach ( $args as $root ) {
1086 if ( $root instanceof PPNode_Hash_Array
) {
1087 $root = $root->value
;
1089 if ( !is_array( $root ) ) {
1090 $root = array( $root );
1092 foreach ( $root as $node ) {
1102 return new PPNode_Hash_Array( $out );
1105 function __toString() {
1109 function getPDBK( $level = false ) {
1110 if ( $level === false ) {
1111 return $this->title
->getPrefixedDBkey();
1113 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1118 * Returns true if there are no arguments in this frame
1120 function isEmpty() {
1124 function getArgument( $name ) {
1129 * Returns true if the infinite loop check is OK, false if a loop is detected
1131 function loopCheck( $title ) {
1132 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1136 * Return true if the frame is a template frame
1138 function isTemplate() {
1144 * Expansion frame with template arguments
1147 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1148 var $numberedArgs, $namedArgs, $parent;
1149 var $numberedExpansionCache, $namedExpansionCache;
1151 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1152 $this->preprocessor
= $preprocessor;
1153 $this->parser
= $preprocessor->parser
;
1154 $this->parent
= $parent;
1155 $this->numberedArgs
= $numberedArgs;
1156 $this->namedArgs
= $namedArgs;
1157 $this->title
= $title;
1158 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1159 $this->titleCache
= $parent->titleCache
;
1160 $this->titleCache
[] = $pdbk;
1161 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1162 if ( $pdbk !== false ) {
1163 $this->loopCheckHash
[$pdbk] = true;
1165 $this->depth
= $parent->depth +
1;
1166 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1169 function __toString() {
1172 $args = $this->numberedArgs +
$this->namedArgs
;
1173 foreach ( $args as $name => $value ) {
1179 $s .= "\"$name\":\"" .
1180 str_replace( '"', '\\"', $value->__toString() ) . '"';
1186 * Returns true if there are no arguments in this frame
1188 function isEmpty() {
1189 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1192 function getArguments() {
1193 $arguments = array();
1194 foreach ( array_merge(
1195 array_keys($this->numberedArgs
),
1196 array_keys($this->namedArgs
)) as $key ) {
1197 $arguments[$key] = $this->getArgument($key);
1202 function getNumberedArguments() {
1203 $arguments = array();
1204 foreach ( array_keys($this->numberedArgs
) as $key ) {
1205 $arguments[$key] = $this->getArgument($key);
1210 function getNamedArguments() {
1211 $arguments = array();
1212 foreach ( array_keys($this->namedArgs
) as $key ) {
1213 $arguments[$key] = $this->getArgument($key);
1218 function getNumberedArgument( $index ) {
1219 if ( !isset( $this->numberedArgs
[$index] ) ) {
1222 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1223 # No trimming for unnamed arguments
1224 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1226 return $this->numberedExpansionCache
[$index];
1229 function getNamedArgument( $name ) {
1230 if ( !isset( $this->namedArgs
[$name] ) ) {
1233 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1234 # Trim named arguments post-expand, for backwards compatibility
1235 $this->namedExpansionCache
[$name] = trim(
1236 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1238 return $this->namedExpansionCache
[$name];
1241 function getArgument( $name ) {
1242 $text = $this->getNumberedArgument( $name );
1243 if ( $text === false ) {
1244 $text = $this->getNamedArgument( $name );
1250 * Return true if the frame is a template frame
1252 function isTemplate() {
1258 * Expansion frame with custom arguments
1261 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1264 function __construct( $preprocessor, $args ) {
1265 $this->preprocessor
= $preprocessor;
1266 $this->parser
= $preprocessor->parser
;
1267 $this->args
= $args;
1270 function __toString() {
1273 foreach ( $this->args
as $name => $value ) {
1279 $s .= "\"$name\":\"" .
1280 str_replace( '"', '\\"', $value->__toString() ) . '"';
1286 function isEmpty() {
1287 return !count( $this->args
);
1290 function getArgument( $index ) {
1291 if ( !isset( $this->args
[$index] ) ) {
1294 return $this->args
[$index];
1301 class PPNode_Hash_Tree
implements PPNode
{
1302 var $name, $firstChild, $lastChild, $nextSibling;
1304 function __construct( $name ) {
1305 $this->name
= $name;
1306 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1309 function __toString() {
1312 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1313 if ( $node instanceof PPNode_Hash_Attr
) {
1314 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1316 $inner .= $node->__toString();
1319 if ( $inner === '' ) {
1320 return "<{$this->name}$attribs/>";
1322 return "<{$this->name}$attribs>$inner</{$this->name}>";
1326 static function newWithText( $name, $text ) {
1327 $obj = new self( $name );
1328 $obj->addChild( new PPNode_Hash_Text( $text ) );
1332 function addChild( $node ) {
1333 if ( $this->lastChild
=== false ) {
1334 $this->firstChild
= $this->lastChild
= $node;
1336 $this->lastChild
->nextSibling
= $node;
1337 $this->lastChild
= $node;
1341 function getChildren() {
1342 $children = array();
1343 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1344 $children[] = $child;
1346 return new PPNode_Hash_Array( $children );
1349 function getFirstChild() {
1350 return $this->firstChild
;
1353 function getNextSibling() {
1354 return $this->nextSibling
;
1357 function getChildrenOfType( $name ) {
1358 $children = array();
1359 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1360 if ( isset( $child->name
) && $child->name
=== $name ) {
1361 $children[] = $name;
1367 function getLength() { return false; }
1368 function item( $i ) { return false; }
1370 function getName() {
1375 * Split a <part> node into an associative array containing:
1377 * index String index
1378 * value PPNode value
1380 function splitArg() {
1382 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1383 if ( !isset( $child->name
) ) {
1386 if ( $child->name
=== 'name' ) {
1387 $bits['name'] = $child;
1388 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1389 && $child->firstChild
->name
=== 'index' )
1391 $bits['index'] = $child->firstChild
->value
;
1393 } elseif ( $child->name
=== 'value' ) {
1394 $bits['value'] = $child;
1398 if ( !isset( $bits['name'] ) ) {
1399 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1401 if ( !isset( $bits['index'] ) ) {
1402 $bits['index'] = '';
1408 * Split an <ext> node into an associative array containing name, attr, inner and close
1409 * All values in the resulting array are PPNodes. Inner and close are optional.
1411 function splitExt() {
1413 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1414 if ( !isset( $child->name
) ) {
1417 if ( $child->name
== 'name' ) {
1418 $bits['name'] = $child;
1419 } elseif ( $child->name
== 'attr' ) {
1420 $bits['attr'] = $child;
1421 } elseif ( $child->name
== 'inner' ) {
1422 $bits['inner'] = $child;
1423 } elseif ( $child->name
== 'close' ) {
1424 $bits['close'] = $child;
1427 if ( !isset( $bits['name'] ) ) {
1428 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1436 function splitHeading() {
1437 if ( $this->name
!== 'h' ) {
1438 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1441 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1442 if ( !isset( $child->name
) ) {
1445 if ( $child->name
== 'i' ) {
1446 $bits['i'] = $child->value
;
1447 } elseif ( $child->name
== 'level' ) {
1448 $bits['level'] = $child->value
;
1451 if ( !isset( $bits['i'] ) ) {
1452 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1458 * Split a <template> or <tplarg> node
1460 function splitTemplate() {
1462 $bits = array( 'lineStart' => '' );
1463 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1464 if ( !isset( $child->name
) ) {
1467 if ( $child->name
== 'title' ) {
1468 $bits['title'] = $child;
1470 if ( $child->name
== 'part' ) {
1473 if ( $child->name
== 'lineStart' ) {
1474 $bits['lineStart'] = '1';
1477 if ( !isset( $bits['title'] ) ) {
1478 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1480 $bits['parts'] = new PPNode_Hash_Array( $parts );
1488 class PPNode_Hash_Text
implements PPNode
{
1489 var $value, $nextSibling;
1491 function __construct( $value ) {
1492 if ( is_object( $value ) ) {
1493 throw new MWException( __CLASS__
. ' given object instead of string' );
1495 $this->value
= $value;
1498 function __toString() {
1499 return htmlspecialchars( $this->value
);
1502 function getNextSibling() {
1503 return $this->nextSibling
;
1506 function getChildren() { return false; }
1507 function getFirstChild() { return false; }
1508 function getChildrenOfType( $name ) { return false; }
1509 function getLength() { return false; }
1510 function item( $i ) { return false; }
1511 function getName() { return '#text'; }
1512 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1513 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1514 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1520 class PPNode_Hash_Array
implements PPNode
{
1521 var $value, $nextSibling;
1523 function __construct( $value ) {
1524 $this->value
= $value;
1527 function __toString() {
1528 return var_export( $this, true );
1531 function getLength() {
1532 return count( $this->value
);
1535 function item( $i ) {
1536 return $this->value
[$i];
1539 function getName() { return '#nodelist'; }
1541 function getNextSibling() {
1542 return $this->nextSibling
;
1545 function getChildren() { return false; }
1546 function getFirstChild() { return false; }
1547 function getChildrenOfType( $name ) { return false; }
1548 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1549 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1550 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1556 class PPNode_Hash_Attr
implements PPNode
{
1557 var $name, $value, $nextSibling;
1559 function __construct( $name, $value ) {
1560 $this->name
= $name;
1561 $this->value
= $value;
1564 function __toString() {
1565 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1568 function getName() {
1572 function getNextSibling() {
1573 return $this->nextSibling
;
1576 function getChildren() { return false; }
1577 function getFirstChild() { return false; }
1578 function getChildrenOfType( $name ) { return false; }
1579 function getLength() { return false; }
1580 function item( $i ) { return false; }
1581 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1582 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1583 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }