3 * Preprocessor using PHP arrays
10 * Differences from DOM schema:
11 * * attribute nodes are children
12 * * <h> nodes that aren't at the top are replaced with <possible-h>
15 class Preprocessor_Hash
implements Preprocessor
{
21 const CACHE_VERSION
= 1;
23 function __construct( $parser ) {
24 $this->parser
= $parser;
28 return new PPFrame_Hash( $this );
31 function newCustomFrame( $args ) {
32 return new PPCustomFrame_Hash( $this, $args );
35 function newPartNodeArray( $values ) {
38 foreach ( $values as $k => $val ) {
39 $partNode = new PPNode_Hash_Tree( 'part' );
40 $nameNode = new PPNode_Hash_Tree( 'name' );
43 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
44 $partNode->addChild( $nameNode );
46 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
47 $partNode->addChild( $nameNode );
48 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
51 $valueNode = new PPNode_Hash_Tree( 'value' );
52 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
53 $partNode->addChild( $valueNode );
58 $node = new PPNode_Hash_Array( $list );
63 * Preprocess some wikitext and return the document tree.
64 * This is the ghost of Parser::replace_variables().
66 * @param $text String: the text to parse
67 * @param $flags Integer: bitwise combination of:
68 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
69 * included. Default is to assume a direct page view.
71 * The generated DOM tree must depend only on the input text and the flags.
72 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
74 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
75 * change in the DOM tree for a given text, must be passed through the section identifier
76 * in the section edit link and thus back to extractSections().
78 * The output of this function is currently only cached in process memory, but a persistent
79 * cache may be implemented at a later date which takes further advantage of these strict
80 * dependency requirements.
84 function preprocessToObj( $text, $flags = 0 ) {
85 wfProfileIn( __METHOD__
);
88 global $wgMemc, $wgPreprocessorCacheThreshold;
90 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
92 wfProfileIn( __METHOD__
.'-cacheable' );
94 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
95 $cacheValue = $wgMemc->get( $cacheKey );
97 $version = substr( $cacheValue, 0, 8 );
98 if ( intval( $version ) == self
::CACHE_VERSION
) {
99 $hash = unserialize( substr( $cacheValue, 8 ) );
101 wfDebugLog( "Preprocessor",
102 "Loaded preprocessor hash from memcached (key $cacheKey)" );
103 wfProfileOut( __METHOD__
.'-cacheable' );
104 wfProfileOut( __METHOD__
);
108 wfProfileIn( __METHOD__
.'-cache-miss' );
123 'names' => array( 2 => null ),
129 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
131 $xmlishElements = $this->parser
->getStripList();
132 $enableOnlyinclude = false;
133 if ( $forInclusion ) {
134 $ignoredTags = array( 'includeonly', '/includeonly' );
135 $ignoredElements = array( 'noinclude' );
136 $xmlishElements[] = 'noinclude';
137 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
138 $enableOnlyinclude = true;
141 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
142 $ignoredElements = array( 'includeonly' );
143 $xmlishElements[] = 'includeonly';
145 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
147 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
148 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
150 $stack = new PPDStack_Hash
;
152 $searchBase = "[{<\n";
153 $revText = strrev( $text ); // For fast reverse searches
155 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
156 $accum =& $stack->getAccum(); # Current accumulator
157 $findEquals = false; # True to find equals signs in arguments
158 $findPipe = false; # True to take notice of pipe characters
160 $inHeading = false; # True if $i is inside a possible heading
161 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
162 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
163 $fakeLineStart = true; # Do a line-start run without outputting an LF character
168 if ( $findOnlyinclude ) {
169 // Ignore all input up to the next <onlyinclude>
170 $startPos = strpos( $text, '<onlyinclude>', $i );
171 if ( $startPos === false ) {
172 // Ignored section runs to the end
173 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
176 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
177 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
179 $findOnlyinclude = false;
182 if ( $fakeLineStart ) {
183 $found = 'line-start';
186 # Find next opening brace, closing brace or pipe
187 $search = $searchBase;
188 if ( $stack->top
=== false ) {
189 $currentClosing = '';
191 $currentClosing = $stack->top
->close
;
192 $search .= $currentClosing;
198 // First equals will be for the template
202 # Output literal section, advance input counter
203 $literalLength = strcspn( $text, $search, $i );
204 if ( $literalLength > 0 ) {
205 $accum->addLiteral( substr( $text, $i, $literalLength ) );
206 $i +
= $literalLength;
208 if ( $i >= strlen( $text ) ) {
209 if ( $currentClosing == "\n" ) {
210 // Do a past-the-end run to finish off the heading
218 $curChar = $text[$i];
219 if ( $curChar == '|' ) {
221 } elseif ( $curChar == '=' ) {
223 } elseif ( $curChar == '<' ) {
225 } elseif ( $curChar == "\n" ) {
229 $found = 'line-start';
231 } elseif ( $curChar == $currentClosing ) {
233 } elseif ( isset( $rules[$curChar] ) ) {
235 $rule = $rules[$curChar];
237 # Some versions of PHP have a strcspn which stops on null characters
238 # Ignore and continue
245 if ( $found == 'angle' ) {
247 // Handle </onlyinclude>
248 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
249 $findOnlyinclude = true;
253 // Determine element name
254 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
255 // Element name missing or not listed
256 $accum->addLiteral( '<' );
261 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
262 // To avoid leaving blank lines, when a comment is both preceded
263 // and followed by a newline (ignoring spaces), trim leading and
264 // trailing spaces and one of the newlines.
267 $endPos = strpos( $text, '-->', $i +
4 );
268 if ( $endPos === false ) {
269 // Unclosed comment in input, runs to end
270 $inner = substr( $text, $i );
271 $accum->addNodeWithText( 'comment', $inner );
272 $i = strlen( $text );
274 // Search backwards for leading whitespace
275 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
276 // Search forwards for trailing whitespace
277 // $wsEnd will be the position of the last space (or the '>' if there's none)
278 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
279 // Eat the line if possible
280 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
281 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
282 // it's a possible beneficial b/c break.
283 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
284 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
286 $startPos = $wsStart;
287 $endPos = $wsEnd +
1;
288 // Remove leading whitespace from the end of the accumulator
289 // Sanity check first though
290 $wsLength = $i - $wsStart;
292 && $accum->lastNode
instanceof PPNode_Hash_Text
293 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
295 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
297 // Do a line-start run next time to look for headings after the comment
298 $fakeLineStart = true;
300 // No line to eat, just take the comment itself
306 $part = $stack->top
->getCurrentPart();
307 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
308 // Comments abutting, no change in visual end
309 $part->commentEnd
= $wsEnd;
311 $part->visualEnd
= $wsStart;
312 $part->commentEnd
= $endPos;
316 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
317 $accum->addNodeWithText( 'comment', $inner );
322 $lowerName = strtolower( $name );
323 $attrStart = $i +
strlen( $name ) +
1;
326 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
327 if ( $tagEndPos === false ) {
328 // Infinite backtrack
329 // Disable tag search to prevent worst-case O(N^2) performance
331 $accum->addLiteral( '<' );
336 // Handle ignored tags
337 if ( in_array( $lowerName, $ignoredTags ) ) {
338 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
344 if ( $text[$tagEndPos-1] == '/' ) {
346 $attrEnd = $tagEndPos - 1;
351 $attrEnd = $tagEndPos;
353 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
354 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
356 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
357 $i = $matches[0][1] +
strlen( $matches[0][0] );
358 $close = $matches[0][0];
360 // No end tag -- let it run out to the end of the text.
361 $inner = substr( $text, $tagEndPos +
1 );
362 $i = strlen( $text );
366 // <includeonly> and <noinclude> just become <ignore> tags
367 if ( in_array( $lowerName, $ignoredElements ) ) {
368 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
372 if ( $attrEnd <= $attrStart ) {
375 // Note that the attr element contains the whitespace between name and attribute,
376 // this is necessary for precise reconstruction during pre-save transform.
377 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
380 $extNode = new PPNode_Hash_Tree( 'ext' );
381 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
382 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
383 if ( $inner !== null ) {
384 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
386 if ( $close !== null ) {
387 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
389 $accum->addNode( $extNode );
392 elseif ( $found == 'line-start' ) {
393 // Is this the start of a heading?
394 // Line break belongs before the heading element in any case
395 if ( $fakeLineStart ) {
396 $fakeLineStart = false;
398 $accum->addLiteral( $curChar );
402 $count = strspn( $text, '=', $i, 6 );
403 if ( $count == 1 && $findEquals ) {
404 // DWIM: This looks kind of like a name/value separator
405 // Let's let the equals handler have it and break the potential heading
406 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
407 } elseif ( $count > 0 ) {
411 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
414 $stack->push( $piece );
415 $accum =& $stack->getAccum();
416 extract( $stack->getFlags() );
421 elseif ( $found == 'line-end' ) {
422 $piece = $stack->top
;
423 // A heading must be open, otherwise \n wouldn't have been in the search list
424 assert( $piece->open
== "\n" );
425 $part = $piece->getCurrentPart();
426 // Search back through the input to see if it has a proper close
427 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
428 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
429 $searchStart = $i - $wsLength;
430 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
431 // Comment found at line end
432 // Search for equals signs before the comment
433 $searchStart = $part->visualEnd
;
434 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
436 $count = $piece->count
;
437 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
438 if ( $equalsLength > 0 ) {
439 if ( $searchStart - $equalsLength == $piece->startPos
) {
440 // This is just a single string of equals signs on its own line
441 // Replicate the doHeadings behaviour /={count}(.+)={count}/
442 // First find out how many equals signs there really are (don't stop at 6)
443 $count = $equalsLength;
447 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
450 $count = min( $equalsLength, $count );
453 // Normal match, output <h>
454 $element = new PPNode_Hash_Tree( 'possible-h' );
455 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
456 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
457 $element->lastChild
->nextSibling
= $accum->firstNode
;
458 $element->lastChild
= $accum->lastNode
;
460 // Single equals sign on its own line, count=0
464 // No match, no <h>, just pass down the inner text
469 $accum =& $stack->getAccum();
470 extract( $stack->getFlags() );
472 // Append the result to the enclosing accumulator
473 if ( $element instanceof PPNode
) {
474 $accum->addNode( $element );
476 $accum->addAccum( $element );
478 // Note that we do NOT increment the input pointer.
479 // This is because the closing linebreak could be the opening linebreak of
480 // another heading. Infinite loops are avoided because the next iteration MUST
481 // hit the heading open case above, which unconditionally increments the
485 elseif ( $found == 'open' ) {
486 # count opening brace characters
487 $count = strspn( $text, $curChar, $i );
489 # we need to add to stack only if opening brace count is enough for one of the rules
490 if ( $count >= $rule['min'] ) {
491 # Add it to the stack
494 'close' => $rule['end'],
496 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
499 $stack->push( $piece );
500 $accum =& $stack->getAccum();
501 extract( $stack->getFlags() );
503 # Add literal brace(s)
504 $accum->addLiteral( str_repeat( $curChar, $count ) );
509 elseif ( $found == 'close' ) {
510 $piece = $stack->top
;
511 # lets check if there are enough characters for closing brace
512 $maxCount = $piece->count
;
513 $count = strspn( $text, $curChar, $i, $maxCount );
515 # check for maximum matching characters (if there are 5 closing
516 # characters, we will probably need only 3 - depending on the rules)
517 $rule = $rules[$piece->open
];
518 if ( $count > $rule['max'] ) {
519 # The specified maximum exists in the callback array, unless the caller
521 $matchingCount = $rule['max'];
523 # Count is less than the maximum
524 # Skip any gaps in the callback array to find the true largest match
525 # Need to use array_key_exists not isset because the callback can be null
526 $matchingCount = $count;
527 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
532 if ($matchingCount <= 0) {
533 # No matching element found in callback array
534 # Output a literal closing brace and continue
535 $accum->addLiteral( str_repeat( $curChar, $count ) );
539 $name = $rule['names'][$matchingCount];
540 if ( $name === null ) {
541 // No element, just literal text
542 $element = $piece->breakSyntax( $matchingCount );
543 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
546 # Note: $parts is already XML, does not need to be encoded further
547 $parts = $piece->parts
;
548 $titleAccum = $parts[0]->out
;
551 $element = new PPNode_Hash_Tree( $name );
553 # The invocation is at the start of the line if lineStart is set in
554 # the stack, and all opening brackets are used up.
555 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
556 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
558 $titleNode = new PPNode_Hash_Tree( 'title' );
559 $titleNode->firstChild
= $titleAccum->firstNode
;
560 $titleNode->lastChild
= $titleAccum->lastNode
;
561 $element->addChild( $titleNode );
563 foreach ( $parts as $part ) {
564 if ( isset( $part->eqpos
) ) {
567 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
568 if ( $node === $part->eqpos
) {
574 throw new MWException( __METHOD__
. ': eqpos not found' );
576 if ( $node->name
!== 'equals' ) {
577 throw new MWException( __METHOD__
.': eqpos is not equals' );
581 // Construct name node
582 $nameNode = new PPNode_Hash_Tree( 'name' );
583 if ( $lastNode !== false ) {
584 $lastNode->nextSibling
= false;
585 $nameNode->firstChild
= $part->out
->firstNode
;
586 $nameNode->lastChild
= $lastNode;
589 // Construct value node
590 $valueNode = new PPNode_Hash_Tree( 'value' );
591 if ( $equalsNode->nextSibling
!== false ) {
592 $valueNode->firstChild
= $equalsNode->nextSibling
;
593 $valueNode->lastChild
= $part->out
->lastNode
;
595 $partNode = new PPNode_Hash_Tree( 'part' );
596 $partNode->addChild( $nameNode );
597 $partNode->addChild( $equalsNode->firstChild
);
598 $partNode->addChild( $valueNode );
599 $element->addChild( $partNode );
601 $partNode = new PPNode_Hash_Tree( 'part' );
602 $nameNode = new PPNode_Hash_Tree( 'name' );
603 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
604 $valueNode = new PPNode_Hash_Tree( 'value' );
605 $valueNode->firstChild
= $part->out
->firstNode
;
606 $valueNode->lastChild
= $part->out
->lastNode
;
607 $partNode->addChild( $nameNode );
608 $partNode->addChild( $valueNode );
609 $element->addChild( $partNode );
614 # Advance input pointer
615 $i +
= $matchingCount;
619 $accum =& $stack->getAccum();
621 # Re-add the old stack element if it still has unmatched opening characters remaining
622 if ($matchingCount < $piece->count
) {
623 $piece->parts
= array( new PPDPart_Hash
);
624 $piece->count
-= $matchingCount;
625 # do we still qualify for any callback with remaining count?
626 $names = $rules[$piece->open
]['names'];
628 $enclosingAccum =& $accum;
629 while ( $piece->count
) {
630 if ( array_key_exists( $piece->count
, $names ) ) {
631 $stack->push( $piece );
632 $accum =& $stack->getAccum();
638 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
641 extract( $stack->getFlags() );
643 # Add XML element to the enclosing accumulator
644 if ( $element instanceof PPNode
) {
645 $accum->addNode( $element );
647 $accum->addAccum( $element );
651 elseif ( $found == 'pipe' ) {
652 $findEquals = true; // shortcut for getFlags()
654 $accum =& $stack->getAccum();
658 elseif ( $found == 'equals' ) {
659 $findEquals = false; // shortcut for getFlags()
660 $accum->addNodeWithText( 'equals', '=' );
661 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
666 # Output any remaining unclosed brackets
667 foreach ( $stack->stack
as $piece ) {
668 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
671 # Enable top-level headings
672 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
673 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
678 $rootNode = new PPNode_Hash_Tree( 'root' );
679 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
680 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
684 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
685 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
686 wfProfileOut( __METHOD__
.'-cache-miss' );
687 wfProfileOut( __METHOD__
.'-cacheable' );
688 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
691 wfProfileOut( __METHOD__
);
697 * Stack class to help Preprocessor::preprocessToObj()
700 class PPDStack_Hash
extends PPDStack
{
701 function __construct() {
702 $this->elementClass
= 'PPDStackElement_Hash';
703 parent
::__construct();
704 $this->rootAccum
= new PPDAccum_Hash
;
711 class PPDStackElement_Hash
extends PPDStackElement
{
712 function __construct( $data = array() ) {
713 $this->partClass
= 'PPDPart_Hash';
714 parent
::__construct( $data );
718 * Get the accumulator that would result if the close is not found.
720 function breakSyntax( $openingCount = false ) {
721 if ( $this->open
== "\n" ) {
722 $accum = $this->parts
[0]->out
;
724 if ( $openingCount === false ) {
725 $openingCount = $this->count
;
727 $accum = new PPDAccum_Hash
;
728 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
730 foreach ( $this->parts
as $part ) {
734 $accum->addLiteral( '|' );
736 $accum->addAccum( $part->out
);
746 class PPDPart_Hash
extends PPDPart
{
747 function __construct( $out = '' ) {
748 $accum = new PPDAccum_Hash
;
750 $accum->addLiteral( $out );
752 parent
::__construct( $accum );
759 class PPDAccum_Hash
{
760 var $firstNode, $lastNode;
762 function __construct() {
763 $this->firstNode
= $this->lastNode
= false;
767 * Append a string literal
769 function addLiteral( $s ) {
770 if ( $this->lastNode
=== false ) {
771 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
772 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
773 $this->lastNode
->value
.= $s;
775 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
776 $this->lastNode
= $this->lastNode
->nextSibling
;
783 function addNode( PPNode
$node ) {
784 if ( $this->lastNode
=== false ) {
785 $this->firstNode
= $this->lastNode
= $node;
787 $this->lastNode
->nextSibling
= $node;
788 $this->lastNode
= $node;
793 * Append a tree node with text contents
795 function addNodeWithText( $name, $value ) {
796 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
797 $this->addNode( $node );
801 * Append a PPAccum_Hash
802 * Takes over ownership of the nodes in the source argument. These nodes may
803 * subsequently be modified, especially nextSibling.
805 function addAccum( $accum ) {
806 if ( $accum->lastNode
=== false ) {
808 } elseif ( $this->lastNode
=== false ) {
809 $this->firstNode
= $accum->firstNode
;
810 $this->lastNode
= $accum->lastNode
;
812 $this->lastNode
->nextSibling
= $accum->firstNode
;
813 $this->lastNode
= $accum->lastNode
;
819 * An expansion frame, used as a context to expand the result of preprocessToObj()
822 class PPFrame_Hash
implements PPFrame
{
823 var $preprocessor, $parser, $title;
827 * Hashtable listing templates which are disallowed for expansion in this frame,
828 * having been encountered previously in parent frames.
833 * Recursion depth of this frame, top = 0
834 * Note that this is NOT the same as expansion depth in expand()
840 * Construct a new preprocessor frame.
841 * @param $preprocessor Preprocessor: the parent preprocessor
843 function __construct( $preprocessor ) {
844 $this->preprocessor
= $preprocessor;
845 $this->parser
= $preprocessor->parser
;
846 $this->title
= $this->parser
->mTitle
;
847 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
848 $this->loopCheckHash
= array();
853 * Create a new child frame
854 * $args is optionally a multi-root PPNode or array containing the template arguments
856 function newChild( $args = false, $title = false ) {
857 $namedArgs = array();
858 $numberedArgs = array();
859 if ( $title === false ) {
860 $title = $this->title
;
862 if ( $args !== false ) {
863 if ( $args instanceof PPNode_Hash_Array
) {
864 $args = $args->value
;
865 } elseif ( !is_array( $args ) ) {
866 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
868 foreach ( $args as $arg ) {
869 $bits = $arg->splitArg();
870 if ( $bits['index'] !== '' ) {
871 // Numbered parameter
872 $numberedArgs[$bits['index']] = $bits['value'];
873 unset( $namedArgs[$bits['index']] );
876 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
877 $namedArgs[$name] = $bits['value'];
878 unset( $numberedArgs[$name] );
882 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
885 function expand( $root, $flags = 0 ) {
886 static $expansionDepth = 0;
887 if ( is_string( $root ) ) {
891 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
893 return '<span class="error">Node-count limit exceeded</span>';
895 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
896 return '<span class="error">Expansion depth limit exceeded</span>';
900 $outStack = array( '', '' );
901 $iteratorStack = array( false, $root );
902 $indexStack = array( 0, 0 );
904 while ( count( $iteratorStack ) > 1 ) {
905 $level = count( $outStack ) - 1;
906 $iteratorNode =& $iteratorStack[ $level ];
907 $out =& $outStack[$level];
908 $index =& $indexStack[$level];
910 if ( is_array( $iteratorNode ) ) {
911 if ( $index >= count( $iteratorNode ) ) {
912 // All done with this iterator
913 $iteratorStack[$level] = false;
914 $contextNode = false;
916 $contextNode = $iteratorNode[$index];
919 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
920 if ( $index >= $iteratorNode->getLength() ) {
921 // All done with this iterator
922 $iteratorStack[$level] = false;
923 $contextNode = false;
925 $contextNode = $iteratorNode->item( $index );
929 // Copy to $contextNode and then delete from iterator stack,
930 // because this is not an iterator but we do have to execute it once
931 $contextNode = $iteratorStack[$level];
932 $iteratorStack[$level] = false;
935 $newIterator = false;
937 if ( $contextNode === false ) {
939 } elseif ( is_string( $contextNode ) ) {
940 $out .= $contextNode;
941 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
942 $newIterator = $contextNode;
943 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
945 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
946 $out .= $contextNode->value
;
947 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
948 if ( $contextNode->name
== 'template' ) {
949 # Double-brace expansion
950 $bits = $contextNode->splitTemplate();
951 if ( $flags & PPFrame
::NO_TEMPLATES
) {
952 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
954 $ret = $this->parser
->braceSubstitution( $bits, $this );
955 if ( isset( $ret['object'] ) ) {
956 $newIterator = $ret['object'];
958 $out .= $ret['text'];
961 } elseif ( $contextNode->name
== 'tplarg' ) {
962 # Triple-brace expansion
963 $bits = $contextNode->splitTemplate();
964 if ( $flags & PPFrame
::NO_ARGS
) {
965 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
967 $ret = $this->parser
->argSubstitution( $bits, $this );
968 if ( isset( $ret['object'] ) ) {
969 $newIterator = $ret['object'];
971 $out .= $ret['text'];
974 } elseif ( $contextNode->name
== 'comment' ) {
976 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
977 if ( $this->parser
->ot
['html']
978 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
979 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
983 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
984 # Not in RECOVER_COMMENTS mode (extractSections) though
985 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
986 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
988 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
990 $out .= $contextNode->firstChild
->value
;
992 } elseif ( $contextNode->name
== 'ignore' ) {
993 # Output suppression used by <includeonly> etc.
994 # OT_WIKI will only respect <ignore> in substed templates.
995 # The other output types respect it unless NO_IGNORE is set.
996 # extractSections() sets NO_IGNORE and so never respects it.
997 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
998 $out .= $contextNode->firstChild
->value
;
1002 } elseif ( $contextNode->name
== 'ext' ) {
1004 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1005 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1006 } elseif ( $contextNode->name
== 'h' ) {
1008 if ( $this->parser
->ot
['html'] ) {
1009 # Expand immediately and insert heading index marker
1011 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1012 $s .= $this->expand( $node, $flags );
1015 $bits = $contextNode->splitHeading();
1016 $titleText = $this->title
->getPrefixedDBkey();
1017 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1018 $serial = count( $this->parser
->mHeadings
) - 1;
1019 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1020 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1021 $this->parser
->mStripState
->setGeneral( $marker, '' );
1024 # Expand in virtual stack
1025 $newIterator = $contextNode->getChildren();
1028 # Generic recursive expansion
1029 $newIterator = $contextNode->getChildren();
1032 throw new MWException( __METHOD__
.': Invalid parameter type' );
1035 if ( $newIterator !== false ) {
1037 $iteratorStack[] = $newIterator;
1039 } elseif ( $iteratorStack[$level] === false ) {
1040 // Return accumulated value to parent
1041 // With tail recursion
1042 while ( $iteratorStack[$level] === false && $level > 0 ) {
1043 $outStack[$level - 1] .= $out;
1044 array_pop( $outStack );
1045 array_pop( $iteratorStack );
1046 array_pop( $indexStack );
1052 return $outStack[0];
1055 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1056 $args = array_slice( func_get_args(), 2 );
1060 foreach ( $args as $root ) {
1061 if ( $root instanceof PPNode_Hash_Array
) {
1062 $root = $root->value
;
1064 if ( !is_array( $root ) ) {
1065 $root = array( $root );
1067 foreach ( $root as $node ) {
1073 $s .= $this->expand( $node, $flags );
1080 * Implode with no flags specified
1081 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1083 function implode( $sep /*, ... */ ) {
1084 $args = array_slice( func_get_args(), 1 );
1088 foreach ( $args as $root ) {
1089 if ( $root instanceof PPNode_Hash_Array
) {
1090 $root = $root->value
;
1092 if ( !is_array( $root ) ) {
1093 $root = array( $root );
1095 foreach ( $root as $node ) {
1101 $s .= $this->expand( $node );
1108 * Makes an object that, when expand()ed, will be the same as one obtained
1111 function virtualImplode( $sep /*, ... */ ) {
1112 $args = array_slice( func_get_args(), 1 );
1116 foreach ( $args as $root ) {
1117 if ( $root instanceof PPNode_Hash_Array
) {
1118 $root = $root->value
;
1120 if ( !is_array( $root ) ) {
1121 $root = array( $root );
1123 foreach ( $root as $node ) {
1132 return new PPNode_Hash_Array( $out );
1136 * Virtual implode with brackets
1138 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1139 $args = array_slice( func_get_args(), 3 );
1140 $out = array( $start );
1143 foreach ( $args as $root ) {
1144 if ( $root instanceof PPNode_Hash_Array
) {
1145 $root = $root->value
;
1147 if ( !is_array( $root ) ) {
1148 $root = array( $root );
1150 foreach ( $root as $node ) {
1160 return new PPNode_Hash_Array( $out );
1163 function __toString() {
1167 function getPDBK( $level = false ) {
1168 if ( $level === false ) {
1169 return $this->title
->getPrefixedDBkey();
1171 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1175 function getArguments() {
1179 function getNumberedArguments() {
1183 function getNamedArguments() {
1188 * Returns true if there are no arguments in this frame
1190 function isEmpty() {
1194 function getArgument( $name ) {
1199 * Returns true if the infinite loop check is OK, false if a loop is detected
1201 function loopCheck( $title ) {
1202 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1206 * Return true if the frame is a template frame
1208 function isTemplate() {
1214 * Expansion frame with template arguments
1217 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1218 var $numberedArgs, $namedArgs, $parent;
1219 var $numberedExpansionCache, $namedExpansionCache;
1221 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1222 parent
::__construct( $preprocessor );
1224 $this->parent
= $parent;
1225 $this->numberedArgs
= $numberedArgs;
1226 $this->namedArgs
= $namedArgs;
1227 $this->title
= $title;
1228 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1229 $this->titleCache
= $parent->titleCache
;
1230 $this->titleCache
[] = $pdbk;
1231 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1232 if ( $pdbk !== false ) {
1233 $this->loopCheckHash
[$pdbk] = true;
1235 $this->depth
= $parent->depth +
1;
1236 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1239 function __toString() {
1242 $args = $this->numberedArgs +
$this->namedArgs
;
1243 foreach ( $args as $name => $value ) {
1249 $s .= "\"$name\":\"" .
1250 str_replace( '"', '\\"', $value->__toString() ) . '"';
1256 * Returns true if there are no arguments in this frame
1258 function isEmpty() {
1259 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1262 function getArguments() {
1263 $arguments = array();
1264 foreach ( array_merge(
1265 array_keys($this->numberedArgs
),
1266 array_keys($this->namedArgs
)) as $key ) {
1267 $arguments[$key] = $this->getArgument($key);
1272 function getNumberedArguments() {
1273 $arguments = array();
1274 foreach ( array_keys($this->numberedArgs
) as $key ) {
1275 $arguments[$key] = $this->getArgument($key);
1280 function getNamedArguments() {
1281 $arguments = array();
1282 foreach ( array_keys($this->namedArgs
) as $key ) {
1283 $arguments[$key] = $this->getArgument($key);
1288 function getNumberedArgument( $index ) {
1289 if ( !isset( $this->numberedArgs
[$index] ) ) {
1292 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1293 # No trimming for unnamed arguments
1294 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1296 return $this->numberedExpansionCache
[$index];
1299 function getNamedArgument( $name ) {
1300 if ( !isset( $this->namedArgs
[$name] ) ) {
1303 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1304 # Trim named arguments post-expand, for backwards compatibility
1305 $this->namedExpansionCache
[$name] = trim(
1306 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1308 return $this->namedExpansionCache
[$name];
1311 function getArgument( $name ) {
1312 $text = $this->getNumberedArgument( $name );
1313 if ( $text === false ) {
1314 $text = $this->getNamedArgument( $name );
1320 * Return true if the frame is a template frame
1322 function isTemplate() {
1328 * Expansion frame with custom arguments
1331 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1334 function __construct( $preprocessor, $args ) {
1335 parent
::__construct( $preprocessor );
1336 $this->args
= $args;
1339 function __toString() {
1342 foreach ( $this->args
as $name => $value ) {
1348 $s .= "\"$name\":\"" .
1349 str_replace( '"', '\\"', $value->__toString() ) . '"';
1355 function isEmpty() {
1356 return !count( $this->args
);
1359 function getArgument( $index ) {
1360 if ( !isset( $this->args
[$index] ) ) {
1363 return $this->args
[$index];
1370 class PPNode_Hash_Tree
implements PPNode
{
1371 var $name, $firstChild, $lastChild, $nextSibling;
1373 function __construct( $name ) {
1374 $this->name
= $name;
1375 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1378 function __toString() {
1381 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1382 if ( $node instanceof PPNode_Hash_Attr
) {
1383 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1385 $inner .= $node->__toString();
1388 if ( $inner === '' ) {
1389 return "<{$this->name}$attribs/>";
1391 return "<{$this->name}$attribs>$inner</{$this->name}>";
1395 static function newWithText( $name, $text ) {
1396 $obj = new self( $name );
1397 $obj->addChild( new PPNode_Hash_Text( $text ) );
1401 function addChild( $node ) {
1402 if ( $this->lastChild
=== false ) {
1403 $this->firstChild
= $this->lastChild
= $node;
1405 $this->lastChild
->nextSibling
= $node;
1406 $this->lastChild
= $node;
1410 function getChildren() {
1411 $children = array();
1412 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1413 $children[] = $child;
1415 return new PPNode_Hash_Array( $children );
1418 function getFirstChild() {
1419 return $this->firstChild
;
1422 function getNextSibling() {
1423 return $this->nextSibling
;
1426 function getChildrenOfType( $name ) {
1427 $children = array();
1428 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1429 if ( isset( $child->name
) && $child->name
=== $name ) {
1430 $children[] = $name;
1436 function getLength() { return false; }
1437 function item( $i ) { return false; }
1439 function getName() {
1444 * Split a <part> node into an associative array containing:
1446 * index String index
1447 * value PPNode value
1449 function splitArg() {
1451 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1452 if ( !isset( $child->name
) ) {
1455 if ( $child->name
=== 'name' ) {
1456 $bits['name'] = $child;
1457 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1458 && $child->firstChild
->name
=== 'index' )
1460 $bits['index'] = $child->firstChild
->value
;
1462 } elseif ( $child->name
=== 'value' ) {
1463 $bits['value'] = $child;
1467 if ( !isset( $bits['name'] ) ) {
1468 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1470 if ( !isset( $bits['index'] ) ) {
1471 $bits['index'] = '';
1477 * Split an <ext> node into an associative array containing name, attr, inner and close
1478 * All values in the resulting array are PPNodes. Inner and close are optional.
1480 function splitExt() {
1482 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1483 if ( !isset( $child->name
) ) {
1486 if ( $child->name
== 'name' ) {
1487 $bits['name'] = $child;
1488 } elseif ( $child->name
== 'attr' ) {
1489 $bits['attr'] = $child;
1490 } elseif ( $child->name
== 'inner' ) {
1491 $bits['inner'] = $child;
1492 } elseif ( $child->name
== 'close' ) {
1493 $bits['close'] = $child;
1496 if ( !isset( $bits['name'] ) ) {
1497 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1505 function splitHeading() {
1506 if ( $this->name
!== 'h' ) {
1507 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1510 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1511 if ( !isset( $child->name
) ) {
1514 if ( $child->name
== 'i' ) {
1515 $bits['i'] = $child->value
;
1516 } elseif ( $child->name
== 'level' ) {
1517 $bits['level'] = $child->value
;
1520 if ( !isset( $bits['i'] ) ) {
1521 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1527 * Split a <template> or <tplarg> node
1529 function splitTemplate() {
1531 $bits = array( 'lineStart' => '' );
1532 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1533 if ( !isset( $child->name
) ) {
1536 if ( $child->name
== 'title' ) {
1537 $bits['title'] = $child;
1539 if ( $child->name
== 'part' ) {
1542 if ( $child->name
== 'lineStart' ) {
1543 $bits['lineStart'] = '1';
1546 if ( !isset( $bits['title'] ) ) {
1547 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1549 $bits['parts'] = new PPNode_Hash_Array( $parts );
1557 class PPNode_Hash_Text
implements PPNode
{
1558 var $value, $nextSibling;
1560 function __construct( $value ) {
1561 if ( is_object( $value ) ) {
1562 throw new MWException( __CLASS__
. ' given object instead of string' );
1564 $this->value
= $value;
1567 function __toString() {
1568 return htmlspecialchars( $this->value
);
1571 function getNextSibling() {
1572 return $this->nextSibling
;
1575 function getChildren() { return false; }
1576 function getFirstChild() { return false; }
1577 function getChildrenOfType( $name ) { return false; }
1578 function getLength() { return false; }
1579 function item( $i ) { return false; }
1580 function getName() { return '#text'; }
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' ); }
1589 class PPNode_Hash_Array
implements PPNode
{
1590 var $value, $nextSibling;
1592 function __construct( $value ) {
1593 $this->value
= $value;
1596 function __toString() {
1597 return var_export( $this, true );
1600 function getLength() {
1601 return count( $this->value
);
1604 function item( $i ) {
1605 return $this->value
[$i];
1608 function getName() { return '#nodelist'; }
1610 function getNextSibling() {
1611 return $this->nextSibling
;
1614 function getChildren() { return false; }
1615 function getFirstChild() { return false; }
1616 function getChildrenOfType( $name ) { return false; }
1617 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1618 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1619 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1625 class PPNode_Hash_Attr
implements PPNode
{
1626 var $name, $value, $nextSibling;
1628 function __construct( $name, $value ) {
1629 $this->name
= $name;
1630 $this->value
= $value;
1633 function __toString() {
1634 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1637 function getName() {
1641 function getNextSibling() {
1642 return $this->nextSibling
;
1645 function getChildren() { return false; }
1646 function getFirstChild() { return false; }
1647 function getChildrenOfType( $name ) { return false; }
1648 function getLength() { return false; }
1649 function item( $i ) { return false; }
1650 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1651 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1652 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }