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 ) {
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 $numberedArgs[$bits['index']] = $bits['value'];
908 unset( $namedArgs[$bits['index']] );
911 $name = trim( $this->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
912 $namedArgs[$name] = $bits['value'];
913 unset( $numberedArgs[$name] );
917 return new PPTemplateFrame_Hash( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
921 * @throws MWException
926 function expand( $root, $flags = 0 ) {
927 static $expansionDepth = 0;
928 if ( is_string( $root ) ) {
932 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
933 $this->parser
->limitationWarn( 'node-count-exceeded',
934 $this->parser
->mPPNodeCount
,
935 $this->parser
->mOptions
->getMaxPPNodeCount()
937 return '<span class="error">Node-count limit exceeded</span>';
939 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
940 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
942 $this->parser
->mOptions
->getMaxPPExpandDepth()
944 return '<span class="error">Expansion depth limit exceeded</span>';
947 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
948 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
951 $outStack = array( '', '' );
952 $iteratorStack = array( false, $root );
953 $indexStack = array( 0, 0 );
955 while ( count( $iteratorStack ) > 1 ) {
956 $level = count( $outStack ) - 1;
957 $iteratorNode =& $iteratorStack[ $level ];
958 $out =& $outStack[$level];
959 $index =& $indexStack[$level];
961 if ( is_array( $iteratorNode ) ) {
962 if ( $index >= count( $iteratorNode ) ) {
963 // All done with this iterator
964 $iteratorStack[$level] = false;
965 $contextNode = false;
967 $contextNode = $iteratorNode[$index];
970 } elseif ( $iteratorNode instanceof PPNode_Hash_Array
) {
971 if ( $index >= $iteratorNode->getLength() ) {
972 // All done with this iterator
973 $iteratorStack[$level] = false;
974 $contextNode = false;
976 $contextNode = $iteratorNode->item( $index );
980 // Copy to $contextNode and then delete from iterator stack,
981 // because this is not an iterator but we do have to execute it once
982 $contextNode = $iteratorStack[$level];
983 $iteratorStack[$level] = false;
986 $newIterator = false;
988 if ( $contextNode === false ) {
990 } elseif ( is_string( $contextNode ) ) {
991 $out .= $contextNode;
992 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof PPNode_Hash_Array
) {
993 $newIterator = $contextNode;
994 } elseif ( $contextNode instanceof PPNode_Hash_Attr
) {
996 } elseif ( $contextNode instanceof PPNode_Hash_Text
) {
997 $out .= $contextNode->value
;
998 } elseif ( $contextNode instanceof PPNode_Hash_Tree
) {
999 if ( $contextNode->name
== 'template' ) {
1000 # Double-brace expansion
1001 $bits = $contextNode->splitTemplate();
1002 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1003 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
1005 $ret = $this->parser
->braceSubstitution( $bits, $this );
1006 if ( isset( $ret['object'] ) ) {
1007 $newIterator = $ret['object'];
1009 $out .= $ret['text'];
1012 } elseif ( $contextNode->name
== 'tplarg' ) {
1013 # Triple-brace expansion
1014 $bits = $contextNode->splitTemplate();
1015 if ( $flags & PPFrame
::NO_ARGS
) {
1016 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1018 $ret = $this->parser
->argSubstitution( $bits, $this );
1019 if ( isset( $ret['object'] ) ) {
1020 $newIterator = $ret['object'];
1022 $out .= $ret['text'];
1025 } elseif ( $contextNode->name
== 'comment' ) {
1026 # HTML-style comment
1027 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1028 if ( $this->parser
->ot
['html']
1029 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1030 ||
( $flags & PPFrame
::STRIP_COMMENTS
) )
1034 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1035 # Not in RECOVER_COMMENTS mode (extractSections) though
1036 elseif ( $this->parser
->ot
['wiki'] && ! ( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1037 $out .= $this->parser
->insertStripItem( $contextNode->firstChild
->value
);
1039 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1041 $out .= $contextNode->firstChild
->value
;
1043 } elseif ( $contextNode->name
== 'ignore' ) {
1044 # Output suppression used by <includeonly> etc.
1045 # OT_WIKI will only respect <ignore> in substed templates.
1046 # The other output types respect it unless NO_IGNORE is set.
1047 # extractSections() sets NO_IGNORE and so never respects it.
1048 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & PPFrame
::NO_IGNORE
) ) {
1049 $out .= $contextNode->firstChild
->value
;
1053 } elseif ( $contextNode->name
== 'ext' ) {
1055 $bits = $contextNode->splitExt() +
array( 'attr' => null, 'inner' => null, 'close' => null );
1056 $out .= $this->parser
->extensionSubstitution( $bits, $this );
1057 } elseif ( $contextNode->name
== 'h' ) {
1059 if ( $this->parser
->ot
['html'] ) {
1060 # Expand immediately and insert heading index marker
1062 for ( $node = $contextNode->firstChild
; $node; $node = $node->nextSibling
) {
1063 $s .= $this->expand( $node, $flags );
1066 $bits = $contextNode->splitHeading();
1067 $titleText = $this->title
->getPrefixedDBkey();
1068 $this->parser
->mHeadings
[] = array( $titleText, $bits['i'] );
1069 $serial = count( $this->parser
->mHeadings
) - 1;
1070 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1071 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1072 $this->parser
->mStripState
->addGeneral( $marker, '' );
1075 # Expand in virtual stack
1076 $newIterator = $contextNode->getChildren();
1079 # Generic recursive expansion
1080 $newIterator = $contextNode->getChildren();
1083 throw new MWException( __METHOD__
.': Invalid parameter type' );
1086 if ( $newIterator !== false ) {
1088 $iteratorStack[] = $newIterator;
1090 } elseif ( $iteratorStack[$level] === false ) {
1091 // Return accumulated value to parent
1092 // With tail recursion
1093 while ( $iteratorStack[$level] === false && $level > 0 ) {
1094 $outStack[$level - 1] .= $out;
1095 array_pop( $outStack );
1096 array_pop( $iteratorStack );
1097 array_pop( $indexStack );
1103 return $outStack[0];
1111 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1112 $args = array_slice( func_get_args(), 2 );
1116 foreach ( $args as $root ) {
1117 if ( $root instanceof PPNode_Hash_Array
) {
1118 $root = $root->value
;
1120 if ( !is_array( $root ) ) {
1121 $root = array( $root );
1123 foreach ( $root as $node ) {
1129 $s .= $this->expand( $node, $flags );
1136 * Implode with no flags specified
1137 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1140 function implode( $sep /*, ... */ ) {
1141 $args = array_slice( func_get_args(), 1 );
1145 foreach ( $args as $root ) {
1146 if ( $root instanceof PPNode_Hash_Array
) {
1147 $root = $root->value
;
1149 if ( !is_array( $root ) ) {
1150 $root = array( $root );
1152 foreach ( $root as $node ) {
1158 $s .= $this->expand( $node );
1165 * Makes an object that, when expand()ed, will be the same as one obtained
1168 * @return PPNode_Hash_Array
1170 function virtualImplode( $sep /*, ... */ ) {
1171 $args = array_slice( func_get_args(), 1 );
1175 foreach ( $args as $root ) {
1176 if ( $root instanceof PPNode_Hash_Array
) {
1177 $root = $root->value
;
1179 if ( !is_array( $root ) ) {
1180 $root = array( $root );
1182 foreach ( $root as $node ) {
1191 return new PPNode_Hash_Array( $out );
1195 * Virtual implode with brackets
1197 * @return PPNode_Hash_Array
1199 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1200 $args = array_slice( func_get_args(), 3 );
1201 $out = array( $start );
1204 foreach ( $args as $root ) {
1205 if ( $root instanceof PPNode_Hash_Array
) {
1206 $root = $root->value
;
1208 if ( !is_array( $root ) ) {
1209 $root = array( $root );
1211 foreach ( $root as $node ) {
1221 return new PPNode_Hash_Array( $out );
1224 function __toString() {
1229 * @param $level bool
1230 * @return array|bool|String
1232 function getPDBK( $level = false ) {
1233 if ( $level === false ) {
1234 return $this->title
->getPrefixedDBkey();
1236 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1243 function getArguments() {
1250 function getNumberedArguments() {
1257 function getNamedArguments() {
1262 * Returns true if there are no arguments in this frame
1266 function isEmpty() {
1274 function getArgument( $name ) {
1279 * Returns true if the infinite loop check is OK, false if a loop is detected
1281 * @param $title Title
1285 function loopCheck( $title ) {
1286 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1290 * Return true if the frame is a template frame
1294 function isTemplate() {
1299 * Get a title of frame
1303 function getTitle() {
1304 return $this->title
;
1309 * Expansion frame with template arguments
1312 class PPTemplateFrame_Hash
extends PPFrame_Hash
{
1313 var $numberedArgs, $namedArgs, $parent;
1314 var $numberedExpansionCache, $namedExpansionCache;
1317 * @param $preprocessor
1319 * @param $numberedArgs array
1320 * @param $namedArgs array
1321 * @param $title Title
1323 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1324 parent
::__construct( $preprocessor );
1326 $this->parent
= $parent;
1327 $this->numberedArgs
= $numberedArgs;
1328 $this->namedArgs
= $namedArgs;
1329 $this->title
= $title;
1330 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1331 $this->titleCache
= $parent->titleCache
;
1332 $this->titleCache
[] = $pdbk;
1333 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1334 if ( $pdbk !== false ) {
1335 $this->loopCheckHash
[$pdbk] = true;
1337 $this->depth
= $parent->depth +
1;
1338 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1341 function __toString() {
1344 $args = $this->numberedArgs +
$this->namedArgs
;
1345 foreach ( $args as $name => $value ) {
1351 $s .= "\"$name\":\"" .
1352 str_replace( '"', '\\"', $value->__toString() ) . '"';
1358 * Returns true if there are no arguments in this frame
1362 function isEmpty() {
1363 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1369 function getArguments() {
1370 $arguments = array();
1371 foreach ( array_merge(
1372 array_keys($this->numberedArgs
),
1373 array_keys($this->namedArgs
)) as $key ) {
1374 $arguments[$key] = $this->getArgument($key);
1382 function getNumberedArguments() {
1383 $arguments = array();
1384 foreach ( array_keys($this->numberedArgs
) as $key ) {
1385 $arguments[$key] = $this->getArgument($key);
1393 function getNamedArguments() {
1394 $arguments = array();
1395 foreach ( array_keys($this->namedArgs
) as $key ) {
1396 $arguments[$key] = $this->getArgument($key);
1403 * @return array|bool
1405 function getNumberedArgument( $index ) {
1406 if ( !isset( $this->numberedArgs
[$index] ) ) {
1409 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1410 # No trimming for unnamed arguments
1411 $this->numberedExpansionCache
[$index] = $this->parent
->expand( $this->numberedArgs
[$index], PPFrame
::STRIP_COMMENTS
);
1413 return $this->numberedExpansionCache
[$index];
1420 function getNamedArgument( $name ) {
1421 if ( !isset( $this->namedArgs
[$name] ) ) {
1424 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1425 # Trim named arguments post-expand, for backwards compatibility
1426 $this->namedExpansionCache
[$name] = trim(
1427 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1429 return $this->namedExpansionCache
[$name];
1434 * @return array|bool
1436 function getArgument( $name ) {
1437 $text = $this->getNumberedArgument( $name );
1438 if ( $text === false ) {
1439 $text = $this->getNamedArgument( $name );
1445 * Return true if the frame is a template frame
1449 function isTemplate() {
1455 * Expansion frame with custom arguments
1458 class PPCustomFrame_Hash
extends PPFrame_Hash
{
1461 function __construct( $preprocessor, $args ) {
1462 parent
::__construct( $preprocessor );
1463 $this->args
= $args;
1466 function __toString() {
1469 foreach ( $this->args
as $name => $value ) {
1475 $s .= "\"$name\":\"" .
1476 str_replace( '"', '\\"', $value->__toString() ) . '"';
1485 function isEmpty() {
1486 return !count( $this->args
);
1493 function getArgument( $index ) {
1494 if ( !isset( $this->args
[$index] ) ) {
1497 return $this->args
[$index];
1504 class PPNode_Hash_Tree
implements PPNode
{
1505 var $name, $firstChild, $lastChild, $nextSibling;
1507 function __construct( $name ) {
1508 $this->name
= $name;
1509 $this->firstChild
= $this->lastChild
= $this->nextSibling
= false;
1512 function __toString() {
1515 for ( $node = $this->firstChild
; $node; $node = $node->nextSibling
) {
1516 if ( $node instanceof PPNode_Hash_Attr
) {
1517 $attribs .= ' ' . $node->name
. '="' . htmlspecialchars( $node->value
) . '"';
1519 $inner .= $node->__toString();
1522 if ( $inner === '' ) {
1523 return "<{$this->name}$attribs/>";
1525 return "<{$this->name}$attribs>$inner</{$this->name}>";
1532 * @return PPNode_Hash_Tree
1534 static function newWithText( $name, $text ) {
1535 $obj = new self( $name );
1536 $obj->addChild( new PPNode_Hash_Text( $text ) );
1540 function addChild( $node ) {
1541 if ( $this->lastChild
=== false ) {
1542 $this->firstChild
= $this->lastChild
= $node;
1544 $this->lastChild
->nextSibling
= $node;
1545 $this->lastChild
= $node;
1550 * @return PPNode_Hash_Array
1552 function getChildren() {
1553 $children = array();
1554 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1555 $children[] = $child;
1557 return new PPNode_Hash_Array( $children );
1560 function getFirstChild() {
1561 return $this->firstChild
;
1564 function getNextSibling() {
1565 return $this->nextSibling
;
1568 function getChildrenOfType( $name ) {
1569 $children = array();
1570 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1571 if ( isset( $child->name
) && $child->name
=== $name ) {
1572 $children[] = $name;
1581 function getLength() {
1589 function item( $i ) {
1596 function getName() {
1601 * Split a <part> node into an associative array containing:
1603 * index String index
1604 * value PPNode value
1608 function splitArg() {
1610 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1611 if ( !isset( $child->name
) ) {
1614 if ( $child->name
=== 'name' ) {
1615 $bits['name'] = $child;
1616 if ( $child->firstChild
instanceof PPNode_Hash_Attr
1617 && $child->firstChild
->name
=== 'index' )
1619 $bits['index'] = $child->firstChild
->value
;
1621 } elseif ( $child->name
=== 'value' ) {
1622 $bits['value'] = $child;
1626 if ( !isset( $bits['name'] ) ) {
1627 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1629 if ( !isset( $bits['index'] ) ) {
1630 $bits['index'] = '';
1636 * Split an <ext> node into an associative array containing name, attr, inner and close
1637 * All values in the resulting array are PPNodes. Inner and close are optional.
1641 function splitExt() {
1643 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1644 if ( !isset( $child->name
) ) {
1647 if ( $child->name
== 'name' ) {
1648 $bits['name'] = $child;
1649 } elseif ( $child->name
== 'attr' ) {
1650 $bits['attr'] = $child;
1651 } elseif ( $child->name
== 'inner' ) {
1652 $bits['inner'] = $child;
1653 } elseif ( $child->name
== 'close' ) {
1654 $bits['close'] = $child;
1657 if ( !isset( $bits['name'] ) ) {
1658 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1668 function splitHeading() {
1669 if ( $this->name
!== 'h' ) {
1670 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1673 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1674 if ( !isset( $child->name
) ) {
1677 if ( $child->name
== 'i' ) {
1678 $bits['i'] = $child->value
;
1679 } elseif ( $child->name
== 'level' ) {
1680 $bits['level'] = $child->value
;
1683 if ( !isset( $bits['i'] ) ) {
1684 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1690 * Split a <template> or <tplarg> node
1694 function splitTemplate() {
1696 $bits = array( 'lineStart' => '' );
1697 for ( $child = $this->firstChild
; $child; $child = $child->nextSibling
) {
1698 if ( !isset( $child->name
) ) {
1701 if ( $child->name
== 'title' ) {
1702 $bits['title'] = $child;
1704 if ( $child->name
== 'part' ) {
1707 if ( $child->name
== 'lineStart' ) {
1708 $bits['lineStart'] = '1';
1711 if ( !isset( $bits['title'] ) ) {
1712 throw new MWException( 'Invalid node passed to ' . __METHOD__
);
1714 $bits['parts'] = new PPNode_Hash_Array( $parts );
1722 class PPNode_Hash_Text
implements PPNode
{
1723 var $value, $nextSibling;
1725 function __construct( $value ) {
1726 if ( is_object( $value ) ) {
1727 throw new MWException( __CLASS__
. ' given object instead of string' );
1729 $this->value
= $value;
1732 function __toString() {
1733 return htmlspecialchars( $this->value
);
1736 function getNextSibling() {
1737 return $this->nextSibling
;
1740 function getChildren() { return false; }
1741 function getFirstChild() { return false; }
1742 function getChildrenOfType( $name ) { return false; }
1743 function getLength() { return false; }
1744 function item( $i ) { return false; }
1745 function getName() { return '#text'; }
1746 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1747 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1748 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1754 class PPNode_Hash_Array
implements PPNode
{
1755 var $value, $nextSibling;
1757 function __construct( $value ) {
1758 $this->value
= $value;
1761 function __toString() {
1762 return var_export( $this, true );
1765 function getLength() {
1766 return count( $this->value
);
1769 function item( $i ) {
1770 return $this->value
[$i];
1773 function getName() { return '#nodelist'; }
1775 function getNextSibling() {
1776 return $this->nextSibling
;
1779 function getChildren() { return false; }
1780 function getFirstChild() { return false; }
1781 function getChildrenOfType( $name ) { return false; }
1782 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1783 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1784 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }
1790 class PPNode_Hash_Attr
implements PPNode
{
1791 var $name, $value, $nextSibling;
1793 function __construct( $name, $value ) {
1794 $this->name
= $name;
1795 $this->value
= $value;
1798 function __toString() {
1799 return "<@{$this->name}>" . htmlspecialchars( $this->value
) . "</@{$this->name}>";
1802 function getName() {
1806 function getNextSibling() {
1807 return $this->nextSibling
;
1810 function getChildren() { return false; }
1811 function getFirstChild() { return false; }
1812 function getChildrenOfType( $name ) { return false; }
1813 function getLength() { return false; }
1814 function item( $i ) { return false; }
1815 function splitArg() { throw new MWException( __METHOD__
. ': not supported' ); }
1816 function splitExt() { throw new MWException( __METHOD__
. ': not supported' ); }
1817 function splitHeading() { throw new MWException( __METHOD__
. ': not supported' ); }