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
{
18 const CACHE_VERSION
= 1;
20 function __construct( $parser ) {
21 $this->parser
= $parser;
25 return new PPFrame_Hash( $this );
28 function newCustomFrame( $args ) {
29 return new PPCustomFrame_Hash( $this, $args );
32 function newPartNodeArray( $values ) {
35 foreach ( $values as $k => $val ) {
36 $partNode = new PPNode_Hash_Tree( 'part' );
37 $nameNode = new PPNode_Hash_Tree( 'name' );
40 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
41 $partNode->addChild( $nameNode );
43 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
44 $partNode->addChild( $nameNode );
45 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
48 $valueNode = new PPNode_Hash_Tree( 'value' );
49 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
50 $partNode->addChild( $valueNode );
55 $node = new PPNode_Hash_Array( $list );
60 * Preprocess some wikitext and return the document tree.
61 * This is the ghost of Parser::replace_variables().
63 * @param $text String: the text to parse
64 * @param $flags Integer: bitwise combination of:
65 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
66 * included. Default is to assume a direct page view.
68 * The generated DOM tree must depend only on the input text and the flags.
69 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
71 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
72 * change in the DOM tree for a given text, must be passed through the section identifier
73 * in the section edit link and thus back to extractSections().
75 * The output of this function is currently only cached in process memory, but a persistent
76 * cache may be implemented at a later date which takes further advantage of these strict
77 * dependency requirements.
81 function preprocessToObj( $text, $flags = 0 ) {
82 wfProfileIn( __METHOD__
);
86 global $wgMemc, $wgPreprocessorCacheThreshold;
88 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
90 wfProfileIn( __METHOD__
.'-cacheable' );
92 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
93 $cacheValue = $wgMemc->get( $cacheKey );
95 $version = substr( $cacheValue, 0, 8 );
96 if ( intval( $version ) == self
::CACHE_VERSION
) {
97 $hash = unserialize( substr( $cacheValue, 8 ) );
99 wfDebugLog( "Preprocessor",
100 "Loaded preprocessor hash from memcached (key $cacheKey)" );
101 wfProfileOut( __METHOD__
.'-cacheable' );
102 wfProfileOut( __METHOD__
);
106 wfProfileIn( __METHOD__
.'-cache-miss' );
121 'names' => array( 2 => null ),
127 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
129 $xmlishElements = $this->parser
->getStripList();
130 $enableOnlyinclude = false;
131 if ( $forInclusion ) {
132 $ignoredTags = array( 'includeonly', '/includeonly' );
133 $ignoredElements = array( 'noinclude' );
134 $xmlishElements[] = 'noinclude';
135 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
136 $enableOnlyinclude = true;
139 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
140 $ignoredElements = array( 'includeonly' );
141 $xmlishElements[] = 'includeonly';
143 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
145 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
146 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
148 $stack = new PPDStack_Hash
;
150 $searchBase = "[{<\n";
151 $revText = strrev( $text ); // For fast reverse searches
153 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
154 $accum =& $stack->getAccum(); # Current accumulator
155 $findEquals = false; # True to find equals signs in arguments
156 $findPipe = false; # True to take notice of pipe characters
158 $inHeading = false; # True if $i is inside a possible heading
159 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
160 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
161 $fakeLineStart = true; # Do a line-start run without outputting an LF character
166 if ( $findOnlyinclude ) {
167 // Ignore all input up to the next <onlyinclude>
168 $startPos = strpos( $text, '<onlyinclude>', $i );
169 if ( $startPos === false ) {
170 // Ignored section runs to the end
171 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
174 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
175 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
177 $findOnlyinclude = false;
180 if ( $fakeLineStart ) {
181 $found = 'line-start';
184 # Find next opening brace, closing brace or pipe
185 $search = $searchBase;
186 if ( $stack->top
=== false ) {
187 $currentClosing = '';
189 $currentClosing = $stack->top
->close
;
190 $search .= $currentClosing;
196 // First equals will be for the template
200 # Output literal section, advance input counter
201 $literalLength = strcspn( $text, $search, $i );
202 if ( $literalLength > 0 ) {
203 $accum->addLiteral( substr( $text, $i, $literalLength ) );
204 $i +
= $literalLength;
206 if ( $i >= strlen( $text ) ) {
207 if ( $currentClosing == "\n" ) {
208 // Do a past-the-end run to finish off the heading
216 $curChar = $text[$i];
217 if ( $curChar == '|' ) {
219 } elseif ( $curChar == '=' ) {
221 } elseif ( $curChar == '<' ) {
223 } elseif ( $curChar == "\n" ) {
227 $found = 'line-start';
229 } elseif ( $curChar == $currentClosing ) {
231 } elseif ( isset( $rules[$curChar] ) ) {
233 $rule = $rules[$curChar];
235 # Some versions of PHP have a strcspn which stops on null characters
236 # Ignore and continue
243 if ( $found == 'angle' ) {
245 // Handle </onlyinclude>
246 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
247 $findOnlyinclude = true;
251 // Determine element name
252 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
253 // Element name missing or not listed
254 $accum->addLiteral( '<' );
259 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
260 // To avoid leaving blank lines, when a comment is both preceded
261 // and followed by a newline (ignoring spaces), trim leading and
262 // trailing spaces and one of the newlines.
265 $endPos = strpos( $text, '-->', $i +
4 );
266 if ( $endPos === false ) {
267 // Unclosed comment in input, runs to end
268 $inner = substr( $text, $i );
269 $accum->addNodeWithText( 'comment', $inner );
270 $i = strlen( $text );
272 // Search backwards for leading whitespace
273 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
274 // Search forwards for trailing whitespace
275 // $wsEnd will be the position of the last space
276 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
277 // Eat the line if possible
278 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
279 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
280 // it's a possible beneficial b/c break.
281 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
282 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
284 $startPos = $wsStart;
285 $endPos = $wsEnd +
1;
286 // Remove leading whitespace from the end of the accumulator
287 // Sanity check first though
288 $wsLength = $i - $wsStart;
290 && $accum->lastNode
instanceof PPNode_Hash_Text
291 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
293 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
295 // Do a line-start run next time to look for headings after the comment
296 $fakeLineStart = true;
298 // No line to eat, just take the comment itself
304 $part = $stack->top
->getCurrentPart();
305 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
306 // Comments abutting, no change in visual end
307 $part->commentEnd
= $wsEnd;
309 $part->visualEnd
= $wsStart;
310 $part->commentEnd
= $endPos;
314 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
315 $accum->addNodeWithText( 'comment', $inner );
320 $lowerName = strtolower( $name );
321 $attrStart = $i +
strlen( $name ) +
1;
324 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
325 if ( $tagEndPos === false ) {
326 // Infinite backtrack
327 // Disable tag search to prevent worst-case O(N^2) performance
329 $accum->addLiteral( '<' );
334 // Handle ignored tags
335 if ( in_array( $lowerName, $ignoredTags ) ) {
336 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
342 if ( $text[$tagEndPos-1] == '/' ) {
344 $attrEnd = $tagEndPos - 1;
349 $attrEnd = $tagEndPos;
351 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
352 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
354 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
355 $i = $matches[0][1] +
strlen( $matches[0][0] );
356 $close = $matches[0][0];
358 // No end tag -- let it run out to the end of the text.
359 $inner = substr( $text, $tagEndPos +
1 );
360 $i = strlen( $text );
364 // <includeonly> and <noinclude> just become <ignore> tags
365 if ( in_array( $lowerName, $ignoredElements ) ) {
366 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
370 if ( $attrEnd <= $attrStart ) {
373 // Note that the attr element contains the whitespace between name and attribute,
374 // this is necessary for precise reconstruction during pre-save transform.
375 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
378 $extNode = new PPNode_Hash_Tree( 'ext' );
379 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
380 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
381 if ( $inner !== null ) {
382 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
384 if ( $close !== null ) {
385 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
387 $accum->addNode( $extNode );
390 elseif ( $found == 'line-start' ) {
391 // Is this the start of a heading?
392 // Line break belongs before the heading element in any case
393 if ( $fakeLineStart ) {
394 $fakeLineStart = false;
396 $accum->addLiteral( $curChar );
400 $count = strspn( $text, '=', $i, 6 );
401 if ( $count == 1 && $findEquals ) {
402 // DWIM: This looks kind of like a name/value separator
403 // Let's let the equals handler have it and break the potential heading
404 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
405 } elseif ( $count > 0 ) {
409 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
412 $stack->push( $piece );
413 $accum =& $stack->getAccum();
414 extract( $stack->getFlags() );
419 elseif ( $found == 'line-end' ) {
420 $piece = $stack->top
;
421 // A heading must be open, otherwise \n wouldn't have been in the search list
422 assert( $piece->open
== "\n" );
423 $part = $piece->getCurrentPart();
424 // Search back through the input to see if it has a proper close
425 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
426 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
427 $searchStart = $i - $wsLength;
428 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
429 // Comment found at line end
430 // Search for equals signs before the comment
431 $searchStart = $part->visualEnd
;
432 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
434 $count = $piece->count
;
435 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
436 if ( $equalsLength > 0 ) {
437 if ( $searchStart - $equalsLength == $piece->startPos
) {
438 // This is just a single string of equals signs on its own line
439 // Replicate the doHeadings behaviour /={count}(.+)={count}/
440 // First find out how many equals signs there really are (don't stop at 6)
441 $count = $equalsLength;
445 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
448 $count = min( $equalsLength, $count );
451 // Normal match, output <h>
452 $element = new PPNode_Hash_Tree( 'possible-h' );
453 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
454 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
455 $element->lastChild
->nextSibling
= $accum->firstNode
;
456 $element->lastChild
= $accum->lastNode
;
458 // Single equals sign on its own line, count=0
462 // No match, no <h>, just pass down the inner text
467 $accum =& $stack->getAccum();
468 extract( $stack->getFlags() );
470 // Append the result to the enclosing accumulator
471 if ( $element instanceof PPNode
) {
472 $accum->addNode( $element );
474 $accum->addAccum( $element );
476 // Note that we do NOT increment the input pointer.
477 // This is because the closing linebreak could be the opening linebreak of
478 // another heading. Infinite loops are avoided because the next iteration MUST
479 // hit the heading open case above, which unconditionally increments the
483 elseif ( $found == 'open' ) {
484 # count opening brace characters
485 $count = strspn( $text, $curChar, $i );
487 # we need to add to stack only if opening brace count is enough for one of the rules
488 if ( $count >= $rule['min'] ) {
489 # Add it to the stack
492 'close' => $rule['end'],
494 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
497 $stack->push( $piece );
498 $accum =& $stack->getAccum();
499 extract( $stack->getFlags() );
501 # Add literal brace(s)
502 $accum->addLiteral( str_repeat( $curChar, $count ) );
507 elseif ( $found == 'close' ) {
508 $piece = $stack->top
;
509 # lets check if there are enough characters for closing brace
510 $maxCount = $piece->count
;
511 $count = strspn( $text, $curChar, $i, $maxCount );
513 # check for maximum matching characters (if there are 5 closing
514 # characters, we will probably need only 3 - depending on the rules)
516 $rule = $rules[$piece->open
];
517 if ( $count > $rule['max'] ) {
518 # The specified maximum exists in the callback array, unless the caller
520 $matchingCount = $rule['max'];
522 # Count is less than the maximum
523 # Skip any gaps in the callback array to find the true largest match
524 # Need to use array_key_exists not isset because the callback can be null
525 $matchingCount = $count;
526 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
531 if ($matchingCount <= 0) {
532 # No matching element found in callback array
533 # Output a literal closing brace and continue
534 $accum->addLiteral( str_repeat( $curChar, $count ) );
538 $name = $rule['names'][$matchingCount];
539 if ( $name === null ) {
540 // No element, just literal text
541 $element = $piece->breakSyntax( $matchingCount );
542 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
545 # Note: $parts is already XML, does not need to be encoded further
546 $parts = $piece->parts
;
547 $titleAccum = $parts[0]->out
;
550 $element = new PPNode_Hash_Tree( $name );
552 # The invocation is at the start of the line if lineStart is set in
553 # the stack, and all opening brackets are used up.
554 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
555 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
557 $titleNode = new PPNode_Hash_Tree( 'title' );
558 $titleNode->firstChild
= $titleAccum->firstNode
;
559 $titleNode->lastChild
= $titleAccum->lastNode
;
560 $element->addChild( $titleNode );
562 foreach ( $parts as $partIndex => $part ) {
563 if ( isset( $part->eqpos
) ) {
566 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
567 if ( $node === $part->eqpos
) {
573 throw new MWException( __METHOD__
. ': eqpos not found' );
575 if ( $node->name
!== 'equals' ) {
576 throw new MWException( __METHOD__
.': eqpos is not equals' );
580 // Construct name node
581 $nameNode = new PPNode_Hash_Tree( 'name' );
582 if ( $lastNode !== false ) {
583 $lastNode->nextSibling
= false;
584 $nameNode->firstChild
= $part->out
->firstNode
;
585 $nameNode->lastChild
= $lastNode;
588 // Construct value node
589 $valueNode = new PPNode_Hash_Tree( 'value' );
590 if ( $equalsNode->nextSibling
!== false ) {
591 $valueNode->firstChild
= $equalsNode->nextSibling
;
592 $valueNode->lastChild
= $part->out
->lastNode
;
594 $partNode = new PPNode_Hash_Tree( 'part' );
595 $partNode->addChild( $nameNode );
596 $partNode->addChild( $equalsNode->firstChild
);
597 $partNode->addChild( $valueNode );
598 $element->addChild( $partNode );
600 $partNode = new PPNode_Hash_Tree( 'part' );
601 $nameNode = new PPNode_Hash_Tree( 'name' );
602 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
603 $valueNode = new PPNode_Hash_Tree( 'value' );
604 $valueNode->firstChild
= $part->out
->firstNode
;
605 $valueNode->lastChild
= $part->out
->lastNode
;
606 $partNode->addChild( $nameNode );
607 $partNode->addChild( $valueNode );
608 $element->addChild( $partNode );
613 # Advance input pointer
614 $i +
= $matchingCount;
618 $accum =& $stack->getAccum();
620 # Re-add the old stack element if it still has unmatched opening characters remaining
621 if ($matchingCount < $piece->count
) {
622 $piece->parts
= array( new PPDPart_Hash
);
623 $piece->count
-= $matchingCount;
624 # do we still qualify for any callback with remaining count?
625 $names = $rules[$piece->open
]['names'];
627 $enclosingAccum =& $accum;
628 while ( $piece->count
) {
629 if ( array_key_exists( $piece->count
, $names ) ) {
630 $stack->push( $piece );
631 $accum =& $stack->getAccum();
637 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
640 extract( $stack->getFlags() );
642 # Add XML element to the enclosing accumulator
643 if ( $element instanceof PPNode
) {
644 $accum->addNode( $element );
646 $accum->addAccum( $element );
650 elseif ( $found == 'pipe' ) {
651 $findEquals = true; // shortcut for getFlags()
653 $accum =& $stack->getAccum();
657 elseif ( $found == 'equals' ) {
658 $findEquals = false; // shortcut for getFlags()
659 $accum->addNodeWithText( 'equals', '=' );
660 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
665 # Output any remaining unclosed brackets
666 foreach ( $stack->stack
as $piece ) {
667 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
670 # Enable top-level headings
671 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
672 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
677 $rootNode = new PPNode_Hash_Tree( 'root' );
678 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
679 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
683 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );;
684 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
685 wfProfileOut( __METHOD__
.'-cache-miss' );
686 wfProfileOut( __METHOD__
.'-cacheable' );
687 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
690 wfProfileOut( __METHOD__
);
696 * Stack class to help Preprocessor::preprocessToObj()
699 class PPDStack_Hash
extends PPDStack
{
700 function __construct() {
701 $this->elementClass
= 'PPDStackElement_Hash';
702 parent
::__construct();
703 $this->rootAccum
= new PPDAccum_Hash
;
710 class PPDStackElement_Hash
extends PPDStackElement
{
711 function __construct( $data = array() ) {
712 $this->partClass
= 'PPDPart_Hash';
713 parent
::__construct( $data );
717 * Get the accumulator that would result if the close is not found.
719 function breakSyntax( $openingCount = false ) {
720 if ( $this->open
== "\n" ) {
721 $accum = $this->parts
[0]->out
;
723 if ( $openingCount === false ) {
724 $openingCount = $this->count
;
726 $accum = new PPDAccum_Hash
;
727 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
729 foreach ( $this->parts
as $part ) {
733 $accum->addLiteral( '|' );
735 $accum->addAccum( $part->out
);
745 class PPDPart_Hash
extends PPDPart
{
746 function __construct( $out = '' ) {
747 $accum = new PPDAccum_Hash
;
749 $accum->addLiteral( $out );
751 parent
::__construct( $accum );
758 class PPDAccum_Hash
{
759 var $firstNode, $lastNode;
761 function __construct() {
762 $this->firstNode
= $this->lastNode
= false;
766 * Append a string literal
768 function addLiteral( $s ) {
769 if ( $this->lastNode
=== false ) {
770 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
771 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
772 $this->lastNode
->value
.= $s;
774 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
775 $this->lastNode
= $this->lastNode
->nextSibling
;
782 function addNode( PPNode
$node ) {
783 if ( $this->lastNode
=== false ) {
784 $this->firstNode
= $this->lastNode
= $node;
786 $this->lastNode
->nextSibling
= $node;
787 $this->lastNode
= $node;
792 * Append a tree node with text contents
794 function addNodeWithText( $name, $value ) {
795 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
796 $this->addNode( $node );
800 * Append a PPAccum_Hash
801 * Takes over ownership of the nodes in the source argument. These nodes may
802 * subsequently be modified, especially nextSibling.
804 function addAccum( $accum ) {
805 if ( $accum->lastNode
=== false ) {
807 } elseif ( $this->lastNode
=== false ) {
808 $this->firstNode
= $accum->firstNode
;
809 $this->lastNode
= $accum->lastNode
;
811 $this->lastNode
->nextSibling
= $accum->firstNode
;
812 $this->lastNode
= $accum->lastNode
;
818 * An expansion frame, used as a context to expand the result of preprocessToObj()
821 class PPFrame_Hash
implements PPFrame
{
822 var $preprocessor, $parser, $title;
826 * Hashtable listing templates which are disallowed for expansion in this frame,
827 * having been encountered previously in parent frames.
832 * Recursion depth of this frame, top = 0
833 * Note that this is NOT the same as expansion depth in expand()
839 * Construct a new preprocessor frame.
840 * @param $preprocessor Preprocessor: the parent preprocessor
842 function __construct( $preprocessor ) {
843 $this->preprocessor
= $preprocessor;
844 $this->parser
= $preprocessor->parser
;
845 $this->title
= $this->parser
->mTitle
;
846 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
847 $this->loopCheckHash
= array();
852 * Create a new child frame
853 * $args is optionally a multi-root PPNode or array containing the template arguments
855 function newChild( $args = false, $title = false ) {
856 $namedArgs = array();
857 $numberedArgs = array();
858 if ( $title === false ) {
859 $title = $this->title
;
861 if ( $args !== false ) {
862 if ( $args instanceof PPNode_Hash_Array
) {
863 $args = $args->value
;
864 } elseif ( !is_array( $args ) ) {
865 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
867 foreach ( $args as $arg ) {
868 $bits = $arg->splitArg();
869 if ( $bits['index'] !== '' ) {
870 // Numbered parameter
871 $numberedArgs[$bits['index']] = $bits['value'];
872 unset( $namedArgs[$bits['index']] );
875 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
876 $namedArgs[$name] = $bits['value'];
877 unset( $numberedArgs[$name] );
881 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
884 function expand( $root, $flags = 0 ) {
885 static $expansionDepth = 0;
886 if ( is_string( $root ) ) {
890 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
892 return '<span class="error">Node-count limit exceeded</span>';
894 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
895 return '<span class="error">Expansion depth limit exceeded</span>';
899 $outStack = array( '', '' );
900 $iteratorStack = array( false, $root );
901 $indexStack = array( 0, 0 );
903 while ( count( $iteratorStack ) > 1 ) {
904 $level = count( $outStack ) - 1;
905 $iteratorNode =& $iteratorStack[ $level ];
906 $out =& $outStack[$level];
907 $index =& $indexStack[$level];
909 if ( is_array( $iteratorNode ) ) {
910 if ( $index >= count( $iteratorNode ) ) {
911 // All done with this iterator
912 $iteratorStack[$level] = false;
913 $contextNode = false;
915 $contextNode = $iteratorNode[$index];
918 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
919 if ( $index >= $iteratorNode->getLength() ) {
920 // All done with this iterator
921 $iteratorStack[$level] = false;
922 $contextNode = false;
924 $contextNode = $iteratorNode->item( $index );
928 // Copy to $contextNode and then delete from iterator stack,
929 // because this is not an iterator but we do have to execute it once
930 $contextNode = $iteratorStack[$level];
931 $iteratorStack[$level] = false;
934 $newIterator = false;
936 if ( $contextNode === false ) {
938 } elseif ( is_string( $contextNode ) ) {
939 $out .= $contextNode;
940 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
941 $newIterator = $contextNode;
942 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
944 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
945 $out .= $contextNode->value
;
946 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
947 if ( $contextNode->name
== 'template' ) {
948 # Double-brace expansion
949 $bits = $contextNode->splitTemplate();
950 if ( $flags & PPFrame
::NO_TEMPLATES
) {
951 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
953 $ret = $this->parser
->braceSubstitution( $bits, $this );
954 if ( isset( $ret['object'] ) ) {
955 $newIterator = $ret['object'];
957 $out .= $ret['text'];
960 } elseif ( $contextNode->name
== 'tplarg' ) {
961 # Triple-brace expansion
962 $bits = $contextNode->splitTemplate();
963 if ( $flags & PPFrame
::NO_ARGS
) {
964 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
966 $ret = $this->parser
->argSubstitution( $bits, $this );
967 if ( isset( $ret['object'] ) ) {
968 $newIterator = $ret['object'];
970 $out .= $ret['text'];
973 } elseif ( $contextNode->name
== 'comment' ) {
975 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
976 if ( $this->parser
->ot
['html']
977 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
978 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
982 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
983 # Not in RECOVER_COMMENTS mode (extractSections) though
984 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
985 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
987 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
989 $out .= $contextNode->firstChild
->value
;
991 } elseif ( $contextNode->name
== 'ignore' ) {
992 # Output suppression used by <includeonly> etc.
993 # OT_WIKI will only respect <ignore> in substed templates.
994 # The other output types respect it unless NO_IGNORE is set.
995 # extractSections() sets NO_IGNORE and so never respects it.
996 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
997 $out .= $contextNode->firstChild
->value
;
1001 } elseif ( $contextNode->name
== 'ext' ) {
1003 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1004 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1005 } elseif ( $contextNode->name
== 'h' ) {
1007 if ( $this->parser
->ot
['html'] ) {
1008 # Expand immediately and insert heading index marker
1010 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1011 $s .= $this->expand( $node, $flags );
1014 $bits = $contextNode->splitHeading();
1015 $titleText = $this->title
->getPrefixedDBkey();
1016 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1017 $serial = count( $this->parser
->mHeadings
) - 1;
1018 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1019 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1020 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1023 # Expand in virtual stack
1024 $newIterator = $contextNode->getChildren();
1027 # Generic recursive expansion
1028 $newIterator = $contextNode->getChildren();
1031 throw new MWException( __METHOD__
.': Invalid parameter type' );
1034 if ( $newIterator !== false ) {
1036 $iteratorStack[] = $newIterator;
1038 } elseif ( $iteratorStack[$level] === false ) {
1039 // Return accumulated value to parent
1040 // With tail recursion
1041 while ( $iteratorStack[$level] === false && $level > 0 ) {
1042 $outStack[$level - 1] .= $out;
1043 array_pop( $outStack );
1044 array_pop( $iteratorStack );
1045 array_pop( $indexStack );
1051 return $outStack[0];
1054 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1055 $args = array_slice( func_get_args(), 2 );
1059 foreach ( $args as $root ) {
1060 if ( $root instanceof PPNode_Hash_Array
) {
1061 $root = $root->value
;
1063 if ( !is_array( $root ) ) {
1064 $root = array( $root );
1066 foreach ( $root as $node ) {
1072 $s .= $this->expand( $node, $flags );
1079 * Implode with no flags specified
1080 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1082 function implode( $sep /*, ... */ ) {
1083 $args = array_slice( func_get_args(), 1 );
1087 foreach ( $args as $root ) {
1088 if ( $root instanceof PPNode_Hash_Array
) {
1089 $root = $root->value
;
1091 if ( !is_array( $root ) ) {
1092 $root = array( $root );
1094 foreach ( $root as $node ) {
1100 $s .= $this->expand( $node );
1107 * Makes an object that, when expand()ed, will be the same as one obtained
1110 function virtualImplode( $sep /*, ... */ ) {
1111 $args = array_slice( func_get_args(), 1 );
1115 foreach ( $args as $root ) {
1116 if ( $root instanceof PPNode_Hash_Array
) {
1117 $root = $root->value
;
1119 if ( !is_array( $root ) ) {
1120 $root = array( $root );
1122 foreach ( $root as $node ) {
1131 return new PPNode_Hash_Array( $out );
1135 * Virtual implode with brackets
1137 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1138 $args = array_slice( func_get_args(), 3 );
1139 $out = array( $start );
1142 foreach ( $args as $root ) {
1143 if ( $root instanceof PPNode_Hash_Array
) {
1144 $root = $root->value
;
1146 if ( !is_array( $root ) ) {
1147 $root = array( $root );
1149 foreach ( $root as $node ) {
1159 return new PPNode_Hash_Array( $out );
1162 function __toString() {
1166 function getPDBK( $level = false ) {
1167 if ( $level === false ) {
1168 return $this->title
->getPrefixedDBkey();
1170 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1174 function getArguments() {
1178 function getNumberedArguments() {
1182 function getNamedArguments() {
1187 * Returns true if there are no arguments in this frame
1189 function isEmpty() {
1193 function getArgument( $name ) {
1198 * Returns true if the infinite loop check is OK, false if a loop is detected
1200 function loopCheck( $title ) {
1201 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1205 * Return true if the frame is a template frame
1207 function isTemplate() {
1213 * Expansion frame with template arguments
1216 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1217 var $numberedArgs, $namedArgs, $parent;
1218 var $numberedExpansionCache, $namedExpansionCache;
1220 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1221 parent
::__construct( $preprocessor );
1223 $this->parent
= $parent;
1224 $this->numberedArgs
= $numberedArgs;
1225 $this->namedArgs
= $namedArgs;
1226 $this->title
= $title;
1227 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1228 $this->titleCache
= $parent->titleCache
;
1229 $this->titleCache
[] = $pdbk;
1230 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1231 if ( $pdbk !== false ) {
1232 $this->loopCheckHash
[$pdbk] = true;
1234 $this->depth
= $parent->depth +
1;
1235 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1238 function __toString() {
1241 $args = $this->numberedArgs +
$this->namedArgs
;
1242 foreach ( $args as $name => $value ) {
1248 $s .= "\"$name\":\"" .
1249 str_replace( '"', '\\"', $value->__toString() ) . '"';
1255 * Returns true if there are no arguments in this frame
1257 function isEmpty() {
1258 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1261 function getArguments() {
1262 $arguments = array();
1263 foreach ( array_merge(
1264 array_keys($this->numberedArgs
),
1265 array_keys($this->namedArgs
)) as $key ) {
1266 $arguments[$key] = $this->getArgument($key);
1271 function getNumberedArguments() {
1272 $arguments = array();
1273 foreach ( array_keys($this->numberedArgs
) as $key ) {
1274 $arguments[$key] = $this->getArgument($key);
1279 function getNamedArguments() {
1280 $arguments = array();
1281 foreach ( array_keys($this->namedArgs
) as $key ) {
1282 $arguments[$key] = $this->getArgument($key);
1287 function getNumberedArgument( $index ) {
1288 if ( !isset( $this->numberedArgs
[$index] ) ) {
1291 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1292 # No trimming for unnamed arguments
1293 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1295 return $this->numberedExpansionCache
[$index];
1298 function getNamedArgument( $name ) {
1299 if ( !isset( $this->namedArgs
[$name] ) ) {
1302 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1303 # Trim named arguments post-expand, for backwards compatibility
1304 $this->namedExpansionCache
[$name] = trim(
1305 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1307 return $this->namedExpansionCache
[$name];
1310 function getArgument( $name ) {
1311 $text = $this->getNumberedArgument( $name );
1312 if ( $text === false ) {
1313 $text = $this->getNamedArgument( $name );
1319 * Return true if the frame is a template frame
1321 function isTemplate() {
1327 * Expansion frame with custom arguments
1330 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1333 function __construct( $preprocessor, $args ) {
1334 parent
::__construct( $preprocessor );
1335 $this->args
= $args;
1338 function __toString() {
1341 foreach ( $this->args
as $name => $value ) {
1347 $s .= "\"$name\":\"" .
1348 str_replace( '"', '\\"', $value->__toString() ) . '"';
1354 function isEmpty() {
1355 return !count( $this->args
);
1358 function getArgument( $index ) {
1359 if ( !isset( $this->args
[$index] ) ) {
1362 return $this->args
[$index];
1369 class PPNode_Hash_Tree
implements PPNode
{
1370 var $name, $firstChild, $lastChild, $nextSibling;
1372 function __construct( $name ) {
1373 $this->name
= $name;
1374 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1377 function __toString() {
1380 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1381 if ( $node instanceof PPNode_Hash_Attr
) {
1382 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1384 $inner .= $node->__toString();
1387 if ( $inner === '' ) {
1388 return "<{$this->name}$attribs/>";
1390 return "<{$this->name}$attribs>$inner</{$this->name}>";
1394 static function newWithText( $name, $text ) {
1395 $obj = new self( $name );
1396 $obj->addChild( new PPNode_Hash_Text( $text ) );
1400 function addChild( $node ) {
1401 if ( $this->lastChild
=== false ) {
1402 $this->firstChild
= $this->lastChild
= $node;
1404 $this->lastChild
->nextSibling
= $node;
1405 $this->lastChild
= $node;
1409 function getChildren() {
1410 $children = array();
1411 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1412 $children[] = $child;
1414 return new PPNode_Hash_Array( $children );
1417 function getFirstChild() {
1418 return $this->firstChild
;
1421 function getNextSibling() {
1422 return $this->nextSibling
;
1425 function getChildrenOfType( $name ) {
1426 $children = array();
1427 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1428 if ( isset( $child->name
) && $child->name
=== $name ) {
1429 $children[] = $name;
1435 function getLength() { return false; }
1436 function item( $i ) { return false; }
1438 function getName() {
1443 * Split a <part> node into an associative array containing:
1445 * index String index
1446 * value PPNode value
1448 function splitArg() {
1450 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1451 if ( !isset( $child->name
) ) {
1454 if ( $child->name
=== 'name' ) {
1455 $bits['name'] = $child;
1456 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1457 && $child->firstChild
->name
=== 'index' )
1459 $bits['index'] = $child->firstChild
->value
;
1461 } elseif ( $child->name
=== 'value' ) {
1462 $bits['value'] = $child;
1466 if ( !isset( $bits['name'] ) ) {
1467 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1469 if ( !isset( $bits['index'] ) ) {
1470 $bits['index'] = '';
1476 * Split an <ext> node into an associative array containing name, attr, inner and close
1477 * All values in the resulting array are PPNodes. Inner and close are optional.
1479 function splitExt() {
1481 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1482 if ( !isset( $child->name
) ) {
1485 if ( $child->name
== 'name' ) {
1486 $bits['name'] = $child;
1487 } elseif ( $child->name
== 'attr' ) {
1488 $bits['attr'] = $child;
1489 } elseif ( $child->name
== 'inner' ) {
1490 $bits['inner'] = $child;
1491 } elseif ( $child->name
== 'close' ) {
1492 $bits['close'] = $child;
1495 if ( !isset( $bits['name'] ) ) {
1496 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1504 function splitHeading() {
1505 if ( $this->name
!== 'h' ) {
1506 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1509 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1510 if ( !isset( $child->name
) ) {
1513 if ( $child->name
== 'i' ) {
1514 $bits['i'] = $child->value
;
1515 } elseif ( $child->name
== 'level' ) {
1516 $bits['level'] = $child->value
;
1519 if ( !isset( $bits['i'] ) ) {
1520 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1526 * Split a <template> or <tplarg> node
1528 function splitTemplate() {
1530 $bits = array( 'lineStart' => '' );
1531 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1532 if ( !isset( $child->name
) ) {
1535 if ( $child->name
== 'title' ) {
1536 $bits['title'] = $child;
1538 if ( $child->name
== 'part' ) {
1541 if ( $child->name
== 'lineStart' ) {
1542 $bits['lineStart'] = '1';
1545 if ( !isset( $bits['title'] ) ) {
1546 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1548 $bits['parts'] = new PPNode_Hash_Array( $parts );
1556 class PPNode_Hash_Text
implements PPNode
{
1557 var $value, $nextSibling;
1559 function __construct( $value ) {
1560 if ( is_object( $value ) ) {
1561 throw new MWException( __CLASS__
. ' given object instead of string' );
1563 $this->value
= $value;
1566 function __toString() {
1567 return htmlspecialchars( $this->value
);
1570 function getNextSibling() {
1571 return $this->nextSibling
;
1574 function getChildren() { return false; }
1575 function getFirstChild() { return false; }
1576 function getChildrenOfType( $name ) { return false; }
1577 function getLength() { return false; }
1578 function item( $i ) { return false; }
1579 function getName() { return '#text'; }
1580 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1581 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1582 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1588 class PPNode_Hash_Array
implements PPNode
{
1589 var $value, $nextSibling;
1591 function __construct( $value ) {
1592 $this->value
= $value;
1595 function __toString() {
1596 return var_export( $this, true );
1599 function getLength() {
1600 return count( $this->value
);
1603 function item( $i ) {
1604 return $this->value
[$i];
1607 function getName() { return '#nodelist'; }
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 splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1617 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1618 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1624 class PPNode_Hash_Attr
implements PPNode
{
1625 var $name, $value, $nextSibling;
1627 function __construct( $name, $value ) {
1628 $this->name
= $name;
1629 $this->value
= $value;
1632 function __toString() {
1633 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1636 function getName() {
1640 function getNextSibling() {
1641 return $this->nextSibling
;
1644 function getChildren() { return false; }
1645 function getFirstChild() { return false; }
1646 function getChildrenOfType( $name ) { return false; }
1647 function getLength() { return false; }
1648 function item( $i ) { return false; }
1649 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1650 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1651 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }