3 * Preprocessor using PHP arrays
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Differences from DOM schema:
26 * * attribute nodes are children
27 * * <h> nodes that aren't at the top are replaced with <possible-h>
30 class Preprocessor_Hash
implements Preprocessor
{
36 const CACHE_VERSION
= 1;
38 function __construct( $parser ) {
39 $this->parser
= $parser;
43 * @return PPFrame_Hash
46 return new PPFrame_Hash( $this );
51 * @return PPCustomFrame_Hash
53 function newCustomFrame( $args ) {
54 return new PPCustomFrame_Hash( $this, $args );
58 * @param $values array
59 * @return PPNode_Hash_Array
61 function newPartNodeArray( $values ) {
64 foreach ( $values as $k => $val ) {
65 $partNode = new PPNode_Hash_Tree( 'part' );
66 $nameNode = new PPNode_Hash_Tree( 'name' );
69 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
70 $partNode->addChild( $nameNode );
72 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
73 $partNode->addChild( $nameNode );
74 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
77 $valueNode = new PPNode_Hash_Tree( 'value' );
78 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
79 $partNode->addChild( $valueNode );
84 $node = new PPNode_Hash_Array( $list );
89 * Preprocess some wikitext and return the document tree.
90 * This is the ghost of Parser::replace_variables().
92 * @param $text String: the text to parse
93 * @param $flags Integer: bitwise combination of:
94 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
95 * included. Default is to assume a direct page view.
97 * The generated DOM tree must depend only on the input text and the flags.
98 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
100 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
101 * change in the DOM tree for a given text, must be passed through the section identifier
102 * in the section edit link and thus back to extractSections().
104 * The output of this function is currently only cached in process memory, but a persistent
105 * cache may be implemented at a later date which takes further advantage of these strict
106 * dependency requirements.
108 * @return PPNode_Hash_Tree
110 function preprocessToObj( $text, $flags = 0 ) {
111 wfProfileIn( __METHOD__
);
114 global $wgMemc, $wgPreprocessorCacheThreshold;
116 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
118 wfProfileIn( __METHOD__
.'-cacheable' );
120 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
121 $cacheValue = $wgMemc->get( $cacheKey );
123 $version = substr( $cacheValue, 0, 8 );
124 if ( intval( $version ) == self
::CACHE_VERSION
) {
125 $hash = unserialize( substr( $cacheValue, 8 ) );
127 wfDebugLog( "Preprocessor",
128 "Loaded preprocessor hash from memcached (key $cacheKey)" );
129 wfProfileOut( __METHOD__
.'-cacheable' );
130 wfProfileOut( __METHOD__
);
134 wfProfileIn( __METHOD__
.'-cache-miss' );
149 'names' => array( 2 => null ),
155 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
157 $xmlishElements = $this->parser
->getStripList();
158 $enableOnlyinclude = false;
159 if ( $forInclusion ) {
160 $ignoredTags = array( 'includeonly', '/includeonly' );
161 $ignoredElements = array( 'noinclude' );
162 $xmlishElements[] = 'noinclude';
163 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
164 $enableOnlyinclude = true;
167 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
168 $ignoredElements = array( 'includeonly' );
169 $xmlishElements[] = 'includeonly';
171 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
173 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
174 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
176 $stack = new PPDStack_Hash
;
178 $searchBase = "[{<\n";
179 $revText = strrev( $text ); // For fast reverse searches
181 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
182 $accum =& $stack->getAccum(); # Current accumulator
183 $findEquals = false; # True to find equals signs in arguments
184 $findPipe = false; # True to take notice of pipe characters
186 $inHeading = false; # True if $i is inside a possible heading
187 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
188 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
189 $fakeLineStart = true; # Do a line-start run without outputting an LF character
194 if ( $findOnlyinclude ) {
195 // Ignore all input up to the next <onlyinclude>
196 $startPos = strpos( $text, '<onlyinclude>', $i );
197 if ( $startPos === false ) {
198 // Ignored section runs to the end
199 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
202 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
203 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
205 $findOnlyinclude = false;
208 if ( $fakeLineStart ) {
209 $found = 'line-start';
212 # Find next opening brace, closing brace or pipe
213 $search = $searchBase;
214 if ( $stack->top
=== false ) {
215 $currentClosing = '';
217 $currentClosing = $stack->top
->close
;
218 $search .= $currentClosing;
224 // First equals will be for the template
228 # Output literal section, advance input counter
229 $literalLength = strcspn( $text, $search, $i );
230 if ( $literalLength > 0 ) {
231 $accum->addLiteral( substr( $text, $i, $literalLength ) );
232 $i +
= $literalLength;
234 if ( $i >= strlen( $text ) ) {
235 if ( $currentClosing == "\n" ) {
236 // Do a past-the-end run to finish off the heading
244 $curChar = $text[$i];
245 if ( $curChar == '|' ) {
247 } elseif ( $curChar == '=' ) {
249 } elseif ( $curChar == '<' ) {
251 } elseif ( $curChar == "\n" ) {
255 $found = 'line-start';
257 } elseif ( $curChar == $currentClosing ) {
259 } elseif ( isset( $rules[$curChar] ) ) {
261 $rule = $rules[$curChar];
263 # Some versions of PHP have a strcspn which stops on null characters
264 # Ignore and continue
271 if ( $found == 'angle' ) {
273 // Handle </onlyinclude>
274 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
275 $findOnlyinclude = true;
279 // Determine element name
280 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
281 // Element name missing or not listed
282 $accum->addLiteral( '<' );
287 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
288 // To avoid leaving blank lines, when a comment is both preceded
289 // and followed by a newline (ignoring spaces), trim leading and
290 // trailing spaces and one of the newlines.
293 $endPos = strpos( $text, '-->', $i +
4 );
294 if ( $endPos === false ) {
295 // Unclosed comment in input, runs to end
296 $inner = substr( $text, $i );
297 $accum->addNodeWithText( 'comment', $inner );
298 $i = strlen( $text );
300 // Search backwards for leading whitespace
301 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
302 // Search forwards for trailing whitespace
303 // $wsEnd will be the position of the last space (or the '>' if there's none)
304 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
305 // Eat the line if possible
306 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
307 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
308 // it's a possible beneficial b/c break.
309 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
310 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
312 $startPos = $wsStart;
313 $endPos = $wsEnd +
1;
314 // Remove leading whitespace from the end of the accumulator
315 // Sanity check first though
316 $wsLength = $i - $wsStart;
318 && $accum->lastNode
instanceof PPNode_Hash_Text
319 && substr( $accum->lastNode
->value
, -$wsLength ) === str_repeat( ' ', $wsLength ) )
321 $accum->lastNode
->value
= substr( $accum->lastNode
->value
, 0, -$wsLength );
323 // Do a line-start run next time to look for headings after the comment
324 $fakeLineStart = true;
326 // No line to eat, just take the comment itself
332 $part = $stack->top
->getCurrentPart();
333 if ( ! (isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 )) {
334 $part->visualEnd
= $wsStart;
336 // Else comments abutting, no change in visual end
337 $part->commentEnd
= $endPos;
340 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
341 $accum->addNodeWithText( 'comment', $inner );
346 $lowerName = strtolower( $name );
347 $attrStart = $i +
strlen( $name ) +
1;
350 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
351 if ( $tagEndPos === false ) {
352 // Infinite backtrack
353 // Disable tag search to prevent worst-case O(N^2) performance
355 $accum->addLiteral( '<' );
360 // Handle ignored tags
361 if ( in_array( $lowerName, $ignoredTags ) ) {
362 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i +
1 ) );
368 if ( $text[$tagEndPos-1] == '/' ) {
370 $attrEnd = $tagEndPos - 1;
375 $attrEnd = $tagEndPos;
377 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
378 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) )
380 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
381 $i = $matches[0][1] +
strlen( $matches[0][0] );
382 $close = $matches[0][0];
384 // No end tag -- let it run out to the end of the text.
385 $inner = substr( $text, $tagEndPos +
1 );
386 $i = strlen( $text );
390 // <includeonly> and <noinclude> just become <ignore> tags
391 if ( in_array( $lowerName, $ignoredElements ) ) {
392 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
396 if ( $attrEnd <= $attrStart ) {
399 // Note that the attr element contains the whitespace between name and attribute,
400 // this is necessary for precise reconstruction during pre-save transform.
401 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
404 $extNode = new PPNode_Hash_Tree( 'ext' );
405 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'name', $name ) );
406 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'attr', $attr ) );
407 if ( $inner !== null ) {
408 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'inner', $inner ) );
410 if ( $close !== null ) {
411 $extNode->addChild( PPNode_Hash_Tree
::newWithText( 'close', $close ) );
413 $accum->addNode( $extNode );
416 elseif ( $found == 'line-start' ) {
417 // Is this the start of a heading?
418 // Line break belongs before the heading element in any case
419 if ( $fakeLineStart ) {
420 $fakeLineStart = false;
422 $accum->addLiteral( $curChar );
426 $count = strspn( $text, '=', $i, 6 );
427 if ( $count == 1 && $findEquals ) {
428 // DWIM: This looks kind of like a name/value separator
429 // Let's let the equals handler have it and break the potential heading
430 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
431 } elseif ( $count > 0 ) {
435 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
438 $stack->push( $piece );
439 $accum =& $stack->getAccum();
440 extract( $stack->getFlags() );
443 } elseif ( $found == 'line-end' ) {
444 $piece = $stack->top
;
445 // A heading must be open, otherwise \n wouldn't have been in the search list
446 assert( '$piece->open == "\n"' );
447 $part = $piece->getCurrentPart();
448 // Search back through the input to see if it has a proper close
449 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
450 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
451 $searchStart = $i - $wsLength;
452 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
453 // Comment found at line end
454 // Search for equals signs before the comment
455 $searchStart = $part->visualEnd
;
456 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
458 $count = $piece->count
;
459 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
460 if ( $equalsLength > 0 ) {
461 if ( $searchStart - $equalsLength == $piece->startPos
) {
462 // This is just a single string of equals signs on its own line
463 // Replicate the doHeadings behaviour /={count}(.+)={count}/
464 // First find out how many equals signs there really are (don't stop at 6)
465 $count = $equalsLength;
469 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
472 $count = min( $equalsLength, $count );
475 // Normal match, output <h>
476 $element = new PPNode_Hash_Tree( 'possible-h' );
477 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
478 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++
) );
479 $element->lastChild
->nextSibling
= $accum->firstNode
;
480 $element->lastChild
= $accum->lastNode
;
482 // Single equals sign on its own line, count=0
486 // No match, no <h>, just pass down the inner text
491 $accum =& $stack->getAccum();
492 extract( $stack->getFlags() );
494 // Append the result to the enclosing accumulator
495 if ( $element instanceof PPNode
) {
496 $accum->addNode( $element );
498 $accum->addAccum( $element );
500 // Note that we do NOT increment the input pointer.
501 // This is because the closing linebreak could be the opening linebreak of
502 // another heading. Infinite loops are avoided because the next iteration MUST
503 // hit the heading open case above, which unconditionally increments the
505 } elseif ( $found == 'open' ) {
506 # count opening brace characters
507 $count = strspn( $text, $curChar, $i );
509 # we need to add to stack only if opening brace count is enough for one of the rules
510 if ( $count >= $rule['min'] ) {
511 # Add it to the stack
514 'close' => $rule['end'],
516 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
519 $stack->push( $piece );
520 $accum =& $stack->getAccum();
521 extract( $stack->getFlags() );
523 # Add literal brace(s)
524 $accum->addLiteral( str_repeat( $curChar, $count ) );
527 } elseif ( $found == 'close' ) {
528 $piece = $stack->top
;
529 # lets check if there are enough characters for closing brace
530 $maxCount = $piece->count
;
531 $count = strspn( $text, $curChar, $i, $maxCount );
533 # check for maximum matching characters (if there are 5 closing
534 # characters, we will probably need only 3 - depending on the rules)
535 $rule = $rules[$piece->open
];
536 if ( $count > $rule['max'] ) {
537 # The specified maximum exists in the callback array, unless the caller
539 $matchingCount = $rule['max'];
541 # Count is less than the maximum
542 # Skip any gaps in the callback array to find the true largest match
543 # Need to use array_key_exists not isset because the callback can be null
544 $matchingCount = $count;
545 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
550 if ($matchingCount <= 0) {
551 # No matching element found in callback array
552 # Output a literal closing brace and continue
553 $accum->addLiteral( str_repeat( $curChar, $count ) );
557 $name = $rule['names'][$matchingCount];
558 if ( $name === null ) {
559 // No element, just literal text
560 $element = $piece->breakSyntax( $matchingCount );
561 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
564 # Note: $parts is already XML, does not need to be encoded further
565 $parts = $piece->parts
;
566 $titleAccum = $parts[0]->out
;
569 $element = new PPNode_Hash_Tree( $name );
571 # The invocation is at the start of the line if lineStart is set in
572 # the stack, and all opening brackets are used up.
573 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
574 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
576 $titleNode = new PPNode_Hash_Tree( 'title' );
577 $titleNode->firstChild
= $titleAccum->firstNode
;
578 $titleNode->lastChild
= $titleAccum->lastNode
;
579 $element->addChild( $titleNode );
581 foreach ( $parts as $part ) {
582 if ( isset( $part->eqpos
) ) {
585 for ( $node = $part->out
->firstNode
; $node; $node = $node->nextSibling
) {
586 if ( $node === $part->eqpos
) {
592 throw new MWException( __METHOD__
. ': eqpos not found' );
594 if ( $node->name
!== 'equals' ) {
595 throw new MWException( __METHOD__
.': eqpos is not equals' );
599 // Construct name node
600 $nameNode = new PPNode_Hash_Tree( 'name' );
601 if ( $lastNode !== false ) {
602 $lastNode->nextSibling
= false;
603 $nameNode->firstChild
= $part->out
->firstNode
;
604 $nameNode->lastChild
= $lastNode;
607 // Construct value node
608 $valueNode = new PPNode_Hash_Tree( 'value' );
609 if ( $equalsNode->nextSibling
!== false ) {
610 $valueNode->firstChild
= $equalsNode->nextSibling
;
611 $valueNode->lastChild
= $part->out
->lastNode
;
613 $partNode = new PPNode_Hash_Tree( 'part' );
614 $partNode->addChild( $nameNode );
615 $partNode->addChild( $equalsNode->firstChild
);
616 $partNode->addChild( $valueNode );
617 $element->addChild( $partNode );
619 $partNode = new PPNode_Hash_Tree( 'part' );
620 $nameNode = new PPNode_Hash_Tree( 'name' );
621 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++
) );
622 $valueNode = new PPNode_Hash_Tree( 'value' );
623 $valueNode->firstChild
= $part->out
->firstNode
;
624 $valueNode->lastChild
= $part->out
->lastNode
;
625 $partNode->addChild( $nameNode );
626 $partNode->addChild( $valueNode );
627 $element->addChild( $partNode );
632 # Advance input pointer
633 $i +
= $matchingCount;
637 $accum =& $stack->getAccum();
639 # Re-add the old stack element if it still has unmatched opening characters remaining
640 if ($matchingCount < $piece->count
) {
641 $piece->parts
= array( new PPDPart_Hash
);
642 $piece->count
-= $matchingCount;
643 # do we still qualify for any callback with remaining count?
644 $names = $rules[$piece->open
]['names'];
646 $enclosingAccum =& $accum;
647 while ( $piece->count
) {
648 if ( array_key_exists( $piece->count
, $names ) ) {
649 $stack->push( $piece );
650 $accum =& $stack->getAccum();
656 $enclosingAccum->addLiteral( str_repeat( $piece->open
, $skippedBraces ) );
659 extract( $stack->getFlags() );
661 # Add XML element to the enclosing accumulator
662 if ( $element instanceof PPNode
) {
663 $accum->addNode( $element );
665 $accum->addAccum( $element );
667 } elseif ( $found == 'pipe' ) {
668 $findEquals = true; // shortcut for getFlags()
670 $accum =& $stack->getAccum();
672 } elseif ( $found == 'equals' ) {
673 $findEquals = false; // shortcut for getFlags()
674 $accum->addNodeWithText( 'equals', '=' );
675 $stack->getCurrentPart()->eqpos
= $accum->lastNode
;
680 # Output any remaining unclosed brackets
681 foreach ( $stack->stack
as $piece ) {
682 $stack->rootAccum
->addAccum( $piece->breakSyntax() );
685 # Enable top-level headings
686 for ( $node = $stack->rootAccum
->firstNode
; $node; $node = $node->nextSibling
) {
687 if ( isset( $node->name
) && $node->name
=== 'possible-h' ) {
692 $rootNode = new PPNode_Hash_Tree( 'root' );
693 $rootNode->firstChild
= $stack->rootAccum
->firstNode
;
694 $rootNode->lastChild
= $stack->rootAccum
->lastNode
;
698 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . serialize( $rootNode );
699 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
700 wfProfileOut( __METHOD__
.'-cache-miss' );
701 wfProfileOut( __METHOD__
.'-cacheable' );
702 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
705 wfProfileOut( __METHOD__
);
711 * Stack class to help Preprocessor::preprocessToObj()
714 class PPDStack_Hash
extends PPDStack
{
715 function __construct() {
716 $this->elementClass
= 'PPDStackElement_Hash';
717 parent
::__construct();
718 $this->rootAccum
= new PPDAccum_Hash
;
725 class PPDStackElement_Hash
extends PPDStackElement
{
726 function __construct( $data = array() ) {
727 $this->partClass
= 'PPDPart_Hash';
728 parent
::__construct( $data );
732 * Get the accumulator that would result if the close is not found.
734 * @return PPDAccum_Hash
736 function breakSyntax( $openingCount = false ) {
737 if ( $this->open
== "\n" ) {
738 $accum = $this->parts
[0]->out
;
740 if ( $openingCount === false ) {
741 $openingCount = $this->count
;
743 $accum = new PPDAccum_Hash
;
744 $accum->addLiteral( str_repeat( $this->open
, $openingCount ) );
746 foreach ( $this->parts
as $part ) {
750 $accum->addLiteral( '|' );
752 $accum->addAccum( $part->out
);
762 class PPDPart_Hash
extends PPDPart
{
763 function __construct( $out = '' ) {
764 $accum = new PPDAccum_Hash
;
766 $accum->addLiteral( $out );
768 parent
::__construct( $accum );
775 class PPDAccum_Hash
{
776 var $firstNode, $lastNode;
778 function __construct() {
779 $this->firstNode
= $this->lastNode
= false;
783 * Append a string literal
785 function addLiteral( $s ) {
786 if ( $this->lastNode
=== false ) {
787 $this->firstNode
= $this->lastNode
= new PPNode_Hash_Text( $s );
788 } elseif ( $this->lastNode
instanceof PPNode_Hash_Text
) {
789 $this->lastNode
->value
.= $s;
791 $this->lastNode
->nextSibling
= new PPNode_Hash_Text( $s );
792 $this->lastNode
= $this->lastNode
->nextSibling
;
799 function addNode( PPNode
$node ) {
800 if ( $this->lastNode
=== false ) {
801 $this->firstNode
= $this->lastNode
= $node;
803 $this->lastNode
->nextSibling
= $node;
804 $this->lastNode
= $node;
809 * Append a tree node with text contents
811 function addNodeWithText( $name, $value ) {
812 $node = PPNode_Hash_Tree
::newWithText( $name, $value );
813 $this->addNode( $node );
817 * Append a PPAccum_Hash
818 * Takes over ownership of the nodes in the source argument. These nodes may
819 * subsequently be modified, especially nextSibling.
821 function addAccum( $accum ) {
822 if ( $accum->lastNode
=== false ) {
824 } elseif ( $this->lastNode
=== false ) {
825 $this->firstNode
= $accum->firstNode
;
826 $this->lastNode
= $accum->lastNode
;
828 $this->lastNode
->nextSibling
= $accum->firstNode
;
829 $this->lastNode
= $accum->lastNode
;
835 * An expansion frame, used as a context to expand the result of preprocessToObj()
838 class PPFrame_Hash
implements PPFrame
{
857 * Hashtable listing templates which are disallowed for expansion in this frame,
858 * having been encountered previously in parent frames.
863 * Recursion depth of this frame, top = 0
864 * Note that this is NOT the same as expansion depth in expand()
870 * Construct a new preprocessor frame.
871 * @param $preprocessor Preprocessor: the parent preprocessor
873 function __construct( $preprocessor ) {
874 $this->preprocessor
= $preprocessor;
875 $this->parser
= $preprocessor->parser
;
876 $this->title
= $this->parser
->mTitle
;
877 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
878 $this->loopCheckHash
= array();
883 * Create a new child frame
884 * $args is optionally a multi-root PPNode or array containing the template arguments
886 * @param $args PPNode_Hash_Array|array
887 * @param $title Title|bool
889 * @return PPTemplateFrame_Hash
891 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
892 $namedArgs = array();
893 $numberedArgs = array();
894 if ( $title === false ) {
895 $title = $this->title
;
897 if ( $args !== false ) {
898 if ( $args instanceof PPNode_Hash_Array
) {
899 $args = $args->value
;
900 } elseif ( !is_array( $args ) ) {
901 throw new MWException( __METHOD__
. ': $args must be array or PPNode_Hash_Array' );
903 foreach ( $args as $arg ) {
904 $bits = $arg->splitArg();
905 if ( $bits['index'] !== '' ) {
906 // Numbered parameter
907 $index = $bits['index'] - $indexOffset;
908 $numberedArgs[$index] = $bits['value'];
909 unset( $namedArgs[$index] );
912 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
913 $namedArgs[$name] = $bits['value'];
914 unset( $numberedArgs[$name] );
918 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
922 * @throws MWException
927 function expand( $root, $flags = 0 ) {
928 static $expansionDepth = 0;
929 if ( is_string( $root ) ) {
933 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
934 $this->parser
->limitationWarn( 'node-count-exceeded',
935 $this->parser
->mPPNodeCount
,
936 $this->parser
->mOptions
->getMaxPPNodeCount()
938 return '<span class="error">Node-count limit exceeded</span>';
940 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
941 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
943 $this->parser
->mOptions
->getMaxPPExpandDepth()
945 return '<span class="error">Expansion depth limit exceeded</span>';
948 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
949 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
952 $outStack = array( '', '' );
953 $iteratorStack = array( false, $root );
954 $indexStack = array( 0, 0 );
956 while ( count( $iteratorStack ) > 1 ) {
957 $level = count( $outStack ) - 1;
958 $iteratorNode =& $iteratorStack[ $level ];
959 $out =& $outStack[$level];
960 $index =& $indexStack[$level];
962 if ( is_array( $iteratorNode ) ) {
963 if ( $index >= count( $iteratorNode ) ) {
964 // All done with this iterator
965 $iteratorStack[$level] = false;
966 $contextNode = false;
968 $contextNode = $iteratorNode[$index];
971 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
972 if ( $index >= $iteratorNode->getLength() ) {
973 // All done with this iterator
974 $iteratorStack[$level] = false;
975 $contextNode = false;
977 $contextNode = $iteratorNode->item( $index );
981 // Copy to $contextNode and then delete from iterator stack,
982 // because this is not an iterator but we do have to execute it once
983 $contextNode = $iteratorStack[$level];
984 $iteratorStack[$level] = false;
987 $newIterator = false;
989 if ( $contextNode === false ) {
991 } elseif ( is_string( $contextNode ) ) {
992 $out .= $contextNode;
993 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
994 $newIterator = $contextNode;
995 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
997 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
998 $out .= $contextNode->value
;
999 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
1000 if ( $contextNode->name
== 'template' ) {
1001 # Double-brace expansion
1002 $bits = $contextNode->splitTemplate();
1003 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1004 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
1006 $ret = $this->parser
->braceSubstitution( $bits, $this );
1007 if ( isset( $ret['object'] ) ) {
1008 $newIterator = $ret['object'];
1010 $out .= $ret['text'];
1013 } elseif ( $contextNode->name
== 'tplarg' ) {
1014 # Triple-brace expansion
1015 $bits = $contextNode->splitTemplate();
1016 if ( $flags & PPFrame
::NO_ARGS
) {
1017 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1019 $ret = $this->parser
->argSubstitution( $bits, $this );
1020 if ( isset( $ret['object'] ) ) {
1021 $newIterator = $ret['object'];
1023 $out .= $ret['text'];
1026 } elseif ( $contextNode->name
== 'comment' ) {
1027 # HTML-style comment
1028 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1029 if ( $this->parser
->ot
['html']
1030 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1031 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1035 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1036 # Not in RECOVER_COMMENTS mode (extractSections) though
1037 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1038 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1040 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1042 $out .= $contextNode->firstChild
->value
;
1044 } elseif ( $contextNode->name
== 'ignore' ) {
1045 # Output suppression used by <includeonly> etc.
1046 # OT_WIKI will only respect <ignore> in substed templates.
1047 # The other output types respect it unless NO_IGNORE is set.
1048 # extractSections() sets NO_IGNORE and so never respects it.
1049 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1050 $out .= $contextNode->firstChild
->value
;
1054 } elseif ( $contextNode->name
== 'ext' ) {
1056 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1057 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1058 } elseif ( $contextNode->name
== 'h' ) {
1060 if ( $this->parser
->ot
['html'] ) {
1061 # Expand immediately and insert heading index marker
1063 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1064 $s .= $this->expand( $node, $flags );
1067 $bits = $contextNode->splitHeading();
1068 $titleText = $this->title
->getPrefixedDBkey();
1069 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1070 $serial = count( $this->parser
->mHeadings
) - 1;
1071 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1072 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1073 $this->parser
->mStripState
->addGeneral( $marker, '' );
1076 # Expand in virtual stack
1077 $newIterator = $contextNode->getChildren();
1080 # Generic recursive expansion
1081 $newIterator = $contextNode->getChildren();
1084 throw new MWException( __METHOD__
.': Invalid parameter type' );
1087 if ( $newIterator !== false ) {
1089 $iteratorStack[] = $newIterator;
1091 } elseif ( $iteratorStack[$level] === false ) {
1092 // Return accumulated value to parent
1093 // With tail recursion
1094 while ( $iteratorStack[$level] === false && $level > 0 ) {
1095 $outStack[$level - 1] .= $out;
1096 array_pop( $outStack );
1097 array_pop( $iteratorStack );
1098 array_pop( $indexStack );
1104 return $outStack[0];
1112 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1113 $args = array_slice( func_get_args(), 2 );
1117 foreach ( $args as $root ) {
1118 if ( $root instanceof PPNode_Hash_Array
) {
1119 $root = $root->value
;
1121 if ( !is_array( $root ) ) {
1122 $root = array( $root );
1124 foreach ( $root as $node ) {
1130 $s .= $this->expand( $node, $flags );
1137 * Implode with no flags specified
1138 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1141 function implode( $sep /*, ... */ ) {
1142 $args = array_slice( func_get_args(), 1 );
1146 foreach ( $args as $root ) {
1147 if ( $root instanceof PPNode_Hash_Array
) {
1148 $root = $root->value
;
1150 if ( !is_array( $root ) ) {
1151 $root = array( $root );
1153 foreach ( $root as $node ) {
1159 $s .= $this->expand( $node );
1166 * Makes an object that, when expand()ed, will be the same as one obtained
1169 * @return PPNode_Hash_Array
1171 function virtualImplode( $sep /*, ... */ ) {
1172 $args = array_slice( func_get_args(), 1 );
1176 foreach ( $args as $root ) {
1177 if ( $root instanceof PPNode_Hash_Array
) {
1178 $root = $root->value
;
1180 if ( !is_array( $root ) ) {
1181 $root = array( $root );
1183 foreach ( $root as $node ) {
1192 return new PPNode_Hash_Array( $out );
1196 * Virtual implode with brackets
1198 * @return PPNode_Hash_Array
1200 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1201 $args = array_slice( func_get_args(), 3 );
1202 $out = array( $start );
1205 foreach ( $args as $root ) {
1206 if ( $root instanceof PPNode_Hash_Array
) {
1207 $root = $root->value
;
1209 if ( !is_array( $root ) ) {
1210 $root = array( $root );
1212 foreach ( $root as $node ) {
1222 return new PPNode_Hash_Array( $out );
1225 function __toString() {
1230 * @param $level bool
1231 * @return array|bool|String
1233 function getPDBK( $level = false ) {
1234 if ( $level === false ) {
1235 return $this->title
->getPrefixedDBkey();
1237 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1244 function getArguments() {
1251 function getNumberedArguments() {
1258 function getNamedArguments() {
1263 * Returns true if there are no arguments in this frame
1267 function isEmpty() {
1275 function getArgument( $name ) {
1280 * Returns true if the infinite loop check is OK, false if a loop is detected
1282 * @param $title Title
1286 function loopCheck( $title ) {
1287 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1291 * Return true if the frame is a template frame
1295 function isTemplate() {
1300 * Get a title of frame
1304 function getTitle() {
1305 return $this->title
;
1310 * Expansion frame with template arguments
1313 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1314 var $numberedArgs, $namedArgs, $parent;
1315 var $numberedExpansionCache, $namedExpansionCache;
1318 * @param $preprocessor
1320 * @param $numberedArgs array
1321 * @param $namedArgs array
1322 * @param $title Title
1324 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1325 parent
::__construct( $preprocessor );
1327 $this->parent
= $parent;
1328 $this->numberedArgs
= $numberedArgs;
1329 $this->namedArgs
= $namedArgs;
1330 $this->title
= $title;
1331 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1332 $this->titleCache
= $parent->titleCache
;
1333 $this->titleCache
[] = $pdbk;
1334 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1335 if ( $pdbk !== false ) {
1336 $this->loopCheckHash
[$pdbk] = true;
1338 $this->depth
= $parent->depth +
1;
1339 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1342 function __toString() {
1345 $args = $this->numberedArgs +
$this->namedArgs
;
1346 foreach ( $args as $name => $value ) {
1352 $s .= "\"$name\":\"" .
1353 str_replace( '"', '\\"', $value->__toString() ) . '"';
1359 * Returns true if there are no arguments in this frame
1363 function isEmpty() {
1364 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1370 function getArguments() {
1371 $arguments = array();
1372 foreach ( array_merge(
1373 array_keys($this->numberedArgs
),
1374 array_keys($this->namedArgs
)) as $key ) {
1375 $arguments[$key] = $this->getArgument($key);
1383 function getNumberedArguments() {
1384 $arguments = array();
1385 foreach ( array_keys($this->numberedArgs
) as $key ) {
1386 $arguments[$key] = $this->getArgument($key);
1394 function getNamedArguments() {
1395 $arguments = array();
1396 foreach ( array_keys($this->namedArgs
) as $key ) {
1397 $arguments[$key] = $this->getArgument($key);
1404 * @return array|bool
1406 function getNumberedArgument( $index ) {
1407 if ( !isset( $this->numberedArgs
[$index] ) ) {
1410 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1411 # No trimming for unnamed arguments
1412 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1414 return $this->numberedExpansionCache
[$index];
1421 function getNamedArgument( $name ) {
1422 if ( !isset( $this->namedArgs
[$name] ) ) {
1425 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1426 # Trim named arguments post-expand, for backwards compatibility
1427 $this->namedExpansionCache
[$name] = trim(
1428 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1430 return $this->namedExpansionCache
[$name];
1435 * @return array|bool
1437 function getArgument( $name ) {
1438 $text = $this->getNumberedArgument( $name );
1439 if ( $text === false ) {
1440 $text = $this->getNamedArgument( $name );
1446 * Return true if the frame is a template frame
1450 function isTemplate() {
1456 * Expansion frame with custom arguments
1459 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1462 function __construct( $preprocessor, $args ) {
1463 parent
::__construct( $preprocessor );
1464 $this->args
= $args;
1467 function __toString() {
1470 foreach ( $this->args
as $name => $value ) {
1476 $s .= "\"$name\":\"" .
1477 str_replace( '"', '\\"', $value->__toString() ) . '"';
1486 function isEmpty() {
1487 return !count( $this->args
);
1494 function getArgument( $index ) {
1495 if ( !isset( $this->args
[$index] ) ) {
1498 return $this->args
[$index];
1501 function getArguments() {
1509 class PPNode_Hash_Tree
implements PPNode
{
1510 var $name, $firstChild, $lastChild, $nextSibling;
1512 function __construct( $name ) {
1513 $this->name
= $name;
1514 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1517 function __toString() {
1520 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1521 if ( $node instanceof PPNode_Hash_Attr
) {
1522 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1524 $inner .= $node->__toString();
1527 if ( $inner === '' ) {
1528 return "<{$this->name}$attribs/>";
1530 return "<{$this->name}$attribs>$inner</{$this->name}>";
1537 * @return PPNode_Hash_Tree
1539 static function newWithText( $name, $text ) {
1540 $obj = new self( $name );
1541 $obj->addChild( new PPNode_Hash_Text( $text ) );
1545 function addChild( $node ) {
1546 if ( $this->lastChild
=== false ) {
1547 $this->firstChild
= $this->lastChild
= $node;
1549 $this->lastChild
->nextSibling
= $node;
1550 $this->lastChild
= $node;
1555 * @return PPNode_Hash_Array
1557 function getChildren() {
1558 $children = array();
1559 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1560 $children[] = $child;
1562 return new PPNode_Hash_Array( $children );
1565 function getFirstChild() {
1566 return $this->firstChild
;
1569 function getNextSibling() {
1570 return $this->nextSibling
;
1573 function getChildrenOfType( $name ) {
1574 $children = array();
1575 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1576 if ( isset( $child->name
) && $child->name
=== $name ) {
1577 $children[] = $name;
1586 function getLength() {
1594 function item( $i ) {
1601 function getName() {
1606 * Split a <part> node into an associative array containing:
1608 * index String index
1609 * value PPNode value
1613 function splitArg() {
1615 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1616 if ( !isset( $child->name
) ) {
1619 if ( $child->name
=== 'name' ) {
1620 $bits['name'] = $child;
1621 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1622 && $child->firstChild
->name
=== 'index' )
1624 $bits['index'] = $child->firstChild
->value
;
1626 } elseif ( $child->name
=== 'value' ) {
1627 $bits['value'] = $child;
1631 if ( !isset( $bits['name'] ) ) {
1632 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1634 if ( !isset( $bits['index'] ) ) {
1635 $bits['index'] = '';
1641 * Split an <ext> node into an associative array containing name, attr, inner and close
1642 * All values in the resulting array are PPNodes. Inner and close are optional.
1646 function splitExt() {
1648 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1649 if ( !isset( $child->name
) ) {
1652 if ( $child->name
== 'name' ) {
1653 $bits['name'] = $child;
1654 } elseif ( $child->name
== 'attr' ) {
1655 $bits['attr'] = $child;
1656 } elseif ( $child->name
== 'inner' ) {
1657 $bits['inner'] = $child;
1658 } elseif ( $child->name
== 'close' ) {
1659 $bits['close'] = $child;
1662 if ( !isset( $bits['name'] ) ) {
1663 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1673 function splitHeading() {
1674 if ( $this->name
!== 'h' ) {
1675 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1678 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1679 if ( !isset( $child->name
) ) {
1682 if ( $child->name
== 'i' ) {
1683 $bits['i'] = $child->value
;
1684 } elseif ( $child->name
== 'level' ) {
1685 $bits['level'] = $child->value
;
1688 if ( !isset( $bits['i'] ) ) {
1689 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1695 * Split a <template> or <tplarg> node
1699 function splitTemplate() {
1701 $bits = array( 'lineStart' => '' );
1702 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1703 if ( !isset( $child->name
) ) {
1706 if ( $child->name
== 'title' ) {
1707 $bits['title'] = $child;
1709 if ( $child->name
== 'part' ) {
1712 if ( $child->name
== 'lineStart' ) {
1713 $bits['lineStart'] = '1';
1716 if ( !isset( $bits['title'] ) ) {
1717 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1719 $bits['parts'] = new PPNode_Hash_Array( $parts );
1727 class PPNode_Hash_Text
implements PPNode
{
1728 var $value, $nextSibling;
1730 function __construct( $value ) {
1731 if ( is_object( $value ) ) {
1732 throw new MWException( __CLASS__
. ' given object instead of string' );
1734 $this->value
= $value;
1737 function __toString() {
1738 return htmlspecialchars( $this->value
);
1741 function getNextSibling() {
1742 return $this->nextSibling
;
1745 function getChildren() { return false; }
1746 function getFirstChild() { return false; }
1747 function getChildrenOfType( $name ) { return false; }
1748 function getLength() { return false; }
1749 function item( $i ) { return false; }
1750 function getName() { return '#text'; }
1751 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1752 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1753 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1759 class PPNode_Hash_Array
implements PPNode
{
1760 var $value, $nextSibling;
1762 function __construct( $value ) {
1763 $this->value
= $value;
1766 function __toString() {
1767 return var_export( $this, true );
1770 function getLength() {
1771 return count( $this->value
);
1774 function item( $i ) {
1775 return $this->value
[$i];
1778 function getName() { return '#nodelist'; }
1780 function getNextSibling() {
1781 return $this->nextSibling
;
1784 function getChildren() { return false; }
1785 function getFirstChild() { return false; }
1786 function getChildrenOfType( $name ) { return false; }
1787 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1788 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1789 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1795 class PPNode_Hash_Attr
implements PPNode
{
1796 var $name, $value, $nextSibling;
1798 function __construct( $name, $value ) {
1799 $this->name
= $name;
1800 $this->value
= $value;
1803 function __toString() {
1804 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1807 function getName() {
1811 function getNextSibling() {
1812 return $this->nextSibling
;
1815 function getChildren() { return false; }
1816 function getFirstChild() { return false; }
1817 function getChildrenOfType( $name ) { return false; }
1818 function getLength() { return false; }
1819 function item( $i ) { return false; }
1820 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1821 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1822 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }