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 PPFrame_Hash
31 return new PPFrame_Hash( $this );
36 * @return PPCustomFrame_Hash
38 function newCustomFrame( $args ) {
39 return new PPCustomFrame_Hash( $this, $args );
43 * @param $values array
44 * @return PPNode_Hash_Array
46 function newPartNodeArray( $values ) {
49 foreach ( $values as $k => $val ) {
50 $partNode = new PPNode_Hash_Tree( 'part' );
51 $nameNode = new PPNode_Hash_Tree( 'name' );
54 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
55 $partNode->addChild( $nameNode );
57 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
58 $partNode->addChild( $nameNode );
59 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
62 $valueNode = new PPNode_Hash_Tree( 'value' );
63 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
64 $partNode->addChild( $valueNode );
69 $node = new PPNode_Hash_Array( $list );
74 * Preprocess some wikitext and return the document tree.
75 * This is the ghost of Parser::replace_variables().
77 * @param $text String: the text to parse
78 * @param $flags Integer: bitwise combination of:
79 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
80 * included. Default is to assume a direct page view.
82 * The generated DOM tree must depend only on the input text and the flags.
83 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
85 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
86 * change in the DOM tree for a given text, must be passed through the section identifier
87 * in the section edit link and thus back to extractSections().
89 * The output of this function is currently only cached in process memory, but a persistent
90 * cache may be implemented at a later date which takes further advantage of these strict
91 * dependency requirements.
93 * @return PPNode_Hash_Tree
95 function preprocessToObj( $text, $flags = 0 ) {
96 wfProfileIn( __METHOD__
);
99 global $wgMemc, $wgPreprocessorCacheThreshold;
101 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
103 wfProfileIn( __METHOD__
.'-cacheable' );
105 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
106 $cacheValue = $wgMemc->get( $cacheKey );
108 $version = substr( $cacheValue, 0, 8 );
109 if ( intval( $version ) == self
::CACHE_VERSION
) {
110 $hash = unserialize( substr( $cacheValue, 8 ) );
112 wfDebugLog( "Preprocessor",
113 "Loaded preprocessor hash from memcached (key $cacheKey)" );
114 wfProfileOut( __METHOD__
.'-cacheable' );
115 wfProfileOut( __METHOD__
);
119 wfProfileIn( __METHOD__
.'-cache-miss' );
134 'names' => array( 2 => null ),
140 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
142 $xmlishElements = $this->parser
->getStripList();
143 $enableOnlyinclude = false;
144 if ( $forInclusion ) {
145 $ignoredTags = array( 'includeonly', '/includeonly' );
146 $ignoredElements = array( 'noinclude' );
147 $xmlishElements[] = 'noinclude';
148 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
149 $enableOnlyinclude = true;
152 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
153 $ignoredElements = array( 'includeonly' );
154 $xmlishElements[] = 'includeonly';
156 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
158 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
159 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
161 $stack = new PPDStack_Hash
;
163 $searchBase = "[{<\n";
164 $revText = strrev( $text ); // For fast reverse searches
166 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
167 $accum =& $stack->getAccum(); # Current accumulator
168 $findEquals = false; # True to find equals signs in arguments
169 $findPipe = false; # True to take notice of pipe characters
171 $inHeading = false; # True if $i is inside a possible heading
172 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
173 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
174 $fakeLineStart = true; # Do a line-start run without outputting an LF character
179 if ( $findOnlyinclude ) {
180 // Ignore all input up to the next <onlyinclude>
181 $startPos = strpos( $text, '<onlyinclude>', $i );
182 if ( $startPos === false ) {
183 // Ignored section runs to the end
184 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
187 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
188 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
190 $findOnlyinclude = false;
193 if ( $fakeLineStart ) {
194 $found = 'line-start';
197 # Find next opening brace, closing brace or pipe
198 $search = $searchBase;
199 if ( $stack->top
=== false ) {
200 $currentClosing = '';
202 $currentClosing = $stack->top
->close
;
203 $search .= $currentClosing;
209 // First equals will be for the template
213 # Output literal section, advance input counter
214 $literalLength = strcspn( $text, $search, $i );
215 if ( $literalLength > 0 ) {
216 $accum->addLiteral( substr( $text, $i, $literalLength ) );
217 $i +
= $literalLength;
219 if ( $i >= strlen( $text ) ) {
220 if ( $currentClosing == "\n" ) {
221 // Do a past-the-end run to finish off the heading
229 $curChar = $text[$i];
230 if ( $curChar == '|' ) {
232 } elseif ( $curChar == '=' ) {
234 } elseif ( $curChar == '<' ) {
236 } elseif ( $curChar == "\n" ) {
240 $found = 'line-start';
242 } elseif ( $curChar == $currentClosing ) {
244 } elseif ( isset( $rules[$curChar] ) ) {
246 $rule = $rules[$curChar];
248 # Some versions of PHP have a strcspn which stops on null characters
249 # Ignore and continue
256 if ( $found == 'angle' ) {
258 // Handle </onlyinclude>
259 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
260 $findOnlyinclude = true;
264 // Determine element name
265 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
266 // Element name missing or not listed
267 $accum->addLiteral( '<' );
272 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
273 // To avoid leaving blank lines, when a comment is both preceded
274 // and followed by a newline (ignoring spaces), trim leading and
275 // trailing spaces and one of the newlines.
278 $endPos = strpos( $text, '-->', $i +
4 );
279 if ( $endPos === false ) {
280 // Unclosed comment in input, runs to end
281 $inner = substr( $text, $i );
282 $accum->addNodeWithText( 'comment', $inner );
283 $i = strlen( $text );
285 // Search backwards for leading whitespace
286 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
287 // Search forwards for trailing whitespace
288 // $wsEnd will be the position of the last space (or the '>' if there's none)
289 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
290 // Eat the line if possible
291 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
292 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
293 // it's a possible beneficial b/c break.
294 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
295 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
297 $startPos = $wsStart;
298 $endPos = $wsEnd +
1;
299 // Remove leading whitespace from the end of the accumulator
300 // Sanity check first though
301 $wsLength = $i - $wsStart;
303 && $accum->lastNode
instanceof PPNode_Hash_Text
304 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
306 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
308 // Do a line-start run next time to look for headings after the comment
309 $fakeLineStart = true;
311 // No line to eat, just take the comment itself
317 $part = $stack->top
->getCurrentPart();
318 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
319 $part->visualEnd
= $wsStart;
321 // Else comments abutting, no change in visual end
322 $part->commentEnd
= $endPos;
325 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
326 $accum->addNodeWithText( 'comment', $inner );
331 $lowerName = strtolower( $name );
332 $attrStart = $i +
strlen( $name ) +
1;
335 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
336 if ( $tagEndPos === false ) {
337 // Infinite backtrack
338 // Disable tag search to prevent worst-case O(N^2) performance
340 $accum->addLiteral( '<' );
345 // Handle ignored tags
346 if ( in_array( $lowerName, $ignoredTags ) ) {
347 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
353 if ( $text[$tagEndPos-1] == '/' ) {
355 $attrEnd = $tagEndPos - 1;
360 $attrEnd = $tagEndPos;
362 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
363 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
365 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
366 $i = $matches[0][1] +
strlen( $matches[0][0] );
367 $close = $matches[0][0];
369 // No end tag -- let it run out to the end of the text.
370 $inner = substr( $text, $tagEndPos +
1 );
371 $i = strlen( $text );
375 // <includeonly> and <noinclude> just become <ignore> tags
376 if ( in_array( $lowerName, $ignoredElements ) ) {
377 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
381 if ( $attrEnd <= $attrStart ) {
384 // Note that the attr element contains the whitespace between name and attribute,
385 // this is necessary for precise reconstruction during pre-save transform.
386 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
389 $extNode = new PPNode_Hash_Tree( 'ext' );
390 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
391 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
392 if ( $inner !== null ) {
393 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
395 if ( $close !== null ) {
396 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
398 $accum->addNode( $extNode );
401 elseif ( $found == 'line-start' ) {
402 // Is this the start of a heading?
403 // Line break belongs before the heading element in any case
404 if ( $fakeLineStart ) {
405 $fakeLineStart = false;
407 $accum->addLiteral( $curChar );
411 $count = strspn( $text, '=', $i, 6 );
412 if ( $count == 1 && $findEquals ) {
413 // DWIM: This looks kind of like a name/value separator
414 // Let's let the equals handler have it and break the potential heading
415 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
416 } elseif ( $count > 0 ) {
420 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
423 $stack->push( $piece );
424 $accum =& $stack->getAccum();
425 extract( $stack->getFlags() );
428 } elseif ( $found == 'line-end' ) {
429 $piece = $stack->top
;
430 // A heading must be open, otherwise \n wouldn't have been in the search list
431 assert( $piece->open
== "\n" );
432 $part = $piece->getCurrentPart();
433 // Search back through the input to see if it has a proper close
434 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
435 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
436 $searchStart = $i - $wsLength;
437 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
438 // Comment found at line end
439 // Search for equals signs before the comment
440 $searchStart = $part->visualEnd
;
441 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
443 $count = $piece->count
;
444 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
445 if ( $equalsLength > 0 ) {
446 if ( $searchStart - $equalsLength == $piece->startPos
) {
447 // This is just a single string of equals signs on its own line
448 // Replicate the doHeadings behaviour /={count}(.+)={count}/
449 // First find out how many equals signs there really are (don't stop at 6)
450 $count = $equalsLength;
454 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
457 $count = min( $equalsLength, $count );
460 // Normal match, output <h>
461 $element = new PPNode_Hash_Tree( 'possible-h' );
462 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
463 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
464 $element->lastChild
->nextSibling
= $accum->firstNode
;
465 $element->lastChild
= $accum->lastNode
;
467 // Single equals sign on its own line, count=0
471 // No match, no <h>, just pass down the inner text
476 $accum =& $stack->getAccum();
477 extract( $stack->getFlags() );
479 // Append the result to the enclosing accumulator
480 if ( $element instanceof PPNode
) {
481 $accum->addNode( $element );
483 $accum->addAccum( $element );
485 // Note that we do NOT increment the input pointer.
486 // This is because the closing linebreak could be the opening linebreak of
487 // another heading. Infinite loops are avoided because the next iteration MUST
488 // hit the heading open case above, which unconditionally increments the
490 } elseif ( $found == 'open' ) {
491 # count opening brace characters
492 $count = strspn( $text, $curChar, $i );
494 # we need to add to stack only if opening brace count is enough for one of the rules
495 if ( $count >= $rule['min'] ) {
496 # Add it to the stack
499 'close' => $rule['end'],
501 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
504 $stack->push( $piece );
505 $accum =& $stack->getAccum();
506 extract( $stack->getFlags() );
508 # Add literal brace(s)
509 $accum->addLiteral( str_repeat( $curChar, $count ) );
512 } elseif ( $found == 'close' ) {
513 $piece = $stack->top
;
514 # lets check if there are enough characters for closing brace
515 $maxCount = $piece->count
;
516 $count = strspn( $text, $curChar, $i, $maxCount );
518 # check for maximum matching characters (if there are 5 closing
519 # characters, we will probably need only 3 - depending on the rules)
520 $rule = $rules[$piece->open
];
521 if ( $count > $rule['max'] ) {
522 # The specified maximum exists in the callback array, unless the caller
524 $matchingCount = $rule['max'];
526 # Count is less than the maximum
527 # Skip any gaps in the callback array to find the true largest match
528 # Need to use array_key_exists not isset because the callback can be null
529 $matchingCount = $count;
530 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
535 if ($matchingCount <= 0) {
536 # No matching element found in callback array
537 # Output a literal closing brace and continue
538 $accum->addLiteral( str_repeat( $curChar, $count ) );
542 $name = $rule['names'][$matchingCount];
543 if ( $name === null ) {
544 // No element, just literal text
545 $element = $piece->breakSyntax( $matchingCount );
546 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
549 # Note: $parts is already XML, does not need to be encoded further
550 $parts = $piece->parts
;
551 $titleAccum = $parts[0]->out
;
554 $element = new PPNode_Hash_Tree( $name );
556 # The invocation is at the start of the line if lineStart is set in
557 # the stack, and all opening brackets are used up.
558 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
559 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
561 $titleNode = new PPNode_Hash_Tree( 'title' );
562 $titleNode->firstChild
= $titleAccum->firstNode
;
563 $titleNode->lastChild
= $titleAccum->lastNode
;
564 $element->addChild( $titleNode );
566 foreach ( $parts as $part ) {
567 if ( isset( $part->eqpos
) ) {
570 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
571 if ( $node === $part->eqpos
) {
577 throw new MWException( __METHOD__
. ': eqpos not found' );
579 if ( $node->name
!== 'equals' ) {
580 throw new MWException( __METHOD__
.': eqpos is not equals' );
584 // Construct name node
585 $nameNode = new PPNode_Hash_Tree( 'name' );
586 if ( $lastNode !== false ) {
587 $lastNode->nextSibling
= false;
588 $nameNode->firstChild
= $part->out
->firstNode
;
589 $nameNode->lastChild
= $lastNode;
592 // Construct value node
593 $valueNode = new PPNode_Hash_Tree( 'value' );
594 if ( $equalsNode->nextSibling
!== false ) {
595 $valueNode->firstChild
= $equalsNode->nextSibling
;
596 $valueNode->lastChild
= $part->out
->lastNode
;
598 $partNode = new PPNode_Hash_Tree( 'part' );
599 $partNode->addChild( $nameNode );
600 $partNode->addChild( $equalsNode->firstChild
);
601 $partNode->addChild( $valueNode );
602 $element->addChild( $partNode );
604 $partNode = new PPNode_Hash_Tree( 'part' );
605 $nameNode = new PPNode_Hash_Tree( 'name' );
606 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
607 $valueNode = new PPNode_Hash_Tree( 'value' );
608 $valueNode->firstChild
= $part->out
->firstNode
;
609 $valueNode->lastChild
= $part->out
->lastNode
;
610 $partNode->addChild( $nameNode );
611 $partNode->addChild( $valueNode );
612 $element->addChild( $partNode );
617 # Advance input pointer
618 $i +
= $matchingCount;
622 $accum =& $stack->getAccum();
624 # Re-add the old stack element if it still has unmatched opening characters remaining
625 if ($matchingCount < $piece->count
) {
626 $piece->parts
= array( new PPDPart_Hash
);
627 $piece->count
-= $matchingCount;
628 # do we still qualify for any callback with remaining count?
629 $names = $rules[$piece->open
]['names'];
631 $enclosingAccum =& $accum;
632 while ( $piece->count
) {
633 if ( array_key_exists( $piece->count
, $names ) ) {
634 $stack->push( $piece );
635 $accum =& $stack->getAccum();
641 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
644 extract( $stack->getFlags() );
646 # Add XML element to the enclosing accumulator
647 if ( $element instanceof PPNode
) {
648 $accum->addNode( $element );
650 $accum->addAccum( $element );
652 } elseif ( $found == 'pipe' ) {
653 $findEquals = true; // shortcut for getFlags()
655 $accum =& $stack->getAccum();
657 } elseif ( $found == 'equals' ) {
658 $findEquals = false; // shortcut for getFlags()
659 $accum->addNodeWithText( 'equals', '=' );
660 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
665 # Output any remaining unclosed brackets
666 foreach ( $stack->stack
as $piece ) {
667 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
670 # Enable top-level headings
671 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
672 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
677 $rootNode = new PPNode_Hash_Tree( 'root' );
678 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
679 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
683 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
684 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
685 wfProfileOut( __METHOD__
.'-cache-miss' );
686 wfProfileOut( __METHOD__
.'-cacheable' );
687 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
690 wfProfileOut( __METHOD__
);
696 * Stack class to help Preprocessor::preprocessToObj()
699 class PPDStack_Hash
extends PPDStack
{
700 function __construct() {
701 $this->elementClass
= 'PPDStackElement_Hash';
702 parent
::__construct();
703 $this->rootAccum
= new PPDAccum_Hash
;
710 class PPDStackElement_Hash
extends PPDStackElement
{
711 function __construct( $data = array() ) {
712 $this->partClass
= 'PPDPart_Hash';
713 parent
::__construct( $data );
717 * Get the accumulator that would result if the close is not found.
719 * @return PPDAccum_Hash
721 function breakSyntax( $openingCount = false ) {
722 if ( $this->open
== "\n" ) {
723 $accum = $this->parts
[0]->out
;
725 if ( $openingCount === false ) {
726 $openingCount = $this->count
;
728 $accum = new PPDAccum_Hash
;
729 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
731 foreach ( $this->parts
as $part ) {
735 $accum->addLiteral( '|' );
737 $accum->addAccum( $part->out
);
747 class PPDPart_Hash
extends PPDPart
{
748 function __construct( $out = '' ) {
749 $accum = new PPDAccum_Hash
;
751 $accum->addLiteral( $out );
753 parent
::__construct( $accum );
760 class PPDAccum_Hash
{
761 var $firstNode, $lastNode;
763 function __construct() {
764 $this->firstNode
= $this->lastNode
= false;
768 * Append a string literal
770 function addLiteral( $s ) {
771 if ( $this->lastNode
=== false ) {
772 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
773 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
774 $this->lastNode
->value
.= $s;
776 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
777 $this->lastNode
= $this->lastNode
->nextSibling
;
784 function addNode( PPNode
$node ) {
785 if ( $this->lastNode
=== false ) {
786 $this->firstNode
= $this->lastNode
= $node;
788 $this->lastNode
->nextSibling
= $node;
789 $this->lastNode
= $node;
794 * Append a tree node with text contents
796 function addNodeWithText( $name, $value ) {
797 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
798 $this->addNode( $node );
802 * Append a PPAccum_Hash
803 * Takes over ownership of the nodes in the source argument. These nodes may
804 * subsequently be modified, especially nextSibling.
806 function addAccum( $accum ) {
807 if ( $accum->lastNode
=== false ) {
809 } elseif ( $this->lastNode
=== false ) {
810 $this->firstNode
= $accum->firstNode
;
811 $this->lastNode
= $accum->lastNode
;
813 $this->lastNode
->nextSibling
= $accum->firstNode
;
814 $this->lastNode
= $accum->lastNode
;
820 * An expansion frame, used as a context to expand the result of preprocessToObj()
823 class PPFrame_Hash
implements PPFrame
{
842 * Hashtable listing templates which are disallowed for expansion in this frame,
843 * having been encountered previously in parent frames.
848 * Recursion depth of this frame, top = 0
849 * Note that this is NOT the same as expansion depth in expand()
855 * Construct a new preprocessor frame.
856 * @param $preprocessor Preprocessor: the parent preprocessor
858 function __construct( $preprocessor ) {
859 $this->preprocessor
= $preprocessor;
860 $this->parser
= $preprocessor->parser
;
861 $this->title
= $this->parser
->mTitle
;
862 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
863 $this->loopCheckHash
= array();
868 * Create a new child frame
869 * $args is optionally a multi-root PPNode or array containing the template arguments
871 * @param $args PPNode_Hash_Array|array
872 * @param $title Title|false
874 * @return PPTemplateFrame_Hash
876 function newChild( $args = false, $title = false ) {
877 $namedArgs = array();
878 $numberedArgs = array();
879 if ( $title === false ) {
880 $title = $this->title
;
882 if ( $args !== false ) {
883 if ( $args instanceof PPNode_Hash_Array
) {
884 $args = $args->value
;
885 } elseif ( !is_array( $args ) ) {
886 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
888 foreach ( $args as $arg ) {
889 $bits = $arg->splitArg();
890 if ( $bits['index'] !== '' ) {
891 // Numbered parameter
892 $numberedArgs[$bits['index']] = $bits['value'];
893 unset( $namedArgs[$bits['index']] );
896 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
897 $namedArgs[$name] = $bits['value'];
898 unset( $numberedArgs[$name] );
902 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
906 * @throws MWException
911 function expand( $root, $flags = 0 ) {
912 static $expansionDepth = 0;
913 if ( is_string( $root ) ) {
917 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
918 return '<span class="error">Node-count limit exceeded</span>';
920 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
921 return '<span class="error">Expansion depth limit exceeded</span>';
925 $outStack = array( '', '' );
926 $iteratorStack = array( false, $root );
927 $indexStack = array( 0, 0 );
929 while ( count( $iteratorStack ) > 1 ) {
930 $level = count( $outStack ) - 1;
931 $iteratorNode =& $iteratorStack[ $level ];
932 $out =& $outStack[$level];
933 $index =& $indexStack[$level];
935 if ( is_array( $iteratorNode ) ) {
936 if ( $index >= count( $iteratorNode ) ) {
937 // All done with this iterator
938 $iteratorStack[$level] = false;
939 $contextNode = false;
941 $contextNode = $iteratorNode[$index];
944 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
945 if ( $index >= $iteratorNode->getLength() ) {
946 // All done with this iterator
947 $iteratorStack[$level] = false;
948 $contextNode = false;
950 $contextNode = $iteratorNode->item( $index );
954 // Copy to $contextNode and then delete from iterator stack,
955 // because this is not an iterator but we do have to execute it once
956 $contextNode = $iteratorStack[$level];
957 $iteratorStack[$level] = false;
960 $newIterator = false;
962 if ( $contextNode === false ) {
964 } elseif ( is_string( $contextNode ) ) {
965 $out .= $contextNode;
966 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
967 $newIterator = $contextNode;
968 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
970 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
971 $out .= $contextNode->value
;
972 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
973 if ( $contextNode->name
== 'template' ) {
974 # Double-brace expansion
975 $bits = $contextNode->splitTemplate();
976 if ( $flags & PPFrame
::NO_TEMPLATES
) {
977 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
979 $bits['interwiki'] = $this->title
->getInterwiki( );
980 $ret = $this->parser
->braceSubstitution( $bits, $this );
981 if ( isset( $ret['object'] ) ) {
982 $newIterator = $ret['object'];
984 $out .= $ret['text'];
987 } elseif ( $contextNode->name
== 'tplarg' ) {
988 # Triple-brace expansion
989 $bits = $contextNode->splitTemplate();
990 if ( $flags & PPFrame
::NO_ARGS
) {
991 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
993 $ret = $this->parser
->argSubstitution( $bits, $this );
994 if ( isset( $ret['object'] ) ) {
995 $newIterator = $ret['object'];
997 $out .= $ret['text'];
1000 } elseif ( $contextNode->name
== 'comment' ) {
1001 # HTML-style comment
1002 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1003 if ( $this->parser
->ot
['html']
1004 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1005 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1009 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1010 # Not in RECOVER_COMMENTS mode (extractSections) though
1011 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1012 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1014 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1016 $out .= $contextNode->firstChild
->value
;
1018 } elseif ( $contextNode->name
== 'ignore' ) {
1019 # Output suppression used by <includeonly> etc.
1020 # OT_WIKI will only respect <ignore> in substed templates.
1021 # The other output types respect it unless NO_IGNORE is set.
1022 # extractSections() sets NO_IGNORE and so never respects it.
1023 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1024 $out .= $contextNode->firstChild
->value
;
1028 } elseif ( $contextNode->name
== 'ext' ) {
1030 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1031 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1032 } elseif ( $contextNode->name
== 'h' ) {
1034 if ( $this->parser
->ot
['html'] ) {
1035 # Expand immediately and insert heading index marker
1037 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1038 $s .= $this->expand( $node, $flags );
1041 $bits = $contextNode->splitHeading();
1042 $titleText = $this->title
->getPrefixedDBkey();
1043 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1044 $serial = count( $this->parser
->mHeadings
) - 1;
1045 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1046 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1047 $this->parser
->mStripState
->addGeneral( $marker, '' );
1050 # Expand in virtual stack
1051 $newIterator = $contextNode->getChildren();
1054 # Generic recursive expansion
1055 $newIterator = $contextNode->getChildren();
1058 throw new MWException( __METHOD__
.': Invalid parameter type' );
1061 if ( $newIterator !== false ) {
1063 $iteratorStack[] = $newIterator;
1065 } elseif ( $iteratorStack[$level] === false ) {
1066 // Return accumulated value to parent
1067 // With tail recursion
1068 while ( $iteratorStack[$level] === false && $level > 0 ) {
1069 $outStack[$level - 1] .= $out;
1070 array_pop( $outStack );
1071 array_pop( $iteratorStack );
1072 array_pop( $indexStack );
1078 return $outStack[0];
1086 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1087 $args = array_slice( func_get_args(), 2 );
1091 foreach ( $args as $root ) {
1092 if ( $root instanceof PPNode_Hash_Array
) {
1093 $root = $root->value
;
1095 if ( !is_array( $root ) ) {
1096 $root = array( $root );
1098 foreach ( $root as $node ) {
1104 $s .= $this->expand( $node, $flags );
1111 * Implode with no flags specified
1112 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1115 function implode( $sep /*, ... */ ) {
1116 $args = array_slice( func_get_args(), 1 );
1120 foreach ( $args as $root ) {
1121 if ( $root instanceof PPNode_Hash_Array
) {
1122 $root = $root->value
;
1124 if ( !is_array( $root ) ) {
1125 $root = array( $root );
1127 foreach ( $root as $node ) {
1133 $s .= $this->expand( $node );
1140 * Makes an object that, when expand()ed, will be the same as one obtained
1143 * @return PPNode_Hash_Array
1145 function virtualImplode( $sep /*, ... */ ) {
1146 $args = array_slice( func_get_args(), 1 );
1150 foreach ( $args as $root ) {
1151 if ( $root instanceof PPNode_Hash_Array
) {
1152 $root = $root->value
;
1154 if ( !is_array( $root ) ) {
1155 $root = array( $root );
1157 foreach ( $root as $node ) {
1166 return new PPNode_Hash_Array( $out );
1170 * Virtual implode with brackets
1172 * @return PPNode_Hash_Array
1174 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1175 $args = array_slice( func_get_args(), 3 );
1176 $out = array( $start );
1179 foreach ( $args as $root ) {
1180 if ( $root instanceof PPNode_Hash_Array
) {
1181 $root = $root->value
;
1183 if ( !is_array( $root ) ) {
1184 $root = array( $root );
1186 foreach ( $root as $node ) {
1196 return new PPNode_Hash_Array( $out );
1199 function __toString() {
1204 * @param $level bool
1205 * @return array|bool|String
1207 function getPDBK( $level = false ) {
1208 if ( $level === false ) {
1209 return $this->title
->getPrefixedDBkey();
1211 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1218 function getArguments() {
1225 function getNumberedArguments() {
1232 function getNamedArguments() {
1237 * Returns true if there are no arguments in this frame
1241 function isEmpty() {
1249 function getArgument( $name ) {
1254 * Returns true if the infinite loop check is OK, false if a loop is detected
1256 * @param $title Title
1260 function loopCheck( $title ) {
1261 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1265 * Return true if the frame is a template frame
1269 function isTemplate() {
1275 * Expansion frame with template arguments
1278 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1279 var $numberedArgs, $namedArgs, $parent;
1280 var $numberedExpansionCache, $namedExpansionCache;
1283 * @param $preprocessor
1285 * @param $numberedArgs array
1286 * @param $namedArgs array
1287 * @param $title Title
1289 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1290 parent
::__construct( $preprocessor );
1292 $this->parent
= $parent;
1293 $this->numberedArgs
= $numberedArgs;
1294 $this->namedArgs
= $namedArgs;
1295 $this->title
= $title;
1296 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1297 $this->titleCache
= $parent->titleCache
;
1298 $this->titleCache
[] = $pdbk;
1299 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1300 if ( $pdbk !== false ) {
1301 $this->loopCheckHash
[$pdbk] = true;
1303 $this->depth
= $parent->depth +
1;
1304 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1307 function __toString() {
1310 $args = $this->numberedArgs +
$this->namedArgs
;
1311 foreach ( $args as $name => $value ) {
1317 $s .= "\"$name\":\"" .
1318 str_replace( '"', '\\"', $value->__toString() ) . '"';
1324 * Returns true if there are no arguments in this frame
1328 function isEmpty() {
1329 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1335 function getArguments() {
1336 $arguments = array();
1337 foreach ( array_merge(
1338 array_keys($this->numberedArgs
),
1339 array_keys($this->namedArgs
)) as $key ) {
1340 $arguments[$key] = $this->getArgument($key);
1348 function getNumberedArguments() {
1349 $arguments = array();
1350 foreach ( array_keys($this->numberedArgs
) as $key ) {
1351 $arguments[$key] = $this->getArgument($key);
1359 function getNamedArguments() {
1360 $arguments = array();
1361 foreach ( array_keys($this->namedArgs
) as $key ) {
1362 $arguments[$key] = $this->getArgument($key);
1369 * @return array|bool
1371 function getNumberedArgument( $index ) {
1372 if ( !isset( $this->numberedArgs
[$index] ) ) {
1375 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1376 # No trimming for unnamed arguments
1377 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1379 return $this->numberedExpansionCache
[$index];
1386 function getNamedArgument( $name ) {
1387 if ( !isset( $this->namedArgs
[$name] ) ) {
1390 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1391 # Trim named arguments post-expand, for backwards compatibility
1392 $this->namedExpansionCache
[$name] = trim(
1393 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1395 return $this->namedExpansionCache
[$name];
1400 * @return array|bool
1402 function getArgument( $name ) {
1403 $text = $this->getNumberedArgument( $name );
1404 if ( $text === false ) {
1405 $text = $this->getNamedArgument( $name );
1411 * Return true if the frame is a template frame
1415 function isTemplate() {
1421 * Expansion frame with custom arguments
1424 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1427 function __construct( $preprocessor, $args ) {
1428 parent
::__construct( $preprocessor );
1429 $this->args
= $args;
1432 function __toString() {
1435 foreach ( $this->args
as $name => $value ) {
1441 $s .= "\"$name\":\"" .
1442 str_replace( '"', '\\"', $value->__toString() ) . '"';
1451 function isEmpty() {
1452 return !count( $this->args
);
1459 function getArgument( $index ) {
1460 if ( !isset( $this->args
[$index] ) ) {
1463 return $this->args
[$index];
1470 class PPNode_Hash_Tree
implements PPNode
{
1471 var $name, $firstChild, $lastChild, $nextSibling;
1473 function __construct( $name ) {
1474 $this->name
= $name;
1475 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1478 function __toString() {
1481 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1482 if ( $node instanceof PPNode_Hash_Attr
) {
1483 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1485 $inner .= $node->__toString();
1488 if ( $inner === '' ) {
1489 return "<{$this->name}$attribs/>";
1491 return "<{$this->name}$attribs>$inner</{$this->name}>";
1498 * @return PPNode_Hash_Tree
1500 static function newWithText( $name, $text ) {
1501 $obj = new self( $name );
1502 $obj->addChild( new PPNode_Hash_Text( $text ) );
1506 function addChild( $node ) {
1507 if ( $this->lastChild
=== false ) {
1508 $this->firstChild
= $this->lastChild
= $node;
1510 $this->lastChild
->nextSibling
= $node;
1511 $this->lastChild
= $node;
1516 * @return PPNode_Hash_Array
1518 function getChildren() {
1519 $children = array();
1520 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1521 $children[] = $child;
1523 return new PPNode_Hash_Array( $children );
1526 function getFirstChild() {
1527 return $this->firstChild
;
1530 function getNextSibling() {
1531 return $this->nextSibling
;
1534 function getChildrenOfType( $name ) {
1535 $children = array();
1536 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1537 if ( isset( $child->name
) && $child->name
=== $name ) {
1538 $children[] = $name;
1547 function getLength() {
1555 function item( $i ) {
1562 function getName() {
1567 * Split a <part> node into an associative array containing:
1569 * index String index
1570 * value PPNode value
1574 function splitArg() {
1576 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1577 if ( !isset( $child->name
) ) {
1580 if ( $child->name
=== 'name' ) {
1581 $bits['name'] = $child;
1582 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1583 && $child->firstChild
->name
=== 'index' )
1585 $bits['index'] = $child->firstChild
->value
;
1587 } elseif ( $child->name
=== 'value' ) {
1588 $bits['value'] = $child;
1592 if ( !isset( $bits['name'] ) ) {
1593 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1595 if ( !isset( $bits['index'] ) ) {
1596 $bits['index'] = '';
1602 * Split an <ext> node into an associative array containing name, attr, inner and close
1603 * All values in the resulting array are PPNodes. Inner and close are optional.
1607 function splitExt() {
1609 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1610 if ( !isset( $child->name
) ) {
1613 if ( $child->name
== 'name' ) {
1614 $bits['name'] = $child;
1615 } elseif ( $child->name
== 'attr' ) {
1616 $bits['attr'] = $child;
1617 } elseif ( $child->name
== 'inner' ) {
1618 $bits['inner'] = $child;
1619 } elseif ( $child->name
== 'close' ) {
1620 $bits['close'] = $child;
1623 if ( !isset( $bits['name'] ) ) {
1624 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1634 function splitHeading() {
1635 if ( $this->name
!== 'h' ) {
1636 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1639 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1640 if ( !isset( $child->name
) ) {
1643 if ( $child->name
== 'i' ) {
1644 $bits['i'] = $child->value
;
1645 } elseif ( $child->name
== 'level' ) {
1646 $bits['level'] = $child->value
;
1649 if ( !isset( $bits['i'] ) ) {
1650 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1656 * Split a <template> or <tplarg> node
1660 function splitTemplate() {
1662 $bits = array( 'lineStart' => '' );
1663 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1664 if ( !isset( $child->name
) ) {
1667 if ( $child->name
== 'title' ) {
1668 $bits['title'] = $child;
1670 if ( $child->name
== 'part' ) {
1673 if ( $child->name
== 'lineStart' ) {
1674 $bits['lineStart'] = '1';
1677 if ( !isset( $bits['title'] ) ) {
1678 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1680 $bits['parts'] = new PPNode_Hash_Array( $parts );
1688 class PPNode_Hash_Text
implements PPNode
{
1689 var $value, $nextSibling;
1691 function __construct( $value ) {
1692 if ( is_object( $value ) ) {
1693 throw new MWException( __CLASS__
. ' given object instead of string' );
1695 $this->value
= $value;
1698 function __toString() {
1699 return htmlspecialchars( $this->value
);
1702 function getNextSibling() {
1703 return $this->nextSibling
;
1706 function getChildren() { return false; }
1707 function getFirstChild() { return false; }
1708 function getChildrenOfType( $name ) { return false; }
1709 function getLength() { return false; }
1710 function item( $i ) { return false; }
1711 function getName() { return '#text'; }
1712 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1713 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1714 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1720 class PPNode_Hash_Array
implements PPNode
{
1721 var $value, $nextSibling;
1723 function __construct( $value ) {
1724 $this->value
= $value;
1727 function __toString() {
1728 return var_export( $this, true );
1731 function getLength() {
1732 return count( $this->value
);
1735 function item( $i ) {
1736 return $this->value
[$i];
1739 function getName() { return '#nodelist'; }
1741 function getNextSibling() {
1742 return $this->nextSibling
;
1745 function getChildren() { return false; }
1746 function getFirstChild() { return false; }
1747 function getChildrenOfType( $name ) { return false; }
1748 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1749 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1750 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1756 class PPNode_Hash_Attr
implements PPNode
{
1757 var $name, $value, $nextSibling;
1759 function __construct( $name, $value ) {
1760 $this->name
= $name;
1761 $this->value
= $value;
1764 function __toString() {
1765 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1768 function getName() {
1772 function getNextSibling() {
1773 return $this->nextSibling
;
1776 function getChildren() { return false; }
1777 function getFirstChild() { return false; }
1778 function getChildrenOfType( $name ) { return false; }
1779 function getLength() { return false; }
1780 function item( $i ) { return false; }
1781 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1782 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1783 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }