Rm back-compat (was moved to the class in r36353) wfLoadAllExtensions(). Not used...
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob991f28cc4262c79bab5a7cc33bca55ff8806a543
1 <?php
2 /**
3 * Preprocessor using PHP's dom extension
5 * @file
6 * @ingroup Parser
7 */
9 /**
10 * @ingroup Parser
12 class Preprocessor_DOM implements Preprocessor {
13 var $parser, $memoryLimit;
15 const CACHE_VERSION = 1;
17 function __construct( $parser ) {
18 $this->parser = $parser;
19 $mem = ini_get( 'memory_limit' );
20 $this->memoryLimit = false;
21 if ( strval( $mem ) !== '' && $mem != -1 ) {
22 if ( preg_match( '/^\d+$/', $mem ) ) {
23 $this->memoryLimit = $mem;
24 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
25 $this->memoryLimit = $m[1] * 1048576;
30 function newFrame() {
31 return new PPFrame_DOM( $this );
34 function newCustomFrame( $args ) {
35 return new PPCustomFrame_DOM( $this, $args );
38 function newPartNodeArray( $values ) {
39 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
40 $xml = "";
41 $xml .= "<list>";
43 foreach ( $values as $k => $val ) {
45 if ( is_int( $k ) ) {
46 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
47 } else {
48 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
52 $xml .= "</list>";
54 $dom = new DOMDocument();
55 $dom->loadXML( $xml );
56 $root = $dom->documentElement;
58 $node = new PPNode_DOM( $root->childNodes );
59 return $node;
62 function memCheck() {
63 if ( $this->memoryLimit === false ) {
64 return;
66 $usage = memory_get_usage();
67 if ( $usage > $this->memoryLimit * 0.9 ) {
68 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
69 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
71 return $usage <= $this->memoryLimit * 0.8;
74 /**
75 * Preprocess some wikitext and return the document tree.
76 * This is the ghost of Parser::replace_variables().
78 * @param $text String: the text to parse
79 * @param $flags Integer: bitwise combination of:
80 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
81 * included. Default is to assume a direct page view.
83 * The generated DOM tree must depend only on the input text and the flags.
84 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
86 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
87 * change in the DOM tree for a given text, must be passed through the section identifier
88 * in the section edit link and thus back to extractSections().
90 * The output of this function is currently only cached in process memory, but a persistent
91 * cache may be implemented at a later date which takes further advantage of these strict
92 * dependency requirements.
94 * @private
96 function preprocessToObj( $text, $flags = 0 ) {
97 wfProfileIn( __METHOD__ );
98 global $wgMemc, $wgPreprocessorCacheThreshold;
100 $xml = false;
101 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
102 if ( $cacheable ) {
103 wfProfileIn( __METHOD__.'-cacheable' );
105 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
106 $cacheValue = $wgMemc->get( $cacheKey );
107 if ( $cacheValue ) {
108 $version = substr( $cacheValue, 0, 8 );
109 if ( intval( $version ) == self::CACHE_VERSION ) {
110 $xml = substr( $cacheValue, 8 );
111 // From the cache
112 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
116 if ( $xml === false ) {
117 if ( $cacheable ) {
118 wfProfileIn( __METHOD__.'-cache-miss' );
119 $xml = $this->preprocessToXml( $text, $flags );
120 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
121 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
122 wfProfileOut( __METHOD__.'-cache-miss' );
123 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
124 } else {
125 $xml = $this->preprocessToXml( $text, $flags );
129 wfProfileIn( __METHOD__.'-loadXML' );
130 $dom = new DOMDocument;
131 wfSuppressWarnings();
132 $result = $dom->loadXML( $xml );
133 wfRestoreWarnings();
134 if ( !$result ) {
135 // Try running the XML through UtfNormal to get rid of invalid characters
136 $xml = UtfNormal::cleanUp( $xml );
137 $result = $dom->loadXML( $xml );
138 if ( !$result ) {
139 throw new MWException( __METHOD__.' generated invalid XML' );
142 $obj = new PPNode_DOM( $dom->documentElement );
143 wfProfileOut( __METHOD__.'-loadXML' );
144 if ( $cacheable ) {
145 wfProfileOut( __METHOD__.'-cacheable' );
147 wfProfileOut( __METHOD__ );
148 return $obj;
151 function preprocessToXml( $text, $flags = 0 ) {
152 wfProfileIn( __METHOD__ );
153 $rules = array(
154 '{' => array(
155 'end' => '}',
156 'names' => array(
157 2 => 'template',
158 3 => 'tplarg',
160 'min' => 2,
161 'max' => 3,
163 '[' => array(
164 'end' => ']',
165 'names' => array( 2 => null ),
166 'min' => 2,
167 'max' => 2,
171 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
173 $xmlishElements = $this->parser->getStripList();
174 $enableOnlyinclude = false;
175 if ( $forInclusion ) {
176 $ignoredTags = array( 'includeonly', '/includeonly' );
177 $ignoredElements = array( 'noinclude' );
178 $xmlishElements[] = 'noinclude';
179 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
180 $enableOnlyinclude = true;
182 } else {
183 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
184 $ignoredElements = array( 'includeonly' );
185 $xmlishElements[] = 'includeonly';
187 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
189 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
190 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
192 $stack = new PPDStack;
194 $searchBase = "[{<\n"; #}
195 $revText = strrev( $text ); // For fast reverse searches
197 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
198 $accum =& $stack->getAccum(); # Current accumulator
199 $accum = '<root>';
200 $findEquals = false; # True to find equals signs in arguments
201 $findPipe = false; # True to take notice of pipe characters
202 $headingIndex = 1;
203 $inHeading = false; # True if $i is inside a possible heading
204 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
205 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
206 $fakeLineStart = true; # Do a line-start run without outputting an LF character
208 while ( true ) {
209 //$this->memCheck();
211 if ( $findOnlyinclude ) {
212 // Ignore all input up to the next <onlyinclude>
213 $startPos = strpos( $text, '<onlyinclude>', $i );
214 if ( $startPos === false ) {
215 // Ignored section runs to the end
216 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
217 break;
219 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
220 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
221 $i = $tagEndPos;
222 $findOnlyinclude = false;
225 if ( $fakeLineStart ) {
226 $found = 'line-start';
227 $curChar = '';
228 } else {
229 # Find next opening brace, closing brace or pipe
230 $search = $searchBase;
231 if ( $stack->top === false ) {
232 $currentClosing = '';
233 } else {
234 $currentClosing = $stack->top->close;
235 $search .= $currentClosing;
237 if ( $findPipe ) {
238 $search .= '|';
240 if ( $findEquals ) {
241 // First equals will be for the template
242 $search .= '=';
244 $rule = null;
245 # Output literal section, advance input counter
246 $literalLength = strcspn( $text, $search, $i );
247 if ( $literalLength > 0 ) {
248 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
249 $i += $literalLength;
251 if ( $i >= strlen( $text ) ) {
252 if ( $currentClosing == "\n" ) {
253 // Do a past-the-end run to finish off the heading
254 $curChar = '';
255 $found = 'line-end';
256 } else {
257 # All done
258 break;
260 } else {
261 $curChar = $text[$i];
262 if ( $curChar == '|' ) {
263 $found = 'pipe';
264 } elseif ( $curChar == '=' ) {
265 $found = 'equals';
266 } elseif ( $curChar == '<' ) {
267 $found = 'angle';
268 } elseif ( $curChar == "\n" ) {
269 if ( $inHeading ) {
270 $found = 'line-end';
271 } else {
272 $found = 'line-start';
274 } elseif ( $curChar == $currentClosing ) {
275 $found = 'close';
276 } elseif ( isset( $rules[$curChar] ) ) {
277 $found = 'open';
278 $rule = $rules[$curChar];
279 } else {
280 # Some versions of PHP have a strcspn which stops on null characters
281 # Ignore and continue
282 ++$i;
283 continue;
288 if ( $found == 'angle' ) {
289 $matches = false;
290 // Handle </onlyinclude>
291 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
292 $findOnlyinclude = true;
293 continue;
296 // Determine element name
297 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
298 // Element name missing or not listed
299 $accum .= '&lt;';
300 ++$i;
301 continue;
303 // Handle comments
304 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
305 // To avoid leaving blank lines, when a comment is both preceded
306 // and followed by a newline (ignoring spaces), trim leading and
307 // trailing spaces and one of the newlines.
309 // Find the end
310 $endPos = strpos( $text, '-->', $i + 4 );
311 if ( $endPos === false ) {
312 // Unclosed comment in input, runs to end
313 $inner = substr( $text, $i );
314 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
315 $i = strlen( $text );
316 } else {
317 // Search backwards for leading whitespace
318 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
319 // Search forwards for trailing whitespace
320 // $wsEnd will be the position of the last space
321 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
322 // Eat the line if possible
323 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
324 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
325 // it's a possible beneficial b/c break.
326 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
327 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
329 $startPos = $wsStart;
330 $endPos = $wsEnd + 1;
331 // Remove leading whitespace from the end of the accumulator
332 // Sanity check first though
333 $wsLength = $i - $wsStart;
334 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
335 $accum = substr( $accum, 0, -$wsLength );
337 // Do a line-start run next time to look for headings after the comment
338 $fakeLineStart = true;
339 } else {
340 // No line to eat, just take the comment itself
341 $startPos = $i;
342 $endPos += 2;
345 if ( $stack->top ) {
346 $part = $stack->top->getCurrentPart();
347 if ( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) {
348 // Comments abutting, no change in visual end
349 $part->commentEnd = $wsEnd;
350 } else {
351 $part->visualEnd = $wsStart;
352 $part->commentEnd = $endPos;
355 $i = $endPos + 1;
356 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
357 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
359 continue;
361 $name = $matches[1];
362 $lowerName = strtolower( $name );
363 $attrStart = $i + strlen( $name ) + 1;
365 // Find end of tag
366 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
367 if ( $tagEndPos === false ) {
368 // Infinite backtrack
369 // Disable tag search to prevent worst-case O(N^2) performance
370 $noMoreGT = true;
371 $accum .= '&lt;';
372 ++$i;
373 continue;
376 // Handle ignored tags
377 if ( in_array( $lowerName, $ignoredTags ) ) {
378 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
379 $i = $tagEndPos + 1;
380 continue;
383 $tagStartPos = $i;
384 if ( $text[$tagEndPos-1] == '/' ) {
385 $attrEnd = $tagEndPos - 1;
386 $inner = null;
387 $i = $tagEndPos + 1;
388 $close = '';
389 } else {
390 $attrEnd = $tagEndPos;
391 // Find closing tag
392 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
393 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
395 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
396 $i = $matches[0][1] + strlen( $matches[0][0] );
397 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
398 } else {
399 // No end tag -- let it run out to the end of the text.
400 $inner = substr( $text, $tagEndPos + 1 );
401 $i = strlen( $text );
402 $close = '';
405 // <includeonly> and <noinclude> just become <ignore> tags
406 if ( in_array( $lowerName, $ignoredElements ) ) {
407 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
408 . '</ignore>';
409 continue;
412 $accum .= '<ext>';
413 if ( $attrEnd <= $attrStart ) {
414 $attr = '';
415 } else {
416 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
418 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
419 // Note that the attr element contains the whitespace between name and attribute,
420 // this is necessary for precise reconstruction during pre-save transform.
421 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
422 if ( $inner !== null ) {
423 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
425 $accum .= $close . '</ext>';
428 elseif ( $found == 'line-start' ) {
429 // Is this the start of a heading?
430 // Line break belongs before the heading element in any case
431 if ( $fakeLineStart ) {
432 $fakeLineStart = false;
433 } else {
434 $accum .= $curChar;
435 $i++;
438 $count = strspn( $text, '=', $i, 6 );
439 if ( $count == 1 && $findEquals ) {
440 // DWIM: This looks kind of like a name/value separator
441 // Let's let the equals handler have it and break the potential heading
442 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
443 } elseif ( $count > 0 ) {
444 $piece = array(
445 'open' => "\n",
446 'close' => "\n",
447 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
448 'startPos' => $i,
449 'count' => $count );
450 $stack->push( $piece );
451 $accum =& $stack->getAccum();
452 $flags = $stack->getFlags();
453 extract( $flags );
454 $i += $count;
458 elseif ( $found == 'line-end' ) {
459 $piece = $stack->top;
460 // A heading must be open, otherwise \n wouldn't have been in the search list
461 assert( $piece->open == "\n" );
462 $part = $piece->getCurrentPart();
463 // Search back through the input to see if it has a proper close
464 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
465 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
466 $searchStart = $i - $wsLength;
467 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
468 // Comment found at line end
469 // Search for equals signs before the comment
470 $searchStart = $part->visualEnd;
471 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
473 $count = $piece->count;
474 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
475 if ( $equalsLength > 0 ) {
476 if ( $searchStart - $equalsLength == $piece->startPos ) {
477 // This is just a single string of equals signs on its own line
478 // Replicate the doHeadings behaviour /={count}(.+)={count}/
479 // First find out how many equals signs there really are (don't stop at 6)
480 $count = $equalsLength;
481 if ( $count < 3 ) {
482 $count = 0;
483 } else {
484 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
486 } else {
487 $count = min( $equalsLength, $count );
489 if ( $count > 0 ) {
490 // Normal match, output <h>
491 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
492 $headingIndex++;
493 } else {
494 // Single equals sign on its own line, count=0
495 $element = $accum;
497 } else {
498 // No match, no <h>, just pass down the inner text
499 $element = $accum;
501 // Unwind the stack
502 $stack->pop();
503 $accum =& $stack->getAccum();
504 $flags = $stack->getFlags();
505 extract( $flags );
507 // Append the result to the enclosing accumulator
508 $accum .= $element;
509 // Note that we do NOT increment the input pointer.
510 // This is because the closing linebreak could be the opening linebreak of
511 // another heading. Infinite loops are avoided because the next iteration MUST
512 // hit the heading open case above, which unconditionally increments the
513 // input pointer.
516 elseif ( $found == 'open' ) {
517 # count opening brace characters
518 $count = strspn( $text, $curChar, $i );
520 # we need to add to stack only if opening brace count is enough for one of the rules
521 if ( $count >= $rule['min'] ) {
522 # Add it to the stack
523 $piece = array(
524 'open' => $curChar,
525 'close' => $rule['end'],
526 'count' => $count,
527 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
530 $stack->push( $piece );
531 $accum =& $stack->getAccum();
532 $flags = $stack->getFlags();
533 extract( $flags );
534 } else {
535 # Add literal brace(s)
536 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
538 $i += $count;
541 elseif ( $found == 'close' ) {
542 $piece = $stack->top;
543 # lets check if there are enough characters for closing brace
544 $maxCount = $piece->count;
545 $count = strspn( $text, $curChar, $i, $maxCount );
547 # check for maximum matching characters (if there are 5 closing
548 # characters, we will probably need only 3 - depending on the rules)
549 $rule = $rules[$piece->open];
550 if ( $count > $rule['max'] ) {
551 # The specified maximum exists in the callback array, unless the caller
552 # has made an error
553 $matchingCount = $rule['max'];
554 } else {
555 # Count is less than the maximum
556 # Skip any gaps in the callback array to find the true largest match
557 # Need to use array_key_exists not isset because the callback can be null
558 $matchingCount = $count;
559 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
560 --$matchingCount;
564 if ($matchingCount <= 0) {
565 # No matching element found in callback array
566 # Output a literal closing brace and continue
567 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
568 $i += $count;
569 continue;
571 $name = $rule['names'][$matchingCount];
572 if ( $name === null ) {
573 // No element, just literal text
574 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
575 } else {
576 # Create XML element
577 # Note: $parts is already XML, does not need to be encoded further
578 $parts = $piece->parts;
579 $title = $parts[0]->out;
580 unset( $parts[0] );
582 # The invocation is at the start of the line if lineStart is set in
583 # the stack, and all opening brackets are used up.
584 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
585 $attr = ' lineStart="1"';
586 } else {
587 $attr = '';
590 $element = "<$name$attr>";
591 $element .= "<title>$title</title>";
592 $argIndex = 1;
593 foreach ( $parts as $part ) {
594 if ( isset( $part->eqpos ) ) {
595 $argName = substr( $part->out, 0, $part->eqpos );
596 $argValue = substr( $part->out, $part->eqpos + 1 );
597 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
598 } else {
599 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
600 $argIndex++;
603 $element .= "</$name>";
606 # Advance input pointer
607 $i += $matchingCount;
609 # Unwind the stack
610 $stack->pop();
611 $accum =& $stack->getAccum();
613 # Re-add the old stack element if it still has unmatched opening characters remaining
614 if ($matchingCount < $piece->count) {
615 $piece->parts = array( new PPDPart );
616 $piece->count -= $matchingCount;
617 # do we still qualify for any callback with remaining count?
618 $names = $rules[$piece->open]['names'];
619 $skippedBraces = 0;
620 $enclosingAccum =& $accum;
621 while ( $piece->count ) {
622 if ( array_key_exists( $piece->count, $names ) ) {
623 $stack->push( $piece );
624 $accum =& $stack->getAccum();
625 break;
627 --$piece->count;
628 $skippedBraces ++;
630 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
632 $flags = $stack->getFlags();
633 extract( $flags );
635 # Add XML element to the enclosing accumulator
636 $accum .= $element;
639 elseif ( $found == 'pipe' ) {
640 $findEquals = true; // shortcut for getFlags()
641 $stack->addPart();
642 $accum =& $stack->getAccum();
643 ++$i;
646 elseif ( $found == 'equals' ) {
647 $findEquals = false; // shortcut for getFlags()
648 $stack->getCurrentPart()->eqpos = strlen( $accum );
649 $accum .= '=';
650 ++$i;
654 # Output any remaining unclosed brackets
655 foreach ( $stack->stack as $piece ) {
656 $stack->rootAccum .= $piece->breakSyntax();
658 $stack->rootAccum .= '</root>';
659 $xml = $stack->rootAccum;
661 wfProfileOut( __METHOD__ );
663 return $xml;
668 * Stack class to help Preprocessor::preprocessToObj()
669 * @ingroup Parser
671 class PPDStack {
672 var $stack, $rootAccum, $top;
673 var $out;
674 var $elementClass = 'PPDStackElement';
676 static $false = false;
678 function __construct() {
679 $this->stack = array();
680 $this->top = false;
681 $this->rootAccum = '';
682 $this->accum =& $this->rootAccum;
685 function count() {
686 return count( $this->stack );
689 function &getAccum() {
690 return $this->accum;
693 function getCurrentPart() {
694 if ( $this->top === false ) {
695 return false;
696 } else {
697 return $this->top->getCurrentPart();
701 function push( $data ) {
702 if ( $data instanceof $this->elementClass ) {
703 $this->stack[] = $data;
704 } else {
705 $class = $this->elementClass;
706 $this->stack[] = new $class( $data );
708 $this->top = $this->stack[ count( $this->stack ) - 1 ];
709 $this->accum =& $this->top->getAccum();
712 function pop() {
713 if ( !count( $this->stack ) ) {
714 throw new MWException( __METHOD__.': no elements remaining' );
716 $temp = array_pop( $this->stack );
718 if ( count( $this->stack ) ) {
719 $this->top = $this->stack[ count( $this->stack ) - 1 ];
720 $this->accum =& $this->top->getAccum();
721 } else {
722 $this->top = self::$false;
723 $this->accum =& $this->rootAccum;
725 return $temp;
728 function addPart( $s = '' ) {
729 $this->top->addPart( $s );
730 $this->accum =& $this->top->getAccum();
733 function getFlags() {
734 if ( !count( $this->stack ) ) {
735 return array(
736 'findEquals' => false,
737 'findPipe' => false,
738 'inHeading' => false,
740 } else {
741 return $this->top->getFlags();
747 * @ingroup Parser
749 class PPDStackElement {
750 var $open, // Opening character (\n for heading)
751 $close, // Matching closing character
752 $count, // Number of opening characters found (number of "=" for heading)
753 $parts, // Array of PPDPart objects describing pipe-separated parts.
754 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
756 var $partClass = 'PPDPart';
758 function __construct( $data = array() ) {
759 $class = $this->partClass;
760 $this->parts = array( new $class );
762 foreach ( $data as $name => $value ) {
763 $this->$name = $value;
767 function &getAccum() {
768 return $this->parts[count($this->parts) - 1]->out;
771 function addPart( $s = '' ) {
772 $class = $this->partClass;
773 $this->parts[] = new $class( $s );
776 function getCurrentPart() {
777 return $this->parts[count($this->parts) - 1];
780 function getFlags() {
781 $partCount = count( $this->parts );
782 $findPipe = $this->open != "\n" && $this->open != '[';
783 return array(
784 'findPipe' => $findPipe,
785 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
786 'inHeading' => $this->open == "\n",
791 * Get the output string that would result if the close is not found.
793 function breakSyntax( $openingCount = false ) {
794 if ( $this->open == "\n" ) {
795 $s = $this->parts[0]->out;
796 } else {
797 if ( $openingCount === false ) {
798 $openingCount = $this->count;
800 $s = str_repeat( $this->open, $openingCount );
801 $first = true;
802 foreach ( $this->parts as $part ) {
803 if ( $first ) {
804 $first = false;
805 } else {
806 $s .= '|';
808 $s .= $part->out;
811 return $s;
816 * @ingroup Parser
818 class PPDPart {
819 var $out; // Output accumulator string
821 // Optional member variables:
822 // eqpos Position of equals sign in output accumulator
823 // commentEnd Past-the-end input pointer for the last comment encountered
824 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
826 function __construct( $out = '' ) {
827 $this->out = $out;
832 * An expansion frame, used as a context to expand the result of preprocessToObj()
833 * @ingroup Parser
835 class PPFrame_DOM implements PPFrame {
836 var $preprocessor, $parser, $title;
837 var $titleCache;
840 * Hashtable listing templates which are disallowed for expansion in this frame,
841 * having been encountered previously in parent frames.
843 var $loopCheckHash;
846 * Recursion depth of this frame, top = 0
847 * Note that this is NOT the same as expansion depth in expand()
849 var $depth;
853 * Construct a new preprocessor frame.
854 * @param $preprocessor Preprocessor: The parent preprocessor
856 function __construct( $preprocessor ) {
857 $this->preprocessor = $preprocessor;
858 $this->parser = $preprocessor->parser;
859 $this->title = $this->parser->mTitle;
860 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
861 $this->loopCheckHash = array();
862 $this->depth = 0;
866 * Create a new child frame
867 * $args is optionally a multi-root PPNode or array containing the template arguments
869 function newChild( $args = false, $title = false ) {
870 $namedArgs = array();
871 $numberedArgs = array();
872 if ( $title === false ) {
873 $title = $this->title;
875 if ( $args !== false ) {
876 $xpath = false;
877 if ( $args instanceof PPNode ) {
878 $args = $args->node;
880 foreach ( $args as $arg ) {
881 if ( !$xpath ) {
882 $xpath = new DOMXPath( $arg->ownerDocument );
885 $nameNodes = $xpath->query( 'name', $arg );
886 $value = $xpath->query( 'value', $arg );
887 if ( $nameNodes->item( 0 )->hasAttributes() ) {
888 // Numbered parameter
889 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
890 $numberedArgs[$index] = $value->item( 0 );
891 unset( $namedArgs[$index] );
892 } else {
893 // Named parameter
894 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
895 $namedArgs[$name] = $value->item( 0 );
896 unset( $numberedArgs[$name] );
900 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
903 function expand( $root, $flags = 0 ) {
904 static $expansionDepth = 0;
905 if ( is_string( $root ) ) {
906 return $root;
909 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() )
911 return '<span class="error">Node-count limit exceeded</span>';
914 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
915 return '<span class="error">Expansion depth limit exceeded</span>';
917 wfProfileIn( __METHOD__ );
918 ++$expansionDepth;
920 if ( $root instanceof PPNode_DOM ) {
921 $root = $root->node;
923 if ( $root instanceof DOMDocument ) {
924 $root = $root->documentElement;
927 $outStack = array( '', '' );
928 $iteratorStack = array( false, $root );
929 $indexStack = array( 0, 0 );
931 while ( count( $iteratorStack ) > 1 ) {
932 $level = count( $outStack ) - 1;
933 $iteratorNode =& $iteratorStack[ $level ];
934 $out =& $outStack[$level];
935 $index =& $indexStack[$level];
937 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
939 if ( is_array( $iteratorNode ) ) {
940 if ( $index >= count( $iteratorNode ) ) {
941 // All done with this iterator
942 $iteratorStack[$level] = false;
943 $contextNode = false;
944 } else {
945 $contextNode = $iteratorNode[$index];
946 $index++;
948 } elseif ( $iteratorNode instanceof DOMNodeList ) {
949 if ( $index >= $iteratorNode->length ) {
950 // All done with this iterator
951 $iteratorStack[$level] = false;
952 $contextNode = false;
953 } else {
954 $contextNode = $iteratorNode->item( $index );
955 $index++;
957 } else {
958 // Copy to $contextNode and then delete from iterator stack,
959 // because this is not an iterator but we do have to execute it once
960 $contextNode = $iteratorStack[$level];
961 $iteratorStack[$level] = false;
964 if ( $contextNode instanceof PPNode_DOM ) $contextNode = $contextNode->node;
966 $newIterator = false;
968 if ( $contextNode === false ) {
969 // nothing to do
970 } elseif ( is_string( $contextNode ) ) {
971 $out .= $contextNode;
972 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
973 $newIterator = $contextNode;
974 } elseif ( $contextNode instanceof DOMNode ) {
975 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
976 $out .= $contextNode->nodeValue;
977 } elseif ( $contextNode->nodeName == 'template' ) {
978 # Double-brace expansion
979 $xpath = new DOMXPath( $contextNode->ownerDocument );
980 $titles = $xpath->query( 'title', $contextNode );
981 $title = $titles->item( 0 );
982 $parts = $xpath->query( 'part', $contextNode );
983 if ( $flags & PPFrame::NO_TEMPLATES ) {
984 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
985 } else {
986 $lineStart = $contextNode->getAttribute( 'lineStart' );
987 $params = array(
988 'title' => new PPNode_DOM( $title ),
989 'parts' => new PPNode_DOM( $parts ),
990 'lineStart' => $lineStart );
991 $ret = $this->parser->braceSubstitution( $params, $this );
992 if ( isset( $ret['object'] ) ) {
993 $newIterator = $ret['object'];
994 } else {
995 $out .= $ret['text'];
998 } elseif ( $contextNode->nodeName == 'tplarg' ) {
999 # Triple-brace expansion
1000 $xpath = new DOMXPath( $contextNode->ownerDocument );
1001 $titles = $xpath->query( 'title', $contextNode );
1002 $title = $titles->item( 0 );
1003 $parts = $xpath->query( 'part', $contextNode );
1004 if ( $flags & PPFrame::NO_ARGS ) {
1005 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1006 } else {
1007 $params = array(
1008 'title' => new PPNode_DOM( $title ),
1009 'parts' => new PPNode_DOM( $parts ) );
1010 $ret = $this->parser->argSubstitution( $params, $this );
1011 if ( isset( $ret['object'] ) ) {
1012 $newIterator = $ret['object'];
1013 } else {
1014 $out .= $ret['text'];
1017 } elseif ( $contextNode->nodeName == 'comment' ) {
1018 # HTML-style comment
1019 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1020 if ( $this->parser->ot['html']
1021 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1022 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1024 $out .= '';
1026 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1027 # Not in RECOVER_COMMENTS mode (extractSections) though
1028 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1029 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1031 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1032 else {
1033 $out .= $contextNode->textContent;
1035 } elseif ( $contextNode->nodeName == 'ignore' ) {
1036 # Output suppression used by <includeonly> etc.
1037 # OT_WIKI will only respect <ignore> in substed templates.
1038 # The other output types respect it unless NO_IGNORE is set.
1039 # extractSections() sets NO_IGNORE and so never respects it.
1040 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1041 $out .= $contextNode->textContent;
1042 } else {
1043 $out .= '';
1045 } elseif ( $contextNode->nodeName == 'ext' ) {
1046 # Extension tag
1047 $xpath = new DOMXPath( $contextNode->ownerDocument );
1048 $names = $xpath->query( 'name', $contextNode );
1049 $attrs = $xpath->query( 'attr', $contextNode );
1050 $inners = $xpath->query( 'inner', $contextNode );
1051 $closes = $xpath->query( 'close', $contextNode );
1052 $params = array(
1053 'name' => new PPNode_DOM( $names->item( 0 ) ),
1054 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1055 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1056 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1058 $out .= $this->parser->extensionSubstitution( $params, $this );
1059 } elseif ( $contextNode->nodeName == 'h' ) {
1060 # Heading
1061 $s = $this->expand( $contextNode->childNodes, $flags );
1063 # Insert a heading marker only for <h> children of <root>
1064 # This is to stop extractSections from going over multiple tree levels
1065 if ( $contextNode->parentNode->nodeName == 'root'
1066 && $this->parser->ot['html'] )
1068 # Insert heading index marker
1069 $headingIndex = $contextNode->getAttribute( 'i' );
1070 $titleText = $this->title->getPrefixedDBkey();
1071 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1072 $serial = count( $this->parser->mHeadings ) - 1;
1073 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1074 $count = $contextNode->getAttribute( 'level' );
1075 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1076 $this->parser->mStripState->general->setPair( $marker, '' );
1078 $out .= $s;
1079 } else {
1080 # Generic recursive expansion
1081 $newIterator = $contextNode->childNodes;
1083 } else {
1084 wfProfileOut( __METHOD__ );
1085 throw new MWException( __METHOD__.': Invalid parameter type' );
1088 if ( $newIterator !== false ) {
1089 if ( $newIterator instanceof PPNode_DOM ) {
1090 $newIterator = $newIterator->node;
1092 $outStack[] = '';
1093 $iteratorStack[] = $newIterator;
1094 $indexStack[] = 0;
1095 } elseif ( $iteratorStack[$level] === false ) {
1096 // Return accumulated value to parent
1097 // With tail recursion
1098 while ( $iteratorStack[$level] === false && $level > 0 ) {
1099 $outStack[$level - 1] .= $out;
1100 array_pop( $outStack );
1101 array_pop( $iteratorStack );
1102 array_pop( $indexStack );
1103 $level--;
1107 --$expansionDepth;
1108 wfProfileOut( __METHOD__ );
1109 return $outStack[0];
1112 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1113 $args = array_slice( func_get_args(), 2 );
1115 $first = true;
1116 $s = '';
1117 foreach ( $args as $root ) {
1118 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1119 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1120 $root = array( $root );
1122 foreach ( $root as $node ) {
1123 if ( $first ) {
1124 $first = false;
1125 } else {
1126 $s .= $sep;
1128 $s .= $this->expand( $node, $flags );
1131 return $s;
1135 * Implode with no flags specified
1136 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1138 function implode( $sep /*, ... */ ) {
1139 $args = array_slice( func_get_args(), 1 );
1141 $first = true;
1142 $s = '';
1143 foreach ( $args as $root ) {
1144 if ( $root instanceof PPNode_DOM ) {
1145 $root = $root->node;
1147 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1148 $root = array( $root );
1150 foreach ( $root as $node ) {
1151 if ( $first ) {
1152 $first = false;
1153 } else {
1154 $s .= $sep;
1156 $s .= $this->expand( $node );
1159 return $s;
1163 * Makes an object that, when expand()ed, will be the same as one obtained
1164 * with implode()
1166 function virtualImplode( $sep /*, ... */ ) {
1167 $args = array_slice( func_get_args(), 1 );
1168 $out = array();
1169 $first = true;
1171 foreach ( $args as $root ) {
1172 if ( $root instanceof PPNode_DOM ) {
1173 $root = $root->node;
1175 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1176 $root = array( $root );
1178 foreach ( $root as $node ) {
1179 if ( $first ) {
1180 $first = false;
1181 } else {
1182 $out[] = $sep;
1184 $out[] = $node;
1187 return $out;
1191 * Virtual implode with brackets
1193 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1194 $args = array_slice( func_get_args(), 3 );
1195 $out = array( $start );
1196 $first = true;
1198 foreach ( $args as $root ) {
1199 if ( $root instanceof PPNode_DOM ) {
1200 $root = $root->node;
1202 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1203 $root = array( $root );
1205 foreach ( $root as $node ) {
1206 if ( $first ) {
1207 $first = false;
1208 } else {
1209 $out[] = $sep;
1211 $out[] = $node;
1214 $out[] = $end;
1215 return $out;
1218 function __toString() {
1219 return 'frame{}';
1222 function getPDBK( $level = false ) {
1223 if ( $level === false ) {
1224 return $this->title->getPrefixedDBkey();
1225 } else {
1226 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1230 function getArguments() {
1231 return array();
1234 function getNumberedArguments() {
1235 return array();
1238 function getNamedArguments() {
1239 return array();
1243 * Returns true if there are no arguments in this frame
1245 function isEmpty() {
1246 return true;
1249 function getArgument( $name ) {
1250 return false;
1254 * Returns true if the infinite loop check is OK, false if a loop is detected
1256 function loopCheck( $title ) {
1257 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1261 * Return true if the frame is a template frame
1263 function isTemplate() {
1264 return false;
1269 * Expansion frame with template arguments
1270 * @ingroup Parser
1272 class PPTemplateFrame_DOM extends PPFrame_DOM {
1273 var $numberedArgs, $namedArgs, $parent;
1274 var $numberedExpansionCache, $namedExpansionCache;
1276 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1277 parent::__construct( $preprocessor );
1279 $this->parent = $parent;
1280 $this->numberedArgs = $numberedArgs;
1281 $this->namedArgs = $namedArgs;
1282 $this->title = $title;
1283 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1284 $this->titleCache = $parent->titleCache;
1285 $this->titleCache[] = $pdbk;
1286 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1287 if ( $pdbk !== false ) {
1288 $this->loopCheckHash[$pdbk] = true;
1290 $this->depth = $parent->depth + 1;
1291 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1294 function __toString() {
1295 $s = 'tplframe{';
1296 $first = true;
1297 $args = $this->numberedArgs + $this->namedArgs;
1298 foreach ( $args as $name => $value ) {
1299 if ( $first ) {
1300 $first = false;
1301 } else {
1302 $s .= ', ';
1304 $s .= "\"$name\":\"" .
1305 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1307 $s .= '}';
1308 return $s;
1311 * Returns true if there are no arguments in this frame
1313 function isEmpty() {
1314 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1317 function getArguments() {
1318 $arguments = array();
1319 foreach ( array_merge(
1320 array_keys($this->numberedArgs),
1321 array_keys($this->namedArgs)) as $key ) {
1322 $arguments[$key] = $this->getArgument($key);
1324 return $arguments;
1327 function getNumberedArguments() {
1328 $arguments = array();
1329 foreach ( array_keys($this->numberedArgs) as $key ) {
1330 $arguments[$key] = $this->getArgument($key);
1332 return $arguments;
1335 function getNamedArguments() {
1336 $arguments = array();
1337 foreach ( array_keys($this->namedArgs) as $key ) {
1338 $arguments[$key] = $this->getArgument($key);
1340 return $arguments;
1343 function getNumberedArgument( $index ) {
1344 if ( !isset( $this->numberedArgs[$index] ) ) {
1345 return false;
1347 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1348 # No trimming for unnamed arguments
1349 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1351 return $this->numberedExpansionCache[$index];
1354 function getNamedArgument( $name ) {
1355 if ( !isset( $this->namedArgs[$name] ) ) {
1356 return false;
1358 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1359 # Trim named arguments post-expand, for backwards compatibility
1360 $this->namedExpansionCache[$name] = trim(
1361 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1363 return $this->namedExpansionCache[$name];
1366 function getArgument( $name ) {
1367 $text = $this->getNumberedArgument( $name );
1368 if ( $text === false ) {
1369 $text = $this->getNamedArgument( $name );
1371 return $text;
1375 * Return true if the frame is a template frame
1377 function isTemplate() {
1378 return true;
1383 * Expansion frame with custom arguments
1384 * @ingroup Parser
1386 class PPCustomFrame_DOM extends PPFrame_DOM {
1387 var $args;
1389 function __construct( $preprocessor, $args ) {
1390 parent::__construct( $preprocessor );
1391 $this->args = $args;
1394 function __toString() {
1395 $s = 'cstmframe{';
1396 $first = true;
1397 foreach ( $this->args as $name => $value ) {
1398 if ( $first ) {
1399 $first = false;
1400 } else {
1401 $s .= ', ';
1403 $s .= "\"$name\":\"" .
1404 str_replace( '"', '\\"', $value->__toString() ) . '"';
1406 $s .= '}';
1407 return $s;
1410 function isEmpty() {
1411 return !count( $this->args );
1414 function getArgument( $index ) {
1415 if ( !isset( $this->args[$index] ) ) {
1416 return false;
1418 return $this->args[$index];
1423 * @ingroup Parser
1425 class PPNode_DOM implements PPNode {
1426 var $node;
1428 function __construct( $node, $xpath = false ) {
1429 $this->node = $node;
1432 function __get( $name ) {
1433 if ( $name == 'xpath' ) {
1434 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1436 return $this->xpath;
1439 function __toString() {
1440 if ( $this->node instanceof DOMNodeList ) {
1441 $s = '';
1442 foreach ( $this->node as $node ) {
1443 $s .= $node->ownerDocument->saveXML( $node );
1445 } else {
1446 $s = $this->node->ownerDocument->saveXML( $this->node );
1448 return $s;
1451 function getChildren() {
1452 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1455 function getFirstChild() {
1456 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1459 function getNextSibling() {
1460 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1463 function getChildrenOfType( $type ) {
1464 return new self( $this->xpath->query( $type, $this->node ) );
1467 function getLength() {
1468 if ( $this->node instanceof DOMNodeList ) {
1469 return $this->node->length;
1470 } else {
1471 return false;
1475 function item( $i ) {
1476 $item = $this->node->item( $i );
1477 return $item ? new self( $item ) : false;
1480 function getName() {
1481 if ( $this->node instanceof DOMNodeList ) {
1482 return '#nodelist';
1483 } else {
1484 return $this->node->nodeName;
1489 * Split a <part> node into an associative array containing:
1490 * name PPNode name
1491 * index String index
1492 * value PPNode value
1494 function splitArg() {
1495 $names = $this->xpath->query( 'name', $this->node );
1496 $values = $this->xpath->query( 'value', $this->node );
1497 if ( !$names->length || !$values->length ) {
1498 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1500 $name = $names->item( 0 );
1501 $index = $name->getAttribute( 'index' );
1502 return array(
1503 'name' => new self( $name ),
1504 'index' => $index,
1505 'value' => new self( $values->item( 0 ) ) );
1509 * Split an <ext> node into an associative array containing name, attr, inner and close
1510 * All values in the resulting array are PPNodes. Inner and close are optional.
1512 function splitExt() {
1513 $names = $this->xpath->query( 'name', $this->node );
1514 $attrs = $this->xpath->query( 'attr', $this->node );
1515 $inners = $this->xpath->query( 'inner', $this->node );
1516 $closes = $this->xpath->query( 'close', $this->node );
1517 if ( !$names->length || !$attrs->length ) {
1518 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1520 $parts = array(
1521 'name' => new self( $names->item( 0 ) ),
1522 'attr' => new self( $attrs->item( 0 ) ) );
1523 if ( $inners->length ) {
1524 $parts['inner'] = new self( $inners->item( 0 ) );
1526 if ( $closes->length ) {
1527 $parts['close'] = new self( $closes->item( 0 ) );
1529 return $parts;
1533 * Split a <h> node
1535 function splitHeading() {
1536 if ( !$this->nodeName == 'h' ) {
1537 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1539 return array(
1540 'i' => $this->node->getAttribute( 'i' ),
1541 'level' => $this->node->getAttribute( 'level' ),
1542 'contents' => $this->getChildren()