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 );
42 function newPartNodeArray( $values ) {
45 foreach ( $values as $k => $val ) {
46 $partNode = new PPNode_Hash_Tree( 'part' );
47 $nameNode = new PPNode_Hash_Tree( 'name' );
50 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
51 $partNode->addChild( $nameNode );
53 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
54 $partNode->addChild( $nameNode );
55 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
58 $valueNode = new PPNode_Hash_Tree( 'value' );
59 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
60 $partNode->addChild( $valueNode );
65 $node = new PPNode_Hash_Array( $list );
70 * Preprocess some wikitext and return the document tree.
71 * This is the ghost of Parser::replace_variables().
73 * @param $text String: the text to parse
74 * @param $flags Integer: bitwise combination of:
75 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
76 * included. Default is to assume a direct page view.
78 * The generated DOM tree must depend only on the input text and the flags.
79 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
81 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
82 * change in the DOM tree for a given text, must be passed through the section identifier
83 * in the section edit link and thus back to extractSections().
85 * The output of this function is currently only cached in process memory, but a persistent
86 * cache may be implemented at a later date which takes further advantage of these strict
87 * dependency requirements.
91 function preprocessToObj( $text, $flags = 0 ) {
92 wfProfileIn( __METHOD__
);
95 global $wgMemc, $wgPreprocessorCacheThreshold;
97 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
99 wfProfileIn( __METHOD__
.'-cacheable' );
101 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
102 $cacheValue = $wgMemc->get( $cacheKey );
104 $version = substr( $cacheValue, 0, 8 );
105 if ( intval( $version ) == self
::CACHE_VERSION
) {
106 $hash = unserialize( substr( $cacheValue, 8 ) );
108 wfDebugLog( "Preprocessor",
109 "Loaded preprocessor hash from memcached (key $cacheKey)" );
110 wfProfileOut( __METHOD__
.'-cacheable' );
111 wfProfileOut( __METHOD__
);
115 wfProfileIn( __METHOD__
.'-cache-miss' );
130 'names' => array( 2 => null ),
136 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
138 $xmlishElements = $this->parser
->getStripList();
139 $enableOnlyinclude = false;
140 if ( $forInclusion ) {
141 $ignoredTags = array( 'includeonly', '/includeonly' );
142 $ignoredElements = array( 'noinclude' );
143 $xmlishElements[] = 'noinclude';
144 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
145 $enableOnlyinclude = true;
148 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
149 $ignoredElements = array( 'includeonly' );
150 $xmlishElements[] = 'includeonly';
152 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
154 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
155 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
157 $stack = new PPDStack_Hash
;
159 $searchBase = "[{<\n";
160 $revText = strrev( $text ); // For fast reverse searches
162 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
163 $accum =& $stack->getAccum(); # Current accumulator
164 $findEquals = false; # True to find equals signs in arguments
165 $findPipe = false; # True to take notice of pipe characters
167 $inHeading = false; # True if $i is inside a possible heading
168 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
169 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
170 $fakeLineStart = true; # Do a line-start run without outputting an LF character
175 if ( $findOnlyinclude ) {
176 // Ignore all input up to the next <onlyinclude>
177 $startPos = strpos( $text, '<onlyinclude>', $i );
178 if ( $startPos === false ) {
179 // Ignored section runs to the end
180 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
183 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
184 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
186 $findOnlyinclude = false;
189 if ( $fakeLineStart ) {
190 $found = 'line-start';
193 # Find next opening brace, closing brace or pipe
194 $search = $searchBase;
195 if ( $stack->top
=== false ) {
196 $currentClosing = '';
198 $currentClosing = $stack->top
->close
;
199 $search .= $currentClosing;
205 // First equals will be for the template
209 # Output literal section, advance input counter
210 $literalLength = strcspn( $text, $search, $i );
211 if ( $literalLength > 0 ) {
212 $accum->addLiteral( substr( $text, $i, $literalLength ) );
213 $i +
= $literalLength;
215 if ( $i >= strlen( $text ) ) {
216 if ( $currentClosing == "\n" ) {
217 // Do a past-the-end run to finish off the heading
225 $curChar = $text[$i];
226 if ( $curChar == '|' ) {
228 } elseif ( $curChar == '=' ) {
230 } elseif ( $curChar == '<' ) {
232 } elseif ( $curChar == "\n" ) {
236 $found = 'line-start';
238 } elseif ( $curChar == $currentClosing ) {
240 } elseif ( isset( $rules[$curChar] ) ) {
242 $rule = $rules[$curChar];
244 # Some versions of PHP have a strcspn which stops on null characters
245 # Ignore and continue
252 if ( $found == 'angle' ) {
254 // Handle </onlyinclude>
255 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
256 $findOnlyinclude = true;
260 // Determine element name
261 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
262 // Element name missing or not listed
263 $accum->addLiteral( '<' );
268 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
269 // To avoid leaving blank lines, when a comment is both preceded
270 // and followed by a newline (ignoring spaces), trim leading and
271 // trailing spaces and one of the newlines.
274 $endPos = strpos( $text, '-->', $i +
4 );
275 if ( $endPos === false ) {
276 // Unclosed comment in input, runs to end
277 $inner = substr( $text, $i );
278 $accum->addNodeWithText( 'comment', $inner );
279 $i = strlen( $text );
281 // Search backwards for leading whitespace
282 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
283 // Search forwards for trailing whitespace
284 // $wsEnd will be the position of the last space (or the '>' if there's none)
285 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
286 // Eat the line if possible
287 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
288 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
289 // it's a possible beneficial b/c break.
290 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
291 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
293 $startPos = $wsStart;
294 $endPos = $wsEnd +
1;
295 // Remove leading whitespace from the end of the accumulator
296 // Sanity check first though
297 $wsLength = $i - $wsStart;
299 && $accum->lastNode
instanceof PPNode_Hash_Text
300 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
302 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
304 // Do a line-start run next time to look for headings after the comment
305 $fakeLineStart = true;
307 // No line to eat, just take the comment itself
313 $part = $stack->top
->getCurrentPart();
314 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
315 $part->visualEnd
= $wsStart;
317 // Else comments abutting, no change in visual end
318 $part->commentEnd
= $endPos;
321 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
322 $accum->addNodeWithText( 'comment', $inner );
327 $lowerName = strtolower( $name );
328 $attrStart = $i +
strlen( $name ) +
1;
331 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
332 if ( $tagEndPos === false ) {
333 // Infinite backtrack
334 // Disable tag search to prevent worst-case O(N^2) performance
336 $accum->addLiteral( '<' );
341 // Handle ignored tags
342 if ( in_array( $lowerName, $ignoredTags ) ) {
343 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
349 if ( $text[$tagEndPos-1] == '/' ) {
351 $attrEnd = $tagEndPos - 1;
356 $attrEnd = $tagEndPos;
358 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
359 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
361 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
362 $i = $matches[0][1] +
strlen( $matches[0][0] );
363 $close = $matches[0][0];
365 // No end tag -- let it run out to the end of the text.
366 $inner = substr( $text, $tagEndPos +
1 );
367 $i = strlen( $text );
371 // <includeonly> and <noinclude> just become <ignore> tags
372 if ( in_array( $lowerName, $ignoredElements ) ) {
373 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
377 if ( $attrEnd <= $attrStart ) {
380 // Note that the attr element contains the whitespace between name and attribute,
381 // this is necessary for precise reconstruction during pre-save transform.
382 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
385 $extNode = new PPNode_Hash_Tree( 'ext' );
386 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
387 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
388 if ( $inner !== null ) {
389 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
391 if ( $close !== null ) {
392 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
394 $accum->addNode( $extNode );
397 elseif ( $found == 'line-start' ) {
398 // Is this the start of a heading?
399 // Line break belongs before the heading element in any case
400 if ( $fakeLineStart ) {
401 $fakeLineStart = false;
403 $accum->addLiteral( $curChar );
407 $count = strspn( $text, '=', $i, 6 );
408 if ( $count == 1 && $findEquals ) {
409 // DWIM: This looks kind of like a name/value separator
410 // Let's let the equals handler have it and break the potential heading
411 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
412 } elseif ( $count > 0 ) {
416 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
419 $stack->push( $piece );
420 $accum =& $stack->getAccum();
421 extract( $stack->getFlags() );
426 elseif ( $found == 'line-end' ) {
427 $piece = $stack->top
;
428 // A heading must be open, otherwise \n wouldn't have been in the search list
429 assert( $piece->open
== "\n" );
430 $part = $piece->getCurrentPart();
431 // Search back through the input to see if it has a proper close
432 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
433 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
434 $searchStart = $i - $wsLength;
435 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
436 // Comment found at line end
437 // Search for equals signs before the comment
438 $searchStart = $part->visualEnd
;
439 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
441 $count = $piece->count
;
442 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
443 if ( $equalsLength > 0 ) {
444 if ( $searchStart - $equalsLength == $piece->startPos
) {
445 // This is just a single string of equals signs on its own line
446 // Replicate the doHeadings behaviour /={count}(.+)={count}/
447 // First find out how many equals signs there really are (don't stop at 6)
448 $count = $equalsLength;
452 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
455 $count = min( $equalsLength, $count );
458 // Normal match, output <h>
459 $element = new PPNode_Hash_Tree( 'possible-h' );
460 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
461 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
462 $element->lastChild
->nextSibling
= $accum->firstNode
;
463 $element->lastChild
= $accum->lastNode
;
465 // Single equals sign on its own line, count=0
469 // No match, no <h>, just pass down the inner text
474 $accum =& $stack->getAccum();
475 extract( $stack->getFlags() );
477 // Append the result to the enclosing accumulator
478 if ( $element instanceof PPNode
) {
479 $accum->addNode( $element );
481 $accum->addAccum( $element );
483 // Note that we do NOT increment the input pointer.
484 // This is because the closing linebreak could be the opening linebreak of
485 // another heading. Infinite loops are avoided because the next iteration MUST
486 // 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 ) );
514 elseif ( $found == 'close' ) {
515 $piece = $stack->top
;
516 # lets check if there are enough characters for closing brace
517 $maxCount = $piece->count
;
518 $count = strspn( $text, $curChar, $i, $maxCount );
520 # check for maximum matching characters (if there are 5 closing
521 # characters, we will probably need only 3 - depending on the rules)
522 $rule = $rules[$piece->open
];
523 if ( $count > $rule['max'] ) {
524 # The specified maximum exists in the callback array, unless the caller
526 $matchingCount = $rule['max'];
528 # Count is less than the maximum
529 # Skip any gaps in the callback array to find the true largest match
530 # Need to use array_key_exists not isset because the callback can be null
531 $matchingCount = $count;
532 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
537 if ($matchingCount <= 0) {
538 # No matching element found in callback array
539 # Output a literal closing brace and continue
540 $accum->addLiteral( str_repeat( $curChar, $count ) );
544 $name = $rule['names'][$matchingCount];
545 if ( $name === null ) {
546 // No element, just literal text
547 $element = $piece->breakSyntax( $matchingCount );
548 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
551 # Note: $parts is already XML, does not need to be encoded further
552 $parts = $piece->parts
;
553 $titleAccum = $parts[0]->out
;
556 $element = new PPNode_Hash_Tree( $name );
558 # The invocation is at the start of the line if lineStart is set in
559 # the stack, and all opening brackets are used up.
560 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
561 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
563 $titleNode = new PPNode_Hash_Tree( 'title' );
564 $titleNode->firstChild
= $titleAccum->firstNode
;
565 $titleNode->lastChild
= $titleAccum->lastNode
;
566 $element->addChild( $titleNode );
568 foreach ( $parts as $part ) {
569 if ( isset( $part->eqpos
) ) {
572 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
573 if ( $node === $part->eqpos
) {
579 throw new MWException( __METHOD__
. ': eqpos not found' );
581 if ( $node->name
!== 'equals' ) {
582 throw new MWException( __METHOD__
.': eqpos is not equals' );
586 // Construct name node
587 $nameNode = new PPNode_Hash_Tree( 'name' );
588 if ( $lastNode !== false ) {
589 $lastNode->nextSibling
= false;
590 $nameNode->firstChild
= $part->out
->firstNode
;
591 $nameNode->lastChild
= $lastNode;
594 // Construct value node
595 $valueNode = new PPNode_Hash_Tree( 'value' );
596 if ( $equalsNode->nextSibling
!== false ) {
597 $valueNode->firstChild
= $equalsNode->nextSibling
;
598 $valueNode->lastChild
= $part->out
->lastNode
;
600 $partNode = new PPNode_Hash_Tree( 'part' );
601 $partNode->addChild( $nameNode );
602 $partNode->addChild( $equalsNode->firstChild
);
603 $partNode->addChild( $valueNode );
604 $element->addChild( $partNode );
606 $partNode = new PPNode_Hash_Tree( 'part' );
607 $nameNode = new PPNode_Hash_Tree( 'name' );
608 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
609 $valueNode = new PPNode_Hash_Tree( 'value' );
610 $valueNode->firstChild
= $part->out
->firstNode
;
611 $valueNode->lastChild
= $part->out
->lastNode
;
612 $partNode->addChild( $nameNode );
613 $partNode->addChild( $valueNode );
614 $element->addChild( $partNode );
619 # Advance input pointer
620 $i +
= $matchingCount;
624 $accum =& $stack->getAccum();
626 # Re-add the old stack element if it still has unmatched opening characters remaining
627 if ($matchingCount < $piece->count
) {
628 $piece->parts
= array( new PPDPart_Hash
);
629 $piece->count
-= $matchingCount;
630 # do we still qualify for any callback with remaining count?
631 $names = $rules[$piece->open
]['names'];
633 $enclosingAccum =& $accum;
634 while ( $piece->count
) {
635 if ( array_key_exists( $piece->count
, $names ) ) {
636 $stack->push( $piece );
637 $accum =& $stack->getAccum();
643 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
646 extract( $stack->getFlags() );
648 # Add XML element to the enclosing accumulator
649 if ( $element instanceof PPNode
) {
650 $accum->addNode( $element );
652 $accum->addAccum( $element );
656 elseif ( $found == 'pipe' ) {
657 $findEquals = true; // shortcut for getFlags()
659 $accum =& $stack->getAccum();
663 elseif ( $found == 'equals' ) {
664 $findEquals = false; // shortcut for getFlags()
665 $accum->addNodeWithText( 'equals', '=' );
666 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
671 # Output any remaining unclosed brackets
672 foreach ( $stack->stack
as $piece ) {
673 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
676 # Enable top-level headings
677 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
678 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
683 $rootNode = new PPNode_Hash_Tree( 'root' );
684 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
685 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
689 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
690 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
691 wfProfileOut( __METHOD__
.'-cache-miss' );
692 wfProfileOut( __METHOD__
.'-cacheable' );
693 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
696 wfProfileOut( __METHOD__
);
702 * Stack class to help Preprocessor::preprocessToObj()
705 class PPDStack_Hash
extends PPDStack
{
706 function __construct() {
707 $this->elementClass
= 'PPDStackElement_Hash';
708 parent
::__construct();
709 $this->rootAccum
= new PPDAccum_Hash
;
716 class PPDStackElement_Hash
extends PPDStackElement
{
717 function __construct( $data = array() ) {
718 $this->partClass
= 'PPDPart_Hash';
719 parent
::__construct( $data );
723 * Get the accumulator that would result if the close is not found.
725 function breakSyntax( $openingCount = false ) {
726 if ( $this->open
== "\n" ) {
727 $accum = $this->parts
[0]->out
;
729 if ( $openingCount === false ) {
730 $openingCount = $this->count
;
732 $accum = new PPDAccum_Hash
;
733 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
735 foreach ( $this->parts
as $part ) {
739 $accum->addLiteral( '|' );
741 $accum->addAccum( $part->out
);
751 class PPDPart_Hash
extends PPDPart
{
752 function __construct( $out = '' ) {
753 $accum = new PPDAccum_Hash
;
755 $accum->addLiteral( $out );
757 parent
::__construct( $accum );
764 class PPDAccum_Hash
{
765 var $firstNode, $lastNode;
767 function __construct() {
768 $this->firstNode
= $this->lastNode
= false;
772 * Append a string literal
774 function addLiteral( $s ) {
775 if ( $this->lastNode
=== false ) {
776 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
777 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
778 $this->lastNode
->value
.= $s;
780 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
781 $this->lastNode
= $this->lastNode
->nextSibling
;
788 function addNode( PPNode
$node ) {
789 if ( $this->lastNode
=== false ) {
790 $this->firstNode
= $this->lastNode
= $node;
792 $this->lastNode
->nextSibling
= $node;
793 $this->lastNode
= $node;
798 * Append a tree node with text contents
800 function addNodeWithText( $name, $value ) {
801 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
802 $this->addNode( $node );
806 * Append a PPAccum_Hash
807 * Takes over ownership of the nodes in the source argument. These nodes may
808 * subsequently be modified, especially nextSibling.
810 function addAccum( $accum ) {
811 if ( $accum->lastNode
=== false ) {
813 } elseif ( $this->lastNode
=== false ) {
814 $this->firstNode
= $accum->firstNode
;
815 $this->lastNode
= $accum->lastNode
;
817 $this->lastNode
->nextSibling
= $accum->firstNode
;
818 $this->lastNode
= $accum->lastNode
;
824 * An expansion frame, used as a context to expand the result of preprocessToObj()
827 class PPFrame_Hash
implements PPFrame
{
846 * Hashtable listing templates which are disallowed for expansion in this frame,
847 * having been encountered previously in parent frames.
852 * Recursion depth of this frame, top = 0
853 * Note that this is NOT the same as expansion depth in expand()
859 * Construct a new preprocessor frame.
860 * @param $preprocessor Preprocessor: the parent preprocessor
862 function __construct( $preprocessor ) {
863 $this->preprocessor
= $preprocessor;
864 $this->parser
= $preprocessor->parser
;
865 $this->title
= $this->parser
->mTitle
;
866 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
867 $this->loopCheckHash
= array();
872 * Create a new child frame
873 * $args is optionally a multi-root PPNode or array containing the template arguments
875 function newChild( $args = false, $title = false ) {
876 $namedArgs = array();
877 $numberedArgs = array();
878 if ( $title === false ) {
879 $title = $this->title
;
881 if ( $args !== false ) {
882 if ( $args instanceof PPNode_Hash_Array
) {
883 $args = $args->value
;
884 } elseif ( !is_array( $args ) ) {
885 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
887 foreach ( $args as $arg ) {
888 $bits = $arg->splitArg();
889 if ( $bits['index'] !== '' ) {
890 // Numbered parameter
891 $numberedArgs[$bits['index']] = $bits['value'];
892 unset( $namedArgs[$bits['index']] );
895 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
896 $namedArgs[$name] = $bits['value'];
897 unset( $numberedArgs[$name] );
901 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
904 function expand( $root, $flags = 0 ) {
905 static $expansionDepth = 0;
906 if ( is_string( $root ) ) {
910 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
911 return '<span class="error">Node-count limit exceeded</span>';
913 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
914 return '<span class="error">Expansion depth limit exceeded</span>';
918 $outStack = array( '', '' );
919 $iteratorStack = array( false, $root );
920 $indexStack = array( 0, 0 );
922 while ( count( $iteratorStack ) > 1 ) {
923 $level = count( $outStack ) - 1;
924 $iteratorNode =& $iteratorStack[ $level ];
925 $out =& $outStack[$level];
926 $index =& $indexStack[$level];
928 if ( is_array( $iteratorNode ) ) {
929 if ( $index >= count( $iteratorNode ) ) {
930 // All done with this iterator
931 $iteratorStack[$level] = false;
932 $contextNode = false;
934 $contextNode = $iteratorNode[$index];
937 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
938 if ( $index >= $iteratorNode->getLength() ) {
939 // All done with this iterator
940 $iteratorStack[$level] = false;
941 $contextNode = false;
943 $contextNode = $iteratorNode->item( $index );
947 // Copy to $contextNode and then delete from iterator stack,
948 // because this is not an iterator but we do have to execute it once
949 $contextNode = $iteratorStack[$level];
950 $iteratorStack[$level] = false;
953 $newIterator = false;
955 if ( $contextNode === false ) {
957 } elseif ( is_string( $contextNode ) ) {
958 $out .= $contextNode;
959 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
960 $newIterator = $contextNode;
961 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
963 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
964 $out .= $contextNode->value
;
965 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
966 if ( $contextNode->name
== 'template' ) {
967 # Double-brace expansion
968 $bits = $contextNode->splitTemplate();
969 if ( $flags & PPFrame
::NO_TEMPLATES
) {
970 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
972 $ret = $this->parser
->braceSubstitution( $bits, $this );
973 if ( isset( $ret['object'] ) ) {
974 $newIterator = $ret['object'];
976 $out .= $ret['text'];
979 } elseif ( $contextNode->name
== 'tplarg' ) {
980 # Triple-brace expansion
981 $bits = $contextNode->splitTemplate();
982 if ( $flags & PPFrame
::NO_ARGS
) {
983 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
985 $ret = $this->parser
->argSubstitution( $bits, $this );
986 if ( isset( $ret['object'] ) ) {
987 $newIterator = $ret['object'];
989 $out .= $ret['text'];
992 } elseif ( $contextNode->name
== 'comment' ) {
994 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
995 if ( $this->parser
->ot
['html']
996 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
997 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1001 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1002 # Not in RECOVER_COMMENTS mode (extractSections) though
1003 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1004 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1006 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1008 $out .= $contextNode->firstChild
->value
;
1010 } elseif ( $contextNode->name
== 'ignore' ) {
1011 # Output suppression used by <includeonly> etc.
1012 # OT_WIKI will only respect <ignore> in substed templates.
1013 # The other output types respect it unless NO_IGNORE is set.
1014 # extractSections() sets NO_IGNORE and so never respects it.
1015 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1016 $out .= $contextNode->firstChild
->value
;
1020 } elseif ( $contextNode->name
== 'ext' ) {
1022 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1023 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1024 } elseif ( $contextNode->name
== 'h' ) {
1026 if ( $this->parser
->ot
['html'] ) {
1027 # Expand immediately and insert heading index marker
1029 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1030 $s .= $this->expand( $node, $flags );
1033 $bits = $contextNode->splitHeading();
1034 $titleText = $this->title
->getPrefixedDBkey();
1035 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1036 $serial = count( $this->parser
->mHeadings
) - 1;
1037 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1038 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1039 $this->parser
->mStripState
->addGeneral( $marker, '' );
1042 # Expand in virtual stack
1043 $newIterator = $contextNode->getChildren();
1046 # Generic recursive expansion
1047 $newIterator = $contextNode->getChildren();
1050 throw new MWException( __METHOD__
.': Invalid parameter type' );
1053 if ( $newIterator !== false ) {
1055 $iteratorStack[] = $newIterator;
1057 } elseif ( $iteratorStack[$level] === false ) {
1058 // Return accumulated value to parent
1059 // With tail recursion
1060 while ( $iteratorStack[$level] === false && $level > 0 ) {
1061 $outStack[$level - 1] .= $out;
1062 array_pop( $outStack );
1063 array_pop( $iteratorStack );
1064 array_pop( $indexStack );
1070 return $outStack[0];
1073 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1074 $args = array_slice( func_get_args(), 2 );
1078 foreach ( $args as $root ) {
1079 if ( $root instanceof PPNode_Hash_Array
) {
1080 $root = $root->value
;
1082 if ( !is_array( $root ) ) {
1083 $root = array( $root );
1085 foreach ( $root as $node ) {
1091 $s .= $this->expand( $node, $flags );
1098 * Implode with no flags specified
1099 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1101 function implode( $sep /*, ... */ ) {
1102 $args = array_slice( func_get_args(), 1 );
1106 foreach ( $args as $root ) {
1107 if ( $root instanceof PPNode_Hash_Array
) {
1108 $root = $root->value
;
1110 if ( !is_array( $root ) ) {
1111 $root = array( $root );
1113 foreach ( $root as $node ) {
1119 $s .= $this->expand( $node );
1126 * Makes an object that, when expand()ed, will be the same as one obtained
1129 function virtualImplode( $sep /*, ... */ ) {
1130 $args = array_slice( func_get_args(), 1 );
1134 foreach ( $args as $root ) {
1135 if ( $root instanceof PPNode_Hash_Array
) {
1136 $root = $root->value
;
1138 if ( !is_array( $root ) ) {
1139 $root = array( $root );
1141 foreach ( $root as $node ) {
1150 return new PPNode_Hash_Array( $out );
1154 * Virtual implode with brackets
1156 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1157 $args = array_slice( func_get_args(), 3 );
1158 $out = array( $start );
1161 foreach ( $args as $root ) {
1162 if ( $root instanceof PPNode_Hash_Array
) {
1163 $root = $root->value
;
1165 if ( !is_array( $root ) ) {
1166 $root = array( $root );
1168 foreach ( $root as $node ) {
1178 return new PPNode_Hash_Array( $out );
1181 function __toString() {
1185 function getPDBK( $level = false ) {
1186 if ( $level === false ) {
1187 return $this->title
->getPrefixedDBkey();
1189 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1193 function getArguments() {
1197 function getNumberedArguments() {
1201 function getNamedArguments() {
1206 * Returns true if there are no arguments in this frame
1208 function isEmpty() {
1212 function getArgument( $name ) {
1217 * Returns true if the infinite loop check is OK, false if a loop is detected
1219 * @param $title Title
1221 function loopCheck( $title ) {
1222 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1226 * Return true if the frame is a template frame
1228 function isTemplate() {
1234 * Expansion frame with template arguments
1237 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1238 var $numberedArgs, $namedArgs, $parent;
1239 var $numberedExpansionCache, $namedExpansionCache;
1242 * @param $preprocessor
1244 * @param $numberedArgs array
1245 * @param $namedArgs array
1246 * @param $title Title
1248 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1249 parent
::__construct( $preprocessor );
1251 $this->parent
= $parent;
1252 $this->numberedArgs
= $numberedArgs;
1253 $this->namedArgs
= $namedArgs;
1254 $this->title
= $title;
1255 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1256 $this->titleCache
= $parent->titleCache
;
1257 $this->titleCache
[] = $pdbk;
1258 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1259 if ( $pdbk !== false ) {
1260 $this->loopCheckHash
[$pdbk] = true;
1262 $this->depth
= $parent->depth +
1;
1263 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1266 function __toString() {
1269 $args = $this->numberedArgs +
$this->namedArgs
;
1270 foreach ( $args as $name => $value ) {
1276 $s .= "\"$name\":\"" .
1277 str_replace( '"', '\\"', $value->__toString() ) . '"';
1283 * Returns true if there are no arguments in this frame
1287 function isEmpty() {
1288 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1294 function getArguments() {
1295 $arguments = array();
1296 foreach ( array_merge(
1297 array_keys($this->numberedArgs
),
1298 array_keys($this->namedArgs
)) as $key ) {
1299 $arguments[$key] = $this->getArgument($key);
1307 function getNumberedArguments() {
1308 $arguments = array();
1309 foreach ( array_keys($this->numberedArgs
) as $key ) {
1310 $arguments[$key] = $this->getArgument($key);
1318 function getNamedArguments() {
1319 $arguments = array();
1320 foreach ( array_keys($this->namedArgs
) as $key ) {
1321 $arguments[$key] = $this->getArgument($key);
1326 function getNumberedArgument( $index ) {
1327 if ( !isset( $this->numberedArgs
[$index] ) ) {
1330 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1331 # No trimming for unnamed arguments
1332 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1334 return $this->numberedExpansionCache
[$index];
1337 function getNamedArgument( $name ) {
1338 if ( !isset( $this->namedArgs
[$name] ) ) {
1341 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1342 # Trim named arguments post-expand, for backwards compatibility
1343 $this->namedExpansionCache
[$name] = trim(
1344 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1346 return $this->namedExpansionCache
[$name];
1349 function getArgument( $name ) {
1350 $text = $this->getNumberedArgument( $name );
1351 if ( $text === false ) {
1352 $text = $this->getNamedArgument( $name );
1358 * Return true if the frame is a template frame
1360 function isTemplate() {
1366 * Expansion frame with custom arguments
1369 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1372 function __construct( $preprocessor, $args ) {
1373 parent
::__construct( $preprocessor );
1374 $this->args
= $args;
1377 function __toString() {
1380 foreach ( $this->args
as $name => $value ) {
1386 $s .= "\"$name\":\"" .
1387 str_replace( '"', '\\"', $value->__toString() ) . '"';
1393 function isEmpty() {
1394 return !count( $this->args
);
1397 function getArgument( $index ) {
1398 if ( !isset( $this->args
[$index] ) ) {
1401 return $this->args
[$index];
1408 class PPNode_Hash_Tree
implements PPNode
{
1409 var $name, $firstChild, $lastChild, $nextSibling;
1411 function __construct( $name ) {
1412 $this->name
= $name;
1413 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1416 function __toString() {
1419 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1420 if ( $node instanceof PPNode_Hash_Attr
) {
1421 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1423 $inner .= $node->__toString();
1426 if ( $inner === '' ) {
1427 return "<{$this->name}$attribs/>";
1429 return "<{$this->name}$attribs>$inner</{$this->name}>";
1433 static function newWithText( $name, $text ) {
1434 $obj = new self( $name );
1435 $obj->addChild( new PPNode_Hash_Text( $text ) );
1439 function addChild( $node ) {
1440 if ( $this->lastChild
=== false ) {
1441 $this->firstChild
= $this->lastChild
= $node;
1443 $this->lastChild
->nextSibling
= $node;
1444 $this->lastChild
= $node;
1448 function getChildren() {
1449 $children = array();
1450 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1451 $children[] = $child;
1453 return new PPNode_Hash_Array( $children );
1456 function getFirstChild() {
1457 return $this->firstChild
;
1460 function getNextSibling() {
1461 return $this->nextSibling
;
1464 function getChildrenOfType( $name ) {
1465 $children = array();
1466 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1467 if ( isset( $child->name
) && $child->name
=== $name ) {
1468 $children[] = $name;
1474 function getLength() { return false; }
1475 function item( $i ) { return false; }
1477 function getName() {
1482 * Split a <part> node into an associative array containing:
1484 * index String index
1485 * value PPNode value
1487 function splitArg() {
1489 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1490 if ( !isset( $child->name
) ) {
1493 if ( $child->name
=== 'name' ) {
1494 $bits['name'] = $child;
1495 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1496 && $child->firstChild
->name
=== 'index' )
1498 $bits['index'] = $child->firstChild
->value
;
1500 } elseif ( $child->name
=== 'value' ) {
1501 $bits['value'] = $child;
1505 if ( !isset( $bits['name'] ) ) {
1506 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1508 if ( !isset( $bits['index'] ) ) {
1509 $bits['index'] = '';
1515 * Split an <ext> node into an associative array containing name, attr, inner and close
1516 * All values in the resulting array are PPNodes. Inner and close are optional.
1518 function splitExt() {
1520 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1521 if ( !isset( $child->name
) ) {
1524 if ( $child->name
== 'name' ) {
1525 $bits['name'] = $child;
1526 } elseif ( $child->name
== 'attr' ) {
1527 $bits['attr'] = $child;
1528 } elseif ( $child->name
== 'inner' ) {
1529 $bits['inner'] = $child;
1530 } elseif ( $child->name
== 'close' ) {
1531 $bits['close'] = $child;
1534 if ( !isset( $bits['name'] ) ) {
1535 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1543 function splitHeading() {
1544 if ( $this->name
!== 'h' ) {
1545 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1548 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1549 if ( !isset( $child->name
) ) {
1552 if ( $child->name
== 'i' ) {
1553 $bits['i'] = $child->value
;
1554 } elseif ( $child->name
== 'level' ) {
1555 $bits['level'] = $child->value
;
1558 if ( !isset( $bits['i'] ) ) {
1559 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1565 * Split a <template> or <tplarg> node
1567 function splitTemplate() {
1569 $bits = array( 'lineStart' => '' );
1570 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1571 if ( !isset( $child->name
) ) {
1574 if ( $child->name
== 'title' ) {
1575 $bits['title'] = $child;
1577 if ( $child->name
== 'part' ) {
1580 if ( $child->name
== 'lineStart' ) {
1581 $bits['lineStart'] = '1';
1584 if ( !isset( $bits['title'] ) ) {
1585 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1587 $bits['parts'] = new PPNode_Hash_Array( $parts );
1595 class PPNode_Hash_Text
implements PPNode
{
1596 var $value, $nextSibling;
1598 function __construct( $value ) {
1599 if ( is_object( $value ) ) {
1600 throw new MWException( __CLASS__
. ' given object instead of string' );
1602 $this->value
= $value;
1605 function __toString() {
1606 return htmlspecialchars( $this->value
);
1609 function getNextSibling() {
1610 return $this->nextSibling
;
1613 function getChildren() { return false; }
1614 function getFirstChild() { return false; }
1615 function getChildrenOfType( $name ) { return false; }
1616 function getLength() { return false; }
1617 function item( $i ) { return false; }
1618 function getName() { return '#text'; }
1619 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1620 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1621 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1627 class PPNode_Hash_Array
implements PPNode
{
1628 var $value, $nextSibling;
1630 function __construct( $value ) {
1631 $this->value
= $value;
1634 function __toString() {
1635 return var_export( $this, true );
1638 function getLength() {
1639 return count( $this->value
);
1642 function item( $i ) {
1643 return $this->value
[$i];
1646 function getName() { return '#nodelist'; }
1648 function getNextSibling() {
1649 return $this->nextSibling
;
1652 function getChildren() { return false; }
1653 function getFirstChild() { return false; }
1654 function getChildrenOfType( $name ) { return false; }
1655 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1656 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1657 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1663 class PPNode_Hash_Attr
implements PPNode
{
1664 var $name, $value, $nextSibling;
1666 function __construct( $name, $value ) {
1667 $this->name
= $name;
1668 $this->value
= $value;
1671 function __toString() {
1672 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1675 function getName() {
1679 function getNextSibling() {
1680 return $this->nextSibling
;
1683 function getChildren() { return false; }
1684 function getFirstChild() { return false; }
1685 function getChildrenOfType( $name ) { return false; }
1686 function getLength() { return false; }
1687 function item( $i ) { return false; }
1688 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1689 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1690 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }