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 );
27 * Preprocess some wikitext and return the document tree.
28 * This is the ghost of Parser::replace_variables().
30 * @param string $text The text to parse
31 * @param integer flags Bitwise combination of:
32 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
33 * included. Default is to assume a direct page view.
35 * The generated DOM tree must depend only on the input text and the flags.
36 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
38 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
39 * change in the DOM tree for a given text, must be passed through the section identifier
40 * in the section edit link and thus back to extractSections().
42 * The output of this function is currently only cached in process memory, but a persistent
43 * cache may be implemented at a later date which takes further advantage of these strict
44 * dependency requirements.
48 function preprocessToObj( $text, $flags = 0 ) {
49 wfProfileIn( __METHOD__
);
53 global $wgMemc, $wgPreprocessorCacheThreshold;
55 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
57 wfProfileIn( __METHOD__
.'-cacheable' );
59 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
60 $cacheValue = $wgMemc->get( $cacheKey );
62 $version = substr( $cacheValue, 0, 8 );
63 if ( intval( $version ) == self
::CACHE_VERSION
) {
64 $hash = unserialize( substr( $cacheValue, 8 ) );
66 wfDebugLog( "Preprocessor",
67 "Loaded preprocessor hash from memcached (key $cacheKey)" );
68 wfProfileOut( __METHOD__
.'-cacheable' );
69 wfProfileOut( __METHOD__
);
73 wfProfileIn( __METHOD__
.'-cache-miss' );
88 'names' => array( 2 => null ),
94 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
96 $xmlishElements = $this->parser
->getStripList();
97 $enableOnlyinclude = false;
98 if ( $forInclusion ) {
99 $ignoredTags = array( 'includeonly', '/includeonly' );
100 $ignoredElements = array( 'noinclude' );
101 $xmlishElements[] = 'noinclude';
102 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
103 $enableOnlyinclude = true;
106 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
107 $ignoredElements = array( 'includeonly' );
108 $xmlishElements[] = 'includeonly';
110 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
112 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
113 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
115 $stack = new PPDStack_Hash
;
117 $searchBase = "[{<\n";
118 $revText = strrev( $text ); // For fast reverse searches
120 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
121 $accum =& $stack->getAccum(); # Current accumulator
122 $findEquals = false; # True to find equals signs in arguments
123 $findPipe = false; # True to take notice of pipe characters
125 $inHeading = false; # True if $i is inside a possible heading
126 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
127 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
128 $fakeLineStart = true; # Do a line-start run without outputting an LF character
133 if ( $findOnlyinclude ) {
134 // Ignore all input up to the next <onlyinclude>
135 $startPos = strpos( $text, '<onlyinclude>', $i );
136 if ( $startPos === false ) {
137 // Ignored section runs to the end
138 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
141 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
142 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
144 $findOnlyinclude = false;
147 if ( $fakeLineStart ) {
148 $found = 'line-start';
151 # Find next opening brace, closing brace or pipe
152 $search = $searchBase;
153 if ( $stack->top
=== false ) {
154 $currentClosing = '';
156 $currentClosing = $stack->top
->close
;
157 $search .= $currentClosing;
163 // First equals will be for the template
167 # Output literal section, advance input counter
168 $literalLength = strcspn( $text, $search, $i );
169 if ( $literalLength > 0 ) {
170 $accum->addLiteral( substr( $text, $i, $literalLength ) );
171 $i +
= $literalLength;
173 if ( $i >= strlen( $text ) ) {
174 if ( $currentClosing == "\n" ) {
175 // Do a past-the-end run to finish off the heading
183 $curChar = $text[$i];
184 if ( $curChar == '|' ) {
186 } elseif ( $curChar == '=' ) {
188 } elseif ( $curChar == '<' ) {
190 } elseif ( $curChar == "\n" ) {
194 $found = 'line-start';
196 } elseif ( $curChar == $currentClosing ) {
198 } elseif ( isset( $rules[$curChar] ) ) {
200 $rule = $rules[$curChar];
202 # Some versions of PHP have a strcspn which stops on null characters
203 # Ignore and continue
210 if ( $found == 'angle' ) {
212 // Handle </onlyinclude>
213 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
214 $findOnlyinclude = true;
218 // Determine element name
219 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
220 // Element name missing or not listed
221 $accum->addLiteral( '<' );
226 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
227 // To avoid leaving blank lines, when a comment is both preceded
228 // and followed by a newline (ignoring spaces), trim leading and
229 // trailing spaces and one of the newlines.
232 $endPos = strpos( $text, '-->', $i +
4 );
233 if ( $endPos === false ) {
234 // Unclosed comment in input, runs to end
235 $inner = substr( $text, $i );
236 $accum->addNodeWithText( 'comment', $inner );
237 $i = strlen( $text );
239 // Search backwards for leading whitespace
240 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
241 // Search forwards for trailing whitespace
242 // $wsEnd will be the position of the last space
243 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
244 // Eat the line if possible
245 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
246 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
247 // it's a possible beneficial b/c break.
248 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
249 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
251 $startPos = $wsStart;
252 $endPos = $wsEnd +
1;
253 // Remove leading whitespace from the end of the accumulator
254 // Sanity check first though
255 $wsLength = $i - $wsStart;
257 && $accum->lastNode
instanceof PPNode_Hash_Text
258 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
260 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
262 // Do a line-start run next time to look for headings after the comment
263 $fakeLineStart = true;
265 // No line to eat, just take the comment itself
271 $part = $stack->top
->getCurrentPart();
272 if ( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) {
273 // Comments abutting, no change in visual end
274 $part->commentEnd
= $wsEnd;
276 $part->visualEnd
= $wsStart;
277 $part->commentEnd
= $endPos;
281 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
282 $accum->addNodeWithText( 'comment', $inner );
287 $lowerName = strtolower( $name );
288 $attrStart = $i +
strlen( $name ) +
1;
291 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
292 if ( $tagEndPos === false ) {
293 // Infinite backtrack
294 // Disable tag search to prevent worst-case O(N^2) performance
296 $accum->addLiteral( '<' );
301 // Handle ignored tags
302 if ( in_array( $lowerName, $ignoredTags ) ) {
303 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
309 if ( $text[$tagEndPos-1] == '/' ) {
311 $attrEnd = $tagEndPos - 1;
316 $attrEnd = $tagEndPos;
318 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
319 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
321 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
322 $i = $matches[0][1] +
strlen( $matches[0][0] );
323 $close = $matches[0][0];
325 // No end tag -- let it run out to the end of the text.
326 $inner = substr( $text, $tagEndPos +
1 );
327 $i = strlen( $text );
331 // <includeonly> and <noinclude> just become <ignore> tags
332 if ( in_array( $lowerName, $ignoredElements ) ) {
333 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
337 if ( $attrEnd <= $attrStart ) {
340 // Note that the attr element contains the whitespace between name and attribute,
341 // this is necessary for precise reconstruction during pre-save transform.
342 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
345 $extNode = new PPNode_Hash_Tree( 'ext' );
346 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
347 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
348 if ( $inner !== null ) {
349 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
351 if ( $close !== null ) {
352 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
354 $accum->addNode( $extNode );
357 elseif ( $found == 'line-start' ) {
358 // Is this the start of a heading?
359 // Line break belongs before the heading element in any case
360 if ( $fakeLineStart ) {
361 $fakeLineStart = false;
363 $accum->addLiteral( $curChar );
367 $count = strspn( $text, '=', $i, 6 );
368 if ( $count == 1 && $findEquals ) {
369 // DWIM: This looks kind of like a name/value separator
370 // Let's let the equals handler have it and break the potential heading
371 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
372 } elseif ( $count > 0 ) {
376 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
379 $stack->push( $piece );
380 $accum =& $stack->getAccum();
381 extract( $stack->getFlags() );
386 elseif ( $found == 'line-end' ) {
387 $piece = $stack->top
;
388 // A heading must be open, otherwise \n wouldn't have been in the search list
389 assert( $piece->open
== "\n" );
390 $part = $piece->getCurrentPart();
391 // Search back through the input to see if it has a proper close
392 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
393 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
394 $searchStart = $i - $wsLength;
395 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
396 // Comment found at line end
397 // Search for equals signs before the comment
398 $searchStart = $part->visualEnd
;
399 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
401 $count = $piece->count
;
402 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
403 if ( $equalsLength > 0 ) {
404 if ( $i - $equalsLength == $piece->startPos
) {
405 // This is just a single string of equals signs on its own line
406 // Replicate the doHeadings behaviour /={count}(.+)={count}/
407 // First find out how many equals signs there really are (don't stop at 6)
408 $count = $equalsLength;
412 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
415 $count = min( $equalsLength, $count );
418 // Normal match, output <h>
419 $element = new PPNode_Hash_Tree( 'possible-h' );
420 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
421 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
422 $element->lastChild
->nextSibling
= $accum->firstNode
;
423 $element->lastChild
= $accum->lastNode
;
425 // Single equals sign on its own line, count=0
429 // No match, no <h>, just pass down the inner text
434 $accum =& $stack->getAccum();
435 extract( $stack->getFlags() );
437 // Append the result to the enclosing accumulator
438 if ( $element instanceof PPNode
) {
439 $accum->addNode( $element );
441 $accum->addAccum( $element );
443 // Note that we do NOT increment the input pointer.
444 // This is because the closing linebreak could be the opening linebreak of
445 // another heading. Infinite loops are avoided because the next iteration MUST
446 // hit the heading open case above, which unconditionally increments the
450 elseif ( $found == 'open' ) {
451 # count opening brace characters
452 $count = strspn( $text, $curChar, $i );
454 # we need to add to stack only if opening brace count is enough for one of the rules
455 if ( $count >= $rule['min'] ) {
456 # Add it to the stack
459 'close' => $rule['end'],
461 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
464 $stack->push( $piece );
465 $accum =& $stack->getAccum();
466 extract( $stack->getFlags() );
468 # Add literal brace(s)
469 $accum->addLiteral( str_repeat( $curChar, $count ) );
474 elseif ( $found == 'close' ) {
475 $piece = $stack->top
;
476 # lets check if there are enough characters for closing brace
477 $maxCount = $piece->count
;
478 $count = strspn( $text, $curChar, $i, $maxCount );
480 # check for maximum matching characters (if there are 5 closing
481 # characters, we will probably need only 3 - depending on the rules)
483 $rule = $rules[$piece->open
];
484 if ( $count > $rule['max'] ) {
485 # The specified maximum exists in the callback array, unless the caller
487 $matchingCount = $rule['max'];
489 # Count is less than the maximum
490 # Skip any gaps in the callback array to find the true largest match
491 # Need to use array_key_exists not isset because the callback can be null
492 $matchingCount = $count;
493 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
498 if ($matchingCount <= 0) {
499 # No matching element found in callback array
500 # Output a literal closing brace and continue
501 $accum->addLiteral( str_repeat( $curChar, $count ) );
505 $name = $rule['names'][$matchingCount];
506 if ( $name === null ) {
507 // No element, just literal text
508 $element = $piece->breakSyntax( $matchingCount );
509 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
512 # Note: $parts is already XML, does not need to be encoded further
513 $parts = $piece->parts
;
514 $titleAccum = $parts[0]->out
;
517 $element = new PPNode_Hash_Tree( $name );
519 # The invocation is at the start of the line if lineStart is set in
520 # the stack, and all opening brackets are used up.
521 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
522 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
524 $titleNode = new PPNode_Hash_Tree( 'title' );
525 $titleNode->firstChild
= $titleAccum->firstNode
;
526 $titleNode->lastChild
= $titleAccum->lastNode
;
527 $element->addChild( $titleNode );
529 foreach ( $parts as $partIndex => $part ) {
530 if ( isset( $part->eqpos
) ) {
533 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
534 if ( $node === $part->eqpos
) {
540 throw new MWException( __METHOD__
. ': eqpos not found' );
542 if ( $node->name
!== 'equals' ) {
543 throw new MWException( __METHOD__
.': eqpos is not equals' );
547 // Construct name node
548 $nameNode = new PPNode_Hash_Tree( 'name' );
549 if ( $lastNode !== false ) {
550 $lastNode->nextSibling
= false;
551 $nameNode->firstChild
= $part->out
->firstNode
;
552 $nameNode->lastChild
= $lastNode;
555 // Construct value node
556 $valueNode = new PPNode_Hash_Tree( 'value' );
557 if ( $equalsNode->nextSibling
!== false ) {
558 $valueNode->firstChild
= $equalsNode->nextSibling
;
559 $valueNode->lastChild
= $part->out
->lastNode
;
561 $partNode = new PPNode_Hash_Tree( 'part' );
562 $partNode->addChild( $nameNode );
563 $partNode->addChild( $equalsNode->firstChild
);
564 $partNode->addChild( $valueNode );
565 $element->addChild( $partNode );
567 $partNode = new PPNode_Hash_Tree( 'part' );
568 $nameNode = new PPNode_Hash_Tree( 'name' );
569 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
570 $valueNode = new PPNode_Hash_Tree( 'value' );
571 $valueNode->firstChild
= $part->out
->firstNode
;
572 $valueNode->lastChild
= $part->out
->lastNode
;
573 $partNode->addChild( $nameNode );
574 $partNode->addChild( $valueNode );
575 $element->addChild( $partNode );
580 # Advance input pointer
581 $i +
= $matchingCount;
585 $accum =& $stack->getAccum();
587 # Re-add the old stack element if it still has unmatched opening characters remaining
588 if ($matchingCount < $piece->count
) {
589 $piece->parts
= array( new PPDPart_Hash
);
590 $piece->count
-= $matchingCount;
591 # do we still qualify for any callback with remaining count?
592 $names = $rules[$piece->open
]['names'];
594 $enclosingAccum =& $accum;
595 while ( $piece->count
) {
596 if ( array_key_exists( $piece->count
, $names ) ) {
597 $stack->push( $piece );
598 $accum =& $stack->getAccum();
604 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
607 extract( $stack->getFlags() );
609 # Add XML element to the enclosing accumulator
610 if ( $element instanceof PPNode
) {
611 $accum->addNode( $element );
613 $accum->addAccum( $element );
617 elseif ( $found == 'pipe' ) {
618 $findEquals = true; // shortcut for getFlags()
620 $accum =& $stack->getAccum();
624 elseif ( $found == 'equals' ) {
625 $findEquals = false; // shortcut for getFlags()
626 $accum->addNodeWithText( 'equals', '=' );
627 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
632 # Output any remaining unclosed brackets
633 foreach ( $stack->stack
as $piece ) {
634 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
637 # Enable top-level headings
638 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
639 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
644 $rootNode = new PPNode_Hash_Tree( 'root' );
645 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
646 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
650 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );;
651 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
652 wfProfileOut( __METHOD__
.'-cache-miss' );
653 wfProfileOut( __METHOD__
.'-cacheable' );
654 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
657 wfProfileOut( __METHOD__
);
663 * Stack class to help Preprocessor::preprocessToObj()
666 class PPDStack_Hash
extends PPDStack
{
667 function __construct() {
668 $this->elementClass
= 'PPDStackElement_Hash';
669 parent
::__construct();
670 $this->rootAccum
= new PPDAccum_Hash
;
677 class PPDStackElement_Hash
extends PPDStackElement
{
678 function __construct( $data = array() ) {
679 $this->partClass
= 'PPDPart_Hash';
680 parent
::__construct( $data );
684 * Get the accumulator that would result if the close is not found.
686 function breakSyntax( $openingCount = false ) {
687 if ( $this->open
== "\n" ) {
688 $accum = $this->parts
[0]->out
;
690 if ( $openingCount === false ) {
691 $openingCount = $this->count
;
693 $accum = new PPDAccum_Hash
;
694 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
696 foreach ( $this->parts
as $part ) {
700 $accum->addLiteral( '|' );
702 $accum->addAccum( $part->out
);
712 class PPDPart_Hash
extends PPDPart
{
713 function __construct( $out = '' ) {
714 $accum = new PPDAccum_Hash
;
716 $accum->addLiteral( $out );
718 parent
::__construct( $accum );
725 class PPDAccum_Hash
{
726 var $firstNode, $lastNode;
728 function __construct() {
729 $this->firstNode
= $this->lastNode
= false;
733 * Append a string literal
735 function addLiteral( $s ) {
736 if ( $this->lastNode
=== false ) {
737 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
738 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
739 $this->lastNode
->value
.= $s;
741 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
742 $this->lastNode
= $this->lastNode
->nextSibling
;
749 function addNode( PPNode
$node ) {
750 if ( $this->lastNode
=== false ) {
751 $this->firstNode
= $this->lastNode
= $node;
753 $this->lastNode
->nextSibling
= $node;
754 $this->lastNode
= $node;
759 * Append a tree node with text contents
761 function addNodeWithText( $name, $value ) {
762 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
763 $this->addNode( $node );
767 * Append a PPAccum_Hash
768 * Takes over ownership of the nodes in the source argument. These nodes may
769 * subsequently be modified, especially nextSibling.
771 function addAccum( $accum ) {
772 if ( $accum->lastNode
=== false ) {
774 } elseif ( $this->lastNode
=== false ) {
775 $this->firstNode
= $accum->firstNode
;
776 $this->lastNode
= $accum->lastNode
;
778 $this->lastNode
->nextSibling
= $accum->firstNode
;
779 $this->lastNode
= $accum->lastNode
;
785 * An expansion frame, used as a context to expand the result of preprocessToObj()
788 class PPFrame_Hash
implements PPFrame
{
789 var $preprocessor, $parser, $title;
793 * Hashtable listing templates which are disallowed for expansion in this frame,
794 * having been encountered previously in parent frames.
799 * Recursion depth of this frame, top = 0
800 * Note that this is NOT the same as expansion depth in expand()
806 * Construct a new preprocessor frame.
807 * @param Preprocessor $preprocessor The parent preprocessor
809 function __construct( $preprocessor ) {
810 $this->preprocessor
= $preprocessor;
811 $this->parser
= $preprocessor->parser
;
812 $this->title
= $this->parser
->mTitle
;
813 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
814 $this->loopCheckHash
= array();
819 * Create a new child frame
820 * $args is optionally a multi-root PPNode or array containing the template arguments
822 function newChild( $args = false, $title = false ) {
823 $namedArgs = array();
824 $numberedArgs = array();
825 if ( $title === false ) {
826 $title = $this->title
;
828 if ( $args !== false ) {
830 if ( $args instanceof PPNode_Hash_Array
) {
831 $args = $args->value
;
832 } elseif ( !is_array( $args ) ) {
833 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
835 foreach ( $args as $arg ) {
836 $bits = $arg->splitArg();
837 if ( $bits['index'] !== '' ) {
838 // Numbered parameter
839 $numberedArgs[$bits['index']] = $bits['value'];
840 unset( $namedArgs[$bits['index']] );
843 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
844 $namedArgs[$name] = $bits['value'];
845 unset( $numberedArgs[$name] );
849 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
852 function expand( $root, $flags = 0 ) {
853 static $expansionDepth = 0;
854 if ( is_string( $root ) ) {
858 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
860 return '<span class="error">Node-count limit exceeded</span>';
862 if ( $expansionDepth > $this->parser
->mOptions
->mMaxPPExpandDepth
) {
863 return '<span class="error">Expansion depth limit exceeded</span>';
867 $outStack = array( '', '' );
868 $iteratorStack = array( false, $root );
869 $indexStack = array( 0, 0 );
871 while ( count( $iteratorStack ) > 1 ) {
872 $level = count( $outStack ) - 1;
873 $iteratorNode =& $iteratorStack[ $level ];
874 $out =& $outStack[$level];
875 $index =& $indexStack[$level];
877 if ( is_array( $iteratorNode ) ) {
878 if ( $index >= count( $iteratorNode ) ) {
879 // All done with this iterator
880 $iteratorStack[$level] = false;
881 $contextNode = false;
883 $contextNode = $iteratorNode[$index];
886 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
887 if ( $index >= $iteratorNode->getLength() ) {
888 // All done with this iterator
889 $iteratorStack[$level] = false;
890 $contextNode = false;
892 $contextNode = $iteratorNode->item( $index );
896 // Copy to $contextNode and then delete from iterator stack,
897 // because this is not an iterator but we do have to execute it once
898 $contextNode = $iteratorStack[$level];
899 $iteratorStack[$level] = false;
902 $newIterator = false;
904 if ( $contextNode === false ) {
906 } elseif ( is_string( $contextNode ) ) {
907 $out .= $contextNode;
908 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
909 $newIterator = $contextNode;
910 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
912 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
913 $out .= $contextNode->value
;
914 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
915 if ( $contextNode->name
== 'template' ) {
916 # Double-brace expansion
917 $bits = $contextNode->splitTemplate();
918 if ( $flags & self
::NO_TEMPLATES
) {
919 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
921 $ret = $this->parser
->braceSubstitution( $bits, $this );
922 if ( isset( $ret['object'] ) ) {
923 $newIterator = $ret['object'];
925 $out .= $ret['text'];
928 } elseif ( $contextNode->name
== 'tplarg' ) {
929 # Triple-brace expansion
930 $bits = $contextNode->splitTemplate();
931 if ( $flags & self
::NO_ARGS
) {
932 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
934 $ret = $this->parser
->argSubstitution( $bits, $this );
935 if ( isset( $ret['object'] ) ) {
936 $newIterator = $ret['object'];
938 $out .= $ret['text'];
941 } elseif ( $contextNode->name
== 'comment' ) {
943 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
944 if ( $this->parser
->ot
['html']
945 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
946 ||
( $flags & self
::STRIP_COMMENTS
) )
950 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
951 # Not in RECOVER_COMMENTS mode (extractSections) though
952 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & self
::RECOVER_COMMENTS
) ) {
953 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
955 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
957 $out .= $contextNode->firstChild
->value
;
959 } elseif ( $contextNode->name
== 'ignore' ) {
960 # Output suppression used by <includeonly> etc.
961 # OT_WIKI will only respect <ignore> in substed templates.
962 # The other output types respect it unless NO_IGNORE is set.
963 # extractSections() sets NO_IGNORE and so never respects it.
964 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
965 $out .= $contextNode->firstChild
->value
;
969 } elseif ( $contextNode->name
== 'ext' ) {
971 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
972 $out .= $this->parser
->extensionSubstitution( $bits, $this );
973 } elseif ( $contextNode->name
== 'h' ) {
975 if ( $this->parser
->ot
['html'] ) {
976 # Expand immediately and insert heading index marker
978 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
979 $s .= $this->expand( $node, $flags );
982 $bits = $contextNode->splitHeading();
983 $titleText = $this->title
->getPrefixedDBkey();
984 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
985 $serial = count( $this->parser
->mHeadings
) - 1;
986 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
987 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
988 $this->parser
->mStripState
->general
->setPair( $marker, '' );
991 # Expand in virtual stack
992 $newIterator = $contextNode->getChildren();
995 # Generic recursive expansion
996 $newIterator = $contextNode->getChildren();
999 throw new MWException( __METHOD__
.': Invalid parameter type' );
1002 if ( $newIterator !== false ) {
1004 $iteratorStack[] = $newIterator;
1006 } elseif ( $iteratorStack[$level] === false ) {
1007 // Return accumulated value to parent
1008 // With tail recursion
1009 while ( $iteratorStack[$level] === false && $level > 0 ) {
1010 $outStack[$level - 1] .= $out;
1011 array_pop( $outStack );
1012 array_pop( $iteratorStack );
1013 array_pop( $indexStack );
1019 return $outStack[0];
1022 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1023 $args = array_slice( func_get_args(), 2 );
1027 foreach ( $args as $root ) {
1028 if ( $root instanceof PPNode_Hash_Array
) {
1029 $root = $root->value
;
1031 if ( !is_array( $root ) ) {
1032 $root = array( $root );
1034 foreach ( $root as $node ) {
1040 $s .= $this->expand( $node, $flags );
1047 * Implode with no flags specified
1048 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1050 function implode( $sep /*, ... */ ) {
1051 $args = array_slice( func_get_args(), 1 );
1055 foreach ( $args as $root ) {
1056 if ( $root instanceof PPNode_Hash_Array
) {
1057 $root = $root->value
;
1059 if ( !is_array( $root ) ) {
1060 $root = array( $root );
1062 foreach ( $root as $node ) {
1068 $s .= $this->expand( $node );
1075 * Makes an object that, when expand()ed, will be the same as one obtained
1078 function virtualImplode( $sep /*, ... */ ) {
1079 $args = array_slice( func_get_args(), 1 );
1083 foreach ( $args as $root ) {
1084 if ( $root instanceof PPNode_Hash_Array
) {
1085 $root = $root->value
;
1087 if ( !is_array( $root ) ) {
1088 $root = array( $root );
1090 foreach ( $root as $node ) {
1099 return new PPNode_Hash_Array( $out );
1103 * Virtual implode with brackets
1105 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1106 $args = array_slice( func_get_args(), 3 );
1107 $out = array( $start );
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 ) {
1127 return new PPNode_Hash_Array( $out );
1130 function __toString() {
1134 function getPDBK( $level = false ) {
1135 if ( $level === false ) {
1136 return $this->title
->getPrefixedDBkey();
1138 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1142 function getArguments() {
1146 function getNumberedArguments() {
1150 function getNamedArguments() {
1155 * Returns true if there are no arguments in this frame
1157 function isEmpty() {
1161 function getArgument( $name ) {
1166 * Returns true if the infinite loop check is OK, false if a loop is detected
1168 function loopCheck( $title ) {
1169 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1173 * Return true if the frame is a template frame
1175 function isTemplate() {
1181 * Expansion frame with template arguments
1184 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1185 var $numberedArgs, $namedArgs, $parent;
1186 var $numberedExpansionCache, $namedExpansionCache;
1188 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1189 PPFrame_Hash
::__construct( $preprocessor );
1190 $this->parent
= $parent;
1191 $this->numberedArgs
= $numberedArgs;
1192 $this->namedArgs
= $namedArgs;
1193 $this->title
= $title;
1194 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1195 $this->titleCache
= $parent->titleCache
;
1196 $this->titleCache
[] = $pdbk;
1197 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1198 if ( $pdbk !== false ) {
1199 $this->loopCheckHash
[$pdbk] = true;
1201 $this->depth
= $parent->depth +
1;
1202 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1205 function __toString() {
1208 $args = $this->numberedArgs +
$this->namedArgs
;
1209 foreach ( $args as $name => $value ) {
1215 $s .= "\"$name\":\"" .
1216 str_replace( '"', '\\"', $value->__toString() ) . '"';
1222 * Returns true if there are no arguments in this frame
1224 function isEmpty() {
1225 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1228 function getArguments() {
1229 $arguments = array();
1230 foreach ( array_merge(
1231 array_keys($this->numberedArgs
),
1232 array_keys($this->namedArgs
)) as $key ) {
1233 $arguments[$key] = $this->getArgument($key);
1238 function getNumberedArguments() {
1239 $arguments = array();
1240 foreach ( array_keys($this->numberedArgs
) as $key ) {
1241 $arguments[$key] = $this->getArgument($key);
1246 function getNamedArguments() {
1247 $arguments = array();
1248 foreach ( array_keys($this->namedArgs
) as $key ) {
1249 $arguments[$key] = $this->getArgument($key);
1254 function getNumberedArgument( $index ) {
1255 if ( !isset( $this->numberedArgs
[$index] ) ) {
1258 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1259 # No trimming for unnamed arguments
1260 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], self
::STRIP_COMMENTS
);
1262 return $this->numberedExpansionCache
[$index];
1265 function getNamedArgument( $name ) {
1266 if ( !isset( $this->namedArgs
[$name] ) ) {
1269 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1270 # Trim named arguments post-expand, for backwards compatibility
1271 $this->namedExpansionCache
[$name] = trim(
1272 $this->parent
->expand( $this->namedArgs
[$name], self
::STRIP_COMMENTS
) );
1274 return $this->namedExpansionCache
[$name];
1277 function getArgument( $name ) {
1278 $text = $this->getNumberedArgument( $name );
1279 if ( $text === false ) {
1280 $text = $this->getNamedArgument( $name );
1286 * Return true if the frame is a template frame
1288 function isTemplate() {
1294 * Expansion frame with custom arguments
1297 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1300 function __construct( $preprocessor, $args ) {
1301 PPFrame_Hash
::__construct( $preprocessor );
1302 $this->args
= $args;
1305 function __toString() {
1308 foreach ( $this->args
as $name => $value ) {
1314 $s .= "\"$name\":\"" .
1315 str_replace( '"', '\\"', $value->__toString() ) . '"';
1321 function isEmpty() {
1322 return !count( $this->args
);
1325 function getArgument( $index ) {
1326 if ( !isset( $this->args
[$index] ) ) {
1329 return $this->args
[$index];
1336 class PPNode_Hash_Tree
implements PPNode
{
1337 var $name, $firstChild, $lastChild, $nextSibling;
1339 function __construct( $name ) {
1340 $this->name
= $name;
1341 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1344 function __toString() {
1347 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1348 if ( $node instanceof PPNode_Hash_Attr
) {
1349 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1351 $inner .= $node->__toString();
1354 if ( $inner === '' ) {
1355 return "<{$this->name}$attribs/>";
1357 return "<{$this->name}$attribs>$inner</{$this->name}>";
1361 static function newWithText( $name, $text ) {
1362 $obj = new self( $name );
1363 $obj->addChild( new PPNode_Hash_Text( $text ) );
1367 function addChild( $node ) {
1368 if ( $this->lastChild
=== false ) {
1369 $this->firstChild
= $this->lastChild
= $node;
1371 $this->lastChild
->nextSibling
= $node;
1372 $this->lastChild
= $node;
1376 function getChildren() {
1377 $children = array();
1378 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1379 $children[] = $child;
1381 return new PPNode_Hash_Array( $children );
1384 function getFirstChild() {
1385 return $this->firstChild
;
1388 function getNextSibling() {
1389 return $this->nextSibling
;
1392 function getChildrenOfType( $name ) {
1393 $children = array();
1394 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1395 if ( isset( $child->name
) && $child->name
=== $name ) {
1396 $children[] = $name;
1402 function getLength() { return false; }
1403 function item( $i ) { return false; }
1405 function getName() {
1410 * Split a <part> node into an associative array containing:
1412 * index String index
1413 * value PPNode value
1415 function splitArg() {
1417 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1418 if ( !isset( $child->name
) ) {
1421 if ( $child->name
=== 'name' ) {
1422 $bits['name'] = $child;
1423 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1424 && $child->firstChild
->name
=== 'index' )
1426 $bits['index'] = $child->firstChild
->value
;
1428 } elseif ( $child->name
=== 'value' ) {
1429 $bits['value'] = $child;
1433 if ( !isset( $bits['name'] ) ) {
1434 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1436 if ( !isset( $bits['index'] ) ) {
1437 $bits['index'] = '';
1443 * Split an <ext> node into an associative array containing name, attr, inner and close
1444 * All values in the resulting array are PPNodes. Inner and close are optional.
1446 function splitExt() {
1448 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1449 if ( !isset( $child->name
) ) {
1452 if ( $child->name
== 'name' ) {
1453 $bits['name'] = $child;
1454 } elseif ( $child->name
== 'attr' ) {
1455 $bits['attr'] = $child;
1456 } elseif ( $child->name
== 'inner' ) {
1457 $bits['inner'] = $child;
1458 } elseif ( $child->name
== 'close' ) {
1459 $bits['close'] = $child;
1462 if ( !isset( $bits['name'] ) ) {
1463 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1471 function splitHeading() {
1472 if ( $this->name
!== 'h' ) {
1473 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1476 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1477 if ( !isset( $child->name
) ) {
1480 if ( $child->name
== 'i' ) {
1481 $bits['i'] = $child->value
;
1482 } elseif ( $child->name
== 'level' ) {
1483 $bits['level'] = $child->value
;
1486 if ( !isset( $bits['i'] ) ) {
1487 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1493 * Split a <template> or <tplarg> node
1495 function splitTemplate() {
1497 $bits = array( 'lineStart' => '' );
1498 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1499 if ( !isset( $child->name
) ) {
1502 if ( $child->name
== 'title' ) {
1503 $bits['title'] = $child;
1505 if ( $child->name
== 'part' ) {
1508 if ( $child->name
== 'lineStart' ) {
1509 $bits['lineStart'] = '1';
1512 if ( !isset( $bits['title'] ) ) {
1513 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1515 $bits['parts'] = new PPNode_Hash_Array( $parts );
1523 class PPNode_Hash_Text
implements PPNode
{
1524 var $value, $nextSibling;
1526 function __construct( $value ) {
1527 if ( is_object( $value ) ) {
1528 throw new MWException( __CLASS__
. ' given object instead of string' );
1530 $this->value
= $value;
1533 function __toString() {
1534 return htmlspecialchars( $this->value
);
1537 function getNextSibling() {
1538 return $this->nextSibling
;
1541 function getChildren() { return false; }
1542 function getFirstChild() { return false; }
1543 function getChildrenOfType( $name ) { return false; }
1544 function getLength() { return false; }
1545 function item( $i ) { return false; }
1546 function getName() { return '#text'; }
1547 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1548 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1549 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1555 class PPNode_Hash_Array
implements PPNode
{
1556 var $value, $nextSibling;
1558 function __construct( $value ) {
1559 $this->value
= $value;
1562 function __toString() {
1563 return var_export( $this, true );
1566 function getLength() {
1567 return count( $this->value
);
1570 function item( $i ) {
1571 return $this->value
[$i];
1574 function getName() { return '#nodelist'; }
1576 function getNextSibling() {
1577 return $this->nextSibling
;
1580 function getChildren() { return false; }
1581 function getFirstChild() { return false; }
1582 function getChildrenOfType( $name ) { return false; }
1583 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1584 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1585 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1591 class PPNode_Hash_Attr
implements PPNode
{
1592 var $name, $value, $nextSibling;
1594 function __construct( $name, $value ) {
1595 $this->name
= $name;
1596 $this->value
= $value;
1599 function __toString() {
1600 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1603 function getName() {
1607 function getNextSibling() {
1608 return $this->nextSibling
;
1611 function getChildren() { return false; }
1612 function getFirstChild() { return false; }
1613 function getChildrenOfType( $name ) { return false; }
1614 function getLength() { return false; }
1615 function item( $i ) { 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' ); }