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
26 * @codingStandardsIgnoreStart
28 class Preprocessor_DOM
implements Preprocessor
{
29 // @codingStandardsIgnoreEnd
38 const CACHE_VERSION
= 1;
40 public function __construct( $parser ) {
41 $this->parser
= $parser;
42 $mem = ini_get( 'memory_limit' );
43 $this->memoryLimit
= false;
44 if ( strval( $mem ) !== '' && $mem != -1 ) {
45 if ( preg_match( '/^\d+$/', $mem ) ) {
46 $this->memoryLimit
= $mem;
47 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
48 $this->memoryLimit
= $m[1] * 1048576;
56 public function newFrame() {
57 return new PPFrame_DOM( $this );
62 * @return PPCustomFrame_DOM
64 public function newCustomFrame( $args ) {
65 return new PPCustomFrame_DOM( $this, $args );
69 * @param array $values
73 public function newPartNodeArray( $values ) {
74 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
77 foreach ( $values as $k => $val ) {
79 $xml .= "<part><name index=\"$k\"/><value>"
80 . htmlspecialchars( $val ) . "</value></part>";
82 $xml .= "<part><name>" . htmlspecialchars( $k )
83 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
89 $dom = new DOMDocument();
91 $result = $dom->loadXML( $xml );
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal
::cleanUp( $xml );
96 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
97 // don't barf when the XML is >256 levels deep
98 $result = $dom->loadXML( $xml, 1 << 19 );
102 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
105 $root = $dom->documentElement
;
106 $node = new PPNode_DOM( $root->childNodes
);
111 * @throws MWException
114 public function memCheck() {
115 if ( $this->memoryLimit
=== false ) {
118 $usage = memory_get_usage();
119 if ( $usage > $this->memoryLimit
* 0.9 ) {
120 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
121 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
123 return $usage <= $this->memoryLimit
* 0.8;
127 * Preprocess some wikitext and return the document tree.
128 * This is the ghost of Parser::replace_variables().
130 * @param string $text The text to parse
131 * @param int $flags Bitwise combination of:
132 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
133 * as if the text is being included. Default
134 * is to assume a direct page view.
136 * The generated DOM tree must depend only on the input text and the flags.
137 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
139 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
140 * change in the DOM tree for a given text, must be passed through the section identifier
141 * in the section edit link and thus back to extractSections().
143 * The output of this function is currently only cached in process memory, but a persistent
144 * cache may be implemented at a later date which takes further advantage of these strict
145 * dependency requirements.
147 * @throws MWException
150 public function preprocessToObj( $text, $flags = 0 ) {
151 global $wgMemc, $wgPreprocessorCacheThreshold;
154 $cacheable = ( $wgPreprocessorCacheThreshold !== false
155 && strlen( $text ) > $wgPreprocessorCacheThreshold );
158 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
159 $cacheValue = $wgMemc->get( $cacheKey );
161 $version = substr( $cacheValue, 0, 8 );
162 if ( intval( $version ) == self
::CACHE_VERSION
) {
163 $xml = substr( $cacheValue, 8 );
165 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
168 if ( $xml === false ) {
169 $xml = $this->preprocessToXml( $text, $flags );
170 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
171 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
172 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
175 $xml = $this->preprocessToXml( $text, $flags );
178 // Fail if the number of elements exceeds acceptable limits
179 // Do not attempt to generate the DOM
180 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
181 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
182 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
185 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
188 $dom = new DOMDocument
;
189 wfSuppressWarnings();
190 $result = $dom->loadXML( $xml );
193 // Try running the XML through UtfNormal to get rid of invalid characters
194 $xml = UtfNormal
::cleanUp( $xml );
195 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
196 // don't barf when the XML is >256 levels deep.
197 $result = $dom->loadXML( $xml, 1 << 19 );
200 $obj = new PPNode_DOM( $dom->documentElement
);
208 throw new MWException( __METHOD__
. ' generated invalid XML' );
214 * @param string $text
218 public function preprocessToXml( $text, $flags = 0 ) {
231 'names' => array( 2 => null ),
237 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
239 $xmlishElements = $this->parser
->getStripList();
240 $enableOnlyinclude = false;
241 if ( $forInclusion ) {
242 $ignoredTags = array( 'includeonly', '/includeonly' );
243 $ignoredElements = array( 'noinclude' );
244 $xmlishElements[] = 'noinclude';
245 if ( strpos( $text, '<onlyinclude>' ) !== false
246 && strpos( $text, '</onlyinclude>' ) !== false
248 $enableOnlyinclude = true;
251 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
252 $ignoredElements = array( 'includeonly' );
253 $xmlishElements[] = 'includeonly';
255 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
257 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
258 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
260 $stack = new PPDStack
;
262 $searchBase = "[{<\n"; #}
263 // For fast reverse searches
264 $revText = strrev( $text );
265 $lengthText = strlen( $text );
267 // Input pointer, starts out pointing to a pseudo-newline before the start
269 // Current accumulator
270 $accum =& $stack->getAccum();
272 // True to find equals signs in arguments
274 // True to take notice of pipe characters
277 // True if $i is inside a possible heading
279 // True if there are no more greater-than (>) signs right of $i
281 // True to ignore all input up to the next <onlyinclude>
282 $findOnlyinclude = $enableOnlyinclude;
283 // Do a line-start run without outputting an LF character
284 $fakeLineStart = true;
289 if ( $findOnlyinclude ) {
290 // Ignore all input up to the next <onlyinclude>
291 $startPos = strpos( $text, '<onlyinclude>', $i );
292 if ( $startPos === false ) {
293 // Ignored section runs to the end
294 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
297 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
298 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
300 $findOnlyinclude = false;
303 if ( $fakeLineStart ) {
304 $found = 'line-start';
307 # Find next opening brace, closing brace or pipe
308 $search = $searchBase;
309 if ( $stack->top
=== false ) {
310 $currentClosing = '';
312 $currentClosing = $stack->top
->close
;
313 $search .= $currentClosing;
319 // First equals will be for the template
323 # Output literal section, advance input counter
324 $literalLength = strcspn( $text, $search, $i );
325 if ( $literalLength > 0 ) {
326 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
327 $i +
= $literalLength;
329 if ( $i >= $lengthText ) {
330 if ( $currentClosing == "\n" ) {
331 // Do a past-the-end run to finish off the heading
339 $curChar = $text[$i];
340 if ( $curChar == '|' ) {
342 } elseif ( $curChar == '=' ) {
344 } elseif ( $curChar == '<' ) {
346 } elseif ( $curChar == "\n" ) {
350 $found = 'line-start';
352 } elseif ( $curChar == $currentClosing ) {
354 } elseif ( isset( $rules[$curChar] ) ) {
356 $rule = $rules[$curChar];
358 # Some versions of PHP have a strcspn which stops on null characters
359 # Ignore and continue
366 if ( $found == 'angle' ) {
368 // Handle </onlyinclude>
369 if ( $enableOnlyinclude
370 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
372 $findOnlyinclude = true;
376 // Determine element name
377 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
378 // Element name missing or not listed
384 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
386 // To avoid leaving blank lines, when a sequence of
387 // space-separated comments is both preceded and followed by
388 // a newline (ignoring spaces), then
389 // trim leading and trailing spaces and the trailing newline.
392 $endPos = strpos( $text, '-->', $i +
4 );
393 if ( $endPos === false ) {
394 // Unclosed comment in input, runs to end
395 $inner = substr( $text, $i );
396 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
399 // Search backwards for leading whitespace
400 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
402 // Search forwards for trailing whitespace
403 // $wsEnd will be the position of the last space (or the '>' if there's none)
404 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
406 // Keep looking forward as long as we're finding more
408 $comments = array( array( $wsStart, $wsEnd ) );
409 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
410 $c = strpos( $text, '-->', $wsEnd +
4 );
411 if ( $c === false ) {
414 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
415 $comments[] = array( $wsEnd +
1, $c );
419 // Eat the line if possible
420 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
421 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
422 // it's a possible beneficial b/c break.
423 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
424 && substr( $text, $wsEnd +
1, 1 ) == "\n"
426 // Remove leading whitespace from the end of the accumulator
427 // Sanity check first though
428 $wsLength = $i - $wsStart;
430 && strspn( $accum, " \t", -$wsLength ) === $wsLength
432 $accum = substr( $accum, 0, -$wsLength );
435 // Dump all but the last comment to the accumulator
436 foreach ( $comments as $j => $com ) {
438 $endPos = $com[1] +
1;
439 if ( $j == ( count( $comments ) - 1 ) ) {
442 $inner = substr( $text, $startPos, $endPos - $startPos );
443 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
446 // Do a line-start run next time to look for headings after the comment
447 $fakeLineStart = true;
449 // No line to eat, just take the comment itself
455 $part = $stack->top
->getCurrentPart();
456 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
457 $part->visualEnd
= $wsStart;
459 // Else comments abutting, no change in visual end
460 $part->commentEnd
= $endPos;
463 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
464 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
469 $lowerName = strtolower( $name );
470 $attrStart = $i +
strlen( $name ) +
1;
473 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
474 if ( $tagEndPos === false ) {
475 // Infinite backtrack
476 // Disable tag search to prevent worst-case O(N^2) performance
483 // Handle ignored tags
484 if ( in_array( $lowerName, $ignoredTags ) ) {
486 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
493 if ( $text[$tagEndPos - 1] == '/' ) {
494 $attrEnd = $tagEndPos - 1;
499 $attrEnd = $tagEndPos;
501 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
502 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
504 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
505 $i = $matches[0][1] +
strlen( $matches[0][0] );
506 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
508 // No end tag -- let it run out to the end of the text.
509 $inner = substr( $text, $tagEndPos +
1 );
514 // <includeonly> and <noinclude> just become <ignore> tags
515 if ( in_array( $lowerName, $ignoredElements ) ) {
516 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
522 if ( $attrEnd <= $attrStart ) {
525 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
527 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
528 // Note that the attr element contains the whitespace between name and attribute,
529 // this is necessary for precise reconstruction during pre-save transform.
530 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
531 if ( $inner !== null ) {
532 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
534 $accum .= $close . '</ext>';
535 } elseif ( $found == 'line-start' ) {
536 // Is this the start of a heading?
537 // Line break belongs before the heading element in any case
538 if ( $fakeLineStart ) {
539 $fakeLineStart = false;
545 $count = strspn( $text, '=', $i, 6 );
546 if ( $count == 1 && $findEquals ) {
547 // DWIM: This looks kind of like a name/value separator.
548 // Let's let the equals handler have it and break the
549 // potential heading. This is heuristic, but AFAICT the
550 // methods for completely correct disambiguation are very
552 } elseif ( $count > 0 ) {
556 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
559 $stack->push( $piece );
560 $accum =& $stack->getAccum();
561 $flags = $stack->getFlags();
565 } elseif ( $found == 'line-end' ) {
566 $piece = $stack->top
;
567 // A heading must be open, otherwise \n wouldn't have been in the search list
568 assert( '$piece->open == "\n"' );
569 $part = $piece->getCurrentPart();
570 // Search back through the input to see if it has a proper close.
571 // Do this using the reversed string since the other solutions
572 // (end anchor, etc.) are inefficient.
573 $wsLength = strspn( $revText, " \t", $lengthText - $i );
574 $searchStart = $i - $wsLength;
575 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
576 // Comment found at line end
577 // Search for equals signs before the comment
578 $searchStart = $part->visualEnd
;
579 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
581 $count = $piece->count
;
582 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
583 if ( $equalsLength > 0 ) {
584 if ( $searchStart - $equalsLength == $piece->startPos
) {
585 // This is just a single string of equals signs on its own line
586 // Replicate the doHeadings behavior /={count}(.+)={count}/
587 // First find out how many equals signs there really are (don't stop at 6)
588 $count = $equalsLength;
592 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
595 $count = min( $equalsLength, $count );
598 // Normal match, output <h>
599 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
602 // Single equals sign on its own line, count=0
606 // No match, no <h>, just pass down the inner text
611 $accum =& $stack->getAccum();
612 $flags = $stack->getFlags();
615 // Append the result to the enclosing accumulator
617 // Note that we do NOT increment the input pointer.
618 // This is because the closing linebreak could be the opening linebreak of
619 // another heading. Infinite loops are avoided because the next iteration MUST
620 // hit the heading open case above, which unconditionally increments the
622 } elseif ( $found == 'open' ) {
623 # count opening brace characters
624 $count = strspn( $text, $curChar, $i );
626 # we need to add to stack only if opening brace count is enough for one of the rules
627 if ( $count >= $rule['min'] ) {
628 # Add it to the stack
631 'close' => $rule['end'],
633 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
636 $stack->push( $piece );
637 $accum =& $stack->getAccum();
638 $flags = $stack->getFlags();
641 # Add literal brace(s)
642 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
645 } elseif ( $found == 'close' ) {
646 $piece = $stack->top
;
647 # lets check if there are enough characters for closing brace
648 $maxCount = $piece->count
;
649 $count = strspn( $text, $curChar, $i, $maxCount );
651 # check for maximum matching characters (if there are 5 closing
652 # characters, we will probably need only 3 - depending on the rules)
653 $rule = $rules[$piece->open
];
654 if ( $count > $rule['max'] ) {
655 # The specified maximum exists in the callback array, unless the caller
657 $matchingCount = $rule['max'];
659 # Count is less than the maximum
660 # Skip any gaps in the callback array to find the true largest match
661 # Need to use array_key_exists not isset because the callback can be null
662 $matchingCount = $count;
663 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
668 if ( $matchingCount <= 0 ) {
669 # No matching element found in callback array
670 # Output a literal closing brace and continue
671 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
675 $name = $rule['names'][$matchingCount];
676 if ( $name === null ) {
677 // No element, just literal text
678 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
681 # Note: $parts is already XML, does not need to be encoded further
682 $parts = $piece->parts
;
683 $title = $parts[0]->out
;
686 # The invocation is at the start of the line if lineStart is set in
687 # the stack, and all opening brackets are used up.
688 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
689 $attr = ' lineStart="1"';
694 $element = "<$name$attr>";
695 $element .= "<title>$title</title>";
697 foreach ( $parts as $part ) {
698 if ( isset( $part->eqpos
) ) {
699 $argName = substr( $part->out
, 0, $part->eqpos
);
700 $argValue = substr( $part->out
, $part->eqpos +
1 );
701 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
703 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
707 $element .= "</$name>";
710 # Advance input pointer
711 $i +
= $matchingCount;
715 $accum =& $stack->getAccum();
717 # Re-add the old stack element if it still has unmatched opening characters remaining
718 if ( $matchingCount < $piece->count
) {
719 $piece->parts
= array( new PPDPart
);
720 $piece->count
-= $matchingCount;
721 # do we still qualify for any callback with remaining count?
722 $min = $rules[$piece->open
]['min'];
723 if ( $piece->count
>= $min ) {
724 $stack->push( $piece );
725 $accum =& $stack->getAccum();
727 $accum .= str_repeat( $piece->open
, $piece->count
);
730 $flags = $stack->getFlags();
733 # Add XML element to the enclosing accumulator
735 } elseif ( $found == 'pipe' ) {
736 $findEquals = true; // shortcut for getFlags()
738 $accum =& $stack->getAccum();
740 } elseif ( $found == 'equals' ) {
741 $findEquals = false; // shortcut for getFlags()
742 $stack->getCurrentPart()->eqpos
= strlen( $accum );
748 # Output any remaining unclosed brackets
749 foreach ( $stack->stack
as $piece ) {
750 $stack->rootAccum
.= $piece->breakSyntax();
752 $stack->rootAccum
.= '</root>';
753 $xml = $stack->rootAccum
;
761 * Stack class to help Preprocessor::preprocessToObj()
765 public $stack, $rootAccum;
772 public $elementClass = 'PPDStackElement';
774 public static $false = false;
776 public function __construct() {
777 $this->stack
= array();
779 $this->rootAccum
= '';
780 $this->accum
=& $this->rootAccum
;
786 public function count() {
787 return count( $this->stack
);
790 public function &getAccum() {
794 public function getCurrentPart() {
795 if ( $this->top
=== false ) {
798 return $this->top
->getCurrentPart();
802 public function push( $data ) {
803 if ( $data instanceof $this->elementClass
) {
804 $this->stack
[] = $data;
806 $class = $this->elementClass
;
807 $this->stack
[] = new $class( $data );
809 $this->top
= $this->stack
[count( $this->stack
) - 1];
810 $this->accum
=& $this->top
->getAccum();
813 public function pop() {
814 if ( !count( $this->stack
) ) {
815 throw new MWException( __METHOD__
. ': no elements remaining' );
817 $temp = array_pop( $this->stack
);
819 if ( count( $this->stack
) ) {
820 $this->top
= $this->stack
[count( $this->stack
) - 1];
821 $this->accum
=& $this->top
->getAccum();
823 $this->top
= self
::$false;
824 $this->accum
=& $this->rootAccum
;
829 public function addPart( $s = '' ) {
830 $this->top
->addPart( $s );
831 $this->accum
=& $this->top
->getAccum();
837 public function getFlags() {
838 if ( !count( $this->stack
) ) {
840 'findEquals' => false,
842 'inHeading' => false,
845 return $this->top
->getFlags();
853 class PPDStackElement
{
854 public $open, // Opening character (\n for heading)
855 $close, // Matching closing character
856 $count, // Number of opening characters found (number of "=" for heading)
857 $parts, // Array of PPDPart objects describing pipe-separated parts.
858 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
860 public $partClass = 'PPDPart';
862 public function __construct( $data = array() ) {
863 $class = $this->partClass
;
864 $this->parts
= array( new $class );
866 foreach ( $data as $name => $value ) {
867 $this->$name = $value;
871 public function &getAccum() {
872 return $this->parts
[count( $this->parts
) - 1]->out
;
875 public function addPart( $s = '' ) {
876 $class = $this->partClass
;
877 $this->parts
[] = new $class( $s );
880 public function getCurrentPart() {
881 return $this->parts
[count( $this->parts
) - 1];
887 public function getFlags() {
888 $partCount = count( $this->parts
);
889 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
891 'findPipe' => $findPipe,
892 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
893 'inHeading' => $this->open
== "\n",
898 * Get the output string that would result if the close is not found.
900 * @param bool|int $openingCount
903 public function breakSyntax( $openingCount = false ) {
904 if ( $this->open
== "\n" ) {
905 $s = $this->parts
[0]->out
;
907 if ( $openingCount === false ) {
908 $openingCount = $this->count
;
910 $s = str_repeat( $this->open
, $openingCount );
912 foreach ( $this->parts
as $part ) {
929 public $out; // Output accumulator string
931 // Optional member variables:
932 // eqpos Position of equals sign in output accumulator
933 // commentEnd Past-the-end input pointer for the last comment encountered
934 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
936 public function __construct( $out = '' ) {
942 * An expansion frame, used as a context to expand the result of preprocessToObj()
944 * @codingStandardsIgnoreStart
946 class PPFrame_DOM
implements PPFrame
{
947 // @codingStandardsIgnoreEnd
952 public $preprocessor;
966 * Hashtable listing templates which are disallowed for expansion in this frame,
967 * having been encountered previously in parent frames.
969 public $loopCheckHash;
972 * Recursion depth of this frame, top = 0
973 * Note that this is NOT the same as expansion depth in expand()
977 private $volatile = false;
983 protected $childExpansionCache;
986 * Construct a new preprocessor frame.
987 * @param Preprocessor $preprocessor The parent preprocessor
989 public function __construct( $preprocessor ) {
990 $this->preprocessor
= $preprocessor;
991 $this->parser
= $preprocessor->parser
;
992 $this->title
= $this->parser
->mTitle
;
993 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
994 $this->loopCheckHash
= array();
996 $this->childExpansionCache
= array();
1000 * Create a new child frame
1001 * $args is optionally a multi-root PPNode or array containing the template arguments
1003 * @param bool|array $args
1004 * @param Title|bool $title
1005 * @param int $indexOffset
1006 * @return PPTemplateFrame_DOM
1008 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1009 $namedArgs = array();
1010 $numberedArgs = array();
1011 if ( $title === false ) {
1012 $title = $this->title
;
1014 if ( $args !== false ) {
1016 if ( $args instanceof PPNode
) {
1017 $args = $args->node
;
1019 foreach ( $args as $arg ) {
1020 if ( $arg instanceof PPNode
) {
1023 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1024 $xpath = new DOMXPath( $arg->ownerDocument
);
1027 $nameNodes = $xpath->query( 'name', $arg );
1028 $value = $xpath->query( 'value', $arg );
1029 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1030 // Numbered parameter
1031 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1032 $index = $index - $indexOffset;
1033 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1034 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1036 $numberedArgs[$index] = $value->item( 0 );
1037 unset( $namedArgs[$index] );
1040 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1041 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1042 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1044 $namedArgs[$name] = $value->item( 0 );
1045 unset( $numberedArgs[$name] );
1049 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1053 * @throws MWException
1054 * @param string|int $key
1055 * @param string|PPNode_DOM|DOMDocument $root
1059 public function cachedExpand( $key, $root, $flags = 0 ) {
1060 // we don't have a parent, so we don't have a cache
1061 return $this->expand( $root, $flags );
1065 * @throws MWException
1066 * @param string|PPNode_DOM|DOMDocument $root
1070 public function expand( $root, $flags = 0 ) {
1071 static $expansionDepth = 0;
1072 if ( is_string( $root ) ) {
1076 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1077 $this->parser
->limitationWarn( 'node-count-exceeded',
1078 $this->parser
->mPPNodeCount
,
1079 $this->parser
->mOptions
->getMaxPPNodeCount()
1081 return '<span class="error">Node-count limit exceeded</span>';
1084 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1085 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1087 $this->parser
->mOptions
->getMaxPPExpandDepth()
1089 return '<span class="error">Expansion depth limit exceeded</span>';
1092 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1093 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1096 if ( $root instanceof PPNode_DOM
) {
1097 $root = $root->node
;
1099 if ( $root instanceof DOMDocument
) {
1100 $root = $root->documentElement
;
1103 $outStack = array( '', '' );
1104 $iteratorStack = array( false, $root );
1105 $indexStack = array( 0, 0 );
1107 while ( count( $iteratorStack ) > 1 ) {
1108 $level = count( $outStack ) - 1;
1109 $iteratorNode =& $iteratorStack[$level];
1110 $out =& $outStack[$level];
1111 $index =& $indexStack[$level];
1113 if ( $iteratorNode instanceof PPNode_DOM
) {
1114 $iteratorNode = $iteratorNode->node
;
1117 if ( is_array( $iteratorNode ) ) {
1118 if ( $index >= count( $iteratorNode ) ) {
1119 // All done with this iterator
1120 $iteratorStack[$level] = false;
1121 $contextNode = false;
1123 $contextNode = $iteratorNode[$index];
1126 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1127 if ( $index >= $iteratorNode->length
) {
1128 // All done with this iterator
1129 $iteratorStack[$level] = false;
1130 $contextNode = false;
1132 $contextNode = $iteratorNode->item( $index );
1136 // Copy to $contextNode and then delete from iterator stack,
1137 // because this is not an iterator but we do have to execute it once
1138 $contextNode = $iteratorStack[$level];
1139 $iteratorStack[$level] = false;
1142 if ( $contextNode instanceof PPNode_DOM
) {
1143 $contextNode = $contextNode->node
;
1146 $newIterator = false;
1148 if ( $contextNode === false ) {
1150 } elseif ( is_string( $contextNode ) ) {
1151 $out .= $contextNode;
1152 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1153 $newIterator = $contextNode;
1154 } elseif ( $contextNode instanceof DOMNode
) {
1155 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1156 $out .= $contextNode->nodeValue
;
1157 } elseif ( $contextNode->nodeName
== 'template' ) {
1158 # Double-brace expansion
1159 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1160 $titles = $xpath->query( 'title', $contextNode );
1161 $title = $titles->item( 0 );
1162 $parts = $xpath->query( 'part', $contextNode );
1163 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1164 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1166 $lineStart = $contextNode->getAttribute( 'lineStart' );
1168 'title' => new PPNode_DOM( $title ),
1169 'parts' => new PPNode_DOM( $parts ),
1170 'lineStart' => $lineStart );
1171 $ret = $this->parser
->braceSubstitution( $params, $this );
1172 if ( isset( $ret['object'] ) ) {
1173 $newIterator = $ret['object'];
1175 $out .= $ret['text'];
1178 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1179 # Triple-brace expansion
1180 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1181 $titles = $xpath->query( 'title', $contextNode );
1182 $title = $titles->item( 0 );
1183 $parts = $xpath->query( 'part', $contextNode );
1184 if ( $flags & PPFrame
::NO_ARGS
) {
1185 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1188 'title' => new PPNode_DOM( $title ),
1189 'parts' => new PPNode_DOM( $parts ) );
1190 $ret = $this->parser
->argSubstitution( $params, $this );
1191 if ( isset( $ret['object'] ) ) {
1192 $newIterator = $ret['object'];
1194 $out .= $ret['text'];
1197 } elseif ( $contextNode->nodeName
== 'comment' ) {
1198 # HTML-style comment
1199 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1200 if ( $this->parser
->ot
['html']
1201 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1202 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1205 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1206 # Add a strip marker in PST mode so that pstPass2() can
1207 # run some old-fashioned regexes on the result.
1208 # Not in RECOVER_COMMENTS mode (extractSections) though.
1209 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1211 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1212 $out .= $contextNode->textContent
;
1214 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1215 # Output suppression used by <includeonly> etc.
1216 # OT_WIKI will only respect <ignore> in substed templates.
1217 # The other output types respect it unless NO_IGNORE is set.
1218 # extractSections() sets NO_IGNORE and so never respects it.
1219 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1220 ||
( $flags & PPFrame
::NO_IGNORE
)
1222 $out .= $contextNode->textContent
;
1226 } elseif ( $contextNode->nodeName
== 'ext' ) {
1228 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1229 $names = $xpath->query( 'name', $contextNode );
1230 $attrs = $xpath->query( 'attr', $contextNode );
1231 $inners = $xpath->query( 'inner', $contextNode );
1232 $closes = $xpath->query( 'close', $contextNode );
1233 if ( $flags & PPFrame
::NO_TAGS
) {
1234 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1235 if ( $attrs->length
> 0 ) {
1236 $s .= $this->expand( $attrs->item( 0 ), $flags );
1238 if ( $inners->length
> 0 ) {
1239 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1240 if ( $closes->length
> 0 ) {
1241 $s .= $this->expand( $closes->item( 0 ), $flags );
1249 'name' => new PPNode_DOM( $names->item( 0 ) ),
1250 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1251 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1252 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1254 $out .= $this->parser
->extensionSubstitution( $params, $this );
1256 } elseif ( $contextNode->nodeName
== 'h' ) {
1258 $s = $this->expand( $contextNode->childNodes
, $flags );
1260 # Insert a heading marker only for <h> children of <root>
1261 # This is to stop extractSections from going over multiple tree levels
1262 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1263 # Insert heading index marker
1264 $headingIndex = $contextNode->getAttribute( 'i' );
1265 $titleText = $this->title
->getPrefixedDBkey();
1266 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1267 $serial = count( $this->parser
->mHeadings
) - 1;
1268 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1269 $count = $contextNode->getAttribute( 'level' );
1270 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1271 $this->parser
->mStripState
->addGeneral( $marker, '' );
1275 # Generic recursive expansion
1276 $newIterator = $contextNode->childNodes
;
1279 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1282 if ( $newIterator !== false ) {
1283 if ( $newIterator instanceof PPNode_DOM
) {
1284 $newIterator = $newIterator->node
;
1287 $iteratorStack[] = $newIterator;
1289 } elseif ( $iteratorStack[$level] === false ) {
1290 // Return accumulated value to parent
1291 // With tail recursion
1292 while ( $iteratorStack[$level] === false && $level > 0 ) {
1293 $outStack[$level - 1] .= $out;
1294 array_pop( $outStack );
1295 array_pop( $iteratorStack );
1296 array_pop( $indexStack );
1302 return $outStack[0];
1306 * @param string $sep
1308 * @param string|PPNode_DOM|DOMDocument $args,...
1311 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1312 $args = array_slice( func_get_args(), 2 );
1316 foreach ( $args as $root ) {
1317 if ( $root instanceof PPNode_DOM
) {
1318 $root = $root->node
;
1320 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1321 $root = array( $root );
1323 foreach ( $root as $node ) {
1329 $s .= $this->expand( $node, $flags );
1336 * Implode with no flags specified
1337 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1339 * @param string $sep
1340 * @param string|PPNode_DOM|DOMDocument $args,...
1343 public function implode( $sep /*, ... */ ) {
1344 $args = array_slice( func_get_args(), 1 );
1348 foreach ( $args as $root ) {
1349 if ( $root instanceof PPNode_DOM
) {
1350 $root = $root->node
;
1352 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1353 $root = array( $root );
1355 foreach ( $root as $node ) {
1361 $s .= $this->expand( $node );
1368 * Makes an object that, when expand()ed, will be the same as one obtained
1371 * @param string $sep
1372 * @param string|PPNode_DOM|DOMDocument $args,...
1375 public function virtualImplode( $sep /*, ... */ ) {
1376 $args = array_slice( func_get_args(), 1 );
1380 foreach ( $args as $root ) {
1381 if ( $root instanceof PPNode_DOM
) {
1382 $root = $root->node
;
1384 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1385 $root = array( $root );
1387 foreach ( $root as $node ) {
1400 * Virtual implode with brackets
1401 * @param string $start
1402 * @param string $sep
1403 * @param string $end
1404 * @param string|PPNode_DOM|DOMDocument $args,...
1407 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1408 $args = array_slice( func_get_args(), 3 );
1409 $out = array( $start );
1412 foreach ( $args as $root ) {
1413 if ( $root instanceof PPNode_DOM
) {
1414 $root = $root->node
;
1416 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1417 $root = array( $root );
1419 foreach ( $root as $node ) {
1432 public function __toString() {
1436 public function getPDBK( $level = false ) {
1437 if ( $level === false ) {
1438 return $this->title
->getPrefixedDBkey();
1440 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1447 public function getArguments() {
1454 public function getNumberedArguments() {
1461 public function getNamedArguments() {
1466 * Returns true if there are no arguments in this frame
1470 public function isEmpty() {
1474 public function getArgument( $name ) {
1479 * Returns true if the infinite loop check is OK, false if a loop is detected
1481 * @param Title $title
1484 public function loopCheck( $title ) {
1485 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1489 * Return true if the frame is a template frame
1493 public function isTemplate() {
1498 * Get a title of frame
1502 public function getTitle() {
1503 return $this->title
;
1507 * Set the volatile flag
1511 public function setVolatile( $flag = true ) {
1512 $this->volatile
= $flag;
1516 * Get the volatile flag
1520 public function isVolatile() {
1521 return $this->volatile
;
1529 public function setTTL( $ttl ) {
1530 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1540 public function getTTL() {
1546 * Expansion frame with template arguments
1548 * @codingStandardsIgnoreStart
1550 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1551 // @codingStandardsIgnoreEnd
1553 public $numberedArgs, $namedArgs;
1559 public $numberedExpansionCache, $namedExpansionCache;
1562 * @param Preprocessor $preprocessor
1563 * @param bool|PPFrame_DOM $parent
1564 * @param array $numberedArgs
1565 * @param array $namedArgs
1566 * @param bool|Title $title
1568 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1569 $namedArgs = array(), $title = false
1571 parent
::__construct( $preprocessor );
1573 $this->parent
= $parent;
1574 $this->numberedArgs
= $numberedArgs;
1575 $this->namedArgs
= $namedArgs;
1576 $this->title
= $title;
1577 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1578 $this->titleCache
= $parent->titleCache
;
1579 $this->titleCache
[] = $pdbk;
1580 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1581 if ( $pdbk !== false ) {
1582 $this->loopCheckHash
[$pdbk] = true;
1584 $this->depth
= $parent->depth +
1;
1585 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1588 public function __toString() {
1591 $args = $this->numberedArgs +
$this->namedArgs
;
1592 foreach ( $args as $name => $value ) {
1598 $s .= "\"$name\":\"" .
1599 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1606 * @throws MWException
1607 * @param string|int $key
1608 * @param string|PPNode_DOM|DOMDocument $root
1612 public function cachedExpand( $key, $root, $flags = 0 ) {
1613 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1614 return $this->parent
->childExpansionCache
[$key];
1616 $retval = $this->expand( $root, $flags );
1617 if ( !$this->isVolatile() ) {
1618 $this->parent
->childExpansionCache
[$key] = $retval;
1624 * Returns true if there are no arguments in this frame
1628 public function isEmpty() {
1629 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1632 public function getArguments() {
1633 $arguments = array();
1634 foreach ( array_merge(
1635 array_keys( $this->numberedArgs
),
1636 array_keys( $this->namedArgs
) ) as $key ) {
1637 $arguments[$key] = $this->getArgument( $key );
1642 public function getNumberedArguments() {
1643 $arguments = array();
1644 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1645 $arguments[$key] = $this->getArgument( $key );
1650 public function getNamedArguments() {
1651 $arguments = array();
1652 foreach ( array_keys( $this->namedArgs
) as $key ) {
1653 $arguments[$key] = $this->getArgument( $key );
1658 public function getNumberedArgument( $index ) {
1659 if ( !isset( $this->numberedArgs
[$index] ) ) {
1662 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1663 # No trimming for unnamed arguments
1664 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1665 $this->numberedArgs
[$index],
1666 PPFrame
::STRIP_COMMENTS
1669 return $this->numberedExpansionCache
[$index];
1672 public function getNamedArgument( $name ) {
1673 if ( !isset( $this->namedArgs
[$name] ) ) {
1676 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1677 # Trim named arguments post-expand, for backwards compatibility
1678 $this->namedExpansionCache
[$name] = trim(
1679 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1681 return $this->namedExpansionCache
[$name];
1684 public function getArgument( $name ) {
1685 $text = $this->getNumberedArgument( $name );
1686 if ( $text === false ) {
1687 $text = $this->getNamedArgument( $name );
1693 * Return true if the frame is a template frame
1697 public function isTemplate() {
1701 public function setVolatile( $flag = true ) {
1702 parent
::setVolatile( $flag );
1703 $this->parent
->setVolatile( $flag );
1706 public function setTTL( $ttl ) {
1707 parent
::setTTL( $ttl );
1708 $this->parent
->setTTL( $ttl );
1713 * Expansion frame with custom arguments
1715 * @codingStandardsIgnoreStart
1717 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1718 // @codingStandardsIgnoreEnd
1722 public function __construct( $preprocessor, $args ) {
1723 parent
::__construct( $preprocessor );
1724 $this->args
= $args;
1727 public function __toString() {
1730 foreach ( $this->args
as $name => $value ) {
1736 $s .= "\"$name\":\"" .
1737 str_replace( '"', '\\"', $value->__toString() ) . '"';
1746 public function isEmpty() {
1747 return !count( $this->args
);
1750 public function getArgument( $index ) {
1751 if ( !isset( $this->args
[$index] ) ) {
1754 return $this->args
[$index];
1757 public function getArguments() {
1764 * @codingStandardsIgnoreStart
1766 class PPNode_DOM
implements PPNode
{
1767 // @codingStandardsIgnoreEnd
1775 public function __construct( $node, $xpath = false ) {
1776 $this->node
= $node;
1782 public function getXPath() {
1783 if ( $this->xpath
=== null ) {
1784 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1786 return $this->xpath
;
1789 public function __toString() {
1790 if ( $this->node
instanceof DOMNodeList
) {
1792 foreach ( $this->node
as $node ) {
1793 $s .= $node->ownerDocument
->saveXML( $node );
1796 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1802 * @return bool|PPNode_DOM
1804 public function getChildren() {
1805 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1809 * @return bool|PPNode_DOM
1811 public function getFirstChild() {
1812 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1816 * @return bool|PPNode_DOM
1818 public function getNextSibling() {
1819 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1823 * @param string $type
1825 * @return bool|PPNode_DOM
1827 public function getChildrenOfType( $type ) {
1828 return new self( $this->getXPath()->query( $type, $this->node
) );
1834 public function getLength() {
1835 if ( $this->node
instanceof DOMNodeList
) {
1836 return $this->node
->length
;
1844 * @return bool|PPNode_DOM
1846 public function item( $i ) {
1847 $item = $this->node
->item( $i );
1848 return $item ?
new self( $item ) : false;
1854 public function getName() {
1855 if ( $this->node
instanceof DOMNodeList
) {
1858 return $this->node
->nodeName
;
1863 * Split a "<part>" node into an associative array containing:
1864 * - name PPNode name
1865 * - index String index
1866 * - value PPNode value
1868 * @throws MWException
1871 public function splitArg() {
1872 $xpath = $this->getXPath();
1873 $names = $xpath->query( 'name', $this->node
);
1874 $values = $xpath->query( 'value', $this->node
);
1875 if ( !$names->length ||
!$values->length
) {
1876 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1878 $name = $names->item( 0 );
1879 $index = $name->getAttribute( 'index' );
1881 'name' => new self( $name ),
1883 'value' => new self( $values->item( 0 ) ) );
1887 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1888 * All values in the resulting array are PPNodes. Inner and close are optional.
1890 * @throws MWException
1893 public function splitExt() {
1894 $xpath = $this->getXPath();
1895 $names = $xpath->query( 'name', $this->node
);
1896 $attrs = $xpath->query( 'attr', $this->node
);
1897 $inners = $xpath->query( 'inner', $this->node
);
1898 $closes = $xpath->query( 'close', $this->node
);
1899 if ( !$names->length ||
!$attrs->length
) {
1900 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1903 'name' => new self( $names->item( 0 ) ),
1904 'attr' => new self( $attrs->item( 0 ) ) );
1905 if ( $inners->length
) {
1906 $parts['inner'] = new self( $inners->item( 0 ) );
1908 if ( $closes->length
) {
1909 $parts['close'] = new self( $closes->item( 0 ) );
1915 * Split a "<h>" node
1916 * @throws MWException
1919 public function splitHeading() {
1920 if ( $this->getName() !== 'h' ) {
1921 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1924 'i' => $this->node
->getAttribute( 'i' ),
1925 'level' => $this->node
->getAttribute( 'level' ),
1926 'contents' => $this->getChildren()