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)
515 $rule = $rules[$piece->open
];
516 if ( $count > $rule['max'] ) {
517 # The specified maximum exists in the callback array, unless the caller
519 $matchingCount = $rule['max'];
521 # Count is less than the maximum
522 # Skip any gaps in the callback array to find the true largest match
523 # Need to use array_key_exists not isset because the callback can be null
524 $matchingCount = $count;
525 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
530 if ($matchingCount <= 0) {
531 # No matching element found in callback array
532 # Output a literal closing brace and continue
533 $accum->addLiteral( str_repeat( $curChar, $count ) );
537 $name = $rule['names'][$matchingCount];
538 if ( $name === null ) {
539 // No element, just literal text
540 $element = $piece->breakSyntax( $matchingCount );
541 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
544 # Note: $parts is already XML, does not need to be encoded further
545 $parts = $piece->parts
;
546 $titleAccum = $parts[0]->out
;
549 $element = new PPNode_Hash_Tree( $name );
551 # The invocation is at the start of the line if lineStart is set in
552 # the stack, and all opening brackets are used up.
553 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
554 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
556 $titleNode = new PPNode_Hash_Tree( 'title' );
557 $titleNode->firstChild
= $titleAccum->firstNode
;
558 $titleNode->lastChild
= $titleAccum->lastNode
;
559 $element->addChild( $titleNode );
561 foreach ( $parts as $part ) {
562 if ( isset( $part->eqpos
) ) {
565 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
566 if ( $node === $part->eqpos
) {
572 throw new MWException( __METHOD__
. ': eqpos not found' );
574 if ( $node->name
!== 'equals' ) {
575 throw new MWException( __METHOD__
.': eqpos is not equals' );
579 // Construct name node
580 $nameNode = new PPNode_Hash_Tree( 'name' );
581 if ( $lastNode !== false ) {
582 $lastNode->nextSibling
= false;
583 $nameNode->firstChild
= $part->out
->firstNode
;
584 $nameNode->lastChild
= $lastNode;
587 // Construct value node
588 $valueNode = new PPNode_Hash_Tree( 'value' );
589 if ( $equalsNode->nextSibling
!== false ) {
590 $valueNode->firstChild
= $equalsNode->nextSibling
;
591 $valueNode->lastChild
= $part->out
->lastNode
;
593 $partNode = new PPNode_Hash_Tree( 'part' );
594 $partNode->addChild( $nameNode );
595 $partNode->addChild( $equalsNode->firstChild
);
596 $partNode->addChild( $valueNode );
597 $element->addChild( $partNode );
599 $partNode = new PPNode_Hash_Tree( 'part' );
600 $nameNode = new PPNode_Hash_Tree( 'name' );
601 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
602 $valueNode = new PPNode_Hash_Tree( 'value' );
603 $valueNode->firstChild
= $part->out
->firstNode
;
604 $valueNode->lastChild
= $part->out
->lastNode
;
605 $partNode->addChild( $nameNode );
606 $partNode->addChild( $valueNode );
607 $element->addChild( $partNode );
612 # Advance input pointer
613 $i +
= $matchingCount;
617 $accum =& $stack->getAccum();
619 # Re-add the old stack element if it still has unmatched opening characters remaining
620 if ($matchingCount < $piece->count
) {
621 $piece->parts
= array( new PPDPart_Hash
);
622 $piece->count
-= $matchingCount;
623 # do we still qualify for any callback with remaining count?
624 $names = $rules[$piece->open
]['names'];
626 $enclosingAccum =& $accum;
627 while ( $piece->count
) {
628 if ( array_key_exists( $piece->count
, $names ) ) {
629 $stack->push( $piece );
630 $accum =& $stack->getAccum();
636 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
639 extract( $stack->getFlags() );
641 # Add XML element to the enclosing accumulator
642 if ( $element instanceof PPNode
) {
643 $accum->addNode( $element );
645 $accum->addAccum( $element );
649 elseif ( $found == 'pipe' ) {
650 $findEquals = true; // shortcut for getFlags()
652 $accum =& $stack->getAccum();
656 elseif ( $found == 'equals' ) {
657 $findEquals = false; // shortcut for getFlags()
658 $accum->addNodeWithText( 'equals', '=' );
659 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
664 # Output any remaining unclosed brackets
665 foreach ( $stack->stack
as $piece ) {
666 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
669 # Enable top-level headings
670 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
671 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
676 $rootNode = new PPNode_Hash_Tree( 'root' );
677 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
678 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
682 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
683 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
684 wfProfileOut( __METHOD__
.'-cache-miss' );
685 wfProfileOut( __METHOD__
.'-cacheable' );
686 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
689 wfProfileOut( __METHOD__
);
695 * Stack class to help Preprocessor::preprocessToObj()
698 class PPDStack_Hash
extends PPDStack
{
699 function __construct() {
700 $this->elementClass
= 'PPDStackElement_Hash';
701 parent
::__construct();
702 $this->rootAccum
= new PPDAccum_Hash
;
709 class PPDStackElement_Hash
extends PPDStackElement
{
710 function __construct( $data = array() ) {
711 $this->partClass
= 'PPDPart_Hash';
712 parent
::__construct( $data );
716 * Get the accumulator that would result if the close is not found.
718 function breakSyntax( $openingCount = false ) {
719 if ( $this->open
== "\n" ) {
720 $accum = $this->parts
[0]->out
;
722 if ( $openingCount === false ) {
723 $openingCount = $this->count
;
725 $accum = new PPDAccum_Hash
;
726 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
728 foreach ( $this->parts
as $part ) {
732 $accum->addLiteral( '|' );
734 $accum->addAccum( $part->out
);
744 class PPDPart_Hash
extends PPDPart
{
745 function __construct( $out = '' ) {
746 $accum = new PPDAccum_Hash
;
748 $accum->addLiteral( $out );
750 parent
::__construct( $accum );
757 class PPDAccum_Hash
{
758 var $firstNode, $lastNode;
760 function __construct() {
761 $this->firstNode
= $this->lastNode
= false;
765 * Append a string literal
767 function addLiteral( $s ) {
768 if ( $this->lastNode
=== false ) {
769 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
770 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
771 $this->lastNode
->value
.= $s;
773 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
774 $this->lastNode
= $this->lastNode
->nextSibling
;
781 function addNode( PPNode
$node ) {
782 if ( $this->lastNode
=== false ) {
783 $this->firstNode
= $this->lastNode
= $node;
785 $this->lastNode
->nextSibling
= $node;
786 $this->lastNode
= $node;
791 * Append a tree node with text contents
793 function addNodeWithText( $name, $value ) {
794 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
795 $this->addNode( $node );
799 * Append a PPAccum_Hash
800 * Takes over ownership of the nodes in the source argument. These nodes may
801 * subsequently be modified, especially nextSibling.
803 function addAccum( $accum ) {
804 if ( $accum->lastNode
=== false ) {
806 } elseif ( $this->lastNode
=== false ) {
807 $this->firstNode
= $accum->firstNode
;
808 $this->lastNode
= $accum->lastNode
;
810 $this->lastNode
->nextSibling
= $accum->firstNode
;
811 $this->lastNode
= $accum->lastNode
;
817 * An expansion frame, used as a context to expand the result of preprocessToObj()
820 class PPFrame_Hash
implements PPFrame
{
821 var $preprocessor, $parser, $title;
825 * Hashtable listing templates which are disallowed for expansion in this frame,
826 * having been encountered previously in parent frames.
831 * Recursion depth of this frame, top = 0
832 * Note that this is NOT the same as expansion depth in expand()
838 * Construct a new preprocessor frame.
839 * @param $preprocessor Preprocessor: the parent preprocessor
841 function __construct( $preprocessor ) {
842 $this->preprocessor
= $preprocessor;
843 $this->parser
= $preprocessor->parser
;
844 $this->title
= $this->parser
->mTitle
;
845 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
846 $this->loopCheckHash
= array();
851 * Create a new child frame
852 * $args is optionally a multi-root PPNode or array containing the template arguments
854 function newChild( $args = false, $title = false ) {
855 $namedArgs = array();
856 $numberedArgs = array();
857 if ( $title === false ) {
858 $title = $this->title
;
860 if ( $args !== false ) {
861 if ( $args instanceof PPNode_Hash_Array
) {
862 $args = $args->value
;
863 } elseif ( !is_array( $args ) ) {
864 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
866 foreach ( $args as $arg ) {
867 $bits = $arg->splitArg();
868 if ( $bits['index'] !== '' ) {
869 // Numbered parameter
870 $numberedArgs[$bits['index']] = $bits['value'];
871 unset( $namedArgs[$bits['index']] );
874 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
875 $namedArgs[$name] = $bits['value'];
876 unset( $numberedArgs[$name] );
880 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
883 function expand( $root, $flags = 0 ) {
884 static $expansionDepth = 0;
885 if ( is_string( $root ) ) {
889 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() )
891 return '<span class="error">Node-count limit exceeded</span>';
893 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
894 return '<span class="error">Expansion depth limit exceeded</span>';
898 $outStack = array( '', '' );
899 $iteratorStack = array( false, $root );
900 $indexStack = array( 0, 0 );
902 while ( count( $iteratorStack ) > 1 ) {
903 $level = count( $outStack ) - 1;
904 $iteratorNode =& $iteratorStack[ $level ];
905 $out =& $outStack[$level];
906 $index =& $indexStack[$level];
908 if ( is_array( $iteratorNode ) ) {
909 if ( $index >= count( $iteratorNode ) ) {
910 // All done with this iterator
911 $iteratorStack[$level] = false;
912 $contextNode = false;
914 $contextNode = $iteratorNode[$index];
917 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
918 if ( $index >= $iteratorNode->getLength() ) {
919 // All done with this iterator
920 $iteratorStack[$level] = false;
921 $contextNode = false;
923 $contextNode = $iteratorNode->item( $index );
927 // Copy to $contextNode and then delete from iterator stack,
928 // because this is not an iterator but we do have to execute it once
929 $contextNode = $iteratorStack[$level];
930 $iteratorStack[$level] = false;
933 $newIterator = false;
935 if ( $contextNode === false ) {
937 } elseif ( is_string( $contextNode ) ) {
938 $out .= $contextNode;
939 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
940 $newIterator = $contextNode;
941 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
943 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
944 $out .= $contextNode->value
;
945 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
946 if ( $contextNode->name
== 'template' ) {
947 # Double-brace expansion
948 $bits = $contextNode->splitTemplate();
949 if ( $flags & PPFrame
::NO_TEMPLATES
) {
950 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
952 $ret = $this->parser
->braceSubstitution( $bits, $this );
953 if ( isset( $ret['object'] ) ) {
954 $newIterator = $ret['object'];
956 $out .= $ret['text'];
959 } elseif ( $contextNode->name
== 'tplarg' ) {
960 # Triple-brace expansion
961 $bits = $contextNode->splitTemplate();
962 if ( $flags & PPFrame
::NO_ARGS
) {
963 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
965 $ret = $this->parser
->argSubstitution( $bits, $this );
966 if ( isset( $ret['object'] ) ) {
967 $newIterator = $ret['object'];
969 $out .= $ret['text'];
972 } elseif ( $contextNode->name
== 'comment' ) {
974 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
975 if ( $this->parser
->ot
['html']
976 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
977 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
981 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
982 # Not in RECOVER_COMMENTS mode (extractSections) though
983 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
984 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
986 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
988 $out .= $contextNode->firstChild
->value
;
990 } elseif ( $contextNode->name
== 'ignore' ) {
991 # Output suppression used by <includeonly> etc.
992 # OT_WIKI will only respect <ignore> in substed templates.
993 # The other output types respect it unless NO_IGNORE is set.
994 # extractSections() sets NO_IGNORE and so never respects it.
995 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
996 $out .= $contextNode->firstChild
->value
;
1000 } elseif ( $contextNode->name
== 'ext' ) {
1002 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1003 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1004 } elseif ( $contextNode->name
== 'h' ) {
1006 if ( $this->parser
->ot
['html'] ) {
1007 # Expand immediately and insert heading index marker
1009 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1010 $s .= $this->expand( $node, $flags );
1013 $bits = $contextNode->splitHeading();
1014 $titleText = $this->title
->getPrefixedDBkey();
1015 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1016 $serial = count( $this->parser
->mHeadings
) - 1;
1017 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1018 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1019 $this->parser
->mStripState
->general
->setPair( $marker, '' );
1022 # Expand in virtual stack
1023 $newIterator = $contextNode->getChildren();
1026 # Generic recursive expansion
1027 $newIterator = $contextNode->getChildren();
1030 throw new MWException( __METHOD__
.': Invalid parameter type' );
1033 if ( $newIterator !== false ) {
1035 $iteratorStack[] = $newIterator;
1037 } elseif ( $iteratorStack[$level] === false ) {
1038 // Return accumulated value to parent
1039 // With tail recursion
1040 while ( $iteratorStack[$level] === false && $level > 0 ) {
1041 $outStack[$level - 1] .= $out;
1042 array_pop( $outStack );
1043 array_pop( $iteratorStack );
1044 array_pop( $indexStack );
1050 return $outStack[0];
1053 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1054 $args = array_slice( func_get_args(), 2 );
1058 foreach ( $args as $root ) {
1059 if ( $root instanceof PPNode_Hash_Array
) {
1060 $root = $root->value
;
1062 if ( !is_array( $root ) ) {
1063 $root = array( $root );
1065 foreach ( $root as $node ) {
1071 $s .= $this->expand( $node, $flags );
1078 * Implode with no flags specified
1079 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1081 function implode( $sep /*, ... */ ) {
1082 $args = array_slice( func_get_args(), 1 );
1086 foreach ( $args as $root ) {
1087 if ( $root instanceof PPNode_Hash_Array
) {
1088 $root = $root->value
;
1090 if ( !is_array( $root ) ) {
1091 $root = array( $root );
1093 foreach ( $root as $node ) {
1099 $s .= $this->expand( $node );
1106 * Makes an object that, when expand()ed, will be the same as one obtained
1109 function virtualImplode( $sep /*, ... */ ) {
1110 $args = array_slice( func_get_args(), 1 );
1114 foreach ( $args as $root ) {
1115 if ( $root instanceof PPNode_Hash_Array
) {
1116 $root = $root->value
;
1118 if ( !is_array( $root ) ) {
1119 $root = array( $root );
1121 foreach ( $root as $node ) {
1130 return new PPNode_Hash_Array( $out );
1134 * Virtual implode with brackets
1136 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1137 $args = array_slice( func_get_args(), 3 );
1138 $out = array( $start );
1141 foreach ( $args as $root ) {
1142 if ( $root instanceof PPNode_Hash_Array
) {
1143 $root = $root->value
;
1145 if ( !is_array( $root ) ) {
1146 $root = array( $root );
1148 foreach ( $root as $node ) {
1158 return new PPNode_Hash_Array( $out );
1161 function __toString() {
1165 function getPDBK( $level = false ) {
1166 if ( $level === false ) {
1167 return $this->title
->getPrefixedDBkey();
1169 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1173 function getArguments() {
1177 function getNumberedArguments() {
1181 function getNamedArguments() {
1186 * Returns true if there are no arguments in this frame
1188 function isEmpty() {
1192 function getArgument( $name ) {
1197 * Returns true if the infinite loop check is OK, false if a loop is detected
1199 function loopCheck( $title ) {
1200 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1204 * Return true if the frame is a template frame
1206 function isTemplate() {
1212 * Expansion frame with template arguments
1215 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1216 var $numberedArgs, $namedArgs, $parent;
1217 var $numberedExpansionCache, $namedExpansionCache;
1219 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1220 parent
::__construct( $preprocessor );
1222 $this->parent
= $parent;
1223 $this->numberedArgs
= $numberedArgs;
1224 $this->namedArgs
= $namedArgs;
1225 $this->title
= $title;
1226 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1227 $this->titleCache
= $parent->titleCache
;
1228 $this->titleCache
[] = $pdbk;
1229 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1230 if ( $pdbk !== false ) {
1231 $this->loopCheckHash
[$pdbk] = true;
1233 $this->depth
= $parent->depth +
1;
1234 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1237 function __toString() {
1240 $args = $this->numberedArgs +
$this->namedArgs
;
1241 foreach ( $args as $name => $value ) {
1247 $s .= "\"$name\":\"" .
1248 str_replace( '"', '\\"', $value->__toString() ) . '"';
1254 * Returns true if there are no arguments in this frame
1256 function isEmpty() {
1257 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1260 function getArguments() {
1261 $arguments = array();
1262 foreach ( array_merge(
1263 array_keys($this->numberedArgs
),
1264 array_keys($this->namedArgs
)) as $key ) {
1265 $arguments[$key] = $this->getArgument($key);
1270 function getNumberedArguments() {
1271 $arguments = array();
1272 foreach ( array_keys($this->numberedArgs
) as $key ) {
1273 $arguments[$key] = $this->getArgument($key);
1278 function getNamedArguments() {
1279 $arguments = array();
1280 foreach ( array_keys($this->namedArgs
) as $key ) {
1281 $arguments[$key] = $this->getArgument($key);
1286 function getNumberedArgument( $index ) {
1287 if ( !isset( $this->numberedArgs
[$index] ) ) {
1290 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1291 # No trimming for unnamed arguments
1292 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1294 return $this->numberedExpansionCache
[$index];
1297 function getNamedArgument( $name ) {
1298 if ( !isset( $this->namedArgs
[$name] ) ) {
1301 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1302 # Trim named arguments post-expand, for backwards compatibility
1303 $this->namedExpansionCache
[$name] = trim(
1304 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1306 return $this->namedExpansionCache
[$name];
1309 function getArgument( $name ) {
1310 $text = $this->getNumberedArgument( $name );
1311 if ( $text === false ) {
1312 $text = $this->getNamedArgument( $name );
1318 * Return true if the frame is a template frame
1320 function isTemplate() {
1326 * Expansion frame with custom arguments
1329 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1332 function __construct( $preprocessor, $args ) {
1333 parent
::__construct( $preprocessor );
1334 $this->args
= $args;
1337 function __toString() {
1340 foreach ( $this->args
as $name => $value ) {
1346 $s .= "\"$name\":\"" .
1347 str_replace( '"', '\\"', $value->__toString() ) . '"';
1353 function isEmpty() {
1354 return !count( $this->args
);
1357 function getArgument( $index ) {
1358 if ( !isset( $this->args
[$index] ) ) {
1361 return $this->args
[$index];
1368 class PPNode_Hash_Tree
implements PPNode
{
1369 var $name, $firstChild, $lastChild, $nextSibling;
1371 function __construct( $name ) {
1372 $this->name
= $name;
1373 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1376 function __toString() {
1379 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1380 if ( $node instanceof PPNode_Hash_Attr
) {
1381 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1383 $inner .= $node->__toString();
1386 if ( $inner === '' ) {
1387 return "<{$this->name}$attribs/>";
1389 return "<{$this->name}$attribs>$inner</{$this->name}>";
1393 static function newWithText( $name, $text ) {
1394 $obj = new self( $name );
1395 $obj->addChild( new PPNode_Hash_Text( $text ) );
1399 function addChild( $node ) {
1400 if ( $this->lastChild
=== false ) {
1401 $this->firstChild
= $this->lastChild
= $node;
1403 $this->lastChild
->nextSibling
= $node;
1404 $this->lastChild
= $node;
1408 function getChildren() {
1409 $children = array();
1410 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1411 $children[] = $child;
1413 return new PPNode_Hash_Array( $children );
1416 function getFirstChild() {
1417 return $this->firstChild
;
1420 function getNextSibling() {
1421 return $this->nextSibling
;
1424 function getChildrenOfType( $name ) {
1425 $children = array();
1426 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1427 if ( isset( $child->name
) && $child->name
=== $name ) {
1428 $children[] = $name;
1434 function getLength() { return false; }
1435 function item( $i ) { return false; }
1437 function getName() {
1442 * Split a <part> node into an associative array containing:
1444 * index String index
1445 * value PPNode value
1447 function splitArg() {
1449 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1450 if ( !isset( $child->name
) ) {
1453 if ( $child->name
=== 'name' ) {
1454 $bits['name'] = $child;
1455 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1456 && $child->firstChild
->name
=== 'index' )
1458 $bits['index'] = $child->firstChild
->value
;
1460 } elseif ( $child->name
=== 'value' ) {
1461 $bits['value'] = $child;
1465 if ( !isset( $bits['name'] ) ) {
1466 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1468 if ( !isset( $bits['index'] ) ) {
1469 $bits['index'] = '';
1475 * Split an <ext> node into an associative array containing name, attr, inner and close
1476 * All values in the resulting array are PPNodes. Inner and close are optional.
1478 function splitExt() {
1480 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1481 if ( !isset( $child->name
) ) {
1484 if ( $child->name
== 'name' ) {
1485 $bits['name'] = $child;
1486 } elseif ( $child->name
== 'attr' ) {
1487 $bits['attr'] = $child;
1488 } elseif ( $child->name
== 'inner' ) {
1489 $bits['inner'] = $child;
1490 } elseif ( $child->name
== 'close' ) {
1491 $bits['close'] = $child;
1494 if ( !isset( $bits['name'] ) ) {
1495 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1503 function splitHeading() {
1504 if ( $this->name
!== 'h' ) {
1505 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1508 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1509 if ( !isset( $child->name
) ) {
1512 if ( $child->name
== 'i' ) {
1513 $bits['i'] = $child->value
;
1514 } elseif ( $child->name
== 'level' ) {
1515 $bits['level'] = $child->value
;
1518 if ( !isset( $bits['i'] ) ) {
1519 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1525 * Split a <template> or <tplarg> node
1527 function splitTemplate() {
1529 $bits = array( 'lineStart' => '' );
1530 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1531 if ( !isset( $child->name
) ) {
1534 if ( $child->name
== 'title' ) {
1535 $bits['title'] = $child;
1537 if ( $child->name
== 'part' ) {
1540 if ( $child->name
== 'lineStart' ) {
1541 $bits['lineStart'] = '1';
1544 if ( !isset( $bits['title'] ) ) {
1545 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1547 $bits['parts'] = new PPNode_Hash_Array( $parts );
1555 class PPNode_Hash_Text
implements PPNode
{
1556 var $value, $nextSibling;
1558 function __construct( $value ) {
1559 if ( is_object( $value ) ) {
1560 throw new MWException( __CLASS__
. ' given object instead of string' );
1562 $this->value
= $value;
1565 function __toString() {
1566 return htmlspecialchars( $this->value
);
1569 function getNextSibling() {
1570 return $this->nextSibling
;
1573 function getChildren() { return false; }
1574 function getFirstChild() { return false; }
1575 function getChildrenOfType( $name ) { return false; }
1576 function getLength() { return false; }
1577 function item( $i ) { return false; }
1578 function getName() { return '#text'; }
1579 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1580 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1581 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1587 class PPNode_Hash_Array
implements PPNode
{
1588 var $value, $nextSibling;
1590 function __construct( $value ) {
1591 $this->value
= $value;
1594 function __toString() {
1595 return var_export( $this, true );
1598 function getLength() {
1599 return count( $this->value
);
1602 function item( $i ) {
1603 return $this->value
[$i];
1606 function getName() { return '#nodelist'; }
1608 function getNextSibling() {
1609 return $this->nextSibling
;
1612 function getChildren() { return false; }
1613 function getFirstChild() { return false; }
1614 function getChildrenOfType( $name ) { return false; }
1615 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1616 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1617 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1623 class PPNode_Hash_Attr
implements PPNode
{
1624 var $name, $value, $nextSibling;
1626 function __construct( $name, $value ) {
1627 $this->name
= $name;
1628 $this->value
= $value;
1631 function __toString() {
1632 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1635 function getName() {
1639 function getNextSibling() {
1640 return $this->nextSibling
;
1643 function getChildren() { return false; }
1644 function getFirstChild() { return false; }
1645 function getChildrenOfType( $name ) { return false; }
1646 function getLength() { return false; }
1647 function item( $i ) { return false; }
1648 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1649 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1650 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }