Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob809e7f7000d9b9c0864a34e304cd6e98ca9a8027
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 ) {
75 if ( is_int( $k ) ) {
76 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) . "</value></part>";
77 } else {
78 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
82 $xml .= "</list>";
84 $dom = new DOMDocument();
85 $dom->loadXML( $xml );
86 $root = $dom->documentElement;
88 $node = new PPNode_DOM( $root->childNodes );
89 return $node;
92 /**
93 * @throws MWException
94 * @return bool
96 function memCheck() {
97 if ( $this->memoryLimit === false ) {
98 return true;
100 $usage = memory_get_usage();
101 if ( $usage > $this->memoryLimit * 0.9 ) {
102 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
103 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
105 return $usage <= $this->memoryLimit * 0.8;
109 * Preprocess some wikitext and return the document tree.
110 * This is the ghost of Parser::replace_variables().
112 * @param string $text the text to parse
113 * @param $flags Integer: bitwise combination of:
114 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
115 * included. Default is to assume a direct page view.
117 * The generated DOM tree must depend only on the input text and the flags.
118 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
120 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
121 * change in the DOM tree for a given text, must be passed through the section identifier
122 * in the section edit link and thus back to extractSections().
124 * The output of this function is currently only cached in process memory, but a persistent
125 * cache may be implemented at a later date which takes further advantage of these strict
126 * dependency requirements.
128 * @throws MWException
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)" );
151 if ( $xml === false ) {
152 wfProfileIn( __METHOD__ . '-cache-miss' );
153 $xml = $this->preprocessToXml( $text, $flags );
154 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
155 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
156 wfProfileOut( __METHOD__ . '-cache-miss' );
157 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
159 } else {
160 $xml = $this->preprocessToXml( $text, $flags );
164 // Fail if the number of elements exceeds acceptable limits
165 // Do not attempt to generate the DOM
166 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
167 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
168 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
169 if ( $cacheable ) {
170 wfProfileOut( __METHOD__ . '-cacheable' );
172 wfProfileOut( __METHOD__ );
173 throw new MWException( __METHOD__ . ': generated node count limit exceeded' );
176 wfProfileIn( __METHOD__ . '-loadXML' );
177 $dom = new DOMDocument;
178 wfSuppressWarnings();
179 $result = $dom->loadXML( $xml );
180 wfRestoreWarnings();
181 if ( !$result ) {
182 // Try running the XML through UtfNormal to get rid of invalid characters
183 $xml = UtfNormal::cleanUp( $xml );
184 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
185 $result = $dom->loadXML( $xml, 1 << 19 );
186 if ( !$result ) {
187 wfProfileOut( __METHOD__ . '-loadXML' );
188 if ( $cacheable ) {
189 wfProfileOut( __METHOD__ . '-cacheable' );
191 wfProfileOut( __METHOD__ );
192 throw new MWException( __METHOD__ . ' generated invalid XML' );
195 $obj = new PPNode_DOM( $dom->documentElement );
196 wfProfileOut( __METHOD__ . '-loadXML' );
197 if ( $cacheable ) {
198 wfProfileOut( __METHOD__ . '-cacheable' );
200 wfProfileOut( __METHOD__ );
201 return $obj;
205 * @param $text string
206 * @param $flags int
207 * @return string
209 function preprocessToXml( $text, $flags = 0 ) {
210 wfProfileIn( __METHOD__ );
211 $rules = array(
212 '{' => array(
213 'end' => '}',
214 'names' => array(
215 2 => 'template',
216 3 => 'tplarg',
218 'min' => 2,
219 'max' => 3,
221 '[' => array(
222 'end' => ']',
223 'names' => array( 2 => null ),
224 'min' => 2,
225 'max' => 2,
229 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
231 $xmlishElements = $this->parser->getStripList();
232 $enableOnlyinclude = false;
233 if ( $forInclusion ) {
234 $ignoredTags = array( 'includeonly', '/includeonly' );
235 $ignoredElements = array( 'noinclude' );
236 $xmlishElements[] = 'noinclude';
237 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
238 $enableOnlyinclude = true;
240 } else {
241 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
242 $ignoredElements = array( 'includeonly' );
243 $xmlishElements[] = 'includeonly';
245 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
247 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
248 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
250 $stack = new PPDStack;
252 $searchBase = "[{<\n"; #}
253 $revText = strrev( $text ); // For fast reverse searches
254 $lengthText = strlen( $text );
256 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
257 $accum =& $stack->getAccum(); # Current accumulator
258 $accum = '<root>';
259 $findEquals = false; # True to find equals signs in arguments
260 $findPipe = false; # True to take notice of pipe characters
261 $headingIndex = 1;
262 $inHeading = false; # True if $i is inside a possible heading
263 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
264 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
265 $fakeLineStart = true; # Do a line-start run without outputting an LF character
267 while ( true ) {
268 //$this->memCheck();
270 if ( $findOnlyinclude ) {
271 // Ignore all input up to the next <onlyinclude>
272 $startPos = strpos( $text, '<onlyinclude>', $i );
273 if ( $startPos === false ) {
274 // Ignored section runs to the end
275 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
276 break;
278 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
279 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
280 $i = $tagEndPos;
281 $findOnlyinclude = false;
284 if ( $fakeLineStart ) {
285 $found = 'line-start';
286 $curChar = '';
287 } else {
288 # Find next opening brace, closing brace or pipe
289 $search = $searchBase;
290 if ( $stack->top === false ) {
291 $currentClosing = '';
292 } else {
293 $currentClosing = $stack->top->close;
294 $search .= $currentClosing;
296 if ( $findPipe ) {
297 $search .= '|';
299 if ( $findEquals ) {
300 // First equals will be for the template
301 $search .= '=';
303 $rule = null;
304 # Output literal section, advance input counter
305 $literalLength = strcspn( $text, $search, $i );
306 if ( $literalLength > 0 ) {
307 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
308 $i += $literalLength;
310 if ( $i >= $lengthText ) {
311 if ( $currentClosing == "\n" ) {
312 // Do a past-the-end run to finish off the heading
313 $curChar = '';
314 $found = 'line-end';
315 } else {
316 # All done
317 break;
319 } else {
320 $curChar = $text[$i];
321 if ( $curChar == '|' ) {
322 $found = 'pipe';
323 } elseif ( $curChar == '=' ) {
324 $found = 'equals';
325 } elseif ( $curChar == '<' ) {
326 $found = 'angle';
327 } elseif ( $curChar == "\n" ) {
328 if ( $inHeading ) {
329 $found = 'line-end';
330 } else {
331 $found = 'line-start';
333 } elseif ( $curChar == $currentClosing ) {
334 $found = 'close';
335 } elseif ( isset( $rules[$curChar] ) ) {
336 $found = 'open';
337 $rule = $rules[$curChar];
338 } else {
339 # Some versions of PHP have a strcspn which stops on null characters
340 # Ignore and continue
341 ++$i;
342 continue;
347 if ( $found == 'angle' ) {
348 $matches = false;
349 // Handle </onlyinclude>
350 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
351 $findOnlyinclude = true;
352 continue;
355 // Determine element name
356 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
357 // Element name missing or not listed
358 $accum .= '&lt;';
359 ++$i;
360 continue;
362 // Handle comments
363 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
364 // To avoid leaving blank lines, when a comment is both preceded
365 // and followed by a newline (ignoring spaces), trim leading and
366 // trailing spaces and one of the newlines.
368 // Find the end
369 $endPos = strpos( $text, '-->', $i + 4 );
370 if ( $endPos === false ) {
371 // Unclosed comment in input, runs to end
372 $inner = substr( $text, $i );
373 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
374 $i = $lengthText;
375 } else {
376 // Search backwards for leading whitespace
377 $wsStart = $i ? ( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
378 // Search forwards for trailing whitespace
379 // $wsEnd will be the position of the last space (or the '>' if there's none)
380 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
381 // Eat the line if possible
382 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
383 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
384 // it's a possible beneficial b/c break.
385 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
386 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
388 $startPos = $wsStart;
389 $endPos = $wsEnd + 1;
390 // Remove leading whitespace from the end of the accumulator
391 // Sanity check first though
392 $wsLength = $i - $wsStart;
393 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
394 $accum = substr( $accum, 0, -$wsLength );
396 // Do a line-start run next time to look for headings after the comment
397 $fakeLineStart = true;
398 } else {
399 // No line to eat, just take the comment itself
400 $startPos = $i;
401 $endPos += 2;
404 if ( $stack->top ) {
405 $part = $stack->top->getCurrentPart();
406 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
407 $part->visualEnd = $wsStart;
409 // Else comments abutting, no change in visual end
410 $part->commentEnd = $endPos;
412 $i = $endPos + 1;
413 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
414 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
416 continue;
418 $name = $matches[1];
419 $lowerName = strtolower( $name );
420 $attrStart = $i + strlen( $name ) + 1;
422 // Find end of tag
423 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
424 if ( $tagEndPos === false ) {
425 // Infinite backtrack
426 // Disable tag search to prevent worst-case O(N^2) performance
427 $noMoreGT = true;
428 $accum .= '&lt;';
429 ++$i;
430 continue;
433 // Handle ignored tags
434 if ( in_array( $lowerName, $ignoredTags ) ) {
435 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
436 $i = $tagEndPos + 1;
437 continue;
440 $tagStartPos = $i;
441 if ( $text[$tagEndPos - 1] == '/' ) {
442 $attrEnd = $tagEndPos - 1;
443 $inner = null;
444 $i = $tagEndPos + 1;
445 $close = '';
446 } else {
447 $attrEnd = $tagEndPos;
448 // Find closing tag
449 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
450 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
452 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
453 $i = $matches[0][1] + strlen( $matches[0][0] );
454 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
455 } else {
456 // No end tag -- let it run out to the end of the text.
457 $inner = substr( $text, $tagEndPos + 1 );
458 $i = $lengthText;
459 $close = '';
462 // <includeonly> and <noinclude> just become <ignore> tags
463 if ( in_array( $lowerName, $ignoredElements ) ) {
464 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
465 . '</ignore>';
466 continue;
469 $accum .= '<ext>';
470 if ( $attrEnd <= $attrStart ) {
471 $attr = '';
472 } else {
473 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
475 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
476 // Note that the attr element contains the whitespace between name and attribute,
477 // this is necessary for precise reconstruction during pre-save transform.
478 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
479 if ( $inner !== null ) {
480 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
482 $accum .= $close . '</ext>';
483 } elseif ( $found == 'line-start' ) {
484 // Is this the start of a heading?
485 // Line break belongs before the heading element in any case
486 if ( $fakeLineStart ) {
487 $fakeLineStart = false;
488 } else {
489 $accum .= $curChar;
490 $i++;
493 $count = strspn( $text, '=', $i, 6 );
494 if ( $count == 1 && $findEquals ) {
495 // DWIM: This looks kind of like a name/value separator
496 // Let's let the equals handler have it and break the potential heading
497 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
498 } elseif ( $count > 0 ) {
499 $piece = array(
500 'open' => "\n",
501 'close' => "\n",
502 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
503 'startPos' => $i,
504 'count' => $count );
505 $stack->push( $piece );
506 $accum =& $stack->getAccum();
507 $flags = $stack->getFlags();
508 extract( $flags );
509 $i += $count;
511 } elseif ( $found == 'line-end' ) {
512 $piece = $stack->top;
513 // A heading must be open, otherwise \n wouldn't have been in the search list
514 assert( '$piece->open == "\n"' );
515 $part = $piece->getCurrentPart();
516 // Search back through the input to see if it has a proper close
517 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
518 $wsLength = strspn( $revText, " \t", $lengthText - $i );
519 $searchStart = $i - $wsLength;
520 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
521 // Comment found at line end
522 // Search for equals signs before the comment
523 $searchStart = $part->visualEnd;
524 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
526 $count = $piece->count;
527 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
528 if ( $equalsLength > 0 ) {
529 if ( $searchStart - $equalsLength == $piece->startPos ) {
530 // This is just a single string of equals signs on its own line
531 // Replicate the doHeadings behavior /={count}(.+)={count}/
532 // First find out how many equals signs there really are (don't stop at 6)
533 $count = $equalsLength;
534 if ( $count < 3 ) {
535 $count = 0;
536 } else {
537 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
539 } else {
540 $count = min( $equalsLength, $count );
542 if ( $count > 0 ) {
543 // Normal match, output <h>
544 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
545 $headingIndex++;
546 } else {
547 // Single equals sign on its own line, count=0
548 $element = $accum;
550 } else {
551 // No match, no <h>, just pass down the inner text
552 $element = $accum;
554 // Unwind the stack
555 $stack->pop();
556 $accum =& $stack->getAccum();
557 $flags = $stack->getFlags();
558 extract( $flags );
560 // Append the result to the enclosing accumulator
561 $accum .= $element;
562 // Note that we do NOT increment the input pointer.
563 // This is because the closing linebreak could be the opening linebreak of
564 // another heading. Infinite loops are avoided because the next iteration MUST
565 // hit the heading open case above, which unconditionally increments the
566 // input pointer.
567 } elseif ( $found == 'open' ) {
568 # count opening brace characters
569 $count = strspn( $text, $curChar, $i );
571 # we need to add to stack only if opening brace count is enough for one of the rules
572 if ( $count >= $rule['min'] ) {
573 # Add it to the stack
574 $piece = array(
575 'open' => $curChar,
576 'close' => $rule['end'],
577 'count' => $count,
578 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
581 $stack->push( $piece );
582 $accum =& $stack->getAccum();
583 $flags = $stack->getFlags();
584 extract( $flags );
585 } else {
586 # Add literal brace(s)
587 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
589 $i += $count;
590 } elseif ( $found == 'close' ) {
591 $piece = $stack->top;
592 # lets check if there are enough characters for closing brace
593 $maxCount = $piece->count;
594 $count = strspn( $text, $curChar, $i, $maxCount );
596 # check for maximum matching characters (if there are 5 closing
597 # characters, we will probably need only 3 - depending on the rules)
598 $rule = $rules[$piece->open];
599 if ( $count > $rule['max'] ) {
600 # The specified maximum exists in the callback array, unless the caller
601 # has made an error
602 $matchingCount = $rule['max'];
603 } else {
604 # Count is less than the maximum
605 # Skip any gaps in the callback array to find the true largest match
606 # Need to use array_key_exists not isset because the callback can be null
607 $matchingCount = $count;
608 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
609 --$matchingCount;
613 if ( $matchingCount <= 0 ) {
614 # No matching element found in callback array
615 # Output a literal closing brace and continue
616 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
617 $i += $count;
618 continue;
620 $name = $rule['names'][$matchingCount];
621 if ( $name === null ) {
622 // No element, just literal text
623 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
624 } else {
625 # Create XML element
626 # Note: $parts is already XML, does not need to be encoded further
627 $parts = $piece->parts;
628 $title = $parts[0]->out;
629 unset( $parts[0] );
631 # The invocation is at the start of the line if lineStart is set in
632 # the stack, and all opening brackets are used up.
633 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
634 $attr = ' lineStart="1"';
635 } else {
636 $attr = '';
639 $element = "<$name$attr>";
640 $element .= "<title>$title</title>";
641 $argIndex = 1;
642 foreach ( $parts as $part ) {
643 if ( isset( $part->eqpos ) ) {
644 $argName = substr( $part->out, 0, $part->eqpos );
645 $argValue = substr( $part->out, $part->eqpos + 1 );
646 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
647 } else {
648 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
649 $argIndex++;
652 $element .= "</$name>";
655 # Advance input pointer
656 $i += $matchingCount;
658 # Unwind the stack
659 $stack->pop();
660 $accum =& $stack->getAccum();
662 # Re-add the old stack element if it still has unmatched opening characters remaining
663 if ( $matchingCount < $piece->count ) {
664 $piece->parts = array( new PPDPart );
665 $piece->count -= $matchingCount;
666 # do we still qualify for any callback with remaining count?
667 $min = $rules[$piece->open]['min'];
668 if ( $piece->count >= $min ) {
669 $stack->push( $piece );
670 $accum =& $stack->getAccum();
671 } else {
672 $accum .= str_repeat( $piece->open, $piece->count );
675 $flags = $stack->getFlags();
676 extract( $flags );
678 # Add XML element to the enclosing accumulator
679 $accum .= $element;
680 } elseif ( $found == 'pipe' ) {
681 $findEquals = true; // shortcut for getFlags()
682 $stack->addPart();
683 $accum =& $stack->getAccum();
684 ++$i;
685 } elseif ( $found == 'equals' ) {
686 $findEquals = false; // shortcut for getFlags()
687 $stack->getCurrentPart()->eqpos = strlen( $accum );
688 $accum .= '=';
689 ++$i;
693 # Output any remaining unclosed brackets
694 foreach ( $stack->stack as $piece ) {
695 $stack->rootAccum .= $piece->breakSyntax();
697 $stack->rootAccum .= '</root>';
698 $xml = $stack->rootAccum;
700 wfProfileOut( __METHOD__ );
702 return $xml;
707 * Stack class to help Preprocessor::preprocessToObj()
708 * @ingroup Parser
710 class PPDStack {
711 var $stack, $rootAccum;
714 * @var PPDStack
716 var $top;
717 var $out;
718 var $elementClass = 'PPDStackElement';
720 static $false = false;
722 function __construct() {
723 $this->stack = array();
724 $this->top = false;
725 $this->rootAccum = '';
726 $this->accum =& $this->rootAccum;
730 * @return int
732 function count() {
733 return count( $this->stack );
736 function &getAccum() {
737 return $this->accum;
740 function getCurrentPart() {
741 if ( $this->top === false ) {
742 return false;
743 } else {
744 return $this->top->getCurrentPart();
748 function push( $data ) {
749 if ( $data instanceof $this->elementClass ) {
750 $this->stack[] = $data;
751 } else {
752 $class = $this->elementClass;
753 $this->stack[] = new $class( $data );
755 $this->top = $this->stack[count( $this->stack ) - 1];
756 $this->accum =& $this->top->getAccum();
759 function pop() {
760 if ( !count( $this->stack ) ) {
761 throw new MWException( __METHOD__ . ': no elements remaining' );
763 $temp = array_pop( $this->stack );
765 if ( count( $this->stack ) ) {
766 $this->top = $this->stack[count( $this->stack ) - 1];
767 $this->accum =& $this->top->getAccum();
768 } else {
769 $this->top = self::$false;
770 $this->accum =& $this->rootAccum;
772 return $temp;
775 function addPart( $s = '' ) {
776 $this->top->addPart( $s );
777 $this->accum =& $this->top->getAccum();
781 * @return array
783 function getFlags() {
784 if ( !count( $this->stack ) ) {
785 return array(
786 'findEquals' => false,
787 'findPipe' => false,
788 'inHeading' => false,
790 } else {
791 return $this->top->getFlags();
797 * @ingroup Parser
799 class PPDStackElement {
800 var $open, // Opening character (\n for heading)
801 $close, // Matching closing character
802 $count, // Number of opening characters found (number of "=" for heading)
803 $parts, // Array of PPDPart objects describing pipe-separated parts.
804 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
806 var $partClass = 'PPDPart';
808 function __construct( $data = array() ) {
809 $class = $this->partClass;
810 $this->parts = array( new $class );
812 foreach ( $data as $name => $value ) {
813 $this->$name = $value;
817 function &getAccum() {
818 return $this->parts[count( $this->parts ) - 1]->out;
821 function addPart( $s = '' ) {
822 $class = $this->partClass;
823 $this->parts[] = new $class( $s );
826 function getCurrentPart() {
827 return $this->parts[count( $this->parts ) - 1];
831 * @return array
833 function getFlags() {
834 $partCount = count( $this->parts );
835 $findPipe = $this->open != "\n" && $this->open != '[';
836 return array(
837 'findPipe' => $findPipe,
838 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
839 'inHeading' => $this->open == "\n",
844 * Get the output string that would result if the close is not found.
846 * @return string
848 function breakSyntax( $openingCount = false ) {
849 if ( $this->open == "\n" ) {
850 $s = $this->parts[0]->out;
851 } else {
852 if ( $openingCount === false ) {
853 $openingCount = $this->count;
855 $s = str_repeat( $this->open, $openingCount );
856 $first = true;
857 foreach ( $this->parts as $part ) {
858 if ( $first ) {
859 $first = false;
860 } else {
861 $s .= '|';
863 $s .= $part->out;
866 return $s;
871 * @ingroup Parser
873 class PPDPart {
874 var $out; // Output accumulator string
876 // Optional member variables:
877 // eqpos Position of equals sign in output accumulator
878 // commentEnd Past-the-end input pointer for the last comment encountered
879 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
881 function __construct( $out = '' ) {
882 $this->out = $out;
887 * An expansion frame, used as a context to expand the result of preprocessToObj()
888 * @ingroup Parser
890 class PPFrame_DOM implements PPFrame {
893 * @var Preprocessor
895 var $preprocessor;
898 * @var Parser
900 var $parser;
903 * @var Title
905 var $title;
906 var $titleCache;
909 * Hashtable listing templates which are disallowed for expansion in this frame,
910 * having been encountered previously in parent frames.
912 var $loopCheckHash;
915 * Recursion depth of this frame, top = 0
916 * Note that this is NOT the same as expansion depth in expand()
918 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 ) {
1028 $iteratorNode = $iteratorNode->node;
1031 if ( is_array( $iteratorNode ) ) {
1032 if ( $index >= count( $iteratorNode ) ) {
1033 // All done with this iterator
1034 $iteratorStack[$level] = false;
1035 $contextNode = false;
1036 } else {
1037 $contextNode = $iteratorNode[$index];
1038 $index++;
1040 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1041 if ( $index >= $iteratorNode->length ) {
1042 // All done with this iterator
1043 $iteratorStack[$level] = false;
1044 $contextNode = false;
1045 } else {
1046 $contextNode = $iteratorNode->item( $index );
1047 $index++;
1049 } else {
1050 // Copy to $contextNode and then delete from iterator stack,
1051 // because this is not an iterator but we do have to execute it once
1052 $contextNode = $iteratorStack[$level];
1053 $iteratorStack[$level] = false;
1056 if ( $contextNode instanceof PPNode_DOM ) {
1057 $contextNode = $contextNode->node;
1060 $newIterator = false;
1062 if ( $contextNode === false ) {
1063 // nothing to do
1064 } elseif ( is_string( $contextNode ) ) {
1065 $out .= $contextNode;
1066 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1067 $newIterator = $contextNode;
1068 } elseif ( $contextNode instanceof DOMNode ) {
1069 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1070 $out .= $contextNode->nodeValue;
1071 } elseif ( $contextNode->nodeName == 'template' ) {
1072 # Double-brace expansion
1073 $xpath = new DOMXPath( $contextNode->ownerDocument );
1074 $titles = $xpath->query( 'title', $contextNode );
1075 $title = $titles->item( 0 );
1076 $parts = $xpath->query( 'part', $contextNode );
1077 if ( $flags & PPFrame::NO_TEMPLATES ) {
1078 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1079 } else {
1080 $lineStart = $contextNode->getAttribute( 'lineStart' );
1081 $params = array(
1082 'title' => new PPNode_DOM( $title ),
1083 'parts' => new PPNode_DOM( $parts ),
1084 'lineStart' => $lineStart );
1085 $ret = $this->parser->braceSubstitution( $params, $this );
1086 if ( isset( $ret['object'] ) ) {
1087 $newIterator = $ret['object'];
1088 } else {
1089 $out .= $ret['text'];
1092 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1093 # Triple-brace expansion
1094 $xpath = new DOMXPath( $contextNode->ownerDocument );
1095 $titles = $xpath->query( 'title', $contextNode );
1096 $title = $titles->item( 0 );
1097 $parts = $xpath->query( 'part', $contextNode );
1098 if ( $flags & PPFrame::NO_ARGS ) {
1099 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1100 } else {
1101 $params = array(
1102 'title' => new PPNode_DOM( $title ),
1103 'parts' => new PPNode_DOM( $parts ) );
1104 $ret = $this->parser->argSubstitution( $params, $this );
1105 if ( isset( $ret['object'] ) ) {
1106 $newIterator = $ret['object'];
1107 } else {
1108 $out .= $ret['text'];
1111 } elseif ( $contextNode->nodeName == 'comment' ) {
1112 # HTML-style comment
1113 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1114 if ( $this->parser->ot['html']
1115 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1116 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1118 $out .= '';
1120 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1121 # Not in RECOVER_COMMENTS mode (extractSections) though
1122 elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1123 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1125 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1126 else {
1127 $out .= $contextNode->textContent;
1129 } elseif ( $contextNode->nodeName == 'ignore' ) {
1130 # Output suppression used by <includeonly> etc.
1131 # OT_WIKI will only respect <ignore> in substed templates.
1132 # The other output types respect it unless NO_IGNORE is set.
1133 # extractSections() sets NO_IGNORE and so never respects it.
1134 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1135 $out .= $contextNode->textContent;
1136 } else {
1137 $out .= '';
1139 } elseif ( $contextNode->nodeName == 'ext' ) {
1140 # Extension tag
1141 $xpath = new DOMXPath( $contextNode->ownerDocument );
1142 $names = $xpath->query( 'name', $contextNode );
1143 $attrs = $xpath->query( 'attr', $contextNode );
1144 $inners = $xpath->query( 'inner', $contextNode );
1145 $closes = $xpath->query( 'close', $contextNode );
1146 $params = array(
1147 'name' => new PPNode_DOM( $names->item( 0 ) ),
1148 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1149 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1150 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1152 $out .= $this->parser->extensionSubstitution( $params, $this );
1153 } elseif ( $contextNode->nodeName == 'h' ) {
1154 # Heading
1155 $s = $this->expand( $contextNode->childNodes, $flags );
1157 # Insert a heading marker only for <h> children of <root>
1158 # This is to stop extractSections from going over multiple tree levels
1159 if ( $contextNode->parentNode->nodeName == 'root' && $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 ) {
1216 $root = $root->node;
1218 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1219 $root = array( $root );
1221 foreach ( $root as $node ) {
1222 if ( $first ) {
1223 $first = false;
1224 } else {
1225 $s .= $sep;
1227 $s .= $this->expand( $node, $flags );
1230 return $s;
1234 * Implode with no flags specified
1235 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1237 * @return string
1239 function implode( $sep /*, ... */ ) {
1240 $args = array_slice( func_get_args(), 1 );
1242 $first = true;
1243 $s = '';
1244 foreach ( $args as $root ) {
1245 if ( $root instanceof PPNode_DOM ) {
1246 $root = $root->node;
1248 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1249 $root = array( $root );
1251 foreach ( $root as $node ) {
1252 if ( $first ) {
1253 $first = false;
1254 } else {
1255 $s .= $sep;
1257 $s .= $this->expand( $node );
1260 return $s;
1264 * Makes an object that, when expand()ed, will be the same as one obtained
1265 * with implode()
1267 * @return array
1269 function virtualImplode( $sep /*, ... */ ) {
1270 $args = array_slice( func_get_args(), 1 );
1271 $out = array();
1272 $first = true;
1274 foreach ( $args as $root ) {
1275 if ( $root instanceof PPNode_DOM ) {
1276 $root = $root->node;
1278 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1279 $root = array( $root );
1281 foreach ( $root as $node ) {
1282 if ( $first ) {
1283 $first = false;
1284 } else {
1285 $out[] = $sep;
1287 $out[] = $node;
1290 return $out;
1294 * Virtual implode with brackets
1295 * @return array
1297 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1298 $args = array_slice( func_get_args(), 3 );
1299 $out = array( $start );
1300 $first = true;
1302 foreach ( $args as $root ) {
1303 if ( $root instanceof PPNode_DOM ) {
1304 $root = $root->node;
1306 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1307 $root = array( $root );
1309 foreach ( $root as $node ) {
1310 if ( $first ) {
1311 $first = false;
1312 } else {
1313 $out[] = $sep;
1315 $out[] = $node;
1318 $out[] = $end;
1319 return $out;
1322 function __toString() {
1323 return 'frame{}';
1326 function getPDBK( $level = false ) {
1327 if ( $level === false ) {
1328 return $this->title->getPrefixedDBkey();
1329 } else {
1330 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1335 * @return array
1337 function getArguments() {
1338 return array();
1342 * @return array
1344 function getNumberedArguments() {
1345 return array();
1349 * @return array
1351 function getNamedArguments() {
1352 return array();
1356 * Returns true if there are no arguments in this frame
1358 * @return bool
1360 function isEmpty() {
1361 return true;
1364 function getArgument( $name ) {
1365 return false;
1369 * Returns true if the infinite loop check is OK, false if a loop is detected
1371 * @return bool
1373 function loopCheck( $title ) {
1374 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1378 * Return true if the frame is a template frame
1380 * @return bool
1382 function isTemplate() {
1383 return false;
1387 * Get a title of frame
1389 * @return Title
1391 function getTitle() {
1392 return $this->title;
1397 * Expansion frame with template arguments
1398 * @ingroup Parser
1400 class PPTemplateFrame_DOM extends PPFrame_DOM {
1401 var $numberedArgs, $namedArgs;
1404 * @var PPFrame_DOM
1406 var $parent;
1407 var $numberedExpansionCache, $namedExpansionCache;
1410 * @param $preprocessor
1411 * @param $parent PPFrame_DOM
1412 * @param $numberedArgs array
1413 * @param $namedArgs array
1414 * @param $title Title
1416 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1417 parent::__construct( $preprocessor );
1419 $this->parent = $parent;
1420 $this->numberedArgs = $numberedArgs;
1421 $this->namedArgs = $namedArgs;
1422 $this->title = $title;
1423 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1424 $this->titleCache = $parent->titleCache;
1425 $this->titleCache[] = $pdbk;
1426 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1427 if ( $pdbk !== false ) {
1428 $this->loopCheckHash[$pdbk] = true;
1430 $this->depth = $parent->depth + 1;
1431 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1434 function __toString() {
1435 $s = 'tplframe{';
1436 $first = true;
1437 $args = $this->numberedArgs + $this->namedArgs;
1438 foreach ( $args as $name => $value ) {
1439 if ( $first ) {
1440 $first = false;
1441 } else {
1442 $s .= ', ';
1444 $s .= "\"$name\":\"" .
1445 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1447 $s .= '}';
1448 return $s;
1452 * Returns true if there are no arguments in this frame
1454 * @return bool
1456 function isEmpty() {
1457 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1460 function getArguments() {
1461 $arguments = array();
1462 foreach ( array_merge(
1463 array_keys( $this->numberedArgs ),
1464 array_keys( $this->namedArgs ) ) as $key ) {
1465 $arguments[$key] = $this->getArgument( $key );
1467 return $arguments;
1470 function getNumberedArguments() {
1471 $arguments = array();
1472 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1473 $arguments[$key] = $this->getArgument( $key );
1475 return $arguments;
1478 function getNamedArguments() {
1479 $arguments = array();
1480 foreach ( array_keys( $this->namedArgs ) as $key ) {
1481 $arguments[$key] = $this->getArgument( $key );
1483 return $arguments;
1486 function getNumberedArgument( $index ) {
1487 if ( !isset( $this->numberedArgs[$index] ) ) {
1488 return false;
1490 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1491 # No trimming for unnamed arguments
1492 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1494 return $this->numberedExpansionCache[$index];
1497 function getNamedArgument( $name ) {
1498 if ( !isset( $this->namedArgs[$name] ) ) {
1499 return false;
1501 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1502 # Trim named arguments post-expand, for backwards compatibility
1503 $this->namedExpansionCache[$name] = trim(
1504 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1506 return $this->namedExpansionCache[$name];
1509 function getArgument( $name ) {
1510 $text = $this->getNumberedArgument( $name );
1511 if ( $text === false ) {
1512 $text = $this->getNamedArgument( $name );
1514 return $text;
1518 * Return true if the frame is a template frame
1520 * @return bool
1522 function isTemplate() {
1523 return true;
1528 * Expansion frame with custom arguments
1529 * @ingroup Parser
1531 class PPCustomFrame_DOM extends PPFrame_DOM {
1532 var $args;
1534 function __construct( $preprocessor, $args ) {
1535 parent::__construct( $preprocessor );
1536 $this->args = $args;
1539 function __toString() {
1540 $s = 'cstmframe{';
1541 $first = true;
1542 foreach ( $this->args as $name => $value ) {
1543 if ( $first ) {
1544 $first = false;
1545 } else {
1546 $s .= ', ';
1548 $s .= "\"$name\":\"" .
1549 str_replace( '"', '\\"', $value->__toString() ) . '"';
1551 $s .= '}';
1552 return $s;
1556 * @return bool
1558 function isEmpty() {
1559 return !count( $this->args );
1562 function getArgument( $index ) {
1563 if ( !isset( $this->args[$index] ) ) {
1564 return false;
1566 return $this->args[$index];
1569 function getArguments() {
1570 return $this->args;
1575 * @ingroup Parser
1577 class PPNode_DOM implements PPNode {
1580 * @var DOMElement
1582 var $node;
1583 var $xpath;
1585 function __construct( $node, $xpath = false ) {
1586 $this->node = $node;
1590 * @return DOMXPath
1592 function getXPath() {
1593 if ( $this->xpath === null ) {
1594 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1596 return $this->xpath;
1599 function __toString() {
1600 if ( $this->node instanceof DOMNodeList ) {
1601 $s = '';
1602 foreach ( $this->node as $node ) {
1603 $s .= $node->ownerDocument->saveXML( $node );
1605 } else {
1606 $s = $this->node->ownerDocument->saveXML( $this->node );
1608 return $s;
1612 * @return bool|PPNode_DOM
1614 function getChildren() {
1615 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1619 * @return bool|PPNode_DOM
1621 function getFirstChild() {
1622 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1626 * @return bool|PPNode_DOM
1628 function getNextSibling() {
1629 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1633 * @param $type
1635 * @return bool|PPNode_DOM
1637 function getChildrenOfType( $type ) {
1638 return new self( $this->getXPath()->query( $type, $this->node ) );
1642 * @return int
1644 function getLength() {
1645 if ( $this->node instanceof DOMNodeList ) {
1646 return $this->node->length;
1647 } else {
1648 return false;
1653 * @param $i
1654 * @return bool|PPNode_DOM
1656 function item( $i ) {
1657 $item = $this->node->item( $i );
1658 return $item ? new self( $item ) : false;
1662 * @return string
1664 function getName() {
1665 if ( $this->node instanceof DOMNodeList ) {
1666 return '#nodelist';
1667 } else {
1668 return $this->node->nodeName;
1673 * Split a "<part>" node into an associative array containing:
1674 * - name PPNode name
1675 * - index String index
1676 * - value PPNode value
1678 * @throws MWException
1679 * @return array
1681 function splitArg() {
1682 $xpath = $this->getXPath();
1683 $names = $xpath->query( 'name', $this->node );
1684 $values = $xpath->query( 'value', $this->node );
1685 if ( !$names->length || !$values->length ) {
1686 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1688 $name = $names->item( 0 );
1689 $index = $name->getAttribute( 'index' );
1690 return array(
1691 'name' => new self( $name ),
1692 'index' => $index,
1693 'value' => new self( $values->item( 0 ) ) );
1697 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1698 * All values in the resulting array are PPNodes. Inner and close are optional.
1700 * @throws MWException
1701 * @return array
1703 function splitExt() {
1704 $xpath = $this->getXPath();
1705 $names = $xpath->query( 'name', $this->node );
1706 $attrs = $xpath->query( 'attr', $this->node );
1707 $inners = $xpath->query( 'inner', $this->node );
1708 $closes = $xpath->query( 'close', $this->node );
1709 if ( !$names->length || !$attrs->length ) {
1710 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1712 $parts = array(
1713 'name' => new self( $names->item( 0 ) ),
1714 'attr' => new self( $attrs->item( 0 ) ) );
1715 if ( $inners->length ) {
1716 $parts['inner'] = new self( $inners->item( 0 ) );
1718 if ( $closes->length ) {
1719 $parts['close'] = new self( $closes->item( 0 ) );
1721 return $parts;
1725 * Split a "<h>" node
1726 * @throws MWException
1727 * @return array
1729 function splitHeading() {
1730 if ( $this->getName() !== 'h' ) {
1731 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1733 return array(
1734 'i' => $this->node->getAttribute( 'i' ),
1735 'level' => $this->node->getAttribute( 'level' ),
1736 'contents' => $this->getChildren()