4 * Differences from DOM schema:
5 * * attribute nodes are children
6 * * <h> nodes that aren't at the top are replaced with <possible-h>
9 class Preprocessor_Hash
implements Preprocessor
{
12 const CACHE_VERSION
= 1;
14 function __construct( $parser ) {
15 $this->parser
= $parser;
19 return new PPFrame_Hash( $this );
22 function newCustomFrame( $args ) {
23 return new PPCustomFrame_Hash( $this, $args );
26 function newPartNodeArray( $values ) {
29 foreach ( $values as $k => $val ) {
30 $partNode = new PPNode_Hash_Tree( 'part' );
31 $nameNode = new PPNode_Hash_Tree( 'name' );
34 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
35 $partNode->addChild( $nameNode );
37 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
38 $partNode->addChild( $nameNode );
39 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
42 $valueNode = new PPNode_Hash_Tree( 'value' );
43 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
44 $partNode->addChild( $valueNode );
49 $node = new PPNode_Hash_Array( $list );
54 * Preprocess some wikitext and return the document tree.
55 * This is the ghost of Parser::replace_variables().
57 * @param $text String: the text to parse
58 * @param $flags Integer: bitwise combination of:
59 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
60 * included. Default is to assume a direct page view.
62 * The generated DOM tree must depend only on the input text and the flags.
63 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
65 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
66 * change in the DOM tree for a given text, must be passed through the section identifier
67 * in the section edit link and thus back to extractSections().
69 * The output of this function is currently only cached in process memory, but a persistent
70 * cache may be implemented at a later date which takes further advantage of these strict
71 * dependency requirements.
75 function preprocessToObj( $text, $flags = 0 ) {
76 wfProfileIn( __METHOD__
);
80 global $wgMemc, $wgPreprocessorCacheThreshold;
82 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
84 wfProfileIn( __METHOD__
.'-cacheable' );
86 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
87 $cacheValue = $wgMemc->get( $cacheKey );
89 $version = substr( $cacheValue, 0, 8 );
90 if ( intval( $version ) == self
::CACHE_VERSION
) {
91 $hash = unserialize( substr( $cacheValue, 8 ) );
93 wfDebugLog( "Preprocessor",
94 "Loaded preprocessor hash from memcached (key $cacheKey)" );
95 wfProfileOut( __METHOD__
.'-cacheable' );
96 wfProfileOut( __METHOD__
);
100 wfProfileIn( __METHOD__
.'-cache-miss' );
115 'names' => array( 2 => null ),
121 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
123 $xmlishElements = $this->parser
->getStripList();
124 $enableOnlyinclude = false;
125 if ( $forInclusion ) {
126 $ignoredTags = array( 'includeonly', '/includeonly' );
127 $ignoredElements = array( 'noinclude' );
128 $xmlishElements[] = 'noinclude';
129 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
130 $enableOnlyinclude = true;
133 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
134 $ignoredElements = array( 'includeonly' );
135 $xmlishElements[] = 'includeonly';
137 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
139 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
140 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
142 $stack = new PPDStack_Hash
;
144 $searchBase = "[{<\n";
145 $revText = strrev( $text ); // For fast reverse searches
147 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
148 $accum =& $stack->getAccum(); # Current accumulator
149 $findEquals = false; # True to find equals signs in arguments
150 $findPipe = false; # True to take notice of pipe characters
152 $inHeading = false; # True if $i is inside a possible heading
153 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
154 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
155 $fakeLineStart = true; # Do a line-start run without outputting an LF character
160 if ( $findOnlyinclude ) {
161 // Ignore all input up to the next <onlyinclude>
162 $startPos = strpos( $text, '<onlyinclude>', $i );
163 if ( $startPos === false ) {
164 // Ignored section runs to the end
165 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
168 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
169 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
171 $findOnlyinclude = false;
174 if ( $fakeLineStart ) {
175 $found = 'line-start';
178 # Find next opening brace, closing brace or pipe
179 $search = $searchBase;
180 if ( $stack->top
=== false ) {
181 $currentClosing = '';
183 $currentClosing = $stack->top
->close
;
184 $search .= $currentClosing;
190 // First equals will be for the template
194 # Output literal section, advance input counter
195 $literalLength = strcspn( $text, $search, $i );
196 if ( $literalLength > 0 ) {
197 $accum->addLiteral( substr( $text, $i, $literalLength ) );
198 $i +
= $literalLength;
200 if ( $i >= strlen( $text ) ) {
201 if ( $currentClosing == "\n" ) {
202 // Do a past-the-end run to finish off the heading
210 $curChar = $text[$i];
211 if ( $curChar == '|' ) {
213 } elseif ( $curChar == '=' ) {
215 } elseif ( $curChar == '<' ) {
217 } elseif ( $curChar == "\n" ) {
221 $found = 'line-start';
223 } elseif ( $curChar == $currentClosing ) {
225 } elseif ( isset( $rules[$curChar] ) ) {
227 $rule = $rules[$curChar];
229 # Some versions of PHP have a strcspn which stops on null characters
230 # Ignore and continue
237 if ( $found == 'angle' ) {
239 // Handle </onlyinclude>
240 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
241 $findOnlyinclude = true;
245 // Determine element name
246 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
247 // Element name missing or not listed
248 $accum->addLiteral( '<' );
253 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
254 // To avoid leaving blank lines, when a comment is both preceded
255 // and followed by a newline (ignoring spaces), trim leading and
256 // trailing spaces and one of the newlines.
259 $endPos = strpos( $text, '-->', $i +
4 );
260 if ( $endPos === false ) {
261 // Unclosed comment in input, runs to end
262 $inner = substr( $text, $i );
263 $accum->addNodeWithText( 'comment', $inner );
264 $i = strlen( $text );
266 // Search backwards for leading whitespace
267 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
268 // Search forwards for trailing whitespace
269 // $wsEnd will be the position of the last space
270 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
271 // Eat the line if possible
272 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
273 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
274 // it's a possible beneficial b/c break.
275 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
276 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
278 $startPos = $wsStart;
279 $endPos = $wsEnd +
1;
280 // Remove leading whitespace from the end of the accumulator
281 // Sanity check first though
282 $wsLength = $i - $wsStart;
284 && $accum->lastNode
instanceof PPNode_Hash_Text
285 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
287 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
289 // Do a line-start run next time to look for headings after the comment
290 $fakeLineStart = true;
292 // No line to eat, just take the comment itself
298 $part = $stack->top
->getCurrentPart();
299 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
300 // Comments abutting, no change in visual end
301 $part->commentEnd
= $wsEnd;
303 $part->visualEnd
= $wsStart;
304 $part->commentEnd
= $endPos;
308 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
309 $accum->addNodeWithText( 'comment', $inner );
314 $lowerName = strtolower( $name );
315 $attrStart = $i +
strlen( $name ) +
1;
318 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
319 if ( $tagEndPos === false ) {
320 // Infinite backtrack
321 // Disable tag search to prevent worst-case O(N^2) performance
323 $accum->addLiteral( '<' );
328 // Handle ignored tags
329 if ( in_array( $lowerName, $ignoredTags ) ) {
330 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
336 if ( $text[$tagEndPos-1] == '/' ) {
338 $attrEnd = $tagEndPos - 1;
343 $attrEnd = $tagEndPos;
345 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
346 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
348 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
349 $i = $matches[0][1] +
strlen( $matches[0][0] );
350 $close = $matches[0][0];
352 // No end tag -- let it run out to the end of the text.
353 $inner = substr( $text, $tagEndPos +
1 );
354 $i = strlen( $text );
358 // <includeonly> and <noinclude> just become <ignore> tags
359 if ( in_array( $lowerName, $ignoredElements ) ) {
360 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
364 if ( $attrEnd <= $attrStart ) {
367 // Note that the attr element contains the whitespace between name and attribute,
368 // this is necessary for precise reconstruction during pre-save transform.
369 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
372 $extNode = new PPNode_Hash_Tree( 'ext' );
373 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
374 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
375 if ( $inner !== null ) {
376 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
378 if ( $close !== null ) {
379 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
381 $accum->addNode( $extNode );
384 elseif ( $found == 'line-start' ) {
385 // Is this the start of a heading?
386 // Line break belongs before the heading element in any case
387 if ( $fakeLineStart ) {
388 $fakeLineStart = false;
390 $accum->addLiteral( $curChar );
394 $count = strspn( $text, '=', $i, 6 );
395 if ( $count == 1 && $findEquals ) {
396 // DWIM: This looks kind of like a name/value separator
397 // Let's let the equals handler have it and break the potential heading
398 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
399 } elseif ( $count > 0 ) {
403 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
406 $stack->push( $piece );
407 $accum =& $stack->getAccum();
408 extract( $stack->getFlags() );
413 elseif ( $found == 'line-end' ) {
414 $piece = $stack->top
;
415 // A heading must be open, otherwise \n wouldn't have been in the search list
416 assert( $piece->open
== "\n" );
417 $part = $piece->getCurrentPart();
418 // Search back through the input to see if it has a proper close
419 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
420 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
421 $searchStart = $i - $wsLength;
422 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
423 // Comment found at line end
424 // Search for equals signs before the comment
425 $searchStart = $part->visualEnd
;
426 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
428 $count = $piece->count
;
429 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
430 if ( $equalsLength > 0 ) {
431 if ( $searchStart - $equalsLength == $piece->startPos
) {
432 // This is just a single string of equals signs on its own line
433 // Replicate the doHeadings behaviour /={count}(.+)={count}/
434 // First find out how many equals signs there really are (don't stop at 6)
435 $count = $equalsLength;
439 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
442 $count = min( $equalsLength, $count );
445 // Normal match, output <h>
446 $element = new PPNode_Hash_Tree( 'possible-h' );
447 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
448 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
449 $element->lastChild
->nextSibling
= $accum->firstNode
;
450 $element->lastChild
= $accum->lastNode
;
452 // Single equals sign on its own line, count=0
456 // No match, no <h>, just pass down the inner text
461 $accum =& $stack->getAccum();
462 extract( $stack->getFlags() );
464 // Append the result to the enclosing accumulator
465 if ( $element instanceof PPNode
) {
466 $accum->addNode( $element );
468 $accum->addAccum( $element );
470 // Note that we do NOT increment the input pointer.
471 // This is because the closing linebreak could be the opening linebreak of
472 // another heading. Infinite loops are avoided because the next iteration MUST
473 // hit the heading open case above, which unconditionally increments the
477 elseif ( $found == 'open' ) {
478 # count opening brace characters
479 $count = strspn( $text, $curChar, $i );
481 # we need to add to stack only if opening brace count is enough for one of the rules
482 if ( $count >= $rule['min'] ) {
483 # Add it to the stack
486 'close' => $rule['end'],
488 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
491 $stack->push( $piece );
492 $accum =& $stack->getAccum();
493 extract( $stack->getFlags() );
495 # Add literal brace(s)
496 $accum->addLiteral( str_repeat( $curChar, $count ) );
501 elseif ( $found == 'close' ) {
502 $piece = $stack->top
;
503 # lets check if there are enough characters for closing brace
504 $maxCount = $piece->count
;
505 $count = strspn( $text, $curChar, $i, $maxCount );
507 # check for maximum matching characters (if there are 5 closing
508 # characters, we will probably need only 3 - depending on the rules)
510 $rule = $rules[$piece->open
];
511 if ( $count > $rule['max'] ) {
512 # The specified maximum exists in the callback array, unless the caller
514 $matchingCount = $rule['max'];
516 # Count is less than the maximum
517 # Skip any gaps in the callback array to find the true largest match
518 # Need to use array_key_exists not isset because the callback can be null
519 $matchingCount = $count;
520 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
525 if ($matchingCount <= 0) {
526 # No matching element found in callback array
527 # Output a literal closing brace and continue
528 $accum->addLiteral( str_repeat( $curChar, $count ) );
532 $name = $rule['names'][$matchingCount];
533 if ( $name === null ) {
534 // No element, just literal text
535 $element = $piece->breakSyntax( $matchingCount );
536 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
539 # Note: $parts is already XML, does not need to be encoded further
540 $parts = $piece->parts
;
541 $titleAccum = $parts[0]->out
;
544 $element = new PPNode_Hash_Tree( $name );
546 # The invocation is at the start of the line if lineStart is set in
547 # the stack, and all opening brackets are used up.
548 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
549 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
551 $titleNode = new PPNode_Hash_Tree( 'title' );
552 $titleNode->firstChild
= $titleAccum->firstNode
;
553 $titleNode->lastChild
= $titleAccum->lastNode
;
554 $element->addChild( $titleNode );
556 foreach ( $parts as $partIndex => $part ) {
557 if ( isset( $part->eqpos
) ) {
560 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
561 if ( $node === $part->eqpos
) {
567 throw new MWException( __METHOD__
. ': eqpos not found' );
569 if ( $node->name
!== 'equals' ) {
570 throw new MWException( __METHOD__
.': eqpos is not equals' );
574 // Construct name node
575 $nameNode = new PPNode_Hash_Tree( 'name' );
576 if ( $lastNode !== false ) {
577 $lastNode->nextSibling
= false;
578 $nameNode->firstChild
= $part->out
->firstNode
;
579 $nameNode->lastChild
= $lastNode;
582 // Construct value node
583 $valueNode = new PPNode_Hash_Tree( 'value' );
584 if ( $equalsNode->nextSibling
!== false ) {
585 $valueNode->firstChild
= $equalsNode->nextSibling
;
586 $valueNode->lastChild
= $part->out
->lastNode
;
588 $partNode = new PPNode_Hash_Tree( 'part' );
589 $partNode->addChild( $nameNode );
590 $partNode->addChild( $equalsNode->firstChild
);
591 $partNode->addChild( $valueNode );
592 $element->addChild( $partNode );
594 $partNode = new PPNode_Hash_Tree( 'part' );
595 $nameNode = new PPNode_Hash_Tree( 'name' );
596 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
597 $valueNode = new PPNode_Hash_Tree( 'value' );
598 $valueNode->firstChild
= $part->out
->firstNode
;
599 $valueNode->lastChild
= $part->out
->lastNode
;
600 $partNode->addChild( $nameNode );
601 $partNode->addChild( $valueNode );
602 $element->addChild( $partNode );
607 # Advance input pointer
608 $i +
= $matchingCount;
612 $accum =& $stack->getAccum();
614 # Re-add the old stack element if it still has unmatched opening characters remaining
615 if ($matchingCount < $piece->count
) {
616 $piece->parts
= array( new PPDPart_Hash
);
617 $piece->count
-= $matchingCount;
618 # do we still qualify for any callback with remaining count?
619 $names = $rules[$piece->open
]['names'];
621 $enclosingAccum =& $accum;
622 while ( $piece->count
) {
623 if ( array_key_exists( $piece->count
, $names ) ) {
624 $stack->push( $piece );
625 $accum =& $stack->getAccum();
631 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
634 extract( $stack->getFlags() );
636 # Add XML element to the enclosing accumulator
637 if ( $element instanceof PPNode
) {
638 $accum->addNode( $element );
640 $accum->addAccum( $element );
644 elseif ( $found == 'pipe' ) {
645 $findEquals = true; // shortcut for getFlags()
647 $accum =& $stack->getAccum();
651 elseif ( $found == 'equals' ) {
652 $findEquals = false; // shortcut for getFlags()
653 $accum->addNodeWithText( 'equals', '=' );
654 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
659 # Output any remaining unclosed brackets
660 foreach ( $stack->stack
as $piece ) {
661 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
664 # Enable top-level headings
665 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
666 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
671 $rootNode = new PPNode_Hash_Tree( 'root' );
672 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
673 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
677 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );;
678 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
679 wfProfileOut( __METHOD__
.'-cache-miss' );
680 wfProfileOut( __METHOD__
.'-cacheable' );
681 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
684 wfProfileOut( __METHOD__
);
690 * Stack class to help Preprocessor::preprocessToObj()
693 class PPDStack_Hash
extends PPDStack
{
694 function __construct() {
695 $this->elementClass
= 'PPDStackElement_Hash';
696 parent
::__construct();
697 $this->rootAccum
= new PPDAccum_Hash
;
704 class PPDStackElement_Hash
extends PPDStackElement
{
705 function __construct( $data = array() ) {
706 $this->partClass
= 'PPDPart_Hash';
707 parent
::__construct( $data );
711 * Get the accumulator that would result if the close is not found.
713 function breakSyntax( $openingCount = false ) {
714 if ( $this->open
== "\n" ) {
715 $accum = $this->parts
[0]->out
;
717 if ( $openingCount === false ) {
718 $openingCount = $this->count
;
720 $accum = new PPDAccum_Hash
;
721 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
723 foreach ( $this->parts
as $part ) {
727 $accum->addLiteral( '|' );
729 $accum->addAccum( $part->out
);
739 class PPDPart_Hash
extends PPDPart
{
740 function __construct( $out = '' ) {
741 $accum = new PPDAccum_Hash
;
743 $accum->addLiteral( $out );
745 parent
::__construct( $accum );
752 class PPDAccum_Hash
{
753 var $firstNode, $lastNode;
755 function __construct() {
756 $this->firstNode
= $this->lastNode
= false;
760 * Append a string literal
762 function addLiteral( $s ) {
763 if ( $this->lastNode
=== false ) {
764 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
765 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
766 $this->lastNode
->value
.= $s;
768 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
769 $this->lastNode
= $this->lastNode
->nextSibling
;
776 function addNode( PPNode
$node ) {
777 if ( $this->lastNode
=== false ) {
778 $this->firstNode
= $this->lastNode
= $node;
780 $this->lastNode
->nextSibling
= $node;
781 $this->lastNode
= $node;
786 * Append a tree node with text contents
788 function addNodeWithText( $name, $value ) {
789 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
790 $this->addNode( $node );
794 * Append a PPAccum_Hash
795 * Takes over ownership of the nodes in the source argument. These nodes may
796 * subsequently be modified, especially nextSibling.
798 function addAccum( $accum ) {
799 if ( $accum->lastNode
=== false ) {
801 } elseif ( $this->lastNode
=== false ) {
802 $this->firstNode
= $accum->firstNode
;
803 $this->lastNode
= $accum->lastNode
;
805 $this->lastNode
->nextSibling
= $accum->firstNode
;
806 $this->lastNode
= $accum->lastNode
;
812 * An expansion frame, used as a context to expand the result of preprocessToObj()
815 class PPFrame_Hash
implements PPFrame
{
816 var $preprocessor, $parser, $title;
820 * Hashtable listing templates which are disallowed for expansion in this frame,
821 * having been encountered previously in parent frames.
826 * Recursion depth of this frame, top = 0
827 * Note that this is NOT the same as expansion depth in expand()
833 * Construct a new preprocessor frame.
834 * @param $preprocessor Preprocessor: the parent preprocessor
836 function __construct( $preprocessor ) {
837 $this->preprocessor
= $preprocessor;
838 $this->parser
= $preprocessor->parser
;
839 $this->title
= $this->parser
->mTitle
;
840 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
841 $this->loopCheckHash
= array();
846 * Create a new child frame
847 * $args is optionally a multi-root PPNode or array containing the template arguments
849 function newChild( $args = false, $title = false ) {
850 $namedArgs = array();
851 $numberedArgs = array();
852 if ( $title === false ) {
853 $title = $this->title
;
855 if ( $args !== false ) {
857 if ( $args instanceof PPNode_Hash_Array
) {
858 $args = $args->value
;
859 } elseif ( !is_array( $args ) ) {
860 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
862 foreach ( $args as $arg ) {
863 $bits = $arg->splitArg();
864 if ( $bits['index'] !== '' ) {
865 // Numbered parameter
866 $numberedArgs[$bits['index']] = $bits['value'];
867 unset( $namedArgs[$bits['index']] );
870 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
871 $namedArgs[$name] = $bits['value'];
872 unset( $numberedArgs[$name] );
876 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
879 function expand( $root, $flags = 0 ) {
880 static $expansionDepth = 0;
881 if ( is_string( $root ) ) {
885 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
887 return '<span class="error">Node-count limit exceeded</span>';
889 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
890 return '<span class="error">Expansion depth limit exceeded</span>';
894 $outStack = array( '', '' );
895 $iteratorStack = array( false, $root );
896 $indexStack = array( 0, 0 );
898 while ( count( $iteratorStack ) > 1 ) {
899 $level = count( $outStack ) - 1;
900 $iteratorNode =& $iteratorStack[ $level ];
901 $out =& $outStack[$level];
902 $index =& $indexStack[$level];
904 if ( is_array( $iteratorNode ) ) {
905 if ( $index >= count( $iteratorNode ) ) {
906 // All done with this iterator
907 $iteratorStack[$level] = false;
908 $contextNode = false;
910 $contextNode = $iteratorNode[$index];
913 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
914 if ( $index >= $iteratorNode->getLength() ) {
915 // All done with this iterator
916 $iteratorStack[$level] = false;
917 $contextNode = false;
919 $contextNode = $iteratorNode->item( $index );
923 // Copy to $contextNode and then delete from iterator stack,
924 // because this is not an iterator but we do have to execute it once
925 $contextNode = $iteratorStack[$level];
926 $iteratorStack[$level] = false;
929 $newIterator = false;
931 if ( $contextNode === false ) {
933 } elseif ( is_string( $contextNode ) ) {
934 $out .= $contextNode;
935 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
936 $newIterator = $contextNode;
937 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
939 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
940 $out .= $contextNode->value
;
941 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
942 if ( $contextNode->name
== 'template' ) {
943 # Double-brace expansion
944 $bits = $contextNode->splitTemplate();
945 if ( $flags & self
::NO_TEMPLATES
) {
946 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
948 $ret = $this->parser
->braceSubstitution( $bits, $this );
949 if ( isset( $ret['object'] ) ) {
950 $newIterator = $ret['object'];
952 $out .= $ret['text'];
955 } elseif ( $contextNode->name
== 'tplarg' ) {
956 # Triple-brace expansion
957 $bits = $contextNode->splitTemplate();
958 if ( $flags & self
::NO_ARGS
) {
959 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
961 $ret = $this->parser
->argSubstitution( $bits, $this );
962 if ( isset( $ret['object'] ) ) {
963 $newIterator = $ret['object'];
965 $out .= $ret['text'];
968 } elseif ( $contextNode->name
== 'comment' ) {
970 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
971 if ( $this->parser
->ot
['html']
972 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
973 ||
( $flags & self
::STRIP_COMMENTS
) )
977 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
978 # Not in RECOVER_COMMENTS mode (extractSections) though
979 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
980 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
982 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
984 $out .= $contextNode->firstChild
->value
;
986 } elseif ( $contextNode->name
== 'ignore' ) {
987 # Output suppression used by <includeonly> etc.
988 # OT_WIKI will only respect <ignore> in substed templates.
989 # The other output types respect it unless NO_IGNORE is set.
990 # extractSections() sets NO_IGNORE and so never respects it.
991 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
992 $out .= $contextNode->firstChild
->value
;
996 } elseif ( $contextNode->name
== 'ext' ) {
998 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
999 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1000 } elseif ( $contextNode->name
== 'h' ) {
1002 if ( $this->parser
->ot
['html'] ) {
1003 # Expand immediately and insert heading index marker
1005 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1006 $s .= $this->expand( $node, $flags );
1009 $bits = $contextNode->splitHeading();
1010 $titleText = $this->title
->getPrefixedDBkey();
1011 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1012 $serial = count( $this->parser
->mHeadings
) - 1;
1013 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1014 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1015 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1018 # Expand in virtual stack
1019 $newIterator = $contextNode->getChildren();
1022 # Generic recursive expansion
1023 $newIterator = $contextNode->getChildren();
1026 throw new MWException( __METHOD__
.': Invalid parameter type' );
1029 if ( $newIterator !== false ) {
1031 $iteratorStack[] = $newIterator;
1033 } elseif ( $iteratorStack[$level] === false ) {
1034 // Return accumulated value to parent
1035 // With tail recursion
1036 while ( $iteratorStack[$level] === false && $level > 0 ) {
1037 $outStack[$level - 1] .= $out;
1038 array_pop( $outStack );
1039 array_pop( $iteratorStack );
1040 array_pop( $indexStack );
1046 return $outStack[0];
1049 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1050 $args = array_slice( func_get_args(), 2 );
1054 foreach ( $args as $root ) {
1055 if ( $root instanceof PPNode_Hash_Array
) {
1056 $root = $root->value
;
1058 if ( !is_array( $root ) ) {
1059 $root = array( $root );
1061 foreach ( $root as $node ) {
1067 $s .= $this->expand( $node, $flags );
1074 * Implode with no flags specified
1075 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1077 function implode( $sep /*, ... */ ) {
1078 $args = array_slice( func_get_args(), 1 );
1082 foreach ( $args as $root ) {
1083 if ( $root instanceof PPNode_Hash_Array
) {
1084 $root = $root->value
;
1086 if ( !is_array( $root ) ) {
1087 $root = array( $root );
1089 foreach ( $root as $node ) {
1095 $s .= $this->expand( $node );
1102 * Makes an object that, when expand()ed, will be the same as one obtained
1105 function virtualImplode( $sep /*, ... */ ) {
1106 $args = array_slice( func_get_args(), 1 );
1110 foreach ( $args as $root ) {
1111 if ( $root instanceof PPNode_Hash_Array
) {
1112 $root = $root->value
;
1114 if ( !is_array( $root ) ) {
1115 $root = array( $root );
1117 foreach ( $root as $node ) {
1126 return new PPNode_Hash_Array( $out );
1130 * Virtual implode with brackets
1132 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1133 $args = array_slice( func_get_args(), 3 );
1134 $out = array( $start );
1137 foreach ( $args as $root ) {
1138 if ( $root instanceof PPNode_Hash_Array
) {
1139 $root = $root->value
;
1141 if ( !is_array( $root ) ) {
1142 $root = array( $root );
1144 foreach ( $root as $node ) {
1154 return new PPNode_Hash_Array( $out );
1157 function __toString() {
1161 function getPDBK( $level = false ) {
1162 if ( $level === false ) {
1163 return $this->title
->getPrefixedDBkey();
1165 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1169 function getArguments() {
1173 function getNumberedArguments() {
1177 function getNamedArguments() {
1182 * Returns true if there are no arguments in this frame
1184 function isEmpty() {
1188 function getArgument( $name ) {
1193 * Returns true if the infinite loop check is OK, false if a loop is detected
1195 function loopCheck( $title ) {
1196 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1200 * Return true if the frame is a template frame
1202 function isTemplate() {
1208 * Expansion frame with template arguments
1211 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1212 var $numberedArgs, $namedArgs, $parent;
1213 var $numberedExpansionCache, $namedExpansionCache;
1215 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1216 parent
::__construct( $preprocessor );
1218 $this->parent
= $parent;
1219 $this->numberedArgs
= $numberedArgs;
1220 $this->namedArgs
= $namedArgs;
1221 $this->title
= $title;
1222 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1223 $this->titleCache
= $parent->titleCache
;
1224 $this->titleCache
[] = $pdbk;
1225 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1226 if ( $pdbk !== false ) {
1227 $this->loopCheckHash
[$pdbk] = true;
1229 $this->depth
= $parent->depth +
1;
1230 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1233 function __toString() {
1236 $args = $this->numberedArgs +
$this->namedArgs
;
1237 foreach ( $args as $name => $value ) {
1243 $s .= "\"$name\":\"" .
1244 str_replace( '"', '\\"', $value->__toString() ) . '"';
1250 * Returns true if there are no arguments in this frame
1252 function isEmpty() {
1253 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1256 function getArguments() {
1257 $arguments = array();
1258 foreach ( array_merge(
1259 array_keys($this->numberedArgs
),
1260 array_keys($this->namedArgs
)) as $key ) {
1261 $arguments[$key] = $this->getArgument($key);
1266 function getNumberedArguments() {
1267 $arguments = array();
1268 foreach ( array_keys($this->numberedArgs
) as $key ) {
1269 $arguments[$key] = $this->getArgument($key);
1274 function getNamedArguments() {
1275 $arguments = array();
1276 foreach ( array_keys($this->namedArgs
) as $key ) {
1277 $arguments[$key] = $this->getArgument($key);
1282 function getNumberedArgument( $index ) {
1283 if ( !isset( $this->numberedArgs
[$index] ) ) {
1286 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1287 # No trimming for unnamed arguments
1288 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1290 return $this->numberedExpansionCache
[$index];
1293 function getNamedArgument( $name ) {
1294 if ( !isset( $this->namedArgs
[$name] ) ) {
1297 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1298 # Trim named arguments post-expand, for backwards compatibility
1299 $this->namedExpansionCache
[$name] = trim(
1300 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1302 return $this->namedExpansionCache
[$name];
1305 function getArgument( $name ) {
1306 $text = $this->getNumberedArgument( $name );
1307 if ( $text === false ) {
1308 $text = $this->getNamedArgument( $name );
1314 * Return true if the frame is a template frame
1316 function isTemplate() {
1322 * Expansion frame with custom arguments
1325 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1328 function __construct( $preprocessor, $args ) {
1329 parent
::__construct( $preprocessor );
1330 $this->args
= $args;
1333 function __toString() {
1336 foreach ( $this->args
as $name => $value ) {
1342 $s .= "\"$name\":\"" .
1343 str_replace( '"', '\\"', $value->__toString() ) . '"';
1349 function isEmpty() {
1350 return !count( $this->args
);
1353 function getArgument( $index ) {
1354 if ( !isset( $this->args
[$index] ) ) {
1357 return $this->args
[$index];
1364 class PPNode_Hash_Tree
implements PPNode
{
1365 var $name, $firstChild, $lastChild, $nextSibling;
1367 function __construct( $name ) {
1368 $this->name
= $name;
1369 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1372 function __toString() {
1375 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1376 if ( $node instanceof PPNode_Hash_Attr
) {
1377 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1379 $inner .= $node->__toString();
1382 if ( $inner === '' ) {
1383 return "<{$this->name}$attribs/>";
1385 return "<{$this->name}$attribs>$inner</{$this->name}>";
1389 static function newWithText( $name, $text ) {
1390 $obj = new self( $name );
1391 $obj->addChild( new PPNode_Hash_Text( $text ) );
1395 function addChild( $node ) {
1396 if ( $this->lastChild
=== false ) {
1397 $this->firstChild
= $this->lastChild
= $node;
1399 $this->lastChild
->nextSibling
= $node;
1400 $this->lastChild
= $node;
1404 function getChildren() {
1405 $children = array();
1406 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1407 $children[] = $child;
1409 return new PPNode_Hash_Array( $children );
1412 function getFirstChild() {
1413 return $this->firstChild
;
1416 function getNextSibling() {
1417 return $this->nextSibling
;
1420 function getChildrenOfType( $name ) {
1421 $children = array();
1422 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1423 if ( isset( $child->name
) && $child->name
=== $name ) {
1424 $children[] = $name;
1430 function getLength() { return false; }
1431 function item( $i ) { return false; }
1433 function getName() {
1438 * Split a <part> node into an associative array containing:
1440 * index String index
1441 * value PPNode value
1443 function splitArg() {
1445 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1446 if ( !isset( $child->name
) ) {
1449 if ( $child->name
=== 'name' ) {
1450 $bits['name'] = $child;
1451 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1452 && $child->firstChild
->name
=== 'index' )
1454 $bits['index'] = $child->firstChild
->value
;
1456 } elseif ( $child->name
=== 'value' ) {
1457 $bits['value'] = $child;
1461 if ( !isset( $bits['name'] ) ) {
1462 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1464 if ( !isset( $bits['index'] ) ) {
1465 $bits['index'] = '';
1471 * Split an <ext> node into an associative array containing name, attr, inner and close
1472 * All values in the resulting array are PPNodes. Inner and close are optional.
1474 function splitExt() {
1476 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1477 if ( !isset( $child->name
) ) {
1480 if ( $child->name
== 'name' ) {
1481 $bits['name'] = $child;
1482 } elseif ( $child->name
== 'attr' ) {
1483 $bits['attr'] = $child;
1484 } elseif ( $child->name
== 'inner' ) {
1485 $bits['inner'] = $child;
1486 } elseif ( $child->name
== 'close' ) {
1487 $bits['close'] = $child;
1490 if ( !isset( $bits['name'] ) ) {
1491 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1499 function splitHeading() {
1500 if ( $this->name
!== 'h' ) {
1501 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1504 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1505 if ( !isset( $child->name
) ) {
1508 if ( $child->name
== 'i' ) {
1509 $bits['i'] = $child->value
;
1510 } elseif ( $child->name
== 'level' ) {
1511 $bits['level'] = $child->value
;
1514 if ( !isset( $bits['i'] ) ) {
1515 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1521 * Split a <template> or <tplarg> node
1523 function splitTemplate() {
1525 $bits = array( 'lineStart' => '' );
1526 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1527 if ( !isset( $child->name
) ) {
1530 if ( $child->name
== 'title' ) {
1531 $bits['title'] = $child;
1533 if ( $child->name
== 'part' ) {
1536 if ( $child->name
== 'lineStart' ) {
1537 $bits['lineStart'] = '1';
1540 if ( !isset( $bits['title'] ) ) {
1541 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1543 $bits['parts'] = new PPNode_Hash_Array( $parts );
1551 class PPNode_Hash_Text
implements PPNode
{
1552 var $value, $nextSibling;
1554 function __construct( $value ) {
1555 if ( is_object( $value ) ) {
1556 throw new MWException( __CLASS__
. ' given object instead of string' );
1558 $this->value
= $value;
1561 function __toString() {
1562 return htmlspecialchars( $this->value
);
1565 function getNextSibling() {
1566 return $this->nextSibling
;
1569 function getChildren() { return false; }
1570 function getFirstChild() { return false; }
1571 function getChildrenOfType( $name ) { return false; }
1572 function getLength() { return false; }
1573 function item( $i ) { return false; }
1574 function getName() { return '#text'; }
1575 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1576 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1577 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1583 class PPNode_Hash_Array
implements PPNode
{
1584 var $value, $nextSibling;
1586 function __construct( $value ) {
1587 $this->value
= $value;
1590 function __toString() {
1591 return var_export( $this, true );
1594 function getLength() {
1595 return count( $this->value
);
1598 function item( $i ) {
1599 return $this->value
[$i];
1602 function getName() { return '#nodelist'; }
1604 function getNextSibling() {
1605 return $this->nextSibling
;
1608 function getChildren() { return false; }
1609 function getFirstChild() { return false; }
1610 function getChildrenOfType( $name ) { return false; }
1611 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1612 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1613 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1619 class PPNode_Hash_Attr
implements PPNode
{
1620 var $name, $value, $nextSibling;
1622 function __construct( $name, $value ) {
1623 $this->name
= $name;
1624 $this->value
= $value;
1627 function __toString() {
1628 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1631 function getName() {
1635 function getNextSibling() {
1636 return $this->nextSibling
;
1639 function getChildren() { return false; }
1640 function getFirstChild() { return false; }
1641 function getChildrenOfType( $name ) { return false; }
1642 function getLength() { return false; }
1643 function item( $i ) { return false; }
1644 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1645 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1646 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }