Don't display multiple language links to the same language
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob34de0ba541d21f9ad56fcc71aac90156857b9b88
1 <?php
2 /**
3 * Preprocessor using PHP's dom extension
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
20 * @file
21 * @ingroup Parser
24 /**
25 * @ingroup Parser
27 class Preprocessor_DOM implements Preprocessor {
29 /**
30 * @var Parser
32 var $parser;
34 var $memoryLimit;
36 const CACHE_VERSION = 1;
38 function __construct( $parser ) {
39 $this->parser = $parser;
40 $mem = ini_get( 'memory_limit' );
41 $this->memoryLimit = false;
42 if ( strval( $mem ) !== '' && $mem != -1 ) {
43 if ( preg_match( '/^\d+$/', $mem ) ) {
44 $this->memoryLimit = $mem;
45 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
46 $this->memoryLimit = $m[1] * 1048576;
51 /**
52 * @return PPFrame_DOM
54 function newFrame() {
55 return new PPFrame_DOM( $this );
58 /**
59 * @param $args array
60 * @return PPCustomFrame_DOM
62 function newCustomFrame( $args ) {
63 return new PPCustomFrame_DOM( $this, $args );
66 /**
67 * @param $values
68 * @return PPNode_DOM
70 function newPartNodeArray( $values ) {
71 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
72 $xml = "<list>";
74 foreach ( $values as $k => $val ) {
76 if ( is_int( $k ) ) {
77 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
78 } else {
79 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
83 $xml .= "</list>";
85 $dom = new DOMDocument();
86 $dom->loadXML( $xml );
87 $root = $dom->documentElement;
89 $node = new PPNode_DOM( $root->childNodes );
90 return $node;
93 /**
94 * @throws MWException
95 * @return bool
97 function memCheck() {
98 if ( $this->memoryLimit === false ) {
99 return true;
101 $usage = memory_get_usage();
102 if ( $usage > $this->memoryLimit * 0.9 ) {
103 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
104 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
106 return $usage <= $this->memoryLimit * 0.8;
110 * Preprocess some wikitext and return the document tree.
111 * This is the ghost of Parser::replace_variables().
113 * @param $text String: the text to parse
114 * @param $flags Integer: bitwise combination of:
115 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
116 * included. Default is to assume a direct page view.
118 * The generated DOM tree must depend only on the input text and the flags.
119 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
121 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
122 * change in the DOM tree for a given text, must be passed through the section identifier
123 * in the section edit link and thus back to extractSections().
125 * The output of this function is currently only cached in process memory, but a persistent
126 * cache may be implemented at a later date which takes further advantage of these strict
127 * dependency requirements.
129 * @return PPNode_DOM
131 function preprocessToObj( $text, $flags = 0 ) {
132 wfProfileIn( __METHOD__ );
133 global $wgMemc, $wgPreprocessorCacheThreshold;
135 $xml = false;
136 $cacheable = ( $wgPreprocessorCacheThreshold !== false
137 && strlen( $text ) > $wgPreprocessorCacheThreshold );
138 if ( $cacheable ) {
139 wfProfileIn( __METHOD__.'-cacheable' );
141 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
142 $cacheValue = $wgMemc->get( $cacheKey );
143 if ( $cacheValue ) {
144 $version = substr( $cacheValue, 0, 8 );
145 if ( intval( $version ) == self::CACHE_VERSION ) {
146 $xml = substr( $cacheValue, 8 );
147 // From the cache
148 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
152 if ( $xml === false ) {
153 if ( $cacheable ) {
154 wfProfileIn( __METHOD__.'-cache-miss' );
155 $xml = $this->preprocessToXml( $text, $flags );
156 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
157 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
158 wfProfileOut( __METHOD__.'-cache-miss' );
159 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
160 } else {
161 $xml = $this->preprocessToXml( $text, $flags );
166 // Fail if the number of elements exceeds acceptable limits
167 // Do not attempt to generate the DOM
168 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
169 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
170 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
171 throw new MWException( __METHOD__.': generated node count limit exceeded' );
174 wfProfileIn( __METHOD__.'-loadXML' );
175 $dom = new DOMDocument;
176 wfSuppressWarnings();
177 $result = $dom->loadXML( $xml );
178 wfRestoreWarnings();
179 if ( !$result ) {
180 // Try running the XML through UtfNormal to get rid of invalid characters
181 $xml = UtfNormal::cleanUp( $xml );
182 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
183 $result = $dom->loadXML( $xml, 1 << 19 );
184 if ( !$result ) {
185 throw new MWException( __METHOD__.' generated invalid XML' );
188 $obj = new PPNode_DOM( $dom->documentElement );
189 wfProfileOut( __METHOD__.'-loadXML' );
190 if ( $cacheable ) {
191 wfProfileOut( __METHOD__.'-cacheable' );
193 wfProfileOut( __METHOD__ );
194 return $obj;
198 * @param $text string
199 * @param $flags int
200 * @return string
202 function preprocessToXml( $text, $flags = 0 ) {
203 wfProfileIn( __METHOD__ );
204 $rules = array(
205 '{' => array(
206 'end' => '}',
207 'names' => array(
208 2 => 'template',
209 3 => 'tplarg',
211 'min' => 2,
212 'max' => 3,
214 '[' => array(
215 'end' => ']',
216 'names' => array( 2 => null ),
217 'min' => 2,
218 'max' => 2,
222 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
224 $xmlishElements = $this->parser->getStripList();
225 $enableOnlyinclude = false;
226 if ( $forInclusion ) {
227 $ignoredTags = array( 'includeonly', '/includeonly' );
228 $ignoredElements = array( 'noinclude' );
229 $xmlishElements[] = 'noinclude';
230 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
231 $enableOnlyinclude = true;
233 } else {
234 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
235 $ignoredElements = array( 'includeonly' );
236 $xmlishElements[] = 'includeonly';
238 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
240 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
241 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
243 $stack = new PPDStack;
245 $searchBase = "[{<\n"; #}
246 $revText = strrev( $text ); // For fast reverse searches
247 $lengthText = strlen( $text );
249 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
250 $accum =& $stack->getAccum(); # Current accumulator
251 $accum = '<root>';
252 $findEquals = false; # True to find equals signs in arguments
253 $findPipe = false; # True to take notice of pipe characters
254 $headingIndex = 1;
255 $inHeading = false; # True if $i is inside a possible heading
256 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
257 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
258 $fakeLineStart = true; # Do a line-start run without outputting an LF character
260 while ( true ) {
261 //$this->memCheck();
263 if ( $findOnlyinclude ) {
264 // Ignore all input up to the next <onlyinclude>
265 $startPos = strpos( $text, '<onlyinclude>', $i );
266 if ( $startPos === false ) {
267 // Ignored section runs to the end
268 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
269 break;
271 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
272 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
273 $i = $tagEndPos;
274 $findOnlyinclude = false;
277 if ( $fakeLineStart ) {
278 $found = 'line-start';
279 $curChar = '';
280 } else {
281 # Find next opening brace, closing brace or pipe
282 $search = $searchBase;
283 if ( $stack->top === false ) {
284 $currentClosing = '';
285 } else {
286 $currentClosing = $stack->top->close;
287 $search .= $currentClosing;
289 if ( $findPipe ) {
290 $search .= '|';
292 if ( $findEquals ) {
293 // First equals will be for the template
294 $search .= '=';
296 $rule = null;
297 # Output literal section, advance input counter
298 $literalLength = strcspn( $text, $search, $i );
299 if ( $literalLength > 0 ) {
300 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
301 $i += $literalLength;
303 if ( $i >= $lengthText ) {
304 if ( $currentClosing == "\n" ) {
305 // Do a past-the-end run to finish off the heading
306 $curChar = '';
307 $found = 'line-end';
308 } else {
309 # All done
310 break;
312 } else {
313 $curChar = $text[$i];
314 if ( $curChar == '|' ) {
315 $found = 'pipe';
316 } elseif ( $curChar == '=' ) {
317 $found = 'equals';
318 } elseif ( $curChar == '<' ) {
319 $found = 'angle';
320 } elseif ( $curChar == "\n" ) {
321 if ( $inHeading ) {
322 $found = 'line-end';
323 } else {
324 $found = 'line-start';
326 } elseif ( $curChar == $currentClosing ) {
327 $found = 'close';
328 } elseif ( isset( $rules[$curChar] ) ) {
329 $found = 'open';
330 $rule = $rules[$curChar];
331 } else {
332 # Some versions of PHP have a strcspn which stops on null characters
333 # Ignore and continue
334 ++$i;
335 continue;
340 if ( $found == 'angle' ) {
341 $matches = false;
342 // Handle </onlyinclude>
343 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
344 $findOnlyinclude = true;
345 continue;
348 // Determine element name
349 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
350 // Element name missing or not listed
351 $accum .= '&lt;';
352 ++$i;
353 continue;
355 // Handle comments
356 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
357 // To avoid leaving blank lines, when a comment is both preceded
358 // and followed by a newline (ignoring spaces), trim leading and
359 // trailing spaces and one of the newlines.
361 // Find the end
362 $endPos = strpos( $text, '-->', $i + 4 );
363 if ( $endPos === false ) {
364 // Unclosed comment in input, runs to end
365 $inner = substr( $text, $i );
366 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
367 $i = $lengthText;
368 } else {
369 // Search backwards for leading whitespace
370 $wsStart = $i ? ( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
371 // Search forwards for trailing whitespace
372 // $wsEnd will be the position of the last space (or the '>' if there's none)
373 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
374 // Eat the line if possible
375 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
376 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
377 // it's a possible beneficial b/c break.
378 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
379 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
381 $startPos = $wsStart;
382 $endPos = $wsEnd + 1;
383 // Remove leading whitespace from the end of the accumulator
384 // Sanity check first though
385 $wsLength = $i - $wsStart;
386 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
387 $accum = substr( $accum, 0, -$wsLength );
389 // Do a line-start run next time to look for headings after the comment
390 $fakeLineStart = true;
391 } else {
392 // No line to eat, just take the comment itself
393 $startPos = $i;
394 $endPos += 2;
397 if ( $stack->top ) {
398 $part = $stack->top->getCurrentPart();
399 if ( ! (isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 )) {
400 $part->visualEnd = $wsStart;
402 // Else comments abutting, no change in visual end
403 $part->commentEnd = $endPos;
405 $i = $endPos + 1;
406 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
407 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
409 continue;
411 $name = $matches[1];
412 $lowerName = strtolower( $name );
413 $attrStart = $i + strlen( $name ) + 1;
415 // Find end of tag
416 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
417 if ( $tagEndPos === false ) {
418 // Infinite backtrack
419 // Disable tag search to prevent worst-case O(N^2) performance
420 $noMoreGT = true;
421 $accum .= '&lt;';
422 ++$i;
423 continue;
426 // Handle ignored tags
427 if ( in_array( $lowerName, $ignoredTags ) ) {
428 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
429 $i = $tagEndPos + 1;
430 continue;
433 $tagStartPos = $i;
434 if ( $text[$tagEndPos-1] == '/' ) {
435 $attrEnd = $tagEndPos - 1;
436 $inner = null;
437 $i = $tagEndPos + 1;
438 $close = '';
439 } else {
440 $attrEnd = $tagEndPos;
441 // Find closing tag
442 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
443 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
445 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
446 $i = $matches[0][1] + strlen( $matches[0][0] );
447 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
448 } else {
449 // No end tag -- let it run out to the end of the text.
450 $inner = substr( $text, $tagEndPos + 1 );
451 $i = $lengthText;
452 $close = '';
455 // <includeonly> and <noinclude> just become <ignore> tags
456 if ( in_array( $lowerName, $ignoredElements ) ) {
457 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
458 . '</ignore>';
459 continue;
462 $accum .= '<ext>';
463 if ( $attrEnd <= $attrStart ) {
464 $attr = '';
465 } else {
466 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
468 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
469 // Note that the attr element contains the whitespace between name and attribute,
470 // this is necessary for precise reconstruction during pre-save transform.
471 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
472 if ( $inner !== null ) {
473 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
475 $accum .= $close . '</ext>';
476 } elseif ( $found == 'line-start' ) {
477 // Is this the start of a heading?
478 // Line break belongs before the heading element in any case
479 if ( $fakeLineStart ) {
480 $fakeLineStart = false;
481 } else {
482 $accum .= $curChar;
483 $i++;
486 $count = strspn( $text, '=', $i, 6 );
487 if ( $count == 1 && $findEquals ) {
488 // DWIM: This looks kind of like a name/value separator
489 // Let's let the equals handler have it and break the potential heading
490 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
491 } elseif ( $count > 0 ) {
492 $piece = array(
493 'open' => "\n",
494 'close' => "\n",
495 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
496 'startPos' => $i,
497 'count' => $count );
498 $stack->push( $piece );
499 $accum =& $stack->getAccum();
500 $flags = $stack->getFlags();
501 extract( $flags );
502 $i += $count;
504 } elseif ( $found == 'line-end' ) {
505 $piece = $stack->top;
506 // A heading must be open, otherwise \n wouldn't have been in the search list
507 assert( '$piece->open == "\n"' );
508 $part = $piece->getCurrentPart();
509 // Search back through the input to see if it has a proper close
510 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
511 $wsLength = strspn( $revText, " \t", $lengthText - $i );
512 $searchStart = $i - $wsLength;
513 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
514 // Comment found at line end
515 // Search for equals signs before the comment
516 $searchStart = $part->visualEnd;
517 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
519 $count = $piece->count;
520 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
521 if ( $equalsLength > 0 ) {
522 if ( $searchStart - $equalsLength == $piece->startPos ) {
523 // This is just a single string of equals signs on its own line
524 // Replicate the doHeadings behaviour /={count}(.+)={count}/
525 // First find out how many equals signs there really are (don't stop at 6)
526 $count = $equalsLength;
527 if ( $count < 3 ) {
528 $count = 0;
529 } else {
530 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
532 } else {
533 $count = min( $equalsLength, $count );
535 if ( $count > 0 ) {
536 // Normal match, output <h>
537 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
538 $headingIndex++;
539 } else {
540 // Single equals sign on its own line, count=0
541 $element = $accum;
543 } else {
544 // No match, no <h>, just pass down the inner text
545 $element = $accum;
547 // Unwind the stack
548 $stack->pop();
549 $accum =& $stack->getAccum();
550 $flags = $stack->getFlags();
551 extract( $flags );
553 // Append the result to the enclosing accumulator
554 $accum .= $element;
555 // Note that we do NOT increment the input pointer.
556 // This is because the closing linebreak could be the opening linebreak of
557 // another heading. Infinite loops are avoided because the next iteration MUST
558 // hit the heading open case above, which unconditionally increments the
559 // input pointer.
560 } elseif ( $found == 'open' ) {
561 # count opening brace characters
562 $count = strspn( $text, $curChar, $i );
564 # we need to add to stack only if opening brace count is enough for one of the rules
565 if ( $count >= $rule['min'] ) {
566 # Add it to the stack
567 $piece = array(
568 'open' => $curChar,
569 'close' => $rule['end'],
570 'count' => $count,
571 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
574 $stack->push( $piece );
575 $accum =& $stack->getAccum();
576 $flags = $stack->getFlags();
577 extract( $flags );
578 } else {
579 # Add literal brace(s)
580 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
582 $i += $count;
583 } elseif ( $found == 'close' ) {
584 $piece = $stack->top;
585 # lets check if there are enough characters for closing brace
586 $maxCount = $piece->count;
587 $count = strspn( $text, $curChar, $i, $maxCount );
589 # check for maximum matching characters (if there are 5 closing
590 # characters, we will probably need only 3 - depending on the rules)
591 $rule = $rules[$piece->open];
592 if ( $count > $rule['max'] ) {
593 # The specified maximum exists in the callback array, unless the caller
594 # has made an error
595 $matchingCount = $rule['max'];
596 } else {
597 # Count is less than the maximum
598 # Skip any gaps in the callback array to find the true largest match
599 # Need to use array_key_exists not isset because the callback can be null
600 $matchingCount = $count;
601 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
602 --$matchingCount;
606 if ( $matchingCount <= 0 ) {
607 # No matching element found in callback array
608 # Output a literal closing brace and continue
609 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
610 $i += $count;
611 continue;
613 $name = $rule['names'][$matchingCount];
614 if ( $name === null ) {
615 // No element, just literal text
616 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
617 } else {
618 # Create XML element
619 # Note: $parts is already XML, does not need to be encoded further
620 $parts = $piece->parts;
621 $title = $parts[0]->out;
622 unset( $parts[0] );
624 # The invocation is at the start of the line if lineStart is set in
625 # the stack, and all opening brackets are used up.
626 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
627 $attr = ' lineStart="1"';
628 } else {
629 $attr = '';
632 $element = "<$name$attr>";
633 $element .= "<title>$title</title>";
634 $argIndex = 1;
635 foreach ( $parts as $part ) {
636 if ( isset( $part->eqpos ) ) {
637 $argName = substr( $part->out, 0, $part->eqpos );
638 $argValue = substr( $part->out, $part->eqpos + 1 );
639 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
640 } else {
641 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
642 $argIndex++;
645 $element .= "</$name>";
648 # Advance input pointer
649 $i += $matchingCount;
651 # Unwind the stack
652 $stack->pop();
653 $accum =& $stack->getAccum();
655 # Re-add the old stack element if it still has unmatched opening characters remaining
656 if ( $matchingCount < $piece->count ) {
657 $piece->parts = array( new PPDPart );
658 $piece->count -= $matchingCount;
659 # do we still qualify for any callback with remaining count?
660 $names = $rules[$piece->open]['names'];
661 $skippedBraces = 0;
662 $enclosingAccum =& $accum;
663 while ( $piece->count ) {
664 if ( array_key_exists( $piece->count, $names ) ) {
665 $stack->push( $piece );
666 $accum =& $stack->getAccum();
667 break;
669 --$piece->count;
670 $skippedBraces ++;
672 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
674 $flags = $stack->getFlags();
675 extract( $flags );
677 # Add XML element to the enclosing accumulator
678 $accum .= $element;
679 } elseif ( $found == 'pipe' ) {
680 $findEquals = true; // shortcut for getFlags()
681 $stack->addPart();
682 $accum =& $stack->getAccum();
683 ++$i;
684 } elseif ( $found == 'equals' ) {
685 $findEquals = false; // shortcut for getFlags()
686 $stack->getCurrentPart()->eqpos = strlen( $accum );
687 $accum .= '=';
688 ++$i;
692 # Output any remaining unclosed brackets
693 foreach ( $stack->stack as $piece ) {
694 $stack->rootAccum .= $piece->breakSyntax();
696 $stack->rootAccum .= '</root>';
697 $xml = $stack->rootAccum;
699 wfProfileOut( __METHOD__ );
701 return $xml;
706 * Stack class to help Preprocessor::preprocessToObj()
707 * @ingroup Parser
709 class PPDStack {
710 var $stack, $rootAccum;
713 * @var PPDStack
715 var $top;
716 var $out;
717 var $elementClass = 'PPDStackElement';
719 static $false = false;
721 function __construct() {
722 $this->stack = array();
723 $this->top = false;
724 $this->rootAccum = '';
725 $this->accum =& $this->rootAccum;
729 * @return int
731 function count() {
732 return count( $this->stack );
735 function &getAccum() {
736 return $this->accum;
739 function getCurrentPart() {
740 if ( $this->top === false ) {
741 return false;
742 } else {
743 return $this->top->getCurrentPart();
747 function push( $data ) {
748 if ( $data instanceof $this->elementClass ) {
749 $this->stack[] = $data;
750 } else {
751 $class = $this->elementClass;
752 $this->stack[] = new $class( $data );
754 $this->top = $this->stack[ count( $this->stack ) - 1 ];
755 $this->accum =& $this->top->getAccum();
758 function pop() {
759 if ( !count( $this->stack ) ) {
760 throw new MWException( __METHOD__.': no elements remaining' );
762 $temp = array_pop( $this->stack );
764 if ( count( $this->stack ) ) {
765 $this->top = $this->stack[ count( $this->stack ) - 1 ];
766 $this->accum =& $this->top->getAccum();
767 } else {
768 $this->top = self::$false;
769 $this->accum =& $this->rootAccum;
771 return $temp;
774 function addPart( $s = '' ) {
775 $this->top->addPart( $s );
776 $this->accum =& $this->top->getAccum();
780 * @return array
782 function getFlags() {
783 if ( !count( $this->stack ) ) {
784 return array(
785 'findEquals' => false,
786 'findPipe' => false,
787 'inHeading' => false,
789 } else {
790 return $this->top->getFlags();
796 * @ingroup Parser
798 class PPDStackElement {
799 var $open, // Opening character (\n for heading)
800 $close, // Matching closing character
801 $count, // Number of opening characters found (number of "=" for heading)
802 $parts, // Array of PPDPart objects describing pipe-separated parts.
803 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
805 var $partClass = 'PPDPart';
807 function __construct( $data = array() ) {
808 $class = $this->partClass;
809 $this->parts = array( new $class );
811 foreach ( $data as $name => $value ) {
812 $this->$name = $value;
816 function &getAccum() {
817 return $this->parts[count($this->parts) - 1]->out;
820 function addPart( $s = '' ) {
821 $class = $this->partClass;
822 $this->parts[] = new $class( $s );
825 function getCurrentPart() {
826 return $this->parts[count($this->parts) - 1];
830 * @return array
832 function getFlags() {
833 $partCount = count( $this->parts );
834 $findPipe = $this->open != "\n" && $this->open != '[';
835 return array(
836 'findPipe' => $findPipe,
837 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
838 'inHeading' => $this->open == "\n",
843 * Get the output string that would result if the close is not found.
845 * @return string
847 function breakSyntax( $openingCount = false ) {
848 if ( $this->open == "\n" ) {
849 $s = $this->parts[0]->out;
850 } else {
851 if ( $openingCount === false ) {
852 $openingCount = $this->count;
854 $s = str_repeat( $this->open, $openingCount );
855 $first = true;
856 foreach ( $this->parts as $part ) {
857 if ( $first ) {
858 $first = false;
859 } else {
860 $s .= '|';
862 $s .= $part->out;
865 return $s;
870 * @ingroup Parser
872 class PPDPart {
873 var $out; // Output accumulator string
875 // Optional member variables:
876 // eqpos Position of equals sign in output accumulator
877 // commentEnd Past-the-end input pointer for the last comment encountered
878 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
880 function __construct( $out = '' ) {
881 $this->out = $out;
886 * An expansion frame, used as a context to expand the result of preprocessToObj()
887 * @ingroup Parser
889 class PPFrame_DOM implements PPFrame {
892 * @var Preprocessor
894 var $preprocessor;
897 * @var Parser
899 var $parser;
902 * @var Title
904 var $title;
905 var $titleCache;
908 * Hashtable listing templates which are disallowed for expansion in this frame,
909 * having been encountered previously in parent frames.
911 var $loopCheckHash;
914 * Recursion depth of this frame, top = 0
915 * Note that this is NOT the same as expansion depth in expand()
917 var $depth;
921 * Construct a new preprocessor frame.
922 * @param $preprocessor Preprocessor The parent preprocessor
924 function __construct( $preprocessor ) {
925 $this->preprocessor = $preprocessor;
926 $this->parser = $preprocessor->parser;
927 $this->title = $this->parser->mTitle;
928 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
929 $this->loopCheckHash = array();
930 $this->depth = 0;
934 * Create a new child frame
935 * $args is optionally a multi-root PPNode or array containing the template arguments
937 * @return PPTemplateFrame_DOM
939 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
940 $namedArgs = array();
941 $numberedArgs = array();
942 if ( $title === false ) {
943 $title = $this->title;
945 if ( $args !== false ) {
946 $xpath = false;
947 if ( $args instanceof PPNode ) {
948 $args = $args->node;
950 foreach ( $args as $arg ) {
951 if ( $arg instanceof PPNode ) {
952 $arg = $arg->node;
954 if ( !$xpath ) {
955 $xpath = new DOMXPath( $arg->ownerDocument );
958 $nameNodes = $xpath->query( 'name', $arg );
959 $value = $xpath->query( 'value', $arg );
960 if ( $nameNodes->item( 0 )->hasAttributes() ) {
961 // Numbered parameter
962 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
963 $index = $index - $indexOffset;
964 $numberedArgs[$index] = $value->item( 0 );
965 unset( $namedArgs[$index] );
966 } else {
967 // Named parameter
968 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
969 $namedArgs[$name] = $value->item( 0 );
970 unset( $numberedArgs[$name] );
974 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
978 * @throws MWException
979 * @param $root
980 * @param $flags int
981 * @return string
983 function expand( $root, $flags = 0 ) {
984 static $expansionDepth = 0;
985 if ( is_string( $root ) ) {
986 return $root;
989 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
990 $this->parser->limitationWarn( 'node-count-exceeded',
991 $this->parser->mPPNodeCount,
992 $this->parser->mOptions->getMaxPPNodeCount()
994 return '<span class="error">Node-count limit exceeded</span>';
997 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
998 $this->parser->limitationWarn( 'expansion-depth-exceeded',
999 $expansionDepth,
1000 $this->parser->mOptions->getMaxPPExpandDepth()
1002 return '<span class="error">Expansion depth limit exceeded</span>';
1004 wfProfileIn( __METHOD__ );
1005 ++$expansionDepth;
1006 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1007 $this->parser->mHighestExpansionDepth = $expansionDepth;
1010 if ( $root instanceof PPNode_DOM ) {
1011 $root = $root->node;
1013 if ( $root instanceof DOMDocument ) {
1014 $root = $root->documentElement;
1017 $outStack = array( '', '' );
1018 $iteratorStack = array( false, $root );
1019 $indexStack = array( 0, 0 );
1021 while ( count( $iteratorStack ) > 1 ) {
1022 $level = count( $outStack ) - 1;
1023 $iteratorNode =& $iteratorStack[ $level ];
1024 $out =& $outStack[$level];
1025 $index =& $indexStack[$level];
1027 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
1029 if ( is_array( $iteratorNode ) ) {
1030 if ( $index >= count( $iteratorNode ) ) {
1031 // All done with this iterator
1032 $iteratorStack[$level] = false;
1033 $contextNode = false;
1034 } else {
1035 $contextNode = $iteratorNode[$index];
1036 $index++;
1038 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1039 if ( $index >= $iteratorNode->length ) {
1040 // All done with this iterator
1041 $iteratorStack[$level] = false;
1042 $contextNode = false;
1043 } else {
1044 $contextNode = $iteratorNode->item( $index );
1045 $index++;
1047 } else {
1048 // Copy to $contextNode and then delete from iterator stack,
1049 // because this is not an iterator but we do have to execute it once
1050 $contextNode = $iteratorStack[$level];
1051 $iteratorStack[$level] = false;
1054 if ( $contextNode instanceof PPNode_DOM ) {
1055 $contextNode = $contextNode->node;
1058 $newIterator = false;
1060 if ( $contextNode === false ) {
1061 // nothing to do
1062 } elseif ( is_string( $contextNode ) ) {
1063 $out .= $contextNode;
1064 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1065 $newIterator = $contextNode;
1066 } elseif ( $contextNode instanceof DOMNode ) {
1067 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1068 $out .= $contextNode->nodeValue;
1069 } elseif ( $contextNode->nodeName == 'template' ) {
1070 # Double-brace expansion
1071 $xpath = new DOMXPath( $contextNode->ownerDocument );
1072 $titles = $xpath->query( 'title', $contextNode );
1073 $title = $titles->item( 0 );
1074 $parts = $xpath->query( 'part', $contextNode );
1075 if ( $flags & PPFrame::NO_TEMPLATES ) {
1076 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1077 } else {
1078 $lineStart = $contextNode->getAttribute( 'lineStart' );
1079 $params = array(
1080 'title' => new PPNode_DOM( $title ),
1081 'parts' => new PPNode_DOM( $parts ),
1082 'lineStart' => $lineStart );
1083 $ret = $this->parser->braceSubstitution( $params, $this );
1084 if ( isset( $ret['object'] ) ) {
1085 $newIterator = $ret['object'];
1086 } else {
1087 $out .= $ret['text'];
1090 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1091 # Triple-brace expansion
1092 $xpath = new DOMXPath( $contextNode->ownerDocument );
1093 $titles = $xpath->query( 'title', $contextNode );
1094 $title = $titles->item( 0 );
1095 $parts = $xpath->query( 'part', $contextNode );
1096 if ( $flags & PPFrame::NO_ARGS ) {
1097 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1098 } else {
1099 $params = array(
1100 'title' => new PPNode_DOM( $title ),
1101 'parts' => new PPNode_DOM( $parts ) );
1102 $ret = $this->parser->argSubstitution( $params, $this );
1103 if ( isset( $ret['object'] ) ) {
1104 $newIterator = $ret['object'];
1105 } else {
1106 $out .= $ret['text'];
1109 } elseif ( $contextNode->nodeName == 'comment' ) {
1110 # HTML-style comment
1111 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1112 if ( $this->parser->ot['html']
1113 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1114 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1116 $out .= '';
1118 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1119 # Not in RECOVER_COMMENTS mode (extractSections) though
1120 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1121 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1123 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1124 else {
1125 $out .= $contextNode->textContent;
1127 } elseif ( $contextNode->nodeName == 'ignore' ) {
1128 # Output suppression used by <includeonly> etc.
1129 # OT_WIKI will only respect <ignore> in substed templates.
1130 # The other output types respect it unless NO_IGNORE is set.
1131 # extractSections() sets NO_IGNORE and so never respects it.
1132 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1133 $out .= $contextNode->textContent;
1134 } else {
1135 $out .= '';
1137 } elseif ( $contextNode->nodeName == 'ext' ) {
1138 # Extension tag
1139 $xpath = new DOMXPath( $contextNode->ownerDocument );
1140 $names = $xpath->query( 'name', $contextNode );
1141 $attrs = $xpath->query( 'attr', $contextNode );
1142 $inners = $xpath->query( 'inner', $contextNode );
1143 $closes = $xpath->query( 'close', $contextNode );
1144 $params = array(
1145 'name' => new PPNode_DOM( $names->item( 0 ) ),
1146 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1147 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1148 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1150 $out .= $this->parser->extensionSubstitution( $params, $this );
1151 } elseif ( $contextNode->nodeName == 'h' ) {
1152 # Heading
1153 $s = $this->expand( $contextNode->childNodes, $flags );
1155 # Insert a heading marker only for <h> children of <root>
1156 # This is to stop extractSections from going over multiple tree levels
1157 if ( $contextNode->parentNode->nodeName == 'root'
1158 && $this->parser->ot['html'] )
1160 # Insert heading index marker
1161 $headingIndex = $contextNode->getAttribute( 'i' );
1162 $titleText = $this->title->getPrefixedDBkey();
1163 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1164 $serial = count( $this->parser->mHeadings ) - 1;
1165 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1166 $count = $contextNode->getAttribute( 'level' );
1167 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1168 $this->parser->mStripState->addGeneral( $marker, '' );
1170 $out .= $s;
1171 } else {
1172 # Generic recursive expansion
1173 $newIterator = $contextNode->childNodes;
1175 } else {
1176 wfProfileOut( __METHOD__ );
1177 throw new MWException( __METHOD__.': Invalid parameter type' );
1180 if ( $newIterator !== false ) {
1181 if ( $newIterator instanceof PPNode_DOM ) {
1182 $newIterator = $newIterator->node;
1184 $outStack[] = '';
1185 $iteratorStack[] = $newIterator;
1186 $indexStack[] = 0;
1187 } elseif ( $iteratorStack[$level] === false ) {
1188 // Return accumulated value to parent
1189 // With tail recursion
1190 while ( $iteratorStack[$level] === false && $level > 0 ) {
1191 $outStack[$level - 1] .= $out;
1192 array_pop( $outStack );
1193 array_pop( $iteratorStack );
1194 array_pop( $indexStack );
1195 $level--;
1199 --$expansionDepth;
1200 wfProfileOut( __METHOD__ );
1201 return $outStack[0];
1205 * @param $sep
1206 * @param $flags
1207 * @return string
1209 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1210 $args = array_slice( func_get_args(), 2 );
1212 $first = true;
1213 $s = '';
1214 foreach ( $args as $root ) {
1215 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1216 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1217 $root = array( $root );
1219 foreach ( $root as $node ) {
1220 if ( $first ) {
1221 $first = false;
1222 } else {
1223 $s .= $sep;
1225 $s .= $this->expand( $node, $flags );
1228 return $s;
1232 * Implode with no flags specified
1233 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1235 * @return string
1237 function implode( $sep /*, ... */ ) {
1238 $args = array_slice( func_get_args(), 1 );
1240 $first = true;
1241 $s = '';
1242 foreach ( $args as $root ) {
1243 if ( $root instanceof PPNode_DOM ) {
1244 $root = $root->node;
1246 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1247 $root = array( $root );
1249 foreach ( $root as $node ) {
1250 if ( $first ) {
1251 $first = false;
1252 } else {
1253 $s .= $sep;
1255 $s .= $this->expand( $node );
1258 return $s;
1262 * Makes an object that, when expand()ed, will be the same as one obtained
1263 * with implode()
1265 * @return array
1267 function virtualImplode( $sep /*, ... */ ) {
1268 $args = array_slice( func_get_args(), 1 );
1269 $out = array();
1270 $first = true;
1272 foreach ( $args as $root ) {
1273 if ( $root instanceof PPNode_DOM ) {
1274 $root = $root->node;
1276 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1277 $root = array( $root );
1279 foreach ( $root as $node ) {
1280 if ( $first ) {
1281 $first = false;
1282 } else {
1283 $out[] = $sep;
1285 $out[] = $node;
1288 return $out;
1292 * Virtual implode with brackets
1293 * @return array
1295 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1296 $args = array_slice( func_get_args(), 3 );
1297 $out = array( $start );
1298 $first = true;
1300 foreach ( $args as $root ) {
1301 if ( $root instanceof PPNode_DOM ) {
1302 $root = $root->node;
1304 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1305 $root = array( $root );
1307 foreach ( $root as $node ) {
1308 if ( $first ) {
1309 $first = false;
1310 } else {
1311 $out[] = $sep;
1313 $out[] = $node;
1316 $out[] = $end;
1317 return $out;
1320 function __toString() {
1321 return 'frame{}';
1324 function getPDBK( $level = false ) {
1325 if ( $level === false ) {
1326 return $this->title->getPrefixedDBkey();
1327 } else {
1328 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1333 * @return array
1335 function getArguments() {
1336 return array();
1340 * @return array
1342 function getNumberedArguments() {
1343 return array();
1347 * @return array
1349 function getNamedArguments() {
1350 return array();
1354 * Returns true if there are no arguments in this frame
1356 * @return bool
1358 function isEmpty() {
1359 return true;
1362 function getArgument( $name ) {
1363 return false;
1367 * Returns true if the infinite loop check is OK, false if a loop is detected
1369 * @return bool
1371 function loopCheck( $title ) {
1372 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1376 * Return true if the frame is a template frame
1378 * @return bool
1380 function isTemplate() {
1381 return false;
1385 * Get a title of frame
1387 * @return Title
1389 function getTitle() {
1390 return $this->title;
1395 * Expansion frame with template arguments
1396 * @ingroup Parser
1398 class PPTemplateFrame_DOM extends PPFrame_DOM {
1399 var $numberedArgs, $namedArgs;
1402 * @var PPFrame_DOM
1404 var $parent;
1405 var $numberedExpansionCache, $namedExpansionCache;
1408 * @param $preprocessor
1409 * @param $parent PPFrame_DOM
1410 * @param $numberedArgs array
1411 * @param $namedArgs array
1412 * @param $title Title
1414 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1415 parent::__construct( $preprocessor );
1417 $this->parent = $parent;
1418 $this->numberedArgs = $numberedArgs;
1419 $this->namedArgs = $namedArgs;
1420 $this->title = $title;
1421 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1422 $this->titleCache = $parent->titleCache;
1423 $this->titleCache[] = $pdbk;
1424 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1425 if ( $pdbk !== false ) {
1426 $this->loopCheckHash[$pdbk] = true;
1428 $this->depth = $parent->depth + 1;
1429 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1432 function __toString() {
1433 $s = 'tplframe{';
1434 $first = true;
1435 $args = $this->numberedArgs + $this->namedArgs;
1436 foreach ( $args as $name => $value ) {
1437 if ( $first ) {
1438 $first = false;
1439 } else {
1440 $s .= ', ';
1442 $s .= "\"$name\":\"" .
1443 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1445 $s .= '}';
1446 return $s;
1450 * Returns true if there are no arguments in this frame
1452 * @return bool
1454 function isEmpty() {
1455 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1458 function getArguments() {
1459 $arguments = array();
1460 foreach ( array_merge(
1461 array_keys($this->numberedArgs),
1462 array_keys($this->namedArgs)) as $key ) {
1463 $arguments[$key] = $this->getArgument($key);
1465 return $arguments;
1468 function getNumberedArguments() {
1469 $arguments = array();
1470 foreach ( array_keys($this->numberedArgs) as $key ) {
1471 $arguments[$key] = $this->getArgument($key);
1473 return $arguments;
1476 function getNamedArguments() {
1477 $arguments = array();
1478 foreach ( array_keys($this->namedArgs) as $key ) {
1479 $arguments[$key] = $this->getArgument($key);
1481 return $arguments;
1484 function getNumberedArgument( $index ) {
1485 if ( !isset( $this->numberedArgs[$index] ) ) {
1486 return false;
1488 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1489 # No trimming for unnamed arguments
1490 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1492 return $this->numberedExpansionCache[$index];
1495 function getNamedArgument( $name ) {
1496 if ( !isset( $this->namedArgs[$name] ) ) {
1497 return false;
1499 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1500 # Trim named arguments post-expand, for backwards compatibility
1501 $this->namedExpansionCache[$name] = trim(
1502 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1504 return $this->namedExpansionCache[$name];
1507 function getArgument( $name ) {
1508 $text = $this->getNumberedArgument( $name );
1509 if ( $text === false ) {
1510 $text = $this->getNamedArgument( $name );
1512 return $text;
1516 * Return true if the frame is a template frame
1518 * @return bool
1520 function isTemplate() {
1521 return true;
1526 * Expansion frame with custom arguments
1527 * @ingroup Parser
1529 class PPCustomFrame_DOM extends PPFrame_DOM {
1530 var $args;
1532 function __construct( $preprocessor, $args ) {
1533 parent::__construct( $preprocessor );
1534 $this->args = $args;
1537 function __toString() {
1538 $s = 'cstmframe{';
1539 $first = true;
1540 foreach ( $this->args as $name => $value ) {
1541 if ( $first ) {
1542 $first = false;
1543 } else {
1544 $s .= ', ';
1546 $s .= "\"$name\":\"" .
1547 str_replace( '"', '\\"', $value->__toString() ) . '"';
1549 $s .= '}';
1550 return $s;
1554 * @return bool
1556 function isEmpty() {
1557 return !count( $this->args );
1560 function getArgument( $index ) {
1561 if ( !isset( $this->args[$index] ) ) {
1562 return false;
1564 return $this->args[$index];
1567 function getArguments() {
1568 return $this->args;
1573 * @ingroup Parser
1575 class PPNode_DOM implements PPNode {
1578 * @var DOMElement
1580 var $node;
1581 var $xpath;
1583 function __construct( $node, $xpath = false ) {
1584 $this->node = $node;
1588 * @return DOMXPath
1590 function getXPath() {
1591 if ( $this->xpath === null ) {
1592 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1594 return $this->xpath;
1597 function __toString() {
1598 if ( $this->node instanceof DOMNodeList ) {
1599 $s = '';
1600 foreach ( $this->node as $node ) {
1601 $s .= $node->ownerDocument->saveXML( $node );
1603 } else {
1604 $s = $this->node->ownerDocument->saveXML( $this->node );
1606 return $s;
1610 * @return bool|PPNode_DOM
1612 function getChildren() {
1613 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1617 * @return bool|PPNode_DOM
1619 function getFirstChild() {
1620 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1624 * @return bool|PPNode_DOM
1626 function getNextSibling() {
1627 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1631 * @param $type
1633 * @return bool|PPNode_DOM
1635 function getChildrenOfType( $type ) {
1636 return new self( $this->getXPath()->query( $type, $this->node ) );
1640 * @return int
1642 function getLength() {
1643 if ( $this->node instanceof DOMNodeList ) {
1644 return $this->node->length;
1645 } else {
1646 return false;
1651 * @param $i
1652 * @return bool|PPNode_DOM
1654 function item( $i ) {
1655 $item = $this->node->item( $i );
1656 return $item ? new self( $item ) : false;
1660 * @return string
1662 function getName() {
1663 if ( $this->node instanceof DOMNodeList ) {
1664 return '#nodelist';
1665 } else {
1666 return $this->node->nodeName;
1671 * Split a "<part>" node into an associative array containing:
1672 * - name PPNode name
1673 * - index String index
1674 * - value PPNode value
1676 * @return array
1678 function splitArg() {
1679 $xpath = $this->getXPath();
1680 $names = $xpath->query( 'name', $this->node );
1681 $values = $xpath->query( 'value', $this->node );
1682 if ( !$names->length || !$values->length ) {
1683 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1685 $name = $names->item( 0 );
1686 $index = $name->getAttribute( 'index' );
1687 return array(
1688 'name' => new self( $name ),
1689 'index' => $index,
1690 'value' => new self( $values->item( 0 ) ) );
1694 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1695 * All values in the resulting array are PPNodes. Inner and close are optional.
1697 * @return array
1699 function splitExt() {
1700 $xpath = $this->getXPath();
1701 $names = $xpath->query( 'name', $this->node );
1702 $attrs = $xpath->query( 'attr', $this->node );
1703 $inners = $xpath->query( 'inner', $this->node );
1704 $closes = $xpath->query( 'close', $this->node );
1705 if ( !$names->length || !$attrs->length ) {
1706 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1708 $parts = array(
1709 'name' => new self( $names->item( 0 ) ),
1710 'attr' => new self( $attrs->item( 0 ) ) );
1711 if ( $inners->length ) {
1712 $parts['inner'] = new self( $inners->item( 0 ) );
1714 if ( $closes->length ) {
1715 $parts['close'] = new self( $closes->item( 0 ) );
1717 return $parts;
1721 * Split a "<h>" node
1722 * @return array
1724 function splitHeading() {
1725 if ( $this->getName() !== 'h' ) {
1726 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1728 return array(
1729 'i' => $this->node->getAttribute( 'i' ),
1730 'level' => $this->node->getAttribute( 'level' ),
1731 'contents' => $this->getChildren()