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 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 $ret = $this->parser
->braceSubstitution( $bits, $this );
980 if ( isset( $ret['object'] ) ) {
981 $newIterator = $ret['object'];
983 $out .= $ret['text'];
986 } elseif ( $contextNode->name
== 'tplarg' ) {
987 # Triple-brace expansion
988 $bits = $contextNode->splitTemplate();
989 if ( $flags & PPFrame
::NO_ARGS
) {
990 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
992 $ret = $this->parser
->argSubstitution( $bits, $this );
993 if ( isset( $ret['object'] ) ) {
994 $newIterator = $ret['object'];
996 $out .= $ret['text'];
999 } elseif ( $contextNode->name
== 'comment' ) {
1000 # HTML-style comment
1001 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1002 if ( $this->parser
->ot
['html']
1003 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1004 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1008 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1009 # Not in RECOVER_COMMENTS mode (extractSections) though
1010 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1011 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1013 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1015 $out .= $contextNode->firstChild
->value
;
1017 } elseif ( $contextNode->name
== 'ignore' ) {
1018 # Output suppression used by <includeonly> etc.
1019 # OT_WIKI will only respect <ignore> in substed templates.
1020 # The other output types respect it unless NO_IGNORE is set.
1021 # extractSections() sets NO_IGNORE and so never respects it.
1022 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1023 $out .= $contextNode->firstChild
->value
;
1027 } elseif ( $contextNode->name
== 'ext' ) {
1029 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1030 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1031 } elseif ( $contextNode->name
== 'h' ) {
1033 if ( $this->parser
->ot
['html'] ) {
1034 # Expand immediately and insert heading index marker
1036 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1037 $s .= $this->expand( $node, $flags );
1040 $bits = $contextNode->splitHeading();
1041 $titleText = $this->title
->getPrefixedDBkey();
1042 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1043 $serial = count( $this->parser
->mHeadings
) - 1;
1044 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1045 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1046 $this->parser
->mStripState
->addGeneral( $marker, '' );
1049 # Expand in virtual stack
1050 $newIterator = $contextNode->getChildren();
1053 # Generic recursive expansion
1054 $newIterator = $contextNode->getChildren();
1057 throw new MWException( __METHOD__
.': Invalid parameter type' );
1060 if ( $newIterator !== false ) {
1062 $iteratorStack[] = $newIterator;
1064 } elseif ( $iteratorStack[$level] === false ) {
1065 // Return accumulated value to parent
1066 // With tail recursion
1067 while ( $iteratorStack[$level] === false && $level > 0 ) {
1068 $outStack[$level - 1] .= $out;
1069 array_pop( $outStack );
1070 array_pop( $iteratorStack );
1071 array_pop( $indexStack );
1077 return $outStack[0];
1085 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1086 $args = array_slice( func_get_args(), 2 );
1090 foreach ( $args as $root ) {
1091 if ( $root instanceof PPNode_Hash_Array
) {
1092 $root = $root->value
;
1094 if ( !is_array( $root ) ) {
1095 $root = array( $root );
1097 foreach ( $root as $node ) {
1103 $s .= $this->expand( $node, $flags );
1110 * Implode with no flags specified
1111 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1114 function implode( $sep /*, ... */ ) {
1115 $args = array_slice( func_get_args(), 1 );
1119 foreach ( $args as $root ) {
1120 if ( $root instanceof PPNode_Hash_Array
) {
1121 $root = $root->value
;
1123 if ( !is_array( $root ) ) {
1124 $root = array( $root );
1126 foreach ( $root as $node ) {
1132 $s .= $this->expand( $node );
1139 * Makes an object that, when expand()ed, will be the same as one obtained
1142 * @return PPNode_Hash_Array
1144 function virtualImplode( $sep /*, ... */ ) {
1145 $args = array_slice( func_get_args(), 1 );
1149 foreach ( $args as $root ) {
1150 if ( $root instanceof PPNode_Hash_Array
) {
1151 $root = $root->value
;
1153 if ( !is_array( $root ) ) {
1154 $root = array( $root );
1156 foreach ( $root as $node ) {
1165 return new PPNode_Hash_Array( $out );
1169 * Virtual implode with brackets
1171 * @return PPNode_Hash_Array
1173 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1174 $args = array_slice( func_get_args(), 3 );
1175 $out = array( $start );
1178 foreach ( $args as $root ) {
1179 if ( $root instanceof PPNode_Hash_Array
) {
1180 $root = $root->value
;
1182 if ( !is_array( $root ) ) {
1183 $root = array( $root );
1185 foreach ( $root as $node ) {
1195 return new PPNode_Hash_Array( $out );
1198 function __toString() {
1203 * @param $level bool
1204 * @return array|bool|String
1206 function getPDBK( $level = false ) {
1207 if ( $level === false ) {
1208 return $this->title
->getPrefixedDBkey();
1210 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1217 function getArguments() {
1224 function getNumberedArguments() {
1231 function getNamedArguments() {
1236 * Returns true if there are no arguments in this frame
1240 function isEmpty() {
1248 function getArgument( $name ) {
1253 * Returns true if the infinite loop check is OK, false if a loop is detected
1255 * @param $title Title
1259 function loopCheck( $title ) {
1260 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1264 * Return true if the frame is a template frame
1268 function isTemplate() {
1273 * Get a title of frame
1277 function getTitle() {
1278 return $this->title
;
1283 * Expansion frame with template arguments
1286 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1287 var $numberedArgs, $namedArgs, $parent;
1288 var $numberedExpansionCache, $namedExpansionCache;
1291 * @param $preprocessor
1293 * @param $numberedArgs array
1294 * @param $namedArgs array
1295 * @param $title Title
1297 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1298 parent
::__construct( $preprocessor );
1300 $this->parent
= $parent;
1301 $this->numberedArgs
= $numberedArgs;
1302 $this->namedArgs
= $namedArgs;
1303 $this->title
= $title;
1304 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1305 $this->titleCache
= $parent->titleCache
;
1306 $this->titleCache
[] = $pdbk;
1307 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1308 if ( $pdbk !== false ) {
1309 $this->loopCheckHash
[$pdbk] = true;
1311 $this->depth
= $parent->depth +
1;
1312 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1315 function __toString() {
1318 $args = $this->numberedArgs +
$this->namedArgs
;
1319 foreach ( $args as $name => $value ) {
1325 $s .= "\"$name\":\"" .
1326 str_replace( '"', '\\"', $value->__toString() ) . '"';
1332 * Returns true if there are no arguments in this frame
1336 function isEmpty() {
1337 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1343 function getArguments() {
1344 $arguments = array();
1345 foreach ( array_merge(
1346 array_keys($this->numberedArgs
),
1347 array_keys($this->namedArgs
)) as $key ) {
1348 $arguments[$key] = $this->getArgument($key);
1356 function getNumberedArguments() {
1357 $arguments = array();
1358 foreach ( array_keys($this->numberedArgs
) as $key ) {
1359 $arguments[$key] = $this->getArgument($key);
1367 function getNamedArguments() {
1368 $arguments = array();
1369 foreach ( array_keys($this->namedArgs
) as $key ) {
1370 $arguments[$key] = $this->getArgument($key);
1377 * @return array|bool
1379 function getNumberedArgument( $index ) {
1380 if ( !isset( $this->numberedArgs
[$index] ) ) {
1383 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1384 # No trimming for unnamed arguments
1385 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1387 return $this->numberedExpansionCache
[$index];
1394 function getNamedArgument( $name ) {
1395 if ( !isset( $this->namedArgs
[$name] ) ) {
1398 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1399 # Trim named arguments post-expand, for backwards compatibility
1400 $this->namedExpansionCache
[$name] = trim(
1401 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1403 return $this->namedExpansionCache
[$name];
1408 * @return array|bool
1410 function getArgument( $name ) {
1411 $text = $this->getNumberedArgument( $name );
1412 if ( $text === false ) {
1413 $text = $this->getNamedArgument( $name );
1419 * Return true if the frame is a template frame
1423 function isTemplate() {
1429 * Expansion frame with custom arguments
1432 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1435 function __construct( $preprocessor, $args ) {
1436 parent
::__construct( $preprocessor );
1437 $this->args
= $args;
1440 function __toString() {
1443 foreach ( $this->args
as $name => $value ) {
1449 $s .= "\"$name\":\"" .
1450 str_replace( '"', '\\"', $value->__toString() ) . '"';
1459 function isEmpty() {
1460 return !count( $this->args
);
1467 function getArgument( $index ) {
1468 if ( !isset( $this->args
[$index] ) ) {
1471 return $this->args
[$index];
1478 class PPNode_Hash_Tree
implements PPNode
{
1479 var $name, $firstChild, $lastChild, $nextSibling;
1481 function __construct( $name ) {
1482 $this->name
= $name;
1483 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1486 function __toString() {
1489 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1490 if ( $node instanceof PPNode_Hash_Attr
) {
1491 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1493 $inner .= $node->__toString();
1496 if ( $inner === '' ) {
1497 return "<{$this->name}$attribs/>";
1499 return "<{$this->name}$attribs>$inner</{$this->name}>";
1506 * @return PPNode_Hash_Tree
1508 static function newWithText( $name, $text ) {
1509 $obj = new self( $name );
1510 $obj->addChild( new PPNode_Hash_Text( $text ) );
1514 function addChild( $node ) {
1515 if ( $this->lastChild
=== false ) {
1516 $this->firstChild
= $this->lastChild
= $node;
1518 $this->lastChild
->nextSibling
= $node;
1519 $this->lastChild
= $node;
1524 * @return PPNode_Hash_Array
1526 function getChildren() {
1527 $children = array();
1528 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1529 $children[] = $child;
1531 return new PPNode_Hash_Array( $children );
1534 function getFirstChild() {
1535 return $this->firstChild
;
1538 function getNextSibling() {
1539 return $this->nextSibling
;
1542 function getChildrenOfType( $name ) {
1543 $children = array();
1544 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1545 if ( isset( $child->name
) && $child->name
=== $name ) {
1546 $children[] = $name;
1555 function getLength() {
1563 function item( $i ) {
1570 function getName() {
1575 * Split a <part> node into an associative array containing:
1577 * index String index
1578 * value PPNode value
1582 function splitArg() {
1584 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1585 if ( !isset( $child->name
) ) {
1588 if ( $child->name
=== 'name' ) {
1589 $bits['name'] = $child;
1590 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1591 && $child->firstChild
->name
=== 'index' )
1593 $bits['index'] = $child->firstChild
->value
;
1595 } elseif ( $child->name
=== 'value' ) {
1596 $bits['value'] = $child;
1600 if ( !isset( $bits['name'] ) ) {
1601 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1603 if ( !isset( $bits['index'] ) ) {
1604 $bits['index'] = '';
1610 * Split an <ext> node into an associative array containing name, attr, inner and close
1611 * All values in the resulting array are PPNodes. Inner and close are optional.
1615 function splitExt() {
1617 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1618 if ( !isset( $child->name
) ) {
1621 if ( $child->name
== 'name' ) {
1622 $bits['name'] = $child;
1623 } elseif ( $child->name
== 'attr' ) {
1624 $bits['attr'] = $child;
1625 } elseif ( $child->name
== 'inner' ) {
1626 $bits['inner'] = $child;
1627 } elseif ( $child->name
== 'close' ) {
1628 $bits['close'] = $child;
1631 if ( !isset( $bits['name'] ) ) {
1632 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1642 function splitHeading() {
1643 if ( $this->name
!== 'h' ) {
1644 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1647 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1648 if ( !isset( $child->name
) ) {
1651 if ( $child->name
== 'i' ) {
1652 $bits['i'] = $child->value
;
1653 } elseif ( $child->name
== 'level' ) {
1654 $bits['level'] = $child->value
;
1657 if ( !isset( $bits['i'] ) ) {
1658 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1664 * Split a <template> or <tplarg> node
1668 function splitTemplate() {
1670 $bits = array( 'lineStart' => '' );
1671 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1672 if ( !isset( $child->name
) ) {
1675 if ( $child->name
== 'title' ) {
1676 $bits['title'] = $child;
1678 if ( $child->name
== 'part' ) {
1681 if ( $child->name
== 'lineStart' ) {
1682 $bits['lineStart'] = '1';
1685 if ( !isset( $bits['title'] ) ) {
1686 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1688 $bits['parts'] = new PPNode_Hash_Array( $parts );
1696 class PPNode_Hash_Text
implements PPNode
{
1697 var $value, $nextSibling;
1699 function __construct( $value ) {
1700 if ( is_object( $value ) ) {
1701 throw new MWException( __CLASS__
. ' given object instead of string' );
1703 $this->value
= $value;
1706 function __toString() {
1707 return htmlspecialchars( $this->value
);
1710 function getNextSibling() {
1711 return $this->nextSibling
;
1714 function getChildren() { return false; }
1715 function getFirstChild() { return false; }
1716 function getChildrenOfType( $name ) { return false; }
1717 function getLength() { return false; }
1718 function item( $i ) { return false; }
1719 function getName() { return '#text'; }
1720 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1721 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1722 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1728 class PPNode_Hash_Array
implements PPNode
{
1729 var $value, $nextSibling;
1731 function __construct( $value ) {
1732 $this->value
= $value;
1735 function __toString() {
1736 return var_export( $this, true );
1739 function getLength() {
1740 return count( $this->value
);
1743 function item( $i ) {
1744 return $this->value
[$i];
1747 function getName() { return '#nodelist'; }
1749 function getNextSibling() {
1750 return $this->nextSibling
;
1753 function getChildren() { return false; }
1754 function getFirstChild() { return false; }
1755 function getChildrenOfType( $name ) { return false; }
1756 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1757 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1758 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1764 class PPNode_Hash_Attr
implements PPNode
{
1765 var $name, $value, $nextSibling;
1767 function __construct( $name, $value ) {
1768 $this->name
= $name;
1769 $this->value
= $value;
1772 function __toString() {
1773 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1776 function getName() {
1780 function getNextSibling() {
1781 return $this->nextSibling
;
1784 function getChildren() { return false; }
1785 function getFirstChild() { return false; }
1786 function getChildrenOfType( $name ) { return false; }
1787 function getLength() { return false; }
1788 function item( $i ) { return false; }
1789 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1790 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1791 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }