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;
151 } else if ( $this->parser
->ot
['wiki'] ) {
152 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude', 'includeonly', '/includeonly' );
153 $ignoredElements = array();
155 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
156 $ignoredElements = array( 'includeonly' );
157 $xmlishElements[] = 'includeonly';
159 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
161 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
162 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
164 $stack = new PPDStack_Hash
;
166 $searchBase = "[{<\n";
167 $revText = strrev( $text ); // For fast reverse searches
169 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
170 $accum =& $stack->getAccum(); # Current accumulator
171 $findEquals = false; # True to find equals signs in arguments
172 $findPipe = false; # True to take notice of pipe characters
174 $inHeading = false; # True if $i is inside a possible heading
175 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
176 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
177 $fakeLineStart = true; # Do a line-start run without outputting an LF character
182 if ( $findOnlyinclude ) {
183 // Ignore all input up to the next <onlyinclude>
184 $startPos = strpos( $text, '<onlyinclude>', $i );
185 if ( $startPos === false ) {
186 // Ignored section runs to the end
187 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
190 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
191 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
193 $findOnlyinclude = false;
196 if ( $fakeLineStart ) {
197 $found = 'line-start';
200 # Find next opening brace, closing brace or pipe
201 $search = $searchBase;
202 if ( $stack->top
=== false ) {
203 $currentClosing = '';
205 $currentClosing = $stack->top
->close
;
206 $search .= $currentClosing;
212 // First equals will be for the template
216 # Output literal section, advance input counter
217 $literalLength = strcspn( $text, $search, $i );
218 if ( $literalLength > 0 ) {
219 $accum->addLiteral( substr( $text, $i, $literalLength ) );
220 $i +
= $literalLength;
222 if ( $i >= strlen( $text ) ) {
223 if ( $currentClosing == "\n" ) {
224 // Do a past-the-end run to finish off the heading
232 $curChar = $text[$i];
233 if ( $curChar == '|' ) {
235 } elseif ( $curChar == '=' ) {
237 } elseif ( $curChar == '<' ) {
239 } elseif ( $curChar == "\n" ) {
243 $found = 'line-start';
245 } elseif ( $curChar == $currentClosing ) {
247 } elseif ( isset( $rules[$curChar] ) ) {
249 $rule = $rules[$curChar];
251 # Some versions of PHP have a strcspn which stops on null characters
252 # Ignore and continue
259 if ( $found == 'angle' ) {
261 // Handle </onlyinclude>
262 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
263 $findOnlyinclude = true;
267 // Determine element name
268 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
269 // Element name missing or not listed
270 $accum->addLiteral( '<' );
275 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
276 // To avoid leaving blank lines, when a comment is both preceded
277 // and followed by a newline (ignoring spaces), trim leading and
278 // trailing spaces and one of the newlines.
281 $endPos = strpos( $text, '-->', $i +
4 );
282 if ( $endPos === false ) {
283 // Unclosed comment in input, runs to end
284 $inner = substr( $text, $i );
285 $accum->addNodeWithText( 'comment', $inner );
286 $i = strlen( $text );
288 // Search backwards for leading whitespace
289 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
290 // Search forwards for trailing whitespace
291 // $wsEnd will be the position of the last space (or the '>' if there's none)
292 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
293 // Eat the line if possible
294 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
295 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
296 // it's a possible beneficial b/c break.
297 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
298 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
300 $startPos = $wsStart;
301 $endPos = $wsEnd +
1;
302 // Remove leading whitespace from the end of the accumulator
303 // Sanity check first though
304 $wsLength = $i - $wsStart;
306 && $accum->lastNode
instanceof PPNode_Hash_Text
307 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
309 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
311 // Do a line-start run next time to look for headings after the comment
312 $fakeLineStart = true;
314 // No line to eat, just take the comment itself
320 $part = $stack->top
->getCurrentPart();
321 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
322 $part->visualEnd
= $wsStart;
324 // Else comments abutting, no change in visual end
325 $part->commentEnd
= $endPos;
328 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
329 $accum->addNodeWithText( 'comment', $inner );
334 $lowerName = strtolower( $name );
335 $attrStart = $i +
strlen( $name ) +
1;
338 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
339 if ( $tagEndPos === false ) {
340 // Infinite backtrack
341 // Disable tag search to prevent worst-case O(N^2) performance
343 $accum->addLiteral( '<' );
348 // Handle ignored tags
349 if ( in_array( $lowerName, $ignoredTags ) ) {
350 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
356 if ( $text[$tagEndPos-1] == '/' ) {
358 $attrEnd = $tagEndPos - 1;
363 $attrEnd = $tagEndPos;
365 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
366 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
368 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
369 $i = $matches[0][1] +
strlen( $matches[0][0] );
370 $close = $matches[0][0];
372 // No end tag -- let it run out to the end of the text.
373 $inner = substr( $text, $tagEndPos +
1 );
374 $i = strlen( $text );
378 // <includeonly> and <noinclude> just become <ignore> tags
379 if ( in_array( $lowerName, $ignoredElements ) ) {
380 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
384 if ( $attrEnd <= $attrStart ) {
387 // Note that the attr element contains the whitespace between name and attribute,
388 // this is necessary for precise reconstruction during pre-save transform.
389 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
392 $extNode = new PPNode_Hash_Tree( 'ext' );
393 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
394 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
395 if ( $inner !== null ) {
396 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
398 if ( $close !== null ) {
399 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
401 $accum->addNode( $extNode );
404 elseif ( $found == 'line-start' ) {
405 // Is this the start of a heading?
406 // Line break belongs before the heading element in any case
407 if ( $fakeLineStart ) {
408 $fakeLineStart = false;
410 $accum->addLiteral( $curChar );
414 $count = strspn( $text, '=', $i, 6 );
415 if ( $count == 1 && $findEquals ) {
416 // DWIM: This looks kind of like a name/value separator
417 // Let's let the equals handler have it and break the potential heading
418 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
419 } elseif ( $count > 0 ) {
423 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
426 $stack->push( $piece );
427 $accum =& $stack->getAccum();
428 extract( $stack->getFlags() );
431 } elseif ( $found == 'line-end' ) {
432 $piece = $stack->top
;
433 // A heading must be open, otherwise \n wouldn't have been in the search list
434 assert( $piece->open
== "\n" );
435 $part = $piece->getCurrentPart();
436 // Search back through the input to see if it has a proper close
437 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
438 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
439 $searchStart = $i - $wsLength;
440 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
441 // Comment found at line end
442 // Search for equals signs before the comment
443 $searchStart = $part->visualEnd
;
444 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
446 $count = $piece->count
;
447 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
448 if ( $equalsLength > 0 ) {
449 if ( $searchStart - $equalsLength == $piece->startPos
) {
450 // This is just a single string of equals signs on its own line
451 // Replicate the doHeadings behaviour /={count}(.+)={count}/
452 // First find out how many equals signs there really are (don't stop at 6)
453 $count = $equalsLength;
457 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
460 $count = min( $equalsLength, $count );
463 // Normal match, output <h>
464 $element = new PPNode_Hash_Tree( 'possible-h' );
465 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
466 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
467 $element->lastChild
->nextSibling
= $accum->firstNode
;
468 $element->lastChild
= $accum->lastNode
;
470 // Single equals sign on its own line, count=0
474 // No match, no <h>, just pass down the inner text
479 $accum =& $stack->getAccum();
480 extract( $stack->getFlags() );
482 // Append the result to the enclosing accumulator
483 if ( $element instanceof PPNode
) {
484 $accum->addNode( $element );
486 $accum->addAccum( $element );
488 // Note that we do NOT increment the input pointer.
489 // This is because the closing linebreak could be the opening linebreak of
490 // another heading. Infinite loops are avoided because the next iteration MUST
491 // hit the heading open case above, which unconditionally increments the
493 } elseif ( $found == 'open' ) {
494 # count opening brace characters
495 $count = strspn( $text, $curChar, $i );
497 # we need to add to stack only if opening brace count is enough for one of the rules
498 if ( $count >= $rule['min'] ) {
499 # Add it to the stack
502 'close' => $rule['end'],
504 'lineStart' => ($i == 0 ||
$text[$i-1] == "\n"),
507 $stack->push( $piece );
508 $accum =& $stack->getAccum();
509 extract( $stack->getFlags() );
511 # Add literal brace(s)
512 $accum->addLiteral( str_repeat( $curChar, $count ) );
515 } elseif ( $found == 'close' ) {
516 $piece = $stack->top
;
517 # lets check if there are enough characters for closing brace
518 $maxCount = $piece->count
;
519 $count = strspn( $text, $curChar, $i, $maxCount );
521 # check for maximum matching characters (if there are 5 closing
522 # characters, we will probably need only 3 - depending on the rules)
523 $rule = $rules[$piece->open
];
524 if ( $count > $rule['max'] ) {
525 # The specified maximum exists in the callback array, unless the caller
527 $matchingCount = $rule['max'];
529 # Count is less than the maximum
530 # Skip any gaps in the callback array to find the true largest match
531 # Need to use array_key_exists not isset because the callback can be null
532 $matchingCount = $count;
533 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
538 if ($matchingCount <= 0) {
539 # No matching element found in callback array
540 # Output a literal closing brace and continue
541 $accum->addLiteral( str_repeat( $curChar, $count ) );
545 $name = $rule['names'][$matchingCount];
546 if ( $name === null ) {
547 // No element, just literal text
548 $element = $piece->breakSyntax( $matchingCount );
549 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
552 # Note: $parts is already XML, does not need to be encoded further
553 $parts = $piece->parts
;
554 $titleAccum = $parts[0]->out
;
557 $element = new PPNode_Hash_Tree( $name );
559 # The invocation is at the start of the line if lineStart is set in
560 # the stack, and all opening brackets are used up.
561 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
562 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
564 $titleNode = new PPNode_Hash_Tree( 'title' );
565 $titleNode->firstChild
= $titleAccum->firstNode
;
566 $titleNode->lastChild
= $titleAccum->lastNode
;
567 $element->addChild( $titleNode );
569 foreach ( $parts as $part ) {
570 if ( isset( $part->eqpos
) ) {
573 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
574 if ( $node === $part->eqpos
) {
580 throw new MWException( __METHOD__
. ': eqpos not found' );
582 if ( $node->name
!== 'equals' ) {
583 throw new MWException( __METHOD__
.': eqpos is not equals' );
587 // Construct name node
588 $nameNode = new PPNode_Hash_Tree( 'name' );
589 if ( $lastNode !== false ) {
590 $lastNode->nextSibling
= false;
591 $nameNode->firstChild
= $part->out
->firstNode
;
592 $nameNode->lastChild
= $lastNode;
595 // Construct value node
596 $valueNode = new PPNode_Hash_Tree( 'value' );
597 if ( $equalsNode->nextSibling
!== false ) {
598 $valueNode->firstChild
= $equalsNode->nextSibling
;
599 $valueNode->lastChild
= $part->out
->lastNode
;
601 $partNode = new PPNode_Hash_Tree( 'part' );
602 $partNode->addChild( $nameNode );
603 $partNode->addChild( $equalsNode->firstChild
);
604 $partNode->addChild( $valueNode );
605 $element->addChild( $partNode );
607 $partNode = new PPNode_Hash_Tree( 'part' );
608 $nameNode = new PPNode_Hash_Tree( 'name' );
609 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
610 $valueNode = new PPNode_Hash_Tree( 'value' );
611 $valueNode->firstChild
= $part->out
->firstNode
;
612 $valueNode->lastChild
= $part->out
->lastNode
;
613 $partNode->addChild( $nameNode );
614 $partNode->addChild( $valueNode );
615 $element->addChild( $partNode );
620 # Advance input pointer
621 $i +
= $matchingCount;
625 $accum =& $stack->getAccum();
627 # Re-add the old stack element if it still has unmatched opening characters remaining
628 if ($matchingCount < $piece->count
) {
629 $piece->parts
= array( new PPDPart_Hash
);
630 $piece->count
-= $matchingCount;
631 # do we still qualify for any callback with remaining count?
632 $names = $rules[$piece->open
]['names'];
634 $enclosingAccum =& $accum;
635 while ( $piece->count
) {
636 if ( array_key_exists( $piece->count
, $names ) ) {
637 $stack->push( $piece );
638 $accum =& $stack->getAccum();
644 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
647 extract( $stack->getFlags() );
649 # Add XML element to the enclosing accumulator
650 if ( $element instanceof PPNode
) {
651 $accum->addNode( $element );
653 $accum->addAccum( $element );
655 } elseif ( $found == 'pipe' ) {
656 $findEquals = true; // shortcut for getFlags()
658 $accum =& $stack->getAccum();
660 } elseif ( $found == 'equals' ) {
661 $findEquals = false; // shortcut for getFlags()
662 $accum->addNodeWithText( 'equals', '=' );
663 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
668 # Output any remaining unclosed brackets
669 foreach ( $stack->stack
as $piece ) {
670 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
673 # Enable top-level headings
674 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
675 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
680 $rootNode = new PPNode_Hash_Tree( 'root' );
681 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
682 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
686 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
687 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
688 wfProfileOut( __METHOD__
.'-cache-miss' );
689 wfProfileOut( __METHOD__
.'-cacheable' );
690 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
693 wfProfileOut( __METHOD__
);
699 * Stack class to help Preprocessor::preprocessToObj()
702 class PPDStack_Hash
extends PPDStack
{
703 function __construct() {
704 $this->elementClass
= 'PPDStackElement_Hash';
705 parent
::__construct();
706 $this->rootAccum
= new PPDAccum_Hash
;
713 class PPDStackElement_Hash
extends PPDStackElement
{
714 function __construct( $data = array() ) {
715 $this->partClass
= 'PPDPart_Hash';
716 parent
::__construct( $data );
720 * Get the accumulator that would result if the close is not found.
722 * @return PPDAccum_Hash
724 function breakSyntax( $openingCount = false ) {
725 if ( $this->open
== "\n" ) {
726 $accum = $this->parts
[0]->out
;
728 if ( $openingCount === false ) {
729 $openingCount = $this->count
;
731 $accum = new PPDAccum_Hash
;
732 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
734 foreach ( $this->parts
as $part ) {
738 $accum->addLiteral( '|' );
740 $accum->addAccum( $part->out
);
750 class PPDPart_Hash
extends PPDPart
{
751 function __construct( $out = '' ) {
752 $accum = new PPDAccum_Hash
;
754 $accum->addLiteral( $out );
756 parent
::__construct( $accum );
763 class PPDAccum_Hash
{
764 var $firstNode, $lastNode;
766 function __construct() {
767 $this->firstNode
= $this->lastNode
= false;
771 * Append a string literal
773 function addLiteral( $s ) {
774 if ( $this->lastNode
=== false ) {
775 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
776 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
777 $this->lastNode
->value
.= $s;
779 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
780 $this->lastNode
= $this->lastNode
->nextSibling
;
787 function addNode( PPNode
$node ) {
788 if ( $this->lastNode
=== false ) {
789 $this->firstNode
= $this->lastNode
= $node;
791 $this->lastNode
->nextSibling
= $node;
792 $this->lastNode
= $node;
797 * Append a tree node with text contents
799 function addNodeWithText( $name, $value ) {
800 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
801 $this->addNode( $node );
805 * Append a PPAccum_Hash
806 * Takes over ownership of the nodes in the source argument. These nodes may
807 * subsequently be modified, especially nextSibling.
809 function addAccum( $accum ) {
810 if ( $accum->lastNode
=== false ) {
812 } elseif ( $this->lastNode
=== false ) {
813 $this->firstNode
= $accum->firstNode
;
814 $this->lastNode
= $accum->lastNode
;
816 $this->lastNode
->nextSibling
= $accum->firstNode
;
817 $this->lastNode
= $accum->lastNode
;
823 * An expansion frame, used as a context to expand the result of preprocessToObj()
826 class PPFrame_Hash
implements PPFrame
{
845 * Hashtable listing templates which are disallowed for expansion in this frame,
846 * having been encountered previously in parent frames.
851 * Recursion depth of this frame, top = 0
852 * Note that this is NOT the same as expansion depth in expand()
858 * Construct a new preprocessor frame.
859 * @param $preprocessor Preprocessor: the parent preprocessor
861 function __construct( $preprocessor ) {
862 $this->preprocessor
= $preprocessor;
863 $this->parser
= $preprocessor->parser
;
864 $this->title
= $this->parser
->mTitle
;
865 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
866 $this->loopCheckHash
= array();
871 * Create a new child frame
872 * $args is optionally a multi-root PPNode or array containing the template arguments
874 * @param $args PPNode_Hash_Array|array
875 * @param $title Title|false
877 * @return PPTemplateFrame_Hash
879 function newChild( $args = false, $title = false ) {
880 $namedArgs = array();
881 $numberedArgs = array();
882 if ( $title === false ) {
883 $title = $this->title
;
885 if ( $args !== false ) {
886 if ( $args instanceof PPNode_Hash_Array
) {
887 $args = $args->value
;
888 } elseif ( !is_array( $args ) ) {
889 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
891 foreach ( $args as $arg ) {
892 $bits = $arg->splitArg();
893 if ( $bits['index'] !== '' ) {
894 // Numbered parameter
895 $numberedArgs[$bits['index']] = $bits['value'];
896 unset( $namedArgs[$bits['index']] );
899 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
900 $namedArgs[$name] = $bits['value'];
901 unset( $numberedArgs[$name] );
905 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
909 * @throws MWException
914 function expand( $root, $flags = 0 ) {
915 static $expansionDepth = 0;
916 if ( is_string( $root ) ) {
920 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
921 return '<span class="error">Node-count limit exceeded</span>';
923 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
924 return '<span class="error">Expansion depth limit exceeded</span>';
928 $outStack = array( '', '' );
929 $iteratorStack = array( false, $root );
930 $indexStack = array( 0, 0 );
932 while ( count( $iteratorStack ) > 1 ) {
933 $level = count( $outStack ) - 1;
934 $iteratorNode =& $iteratorStack[ $level ];
935 $out =& $outStack[$level];
936 $index =& $indexStack[$level];
938 if ( is_array( $iteratorNode ) ) {
939 if ( $index >= count( $iteratorNode ) ) {
940 // All done with this iterator
941 $iteratorStack[$level] = false;
942 $contextNode = false;
944 $contextNode = $iteratorNode[$index];
947 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
948 if ( $index >= $iteratorNode->getLength() ) {
949 // All done with this iterator
950 $iteratorStack[$level] = false;
951 $contextNode = false;
953 $contextNode = $iteratorNode->item( $index );
957 // Copy to $contextNode and then delete from iterator stack,
958 // because this is not an iterator but we do have to execute it once
959 $contextNode = $iteratorStack[$level];
960 $iteratorStack[$level] = false;
963 $newIterator = false;
965 if ( $contextNode === false ) {
967 } elseif ( is_string( $contextNode ) ) {
968 $out .= $contextNode;
969 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
970 $newIterator = $contextNode;
971 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
973 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
974 $out .= $contextNode->value
;
975 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
976 if ( $contextNode->name
== 'template' ) {
977 # Double-brace expansion
978 $bits = $contextNode->splitTemplate();
979 if ( $flags & PPFrame
::NO_TEMPLATES
) {
980 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
982 $ret = $this->parser
->braceSubstitution( $bits, $this );
983 if ( isset( $ret['object'] ) ) {
984 $newIterator = $ret['object'];
986 $out .= $ret['text'];
989 } elseif ( $contextNode->name
== 'tplarg' ) {
990 # Triple-brace expansion
991 $bits = $contextNode->splitTemplate();
992 if ( $flags & PPFrame
::NO_ARGS
) {
993 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
995 $ret = $this->parser
->argSubstitution( $bits, $this );
996 if ( isset( $ret['object'] ) ) {
997 $newIterator = $ret['object'];
999 $out .= $ret['text'];
1002 } elseif ( $contextNode->name
== 'comment' ) {
1003 # HTML-style comment
1004 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1005 if ( $this->parser
->ot
['html']
1006 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1007 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1011 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1012 # Not in RECOVER_COMMENTS mode (extractSections) though
1013 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1014 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1016 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1018 $out .= $contextNode->firstChild
->value
;
1020 } elseif ( $contextNode->name
== 'ignore' ) {
1021 # Output suppression used by <includeonly> etc.
1022 # OT_WIKI will only respect <ignore> in substed templates.
1023 # The other output types respect it unless NO_IGNORE is set.
1024 # extractSections() sets NO_IGNORE and so never respects it.
1025 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1026 $out .= $contextNode->firstChild
->value
;
1030 } elseif ( $contextNode->name
== 'ext' ) {
1032 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1033 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1034 } elseif ( $contextNode->name
== 'h' ) {
1036 if ( $this->parser
->ot
['html'] ) {
1037 # Expand immediately and insert heading index marker
1039 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1040 $s .= $this->expand( $node, $flags );
1043 $bits = $contextNode->splitHeading();
1044 $titleText = $this->title
->getPrefixedDBkey();
1045 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1046 $serial = count( $this->parser
->mHeadings
) - 1;
1047 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1048 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1049 $this->parser
->mStripState
->addGeneral( $marker, '' );
1052 # Expand in virtual stack
1053 $newIterator = $contextNode->getChildren();
1056 # Generic recursive expansion
1057 $newIterator = $contextNode->getChildren();
1060 throw new MWException( __METHOD__
.': Invalid parameter type' );
1063 if ( $newIterator !== false ) {
1065 $iteratorStack[] = $newIterator;
1067 } elseif ( $iteratorStack[$level] === false ) {
1068 // Return accumulated value to parent
1069 // With tail recursion
1070 while ( $iteratorStack[$level] === false && $level > 0 ) {
1071 $outStack[$level - 1] .= $out;
1072 array_pop( $outStack );
1073 array_pop( $iteratorStack );
1074 array_pop( $indexStack );
1080 return $outStack[0];
1088 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1089 $args = array_slice( func_get_args(), 2 );
1093 foreach ( $args as $root ) {
1094 if ( $root instanceof PPNode_Hash_Array
) {
1095 $root = $root->value
;
1097 if ( !is_array( $root ) ) {
1098 $root = array( $root );
1100 foreach ( $root as $node ) {
1106 $s .= $this->expand( $node, $flags );
1113 * Implode with no flags specified
1114 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1117 function implode( $sep /*, ... */ ) {
1118 $args = array_slice( func_get_args(), 1 );
1122 foreach ( $args as $root ) {
1123 if ( $root instanceof PPNode_Hash_Array
) {
1124 $root = $root->value
;
1126 if ( !is_array( $root ) ) {
1127 $root = array( $root );
1129 foreach ( $root as $node ) {
1135 $s .= $this->expand( $node );
1142 * Makes an object that, when expand()ed, will be the same as one obtained
1145 * @return PPNode_Hash_Array
1147 function virtualImplode( $sep /*, ... */ ) {
1148 $args = array_slice( func_get_args(), 1 );
1152 foreach ( $args as $root ) {
1153 if ( $root instanceof PPNode_Hash_Array
) {
1154 $root = $root->value
;
1156 if ( !is_array( $root ) ) {
1157 $root = array( $root );
1159 foreach ( $root as $node ) {
1168 return new PPNode_Hash_Array( $out );
1172 * Virtual implode with brackets
1174 * @return PPNode_Hash_Array
1176 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1177 $args = array_slice( func_get_args(), 3 );
1178 $out = array( $start );
1181 foreach ( $args as $root ) {
1182 if ( $root instanceof PPNode_Hash_Array
) {
1183 $root = $root->value
;
1185 if ( !is_array( $root ) ) {
1186 $root = array( $root );
1188 foreach ( $root as $node ) {
1198 return new PPNode_Hash_Array( $out );
1201 function __toString() {
1206 * @param $level bool
1207 * @return array|bool|String
1209 function getPDBK( $level = false ) {
1210 if ( $level === false ) {
1211 return $this->title
->getPrefixedDBkey();
1213 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1220 function getArguments() {
1227 function getNumberedArguments() {
1234 function getNamedArguments() {
1239 * Returns true if there are no arguments in this frame
1243 function isEmpty() {
1251 function getArgument( $name ) {
1256 * Returns true if the infinite loop check is OK, false if a loop is detected
1258 * @param $title Title
1262 function loopCheck( $title ) {
1263 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1267 * Return true if the frame is a template frame
1271 function isTemplate() {
1277 * Expansion frame with template arguments
1280 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1281 var $numberedArgs, $namedArgs, $parent;
1282 var $numberedExpansionCache, $namedExpansionCache;
1285 * @param $preprocessor
1287 * @param $numberedArgs array
1288 * @param $namedArgs array
1289 * @param $title Title
1291 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1292 parent
::__construct( $preprocessor );
1294 $this->parent
= $parent;
1295 $this->numberedArgs
= $numberedArgs;
1296 $this->namedArgs
= $namedArgs;
1297 $this->title
= $title;
1298 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1299 $this->titleCache
= $parent->titleCache
;
1300 $this->titleCache
[] = $pdbk;
1301 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1302 if ( $pdbk !== false ) {
1303 $this->loopCheckHash
[$pdbk] = true;
1305 $this->depth
= $parent->depth +
1;
1306 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1309 function __toString() {
1312 $args = $this->numberedArgs +
$this->namedArgs
;
1313 foreach ( $args as $name => $value ) {
1319 $s .= "\"$name\":\"" .
1320 str_replace( '"', '\\"', $value->__toString() ) . '"';
1326 * Returns true if there are no arguments in this frame
1330 function isEmpty() {
1331 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1337 function getArguments() {
1338 $arguments = array();
1339 foreach ( array_merge(
1340 array_keys($this->numberedArgs
),
1341 array_keys($this->namedArgs
)) as $key ) {
1342 $arguments[$key] = $this->getArgument($key);
1350 function getNumberedArguments() {
1351 $arguments = array();
1352 foreach ( array_keys($this->numberedArgs
) as $key ) {
1353 $arguments[$key] = $this->getArgument($key);
1361 function getNamedArguments() {
1362 $arguments = array();
1363 foreach ( array_keys($this->namedArgs
) as $key ) {
1364 $arguments[$key] = $this->getArgument($key);
1371 * @return array|bool
1373 function getNumberedArgument( $index ) {
1374 if ( !isset( $this->numberedArgs
[$index] ) ) {
1377 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1378 # No trimming for unnamed arguments
1379 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1381 return $this->numberedExpansionCache
[$index];
1388 function getNamedArgument( $name ) {
1389 if ( !isset( $this->namedArgs
[$name] ) ) {
1392 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1393 # Trim named arguments post-expand, for backwards compatibility
1394 $this->namedExpansionCache
[$name] = trim(
1395 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1397 return $this->namedExpansionCache
[$name];
1402 * @return array|bool
1404 function getArgument( $name ) {
1405 $text = $this->getNumberedArgument( $name );
1406 if ( $text === false ) {
1407 $text = $this->getNamedArgument( $name );
1413 * Return true if the frame is a template frame
1417 function isTemplate() {
1423 * Expansion frame with custom arguments
1426 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1429 function __construct( $preprocessor, $args ) {
1430 parent
::__construct( $preprocessor );
1431 $this->args
= $args;
1434 function __toString() {
1437 foreach ( $this->args
as $name => $value ) {
1443 $s .= "\"$name\":\"" .
1444 str_replace( '"', '\\"', $value->__toString() ) . '"';
1453 function isEmpty() {
1454 return !count( $this->args
);
1461 function getArgument( $index ) {
1462 if ( !isset( $this->args
[$index] ) ) {
1465 return $this->args
[$index];
1472 class PPNode_Hash_Tree
implements PPNode
{
1473 var $name, $firstChild, $lastChild, $nextSibling;
1475 function __construct( $name ) {
1476 $this->name
= $name;
1477 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1480 function __toString() {
1483 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1484 if ( $node instanceof PPNode_Hash_Attr
) {
1485 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1487 $inner .= $node->__toString();
1490 if ( $inner === '' ) {
1491 return "<{$this->name}$attribs/>";
1493 return "<{$this->name}$attribs>$inner</{$this->name}>";
1500 * @return PPNode_Hash_Tree
1502 static function newWithText( $name, $text ) {
1503 $obj = new self( $name );
1504 $obj->addChild( new PPNode_Hash_Text( $text ) );
1508 function addChild( $node ) {
1509 if ( $this->lastChild
=== false ) {
1510 $this->firstChild
= $this->lastChild
= $node;
1512 $this->lastChild
->nextSibling
= $node;
1513 $this->lastChild
= $node;
1518 * @return PPNode_Hash_Array
1520 function getChildren() {
1521 $children = array();
1522 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1523 $children[] = $child;
1525 return new PPNode_Hash_Array( $children );
1528 function getFirstChild() {
1529 return $this->firstChild
;
1532 function getNextSibling() {
1533 return $this->nextSibling
;
1536 function getChildrenOfType( $name ) {
1537 $children = array();
1538 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1539 if ( isset( $child->name
) && $child->name
=== $name ) {
1540 $children[] = $name;
1549 function getLength() {
1557 function item( $i ) {
1564 function getName() {
1569 * Split a <part> node into an associative array containing:
1571 * index String index
1572 * value PPNode value
1576 function splitArg() {
1578 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1579 if ( !isset( $child->name
) ) {
1582 if ( $child->name
=== 'name' ) {
1583 $bits['name'] = $child;
1584 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1585 && $child->firstChild
->name
=== 'index' )
1587 $bits['index'] = $child->firstChild
->value
;
1589 } elseif ( $child->name
=== 'value' ) {
1590 $bits['value'] = $child;
1594 if ( !isset( $bits['name'] ) ) {
1595 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1597 if ( !isset( $bits['index'] ) ) {
1598 $bits['index'] = '';
1604 * Split an <ext> node into an associative array containing name, attr, inner and close
1605 * All values in the resulting array are PPNodes. Inner and close are optional.
1609 function splitExt() {
1611 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1612 if ( !isset( $child->name
) ) {
1615 if ( $child->name
== 'name' ) {
1616 $bits['name'] = $child;
1617 } elseif ( $child->name
== 'attr' ) {
1618 $bits['attr'] = $child;
1619 } elseif ( $child->name
== 'inner' ) {
1620 $bits['inner'] = $child;
1621 } elseif ( $child->name
== 'close' ) {
1622 $bits['close'] = $child;
1625 if ( !isset( $bits['name'] ) ) {
1626 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1636 function splitHeading() {
1637 if ( $this->name
!== 'h' ) {
1638 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1641 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1642 if ( !isset( $child->name
) ) {
1645 if ( $child->name
== 'i' ) {
1646 $bits['i'] = $child->value
;
1647 } elseif ( $child->name
== 'level' ) {
1648 $bits['level'] = $child->value
;
1651 if ( !isset( $bits['i'] ) ) {
1652 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1658 * Split a <template> or <tplarg> node
1662 function splitTemplate() {
1664 $bits = array( 'lineStart' => '' );
1665 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1666 if ( !isset( $child->name
) ) {
1669 if ( $child->name
== 'title' ) {
1670 $bits['title'] = $child;
1672 if ( $child->name
== 'part' ) {
1675 if ( $child->name
== 'lineStart' ) {
1676 $bits['lineStart'] = '1';
1679 if ( !isset( $bits['title'] ) ) {
1680 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1682 $bits['parts'] = new PPNode_Hash_Array( $parts );
1690 class PPNode_Hash_Text
implements PPNode
{
1691 var $value, $nextSibling;
1693 function __construct( $value ) {
1694 if ( is_object( $value ) ) {
1695 throw new MWException( __CLASS__
. ' given object instead of string' );
1697 $this->value
= $value;
1700 function __toString() {
1701 return htmlspecialchars( $this->value
);
1704 function getNextSibling() {
1705 return $this->nextSibling
;
1708 function getChildren() { return false; }
1709 function getFirstChild() { return false; }
1710 function getChildrenOfType( $name ) { return false; }
1711 function getLength() { return false; }
1712 function item( $i ) { return false; }
1713 function getName() { return '#text'; }
1714 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1715 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1716 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1722 class PPNode_Hash_Array
implements PPNode
{
1723 var $value, $nextSibling;
1725 function __construct( $value ) {
1726 $this->value
= $value;
1729 function __toString() {
1730 return var_export( $this, true );
1733 function getLength() {
1734 return count( $this->value
);
1737 function item( $i ) {
1738 return $this->value
[$i];
1741 function getName() { return '#nodelist'; }
1743 function getNextSibling() {
1744 return $this->nextSibling
;
1747 function getChildren() { return false; }
1748 function getFirstChild() { return false; }
1749 function getChildrenOfType( $name ) { return false; }
1750 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1751 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1752 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1758 class PPNode_Hash_Attr
implements PPNode
{
1759 var $name, $value, $nextSibling;
1761 function __construct( $name, $value ) {
1762 $this->name
= $name;
1763 $this->value
= $value;
1766 function __toString() {
1767 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1770 function getName() {
1774 function getNextSibling() {
1775 return $this->nextSibling
;
1778 function getChildren() { return false; }
1779 function getFirstChild() { return false; }
1780 function getChildrenOfType( $name ) { return false; }
1781 function getLength() { return false; }
1782 function item( $i ) { return false; }
1783 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1784 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1785 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }