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|bool
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 $this->parser
->limitationWarn( 'node-count-exceeded',
919 $this->parser
->mPPNodeCount
,
920 $this->parser
->mOptions
->getMaxPPNodeCount()
922 return '<span class="error">Node-count limit exceeded</span>';
924 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
925 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
927 $this->parser
->mOptions
->getMaxPPExpandDepth()
929 return '<span class="error">Expansion depth limit exceeded</span>';
933 $outStack = array( '', '' );
934 $iteratorStack = array( false, $root );
935 $indexStack = array( 0, 0 );
937 while ( count( $iteratorStack ) > 1 ) {
938 $level = count( $outStack ) - 1;
939 $iteratorNode =& $iteratorStack[ $level ];
940 $out =& $outStack[$level];
941 $index =& $indexStack[$level];
943 if ( is_array( $iteratorNode ) ) {
944 if ( $index >= count( $iteratorNode ) ) {
945 // All done with this iterator
946 $iteratorStack[$level] = false;
947 $contextNode = false;
949 $contextNode = $iteratorNode[$index];
952 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
953 if ( $index >= $iteratorNode->getLength() ) {
954 // All done with this iterator
955 $iteratorStack[$level] = false;
956 $contextNode = false;
958 $contextNode = $iteratorNode->item( $index );
962 // Copy to $contextNode and then delete from iterator stack,
963 // because this is not an iterator but we do have to execute it once
964 $contextNode = $iteratorStack[$level];
965 $iteratorStack[$level] = false;
968 $newIterator = false;
970 if ( $contextNode === false ) {
972 } elseif ( is_string( $contextNode ) ) {
973 $out .= $contextNode;
974 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
975 $newIterator = $contextNode;
976 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
978 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
979 $out .= $contextNode->value
;
980 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
981 if ( $contextNode->name
== 'template' ) {
982 # Double-brace expansion
983 $bits = $contextNode->splitTemplate();
984 if ( $flags & PPFrame
::NO_TEMPLATES
) {
985 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
987 $ret = $this->parser
->braceSubstitution( $bits, $this );
988 if ( isset( $ret['object'] ) ) {
989 $newIterator = $ret['object'];
991 $out .= $ret['text'];
994 } elseif ( $contextNode->name
== 'tplarg' ) {
995 # Triple-brace expansion
996 $bits = $contextNode->splitTemplate();
997 if ( $flags & PPFrame
::NO_ARGS
) {
998 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1000 $ret = $this->parser
->argSubstitution( $bits, $this );
1001 if ( isset( $ret['object'] ) ) {
1002 $newIterator = $ret['object'];
1004 $out .= $ret['text'];
1007 } elseif ( $contextNode->name
== 'comment' ) {
1008 # HTML-style comment
1009 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1010 if ( $this->parser
->ot
['html']
1011 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1012 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1016 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1017 # Not in RECOVER_COMMENTS mode (extractSections) though
1018 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1019 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1021 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1023 $out .= $contextNode->firstChild
->value
;
1025 } elseif ( $contextNode->name
== 'ignore' ) {
1026 # Output suppression used by <includeonly> etc.
1027 # OT_WIKI will only respect <ignore> in substed templates.
1028 # The other output types respect it unless NO_IGNORE is set.
1029 # extractSections() sets NO_IGNORE and so never respects it.
1030 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1031 $out .= $contextNode->firstChild
->value
;
1035 } elseif ( $contextNode->name
== 'ext' ) {
1037 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1038 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1039 } elseif ( $contextNode->name
== 'h' ) {
1041 if ( $this->parser
->ot
['html'] ) {
1042 # Expand immediately and insert heading index marker
1044 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1045 $s .= $this->expand( $node, $flags );
1048 $bits = $contextNode->splitHeading();
1049 $titleText = $this->title
->getPrefixedDBkey();
1050 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1051 $serial = count( $this->parser
->mHeadings
) - 1;
1052 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1053 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1054 $this->parser
->mStripState
->addGeneral( $marker, '' );
1057 # Expand in virtual stack
1058 $newIterator = $contextNode->getChildren();
1061 # Generic recursive expansion
1062 $newIterator = $contextNode->getChildren();
1065 throw new MWException( __METHOD__
.': Invalid parameter type' );
1068 if ( $newIterator !== false ) {
1070 $iteratorStack[] = $newIterator;
1072 } elseif ( $iteratorStack[$level] === false ) {
1073 // Return accumulated value to parent
1074 // With tail recursion
1075 while ( $iteratorStack[$level] === false && $level > 0 ) {
1076 $outStack[$level - 1] .= $out;
1077 array_pop( $outStack );
1078 array_pop( $iteratorStack );
1079 array_pop( $indexStack );
1085 return $outStack[0];
1093 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1094 $args = array_slice( func_get_args(), 2 );
1098 foreach ( $args as $root ) {
1099 if ( $root instanceof PPNode_Hash_Array
) {
1100 $root = $root->value
;
1102 if ( !is_array( $root ) ) {
1103 $root = array( $root );
1105 foreach ( $root as $node ) {
1111 $s .= $this->expand( $node, $flags );
1118 * Implode with no flags specified
1119 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1122 function implode( $sep /*, ... */ ) {
1123 $args = array_slice( func_get_args(), 1 );
1127 foreach ( $args as $root ) {
1128 if ( $root instanceof PPNode_Hash_Array
) {
1129 $root = $root->value
;
1131 if ( !is_array( $root ) ) {
1132 $root = array( $root );
1134 foreach ( $root as $node ) {
1140 $s .= $this->expand( $node );
1147 * Makes an object that, when expand()ed, will be the same as one obtained
1150 * @return PPNode_Hash_Array
1152 function virtualImplode( $sep /*, ... */ ) {
1153 $args = array_slice( func_get_args(), 1 );
1157 foreach ( $args as $root ) {
1158 if ( $root instanceof PPNode_Hash_Array
) {
1159 $root = $root->value
;
1161 if ( !is_array( $root ) ) {
1162 $root = array( $root );
1164 foreach ( $root as $node ) {
1173 return new PPNode_Hash_Array( $out );
1177 * Virtual implode with brackets
1179 * @return PPNode_Hash_Array
1181 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1182 $args = array_slice( func_get_args(), 3 );
1183 $out = array( $start );
1186 foreach ( $args as $root ) {
1187 if ( $root instanceof PPNode_Hash_Array
) {
1188 $root = $root->value
;
1190 if ( !is_array( $root ) ) {
1191 $root = array( $root );
1193 foreach ( $root as $node ) {
1203 return new PPNode_Hash_Array( $out );
1206 function __toString() {
1211 * @param $level bool
1212 * @return array|bool|String
1214 function getPDBK( $level = false ) {
1215 if ( $level === false ) {
1216 return $this->title
->getPrefixedDBkey();
1218 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1225 function getArguments() {
1232 function getNumberedArguments() {
1239 function getNamedArguments() {
1244 * Returns true if there are no arguments in this frame
1248 function isEmpty() {
1256 function getArgument( $name ) {
1261 * Returns true if the infinite loop check is OK, false if a loop is detected
1263 * @param $title Title
1267 function loopCheck( $title ) {
1268 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1272 * Return true if the frame is a template frame
1276 function isTemplate() {
1281 * Get a title of frame
1285 function getTitle() {
1286 return $this->title
;
1291 * Expansion frame with template arguments
1294 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1295 var $numberedArgs, $namedArgs, $parent;
1296 var $numberedExpansionCache, $namedExpansionCache;
1299 * @param $preprocessor
1301 * @param $numberedArgs array
1302 * @param $namedArgs array
1303 * @param $title Title
1305 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1306 parent
::__construct( $preprocessor );
1308 $this->parent
= $parent;
1309 $this->numberedArgs
= $numberedArgs;
1310 $this->namedArgs
= $namedArgs;
1311 $this->title
= $title;
1312 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1313 $this->titleCache
= $parent->titleCache
;
1314 $this->titleCache
[] = $pdbk;
1315 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1316 if ( $pdbk !== false ) {
1317 $this->loopCheckHash
[$pdbk] = true;
1319 $this->depth
= $parent->depth +
1;
1320 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1323 function __toString() {
1326 $args = $this->numberedArgs +
$this->namedArgs
;
1327 foreach ( $args as $name => $value ) {
1333 $s .= "\"$name\":\"" .
1334 str_replace( '"', '\\"', $value->__toString() ) . '"';
1340 * Returns true if there are no arguments in this frame
1344 function isEmpty() {
1345 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1351 function getArguments() {
1352 $arguments = array();
1353 foreach ( array_merge(
1354 array_keys($this->numberedArgs
),
1355 array_keys($this->namedArgs
)) as $key ) {
1356 $arguments[$key] = $this->getArgument($key);
1364 function getNumberedArguments() {
1365 $arguments = array();
1366 foreach ( array_keys($this->numberedArgs
) as $key ) {
1367 $arguments[$key] = $this->getArgument($key);
1375 function getNamedArguments() {
1376 $arguments = array();
1377 foreach ( array_keys($this->namedArgs
) as $key ) {
1378 $arguments[$key] = $this->getArgument($key);
1385 * @return array|bool
1387 function getNumberedArgument( $index ) {
1388 if ( !isset( $this->numberedArgs
[$index] ) ) {
1391 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1392 # No trimming for unnamed arguments
1393 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1395 return $this->numberedExpansionCache
[$index];
1402 function getNamedArgument( $name ) {
1403 if ( !isset( $this->namedArgs
[$name] ) ) {
1406 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1407 # Trim named arguments post-expand, for backwards compatibility
1408 $this->namedExpansionCache
[$name] = trim(
1409 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1411 return $this->namedExpansionCache
[$name];
1416 * @return array|bool
1418 function getArgument( $name ) {
1419 $text = $this->getNumberedArgument( $name );
1420 if ( $text === false ) {
1421 $text = $this->getNamedArgument( $name );
1427 * Return true if the frame is a template frame
1431 function isTemplate() {
1437 * Expansion frame with custom arguments
1440 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1443 function __construct( $preprocessor, $args ) {
1444 parent
::__construct( $preprocessor );
1445 $this->args
= $args;
1448 function __toString() {
1451 foreach ( $this->args
as $name => $value ) {
1457 $s .= "\"$name\":\"" .
1458 str_replace( '"', '\\"', $value->__toString() ) . '"';
1467 function isEmpty() {
1468 return !count( $this->args
);
1475 function getArgument( $index ) {
1476 if ( !isset( $this->args
[$index] ) ) {
1479 return $this->args
[$index];
1486 class PPNode_Hash_Tree
implements PPNode
{
1487 var $name, $firstChild, $lastChild, $nextSibling;
1489 function __construct( $name ) {
1490 $this->name
= $name;
1491 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1494 function __toString() {
1497 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1498 if ( $node instanceof PPNode_Hash_Attr
) {
1499 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1501 $inner .= $node->__toString();
1504 if ( $inner === '' ) {
1505 return "<{$this->name}$attribs/>";
1507 return "<{$this->name}$attribs>$inner</{$this->name}>";
1514 * @return PPNode_Hash_Tree
1516 static function newWithText( $name, $text ) {
1517 $obj = new self( $name );
1518 $obj->addChild( new PPNode_Hash_Text( $text ) );
1522 function addChild( $node ) {
1523 if ( $this->lastChild
=== false ) {
1524 $this->firstChild
= $this->lastChild
= $node;
1526 $this->lastChild
->nextSibling
= $node;
1527 $this->lastChild
= $node;
1532 * @return PPNode_Hash_Array
1534 function getChildren() {
1535 $children = array();
1536 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1537 $children[] = $child;
1539 return new PPNode_Hash_Array( $children );
1542 function getFirstChild() {
1543 return $this->firstChild
;
1546 function getNextSibling() {
1547 return $this->nextSibling
;
1550 function getChildrenOfType( $name ) {
1551 $children = array();
1552 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1553 if ( isset( $child->name
) && $child->name
=== $name ) {
1554 $children[] = $name;
1563 function getLength() {
1571 function item( $i ) {
1578 function getName() {
1583 * Split a <part> node into an associative array containing:
1585 * index String index
1586 * value PPNode value
1590 function splitArg() {
1592 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1593 if ( !isset( $child->name
) ) {
1596 if ( $child->name
=== 'name' ) {
1597 $bits['name'] = $child;
1598 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1599 && $child->firstChild
->name
=== 'index' )
1601 $bits['index'] = $child->firstChild
->value
;
1603 } elseif ( $child->name
=== 'value' ) {
1604 $bits['value'] = $child;
1608 if ( !isset( $bits['name'] ) ) {
1609 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1611 if ( !isset( $bits['index'] ) ) {
1612 $bits['index'] = '';
1618 * Split an <ext> node into an associative array containing name, attr, inner and close
1619 * All values in the resulting array are PPNodes. Inner and close are optional.
1623 function splitExt() {
1625 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1626 if ( !isset( $child->name
) ) {
1629 if ( $child->name
== 'name' ) {
1630 $bits['name'] = $child;
1631 } elseif ( $child->name
== 'attr' ) {
1632 $bits['attr'] = $child;
1633 } elseif ( $child->name
== 'inner' ) {
1634 $bits['inner'] = $child;
1635 } elseif ( $child->name
== 'close' ) {
1636 $bits['close'] = $child;
1639 if ( !isset( $bits['name'] ) ) {
1640 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1650 function splitHeading() {
1651 if ( $this->name
!== 'h' ) {
1652 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1655 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1656 if ( !isset( $child->name
) ) {
1659 if ( $child->name
== 'i' ) {
1660 $bits['i'] = $child->value
;
1661 } elseif ( $child->name
== 'level' ) {
1662 $bits['level'] = $child->value
;
1665 if ( !isset( $bits['i'] ) ) {
1666 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1672 * Split a <template> or <tplarg> node
1676 function splitTemplate() {
1678 $bits = array( 'lineStart' => '' );
1679 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1680 if ( !isset( $child->name
) ) {
1683 if ( $child->name
== 'title' ) {
1684 $bits['title'] = $child;
1686 if ( $child->name
== 'part' ) {
1689 if ( $child->name
== 'lineStart' ) {
1690 $bits['lineStart'] = '1';
1693 if ( !isset( $bits['title'] ) ) {
1694 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1696 $bits['parts'] = new PPNode_Hash_Array( $parts );
1704 class PPNode_Hash_Text
implements PPNode
{
1705 var $value, $nextSibling;
1707 function __construct( $value ) {
1708 if ( is_object( $value ) ) {
1709 throw new MWException( __CLASS__
. ' given object instead of string' );
1711 $this->value
= $value;
1714 function __toString() {
1715 return htmlspecialchars( $this->value
);
1718 function getNextSibling() {
1719 return $this->nextSibling
;
1722 function getChildren() { return false; }
1723 function getFirstChild() { return false; }
1724 function getChildrenOfType( $name ) { return false; }
1725 function getLength() { return false; }
1726 function item( $i ) { return false; }
1727 function getName() { return '#text'; }
1728 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1729 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1730 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1736 class PPNode_Hash_Array
implements PPNode
{
1737 var $value, $nextSibling;
1739 function __construct( $value ) {
1740 $this->value
= $value;
1743 function __toString() {
1744 return var_export( $this, true );
1747 function getLength() {
1748 return count( $this->value
);
1751 function item( $i ) {
1752 return $this->value
[$i];
1755 function getName() { return '#nodelist'; }
1757 function getNextSibling() {
1758 return $this->nextSibling
;
1761 function getChildren() { return false; }
1762 function getFirstChild() { return false; }
1763 function getChildrenOfType( $name ) { return false; }
1764 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1765 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1766 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1772 class PPNode_Hash_Attr
implements PPNode
{
1773 var $name, $value, $nextSibling;
1775 function __construct( $name, $value ) {
1776 $this->name
= $name;
1777 $this->value
= $value;
1780 function __toString() {
1781 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1784 function getName() {
1788 function getNextSibling() {
1789 return $this->nextSibling
;
1792 function getChildren() { return false; }
1793 function getFirstChild() { return false; }
1794 function getChildrenOfType( $name ) { return false; }
1795 function getLength() { return false; }
1796 function item( $i ) { return false; }
1797 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1798 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1799 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }