(bug 19441) Updated date formatting for Lithuanian
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob2e1145459cbfd3e4e0275d3635a5d44ca52f0b67
1 <?php
3 /**
4 * @ingroup Parser
5 */
6 class Preprocessor_DOM implements Preprocessor {
7 var $parser, $memoryLimit;
9 const CACHE_VERSION = 1;
11 function __construct( $parser ) {
12 $this->parser = $parser;
13 $mem = ini_get( 'memory_limit' );
14 $this->memoryLimit = false;
15 if ( strval( $mem ) !== '' && $mem != -1 ) {
16 if ( preg_match( '/^\d+$/', $mem ) ) {
17 $this->memoryLimit = $mem;
18 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
19 $this->memoryLimit = $m[1] * 1048576;
24 function newFrame() {
25 return new PPFrame_DOM( $this );
28 function newCustomFrame( $args ) {
29 return new PPCustomFrame_DOM( $this, $args );
32 function memCheck() {
33 if ( $this->memoryLimit === false ) {
34 return;
36 $usage = memory_get_usage();
37 if ( $usage > $this->memoryLimit * 0.9 ) {
38 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
39 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
41 return $usage <= $this->memoryLimit * 0.8;
44 /**
45 * Preprocess some wikitext and return the document tree.
46 * This is the ghost of Parser::replace_variables().
48 * @param string $text The text to parse
49 * @param integer flags Bitwise combination of:
50 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
51 * included. Default is to assume a direct page view.
53 * The generated DOM tree must depend only on the input text and the flags.
54 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
56 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
57 * change in the DOM tree for a given text, must be passed through the section identifier
58 * in the section edit link and thus back to extractSections().
60 * The output of this function is currently only cached in process memory, but a persistent
61 * cache may be implemented at a later date which takes further advantage of these strict
62 * dependency requirements.
64 * @private
66 function preprocessToObj( $text, $flags = 0 ) {
67 wfProfileIn( __METHOD__ );
68 global $wgMemc, $wgPreprocessorCacheThreshold;
70 $xml = false;
71 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
72 if ( $cacheable ) {
73 wfProfileIn( __METHOD__.'-cacheable' );
75 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
76 $cacheValue = $wgMemc->get( $cacheKey );
77 if ( $cacheValue ) {
78 $version = substr( $cacheValue, 0, 8 );
79 if ( intval( $version ) == self::CACHE_VERSION ) {
80 $xml = substr( $cacheValue, 8 );
81 // From the cache
82 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
86 if ( $xml === false ) {
87 if ( $cacheable ) {
88 wfProfileIn( __METHOD__.'-cache-miss' );
89 $xml = $this->preprocessToXml( $text, $flags );
90 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
91 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
92 wfProfileOut( __METHOD__.'-cache-miss' );
93 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
94 } else {
95 $xml = $this->preprocessToXml( $text, $flags );
99 wfProfileIn( __METHOD__.'-loadXML' );
100 $dom = new DOMDocument;
101 wfSuppressWarnings();
102 $result = $dom->loadXML( $xml );
103 wfRestoreWarnings();
104 if ( !$result ) {
105 // Try running the XML through UtfNormal to get rid of invalid characters
106 $xml = UtfNormal::cleanUp( $xml );
107 $result = $dom->loadXML( $xml );
108 if ( !$result ) {
109 throw new MWException( __METHOD__.' generated invalid XML' );
112 $obj = new PPNode_DOM( $dom->documentElement );
113 wfProfileOut( __METHOD__.'-loadXML' );
114 if ( $cacheable ) {
115 wfProfileOut( __METHOD__.'-cacheable' );
117 wfProfileOut( __METHOD__ );
118 return $obj;
121 function preprocessToXml( $text, $flags = 0 ) {
122 wfProfileIn( __METHOD__ );
123 $rules = array(
124 '{' => array(
125 'end' => '}',
126 'names' => array(
127 2 => 'template',
128 3 => 'tplarg',
130 'min' => 2,
131 'max' => 3,
133 '[' => array(
134 'end' => ']',
135 'names' => array( 2 => null ),
136 'min' => 2,
137 'max' => 2,
141 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
143 $xmlishElements = $this->parser->getStripList();
144 $enableOnlyinclude = false;
145 if ( $forInclusion ) {
146 $ignoredTags = array( 'includeonly', '/includeonly' );
147 $ignoredElements = array( 'noinclude' );
148 $xmlishElements[] = 'noinclude';
149 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
150 $enableOnlyinclude = true;
152 } else {
153 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
154 $ignoredElements = array( 'includeonly' );
155 $xmlishElements[] = 'includeonly';
157 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
159 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
160 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
162 $stack = new PPDStack;
164 $searchBase = "[{<\n"; #}
165 $revText = strrev( $text ); // For fast reverse searches
167 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
168 $accum =& $stack->getAccum(); # Current accumulator
169 $accum = '<root>';
170 $findEquals = false; # True to find equals signs in arguments
171 $findPipe = false; # True to take notice of pipe characters
172 $headingIndex = 1;
173 $inHeading = false; # True if $i is inside a possible heading
174 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
175 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
176 $fakeLineStart = true; # Do a line-start run without outputting an LF character
178 while ( true ) {
179 //$this->memCheck();
181 if ( $findOnlyinclude ) {
182 // Ignore all input up to the next <onlyinclude>
183 $startPos = strpos( $text, '<onlyinclude>', $i );
184 if ( $startPos === false ) {
185 // Ignored section runs to the end
186 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
187 break;
189 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
190 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
191 $i = $tagEndPos;
192 $findOnlyinclude = false;
195 if ( $fakeLineStart ) {
196 $found = 'line-start';
197 $curChar = '';
198 } else {
199 # Find next opening brace, closing brace or pipe
200 $search = $searchBase;
201 if ( $stack->top === false ) {
202 $currentClosing = '';
203 } else {
204 $currentClosing = $stack->top->close;
205 $search .= $currentClosing;
207 if ( $findPipe ) {
208 $search .= '|';
210 if ( $findEquals ) {
211 // First equals will be for the template
212 $search .= '=';
214 $rule = null;
215 # Output literal section, advance input counter
216 $literalLength = strcspn( $text, $search, $i );
217 if ( $literalLength > 0 ) {
218 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
219 $i += $literalLength;
221 if ( $i >= strlen( $text ) ) {
222 if ( $currentClosing == "\n" ) {
223 // Do a past-the-end run to finish off the heading
224 $curChar = '';
225 $found = 'line-end';
226 } else {
227 # All done
228 break;
230 } else {
231 $curChar = $text[$i];
232 if ( $curChar == '|' ) {
233 $found = 'pipe';
234 } elseif ( $curChar == '=' ) {
235 $found = 'equals';
236 } elseif ( $curChar == '<' ) {
237 $found = 'angle';
238 } elseif ( $curChar == "\n" ) {
239 if ( $inHeading ) {
240 $found = 'line-end';
241 } else {
242 $found = 'line-start';
244 } elseif ( $curChar == $currentClosing ) {
245 $found = 'close';
246 } elseif ( isset( $rules[$curChar] ) ) {
247 $found = 'open';
248 $rule = $rules[$curChar];
249 } else {
250 # Some versions of PHP have a strcspn which stops on null characters
251 # Ignore and continue
252 ++$i;
253 continue;
258 if ( $found == 'angle' ) {
259 $matches = false;
260 // Handle </onlyinclude>
261 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
262 $findOnlyinclude = true;
263 continue;
266 // Determine element name
267 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
268 // Element name missing or not listed
269 $accum .= '&lt;';
270 ++$i;
271 continue;
273 // Handle comments
274 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
275 // To avoid leaving blank lines, when a comment is both preceded
276 // and followed by a newline (ignoring spaces), trim leading and
277 // trailing spaces and one of the newlines.
279 // Find the end
280 $endPos = strpos( $text, '-->', $i + 4 );
281 if ( $endPos === false ) {
282 // Unclosed comment in input, runs to end
283 $inner = substr( $text, $i );
284 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
285 $i = strlen( $text );
286 } else {
287 // Search backwards for leading whitespace
288 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
289 // Search forwards for trailing whitespace
290 // $wsEnd will be the position of the last space
291 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
292 // Eat the line if possible
293 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
294 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
295 // it's a possible beneficial b/c break.
296 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
297 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
299 $startPos = $wsStart;
300 $endPos = $wsEnd + 1;
301 // Remove leading whitespace from the end of the accumulator
302 // Sanity check first though
303 $wsLength = $i - $wsStart;
304 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
305 $accum = substr( $accum, 0, -$wsLength );
307 // Do a line-start run next time to look for headings after the comment
308 $fakeLineStart = true;
309 } else {
310 // No line to eat, just take the comment itself
311 $startPos = $i;
312 $endPos += 2;
315 if ( $stack->top ) {
316 $part = $stack->top->getCurrentPart();
317 if ( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) {
318 // Comments abutting, no change in visual end
319 $part->commentEnd = $wsEnd;
320 } else {
321 $part->visualEnd = $wsStart;
322 $part->commentEnd = $endPos;
325 $i = $endPos + 1;
326 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
327 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
329 continue;
331 $name = $matches[1];
332 $lowerName = strtolower( $name );
333 $attrStart = $i + strlen( $name ) + 1;
335 // Find end of tag
336 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
337 if ( $tagEndPos === false ) {
338 // Infinite backtrack
339 // Disable tag search to prevent worst-case O(N^2) performance
340 $noMoreGT = true;
341 $accum .= '&lt;';
342 ++$i;
343 continue;
346 // Handle ignored tags
347 if ( in_array( $lowerName, $ignoredTags ) ) {
348 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
349 $i = $tagEndPos + 1;
350 continue;
353 $tagStartPos = $i;
354 if ( $text[$tagEndPos-1] == '/' ) {
355 $attrEnd = $tagEndPos - 1;
356 $inner = null;
357 $i = $tagEndPos + 1;
358 $close = '';
359 } else {
360 $attrEnd = $tagEndPos;
361 // Find closing tag
362 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
363 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
365 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
366 $i = $matches[0][1] + strlen( $matches[0][0] );
367 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
368 } else {
369 // No end tag -- let it run out to the end of the text.
370 $inner = substr( $text, $tagEndPos + 1 );
371 $i = strlen( $text );
372 $close = '';
375 // <includeonly> and <noinclude> just become <ignore> tags
376 if ( in_array( $lowerName, $ignoredElements ) ) {
377 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
378 . '</ignore>';
379 continue;
382 $accum .= '<ext>';
383 if ( $attrEnd <= $attrStart ) {
384 $attr = '';
385 } else {
386 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
388 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
389 // Note that the attr element contains the whitespace between name and attribute,
390 // this is necessary for precise reconstruction during pre-save transform.
391 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
392 if ( $inner !== null ) {
393 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
395 $accum .= $close . '</ext>';
398 elseif ( $found == 'line-start' ) {
399 // Is this the start of a heading?
400 // Line break belongs before the heading element in any case
401 if ( $fakeLineStart ) {
402 $fakeLineStart = false;
403 } else {
404 $accum .= $curChar;
405 $i++;
408 $count = strspn( $text, '=', $i, 6 );
409 if ( $count == 1 && $findEquals ) {
410 // DWIM: This looks kind of like a name/value separator
411 // Let's let the equals handler have it and break the potential heading
412 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
413 } elseif ( $count > 0 ) {
414 $piece = array(
415 'open' => "\n",
416 'close' => "\n",
417 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
418 'startPos' => $i,
419 'count' => $count );
420 $stack->push( $piece );
421 $accum =& $stack->getAccum();
422 extract( $stack->getFlags() );
423 $i += $count;
427 elseif ( $found == 'line-end' ) {
428 $piece = $stack->top;
429 // A heading must be open, otherwise \n wouldn't have been in the search list
430 assert( $piece->open == "\n" );
431 $part = $piece->getCurrentPart();
432 // Search back through the input to see if it has a proper close
433 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
434 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
435 $searchStart = $i - $wsLength;
436 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
437 // Comment found at line end
438 // Search for equals signs before the comment
439 $searchStart = $part->visualEnd;
440 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
442 $count = $piece->count;
443 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
444 if ( $equalsLength > 0 ) {
445 if ( $i - $equalsLength == $piece->startPos ) {
446 // This is just a single string of equals signs on its own line
447 // Replicate the doHeadings behaviour /={count}(.+)={count}/
448 // First find out how many equals signs there really are (don't stop at 6)
449 $count = $equalsLength;
450 if ( $count < 3 ) {
451 $count = 0;
452 } else {
453 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
455 } else {
456 $count = min( $equalsLength, $count );
458 if ( $count > 0 ) {
459 // Normal match, output <h>
460 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
461 $headingIndex++;
462 } else {
463 // Single equals sign on its own line, count=0
464 $element = $accum;
466 } else {
467 // No match, no <h>, just pass down the inner text
468 $element = $accum;
470 // Unwind the stack
471 $stack->pop();
472 $accum =& $stack->getAccum();
473 extract( $stack->getFlags() );
475 // Append the result to the enclosing accumulator
476 $accum .= $element;
477 // Note that we do NOT increment the input pointer.
478 // This is because the closing linebreak could be the opening linebreak of
479 // another heading. Infinite loops are avoided because the next iteration MUST
480 // hit the heading open case above, which unconditionally increments the
481 // input pointer.
484 elseif ( $found == 'open' ) {
485 # count opening brace characters
486 $count = strspn( $text, $curChar, $i );
488 # we need to add to stack only if opening brace count is enough for one of the rules
489 if ( $count >= $rule['min'] ) {
490 # Add it to the stack
491 $piece = array(
492 'open' => $curChar,
493 'close' => $rule['end'],
494 'count' => $count,
495 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
498 $stack->push( $piece );
499 $accum =& $stack->getAccum();
500 extract( $stack->getFlags() );
501 } else {
502 # Add literal brace(s)
503 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
505 $i += $count;
508 elseif ( $found == 'close' ) {
509 $piece = $stack->top;
510 # lets check if there are enough characters for closing brace
511 $maxCount = $piece->count;
512 $count = strspn( $text, $curChar, $i, $maxCount );
514 # check for maximum matching characters (if there are 5 closing
515 # characters, we will probably need only 3 - depending on the rules)
516 $matchingCount = 0;
517 $rule = $rules[$piece->open];
518 if ( $count > $rule['max'] ) {
519 # The specified maximum exists in the callback array, unless the caller
520 # has made an error
521 $matchingCount = $rule['max'];
522 } else {
523 # Count is less than the maximum
524 # Skip any gaps in the callback array to find the true largest match
525 # Need to use array_key_exists not isset because the callback can be null
526 $matchingCount = $count;
527 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
528 --$matchingCount;
532 if ($matchingCount <= 0) {
533 # No matching element found in callback array
534 # Output a literal closing brace and continue
535 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
536 $i += $count;
537 continue;
539 $name = $rule['names'][$matchingCount];
540 if ( $name === null ) {
541 // No element, just literal text
542 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
543 } else {
544 # Create XML element
545 # Note: $parts is already XML, does not need to be encoded further
546 $parts = $piece->parts;
547 $title = $parts[0]->out;
548 unset( $parts[0] );
550 # The invocation is at the start of the line if lineStart is set in
551 # the stack, and all opening brackets are used up.
552 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
553 $attr = ' lineStart="1"';
554 } else {
555 $attr = '';
558 $element = "<$name$attr>";
559 $element .= "<title>$title</title>";
560 $argIndex = 1;
561 foreach ( $parts as $partIndex => $part ) {
562 if ( isset( $part->eqpos ) ) {
563 $argName = substr( $part->out, 0, $part->eqpos );
564 $argValue = substr( $part->out, $part->eqpos + 1 );
565 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
566 } else {
567 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
568 $argIndex++;
571 $element .= "</$name>";
574 # Advance input pointer
575 $i += $matchingCount;
577 # Unwind the stack
578 $stack->pop();
579 $accum =& $stack->getAccum();
581 # Re-add the old stack element if it still has unmatched opening characters remaining
582 if ($matchingCount < $piece->count) {
583 $piece->parts = array( new PPDPart );
584 $piece->count -= $matchingCount;
585 # do we still qualify for any callback with remaining count?
586 $names = $rules[$piece->open]['names'];
587 $skippedBraces = 0;
588 $enclosingAccum =& $accum;
589 while ( $piece->count ) {
590 if ( array_key_exists( $piece->count, $names ) ) {
591 $stack->push( $piece );
592 $accum =& $stack->getAccum();
593 break;
595 --$piece->count;
596 $skippedBraces ++;
598 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
601 extract( $stack->getFlags() );
603 # Add XML element to the enclosing accumulator
604 $accum .= $element;
607 elseif ( $found == 'pipe' ) {
608 $findEquals = true; // shortcut for getFlags()
609 $stack->addPart();
610 $accum =& $stack->getAccum();
611 ++$i;
614 elseif ( $found == 'equals' ) {
615 $findEquals = false; // shortcut for getFlags()
616 $stack->getCurrentPart()->eqpos = strlen( $accum );
617 $accum .= '=';
618 ++$i;
622 # Output any remaining unclosed brackets
623 foreach ( $stack->stack as $piece ) {
624 $stack->rootAccum .= $piece->breakSyntax();
626 $stack->rootAccum .= '</root>';
627 $xml = $stack->rootAccum;
629 wfProfileOut( __METHOD__ );
631 return $xml;
636 * Stack class to help Preprocessor::preprocessToObj()
637 * @ingroup Parser
639 class PPDStack {
640 var $stack, $rootAccum, $top;
641 var $out;
642 var $elementClass = 'PPDStackElement';
644 static $false = false;
646 function __construct() {
647 $this->stack = array();
648 $this->top = false;
649 $this->rootAccum = '';
650 $this->accum =& $this->rootAccum;
653 function count() {
654 return count( $this->stack );
657 function &getAccum() {
658 return $this->accum;
661 function getCurrentPart() {
662 if ( $this->top === false ) {
663 return false;
664 } else {
665 return $this->top->getCurrentPart();
669 function push( $data ) {
670 if ( $data instanceof $this->elementClass ) {
671 $this->stack[] = $data;
672 } else {
673 $class = $this->elementClass;
674 $this->stack[] = new $class( $data );
676 $this->top = $this->stack[ count( $this->stack ) - 1 ];
677 $this->accum =& $this->top->getAccum();
680 function pop() {
681 if ( !count( $this->stack ) ) {
682 throw new MWException( __METHOD__.': no elements remaining' );
684 $temp = array_pop( $this->stack );
686 if ( count( $this->stack ) ) {
687 $this->top = $this->stack[ count( $this->stack ) - 1 ];
688 $this->accum =& $this->top->getAccum();
689 } else {
690 $this->top = self::$false;
691 $this->accum =& $this->rootAccum;
693 return $temp;
696 function addPart( $s = '' ) {
697 $this->top->addPart( $s );
698 $this->accum =& $this->top->getAccum();
701 function getFlags() {
702 if ( !count( $this->stack ) ) {
703 return array(
704 'findEquals' => false,
705 'findPipe' => false,
706 'inHeading' => false,
708 } else {
709 return $this->top->getFlags();
715 * @ingroup Parser
717 class PPDStackElement {
718 var $open, // Opening character (\n for heading)
719 $close, // Matching closing character
720 $count, // Number of opening characters found (number of "=" for heading)
721 $parts, // Array of PPDPart objects describing pipe-separated parts.
722 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
724 var $partClass = 'PPDPart';
726 function __construct( $data = array() ) {
727 $class = $this->partClass;
728 $this->parts = array( new $class );
730 foreach ( $data as $name => $value ) {
731 $this->$name = $value;
735 function &getAccum() {
736 return $this->parts[count($this->parts) - 1]->out;
739 function addPart( $s = '' ) {
740 $class = $this->partClass;
741 $this->parts[] = new $class( $s );
744 function getCurrentPart() {
745 return $this->parts[count($this->parts) - 1];
748 function getFlags() {
749 $partCount = count( $this->parts );
750 $findPipe = $this->open != "\n" && $this->open != '[';
751 return array(
752 'findPipe' => $findPipe,
753 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
754 'inHeading' => $this->open == "\n",
759 * Get the output string that would result if the close is not found.
761 function breakSyntax( $openingCount = false ) {
762 if ( $this->open == "\n" ) {
763 $s = $this->parts[0]->out;
764 } else {
765 if ( $openingCount === false ) {
766 $openingCount = $this->count;
768 $s = str_repeat( $this->open, $openingCount );
769 $first = true;
770 foreach ( $this->parts as $part ) {
771 if ( $first ) {
772 $first = false;
773 } else {
774 $s .= '|';
776 $s .= $part->out;
779 return $s;
784 * @ingroup Parser
786 class PPDPart {
787 var $out; // Output accumulator string
789 // Optional member variables:
790 // eqpos Position of equals sign in output accumulator
791 // commentEnd Past-the-end input pointer for the last comment encountered
792 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
794 function __construct( $out = '' ) {
795 $this->out = $out;
800 * An expansion frame, used as a context to expand the result of preprocessToObj()
801 * @ingroup Parser
803 class PPFrame_DOM implements PPFrame {
804 var $preprocessor, $parser, $title;
805 var $titleCache;
808 * Hashtable listing templates which are disallowed for expansion in this frame,
809 * having been encountered previously in parent frames.
811 var $loopCheckHash;
814 * Recursion depth of this frame, top = 0
815 * Note that this is NOT the same as expansion depth in expand()
817 var $depth;
821 * Construct a new preprocessor frame.
822 * @param Preprocessor $preprocessor The parent preprocessor
824 function __construct( $preprocessor ) {
825 $this->preprocessor = $preprocessor;
826 $this->parser = $preprocessor->parser;
827 $this->title = $this->parser->mTitle;
828 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
829 $this->loopCheckHash = array();
830 $this->depth = 0;
834 * Create a new child frame
835 * $args is optionally a multi-root PPNode or array containing the template arguments
837 function newChild( $args = false, $title = false ) {
838 $namedArgs = array();
839 $numberedArgs = array();
840 if ( $title === false ) {
841 $title = $this->title;
843 if ( $args !== false ) {
844 $xpath = false;
845 if ( $args instanceof PPNode ) {
846 $args = $args->node;
848 foreach ( $args as $arg ) {
849 if ( !$xpath ) {
850 $xpath = new DOMXPath( $arg->ownerDocument );
853 $nameNodes = $xpath->query( 'name', $arg );
854 $value = $xpath->query( 'value', $arg );
855 if ( $nameNodes->item( 0 )->hasAttributes() ) {
856 // Numbered parameter
857 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
858 $numberedArgs[$index] = $value->item( 0 );
859 unset( $namedArgs[$index] );
860 } else {
861 // Named parameter
862 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
863 $namedArgs[$name] = $value->item( 0 );
864 unset( $numberedArgs[$name] );
868 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
871 function expand( $root, $flags = 0 ) {
872 static $expansionDepth = 0;
873 if ( is_string( $root ) ) {
874 return $root;
877 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
879 return '<span class="error">Node-count limit exceeded</span>';
882 if ( $expansionDepth > $this->parser->mOptions->mMaxPPExpandDepth ) {
883 return '<span class="error">Expansion depth limit exceeded</span>';
885 wfProfileIn( __METHOD__ );
886 ++$expansionDepth;
888 if ( $root instanceof PPNode_DOM ) {
889 $root = $root->node;
891 if ( $root instanceof DOMDocument ) {
892 $root = $root->documentElement;
895 $outStack = array( '', '' );
896 $iteratorStack = array( false, $root );
897 $indexStack = array( 0, 0 );
899 while ( count( $iteratorStack ) > 1 ) {
900 $level = count( $outStack ) - 1;
901 $iteratorNode =& $iteratorStack[ $level ];
902 $out =& $outStack[$level];
903 $index =& $indexStack[$level];
905 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
907 if ( is_array( $iteratorNode ) ) {
908 if ( $index >= count( $iteratorNode ) ) {
909 // All done with this iterator
910 $iteratorStack[$level] = false;
911 $contextNode = false;
912 } else {
913 $contextNode = $iteratorNode[$index];
914 $index++;
916 } elseif ( $iteratorNode instanceof DOMNodeList ) {
917 if ( $index >= $iteratorNode->length ) {
918 // All done with this iterator
919 $iteratorStack[$level] = false;
920 $contextNode = false;
921 } else {
922 $contextNode = $iteratorNode->item( $index );
923 $index++;
925 } else {
926 // Copy to $contextNode and then delete from iterator stack,
927 // because this is not an iterator but we do have to execute it once
928 $contextNode = $iteratorStack[$level];
929 $iteratorStack[$level] = false;
932 if ( $contextNode instanceof PPNode_DOM ) $contextNode = $contextNode->node;
934 $newIterator = false;
936 if ( $contextNode === false ) {
937 // nothing to do
938 } elseif ( is_string( $contextNode ) ) {
939 $out .= $contextNode;
940 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
941 $newIterator = $contextNode;
942 } elseif ( $contextNode instanceof DOMNode ) {
943 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
944 $out .= $contextNode->nodeValue;
945 } elseif ( $contextNode->nodeName == 'template' ) {
946 # Double-brace expansion
947 $xpath = new DOMXPath( $contextNode->ownerDocument );
948 $titles = $xpath->query( 'title', $contextNode );
949 $title = $titles->item( 0 );
950 $parts = $xpath->query( 'part', $contextNode );
951 if ( $flags & self::NO_TEMPLATES ) {
952 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
953 } else {
954 $lineStart = $contextNode->getAttribute( 'lineStart' );
955 $params = array(
956 'title' => new PPNode_DOM( $title ),
957 'parts' => new PPNode_DOM( $parts ),
958 'lineStart' => $lineStart );
959 $ret = $this->parser->braceSubstitution( $params, $this );
960 if ( isset( $ret['object'] ) ) {
961 $newIterator = $ret['object'];
962 } else {
963 $out .= $ret['text'];
966 } elseif ( $contextNode->nodeName == 'tplarg' ) {
967 # Triple-brace expansion
968 $xpath = new DOMXPath( $contextNode->ownerDocument );
969 $titles = $xpath->query( 'title', $contextNode );
970 $title = $titles->item( 0 );
971 $parts = $xpath->query( 'part', $contextNode );
972 if ( $flags & self::NO_ARGS ) {
973 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
974 } else {
975 $params = array(
976 'title' => new PPNode_DOM( $title ),
977 'parts' => new PPNode_DOM( $parts ) );
978 $ret = $this->parser->argSubstitution( $params, $this );
979 if ( isset( $ret['object'] ) ) {
980 $newIterator = $ret['object'];
981 } else {
982 $out .= $ret['text'];
985 } elseif ( $contextNode->nodeName == 'comment' ) {
986 # HTML-style comment
987 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
988 if ( $this->parser->ot['html']
989 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
990 || ( $flags & self::STRIP_COMMENTS ) )
992 $out .= '';
994 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
995 # Not in RECOVER_COMMENTS mode (extractSections) though
996 elseif ( $this->parser->ot['wiki'] && ! ( $flags & self::RECOVER_COMMENTS ) ) {
997 $out .= $this->parser->insertStripItem( $contextNode->textContent );
999 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1000 else {
1001 $out .= $contextNode->textContent;
1003 } elseif ( $contextNode->nodeName == 'ignore' ) {
1004 # Output suppression used by <includeonly> etc.
1005 # OT_WIKI will only respect <ignore> in substed templates.
1006 # The other output types respect it unless NO_IGNORE is set.
1007 # extractSections() sets NO_IGNORE and so never respects it.
1008 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
1009 $out .= $contextNode->textContent;
1010 } else {
1011 $out .= '';
1013 } elseif ( $contextNode->nodeName == 'ext' ) {
1014 # Extension tag
1015 $xpath = new DOMXPath( $contextNode->ownerDocument );
1016 $names = $xpath->query( 'name', $contextNode );
1017 $attrs = $xpath->query( 'attr', $contextNode );
1018 $inners = $xpath->query( 'inner', $contextNode );
1019 $closes = $xpath->query( 'close', $contextNode );
1020 $params = array(
1021 'name' => new PPNode_DOM( $names->item( 0 ) ),
1022 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1023 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1024 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1026 $out .= $this->parser->extensionSubstitution( $params, $this );
1027 } elseif ( $contextNode->nodeName == 'h' ) {
1028 # Heading
1029 $s = $this->expand( $contextNode->childNodes, $flags );
1031 # Insert a heading marker only for <h> children of <root>
1032 # This is to stop extractSections from going over multiple tree levels
1033 if ( $contextNode->parentNode->nodeName == 'root'
1034 && $this->parser->ot['html'] )
1036 # Insert heading index marker
1037 $headingIndex = $contextNode->getAttribute( 'i' );
1038 $titleText = $this->title->getPrefixedDBkey();
1039 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1040 $serial = count( $this->parser->mHeadings ) - 1;
1041 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1042 $count = $contextNode->getAttribute( 'level' );
1043 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1044 $this->parser->mStripState->general->setPair( $marker, '' );
1046 $out .= $s;
1047 } else {
1048 # Generic recursive expansion
1049 $newIterator = $contextNode->childNodes;
1051 } else {
1052 wfProfileOut( __METHOD__ );
1053 throw new MWException( __METHOD__.': Invalid parameter type' );
1056 if ( $newIterator !== false ) {
1057 if ( $newIterator instanceof PPNode_DOM ) {
1058 $newIterator = $newIterator->node;
1060 $outStack[] = '';
1061 $iteratorStack[] = $newIterator;
1062 $indexStack[] = 0;
1063 } elseif ( $iteratorStack[$level] === false ) {
1064 // Return accumulated value to parent
1065 // With tail recursion
1066 while ( $iteratorStack[$level] === false && $level > 0 ) {
1067 $outStack[$level - 1] .= $out;
1068 array_pop( $outStack );
1069 array_pop( $iteratorStack );
1070 array_pop( $indexStack );
1071 $level--;
1075 --$expansionDepth;
1076 wfProfileOut( __METHOD__ );
1077 return $outStack[0];
1080 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1081 $args = array_slice( func_get_args(), 2 );
1083 $first = true;
1084 $s = '';
1085 foreach ( $args as $root ) {
1086 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1087 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1088 $root = array( $root );
1090 foreach ( $root as $node ) {
1091 if ( $first ) {
1092 $first = false;
1093 } else {
1094 $s .= $sep;
1096 $s .= $this->expand( $node, $flags );
1099 return $s;
1103 * Implode with no flags specified
1104 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1106 function implode( $sep /*, ... */ ) {
1107 $args = array_slice( func_get_args(), 1 );
1109 $first = true;
1110 $s = '';
1111 foreach ( $args as $root ) {
1112 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1113 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1114 $root = array( $root );
1116 foreach ( $root as $node ) {
1117 if ( $first ) {
1118 $first = false;
1119 } else {
1120 $s .= $sep;
1122 $s .= $this->expand( $node );
1125 return $s;
1129 * Makes an object that, when expand()ed, will be the same as one obtained
1130 * with implode()
1132 function virtualImplode( $sep /*, ... */ ) {
1133 $args = array_slice( func_get_args(), 1 );
1134 $out = array();
1135 $first = true;
1136 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1138 foreach ( $args as $root ) {
1139 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1140 $root = array( $root );
1142 foreach ( $root as $node ) {
1143 if ( $first ) {
1144 $first = false;
1145 } else {
1146 $out[] = $sep;
1148 $out[] = $node;
1151 return $out;
1155 * Virtual implode with brackets
1157 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1158 $args = array_slice( func_get_args(), 3 );
1159 $out = array( $start );
1160 $first = true;
1162 foreach ( $args as $root ) {
1163 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1164 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1165 $root = array( $root );
1167 foreach ( $root as $node ) {
1168 if ( $first ) {
1169 $first = false;
1170 } else {
1171 $out[] = $sep;
1173 $out[] = $node;
1176 $out[] = $end;
1177 return $out;
1180 function __toString() {
1181 return 'frame{}';
1184 function getPDBK( $level = false ) {
1185 if ( $level === false ) {
1186 return $this->title->getPrefixedDBkey();
1187 } else {
1188 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1193 * Returns true if there are no arguments in this frame
1195 function isEmpty() {
1196 return true;
1199 function getArgument( $name ) {
1200 return false;
1204 * Returns true if the infinite loop check is OK, false if a loop is detected
1206 function loopCheck( $title ) {
1207 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1211 * Return true if the frame is a template frame
1213 function isTemplate() {
1214 return false;
1219 * Expansion frame with template arguments
1220 * @ingroup Parser
1222 class PPTemplateFrame_DOM extends PPFrame_DOM {
1223 var $numberedArgs, $namedArgs, $parent;
1224 var $numberedExpansionCache, $namedExpansionCache;
1226 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1227 $this->preprocessor = $preprocessor;
1228 $this->parser = $preprocessor->parser;
1229 $this->parent = $parent;
1230 $this->numberedArgs = $numberedArgs;
1231 $this->namedArgs = $namedArgs;
1232 $this->title = $title;
1233 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1234 $this->titleCache = $parent->titleCache;
1235 $this->titleCache[] = $pdbk;
1236 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1237 if ( $pdbk !== false ) {
1238 $this->loopCheckHash[$pdbk] = true;
1240 $this->depth = $parent->depth + 1;
1241 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1244 function __toString() {
1245 $s = 'tplframe{';
1246 $first = true;
1247 $args = $this->numberedArgs + $this->namedArgs;
1248 foreach ( $args as $name => $value ) {
1249 if ( $first ) {
1250 $first = false;
1251 } else {
1252 $s .= ', ';
1254 $s .= "\"$name\":\"" .
1255 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1257 $s .= '}';
1258 return $s;
1261 * Returns true if there are no arguments in this frame
1263 function isEmpty() {
1264 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1267 function getArguments() {
1268 $arguments = array();
1269 foreach ( array_merge(
1270 array_keys($this->numberedArgs),
1271 array_keys($this->namedArgs)) as $key ) {
1272 $arguments[$key] = $this->getArgument($key);
1274 return $arguments;
1277 function getNumberedArguments() {
1278 $arguments = array();
1279 foreach ( array_keys($this->numberedArgs) as $key ) {
1280 $arguments[$key] = $this->getArgument($key);
1282 return $arguments;
1285 function getNamedArguments() {
1286 $arguments = array();
1287 foreach ( array_keys($this->namedArgs) as $key ) {
1288 $arguments[$key] = $this->getArgument($key);
1290 return $arguments;
1293 function getNumberedArgument( $index ) {
1294 if ( !isset( $this->numberedArgs[$index] ) ) {
1295 return false;
1297 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1298 # No trimming for unnamed arguments
1299 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], self::STRIP_COMMENTS );
1301 return $this->numberedExpansionCache[$index];
1304 function getNamedArgument( $name ) {
1305 if ( !isset( $this->namedArgs[$name] ) ) {
1306 return false;
1308 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1309 # Trim named arguments post-expand, for backwards compatibility
1310 $this->namedExpansionCache[$name] = trim(
1311 $this->parent->expand( $this->namedArgs[$name], self::STRIP_COMMENTS ) );
1313 return $this->namedExpansionCache[$name];
1316 function getArgument( $name ) {
1317 $text = $this->getNumberedArgument( $name );
1318 if ( $text === false ) {
1319 $text = $this->getNamedArgument( $name );
1321 return $text;
1325 * Return true if the frame is a template frame
1327 function isTemplate() {
1328 return true;
1333 * Expansion frame with custom arguments
1334 * @ingroup Parser
1336 class PPCustomFrame_DOM extends PPFrame_DOM {
1337 var $args;
1339 function __construct( $preprocessor, $args ) {
1340 $this->preprocessor = $preprocessor;
1341 $this->parser = $preprocessor->parser;
1342 $this->args = $args;
1345 function __toString() {
1346 $s = 'cstmframe{';
1347 $first = true;
1348 foreach ( $this->args as $name => $value ) {
1349 if ( $first ) {
1350 $first = false;
1351 } else {
1352 $s .= ', ';
1354 $s .= "\"$name\":\"" .
1355 str_replace( '"', '\\"', $value->__toString() ) . '"';
1357 $s .= '}';
1358 return $s;
1361 function isEmpty() {
1362 return !count( $this->args );
1365 function getArgument( $index ) {
1366 if ( !isset( $this->args[$index] ) ) {
1367 return false;
1369 return $this->args[$index];
1374 * @ingroup Parser
1376 class PPNode_DOM implements PPNode {
1377 var $node;
1379 function __construct( $node, $xpath = false ) {
1380 $this->node = $node;
1383 function __get( $name ) {
1384 if ( $name == 'xpath' ) {
1385 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1387 return $this->xpath;
1390 function __toString() {
1391 if ( $this->node instanceof DOMNodeList ) {
1392 $s = '';
1393 foreach ( $this->node as $node ) {
1394 $s .= $node->ownerDocument->saveXML( $node );
1396 } else {
1397 $s = $this->node->ownerDocument->saveXML( $this->node );
1399 return $s;
1402 function getChildren() {
1403 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1406 function getFirstChild() {
1407 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1410 function getNextSibling() {
1411 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1414 function getChildrenOfType( $type ) {
1415 return new self( $this->xpath->query( $type, $this->node ) );
1418 function getLength() {
1419 if ( $this->node instanceof DOMNodeList ) {
1420 return $this->node->length;
1421 } else {
1422 return false;
1426 function item( $i ) {
1427 $item = $this->node->item( $i );
1428 return $item ? new self( $item ) : false;
1431 function getName() {
1432 if ( $this->node instanceof DOMNodeList ) {
1433 return '#nodelist';
1434 } else {
1435 return $this->node->nodeName;
1440 * Split a <part> node into an associative array containing:
1441 * name PPNode name
1442 * index String index
1443 * value PPNode value
1445 function splitArg() {
1446 $names = $this->xpath->query( 'name', $this->node );
1447 $values = $this->xpath->query( 'value', $this->node );
1448 if ( !$names->length || !$values->length ) {
1449 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1451 $name = $names->item( 0 );
1452 $index = $name->getAttribute( 'index' );
1453 return array(
1454 'name' => new self( $name ),
1455 'index' => $index,
1456 'value' => new self( $values->item( 0 ) ) );
1460 * Split an <ext> node into an associative array containing name, attr, inner and close
1461 * All values in the resulting array are PPNodes. Inner and close are optional.
1463 function splitExt() {
1464 $names = $this->xpath->query( 'name', $this->node );
1465 $attrs = $this->xpath->query( 'attr', $this->node );
1466 $inners = $this->xpath->query( 'inner', $this->node );
1467 $closes = $this->xpath->query( 'close', $this->node );
1468 if ( !$names->length || !$attrs->length ) {
1469 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1471 $parts = array(
1472 'name' => new self( $names->item( 0 ) ),
1473 'attr' => new self( $attrs->item( 0 ) ) );
1474 if ( $inners->length ) {
1475 $parts['inner'] = new self( $inners->item( 0 ) );
1477 if ( $closes->length ) {
1478 $parts['close'] = new self( $closes->item( 0 ) );
1480 return $parts;
1484 * Split a <h> node
1486 function splitHeading() {
1487 if ( !$this->nodeName == 'h' ) {
1488 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1490 return array(
1491 'i' => $this->node->getAttribute( 'i' ),
1492 'level' => $this->node->getAttribute( 'level' ),
1493 'contents' => $this->getChildren()