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
);
207 throw new MWException( __METHOD__
. ' generated invalid XML' );
213 * @param string $text
217 public function preprocessToXml( $text, $flags = 0 ) {
230 'names' => array( 2 => null ),
236 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
238 $xmlishElements = $this->parser
->getStripList();
239 $enableOnlyinclude = false;
240 if ( $forInclusion ) {
241 $ignoredTags = array( 'includeonly', '/includeonly' );
242 $ignoredElements = array( 'noinclude' );
243 $xmlishElements[] = 'noinclude';
244 if ( strpos( $text, '<onlyinclude>' ) !== false
245 && strpos( $text, '</onlyinclude>' ) !== false
247 $enableOnlyinclude = true;
250 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
251 $ignoredElements = array( 'includeonly' );
252 $xmlishElements[] = 'includeonly';
254 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
256 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
257 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
259 $stack = new PPDStack
;
261 $searchBase = "[{<\n"; #}
262 // For fast reverse searches
263 $revText = strrev( $text );
264 $lengthText = strlen( $text );
266 // Input pointer, starts out pointing to a pseudo-newline before the start
268 // Current accumulator
269 $accum =& $stack->getAccum();
271 // True to find equals signs in arguments
273 // True to take notice of pipe characters
276 // True if $i is inside a possible heading
278 // True if there are no more greater-than (>) signs right of $i
280 // True to ignore all input up to the next <onlyinclude>
281 $findOnlyinclude = $enableOnlyinclude;
282 // Do a line-start run without outputting an LF character
283 $fakeLineStart = true;
288 if ( $findOnlyinclude ) {
289 // Ignore all input up to the next <onlyinclude>
290 $startPos = strpos( $text, '<onlyinclude>', $i );
291 if ( $startPos === false ) {
292 // Ignored section runs to the end
293 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
296 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
297 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
299 $findOnlyinclude = false;
302 if ( $fakeLineStart ) {
303 $found = 'line-start';
306 # Find next opening brace, closing brace or pipe
307 $search = $searchBase;
308 if ( $stack->top
=== false ) {
309 $currentClosing = '';
311 $currentClosing = $stack->top
->close
;
312 $search .= $currentClosing;
318 // First equals will be for the template
322 # Output literal section, advance input counter
323 $literalLength = strcspn( $text, $search, $i );
324 if ( $literalLength > 0 ) {
325 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
326 $i +
= $literalLength;
328 if ( $i >= $lengthText ) {
329 if ( $currentClosing == "\n" ) {
330 // Do a past-the-end run to finish off the heading
338 $curChar = $text[$i];
339 if ( $curChar == '|' ) {
341 } elseif ( $curChar == '=' ) {
343 } elseif ( $curChar == '<' ) {
345 } elseif ( $curChar == "\n" ) {
349 $found = 'line-start';
351 } elseif ( $curChar == $currentClosing ) {
353 } elseif ( isset( $rules[$curChar] ) ) {
355 $rule = $rules[$curChar];
357 # Some versions of PHP have a strcspn which stops on null characters
358 # Ignore and continue
365 if ( $found == 'angle' ) {
367 // Handle </onlyinclude>
368 if ( $enableOnlyinclude
369 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
371 $findOnlyinclude = true;
375 // Determine element name
376 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
377 // Element name missing or not listed
383 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
385 // To avoid leaving blank lines, when a sequence of
386 // space-separated comments is both preceded and followed by
387 // a newline (ignoring spaces), then
388 // trim leading and trailing spaces and the trailing newline.
391 $endPos = strpos( $text, '-->', $i +
4 );
392 if ( $endPos === false ) {
393 // Unclosed comment in input, runs to end
394 $inner = substr( $text, $i );
395 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
398 // Search backwards for leading whitespace
399 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
401 // Search forwards for trailing whitespace
402 // $wsEnd will be the position of the last space (or the '>' if there's none)
403 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
405 // Keep looking forward as long as we're finding more
407 $comments = array( array( $wsStart, $wsEnd ) );
408 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
409 $c = strpos( $text, '-->', $wsEnd +
4 );
410 if ( $c === false ) {
413 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
414 $comments[] = array( $wsEnd +
1, $c );
418 // Eat the line if possible
419 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
420 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
421 // it's a possible beneficial b/c break.
422 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
423 && substr( $text, $wsEnd +
1, 1 ) == "\n"
425 // Remove leading whitespace from the end of the accumulator
426 // Sanity check first though
427 $wsLength = $i - $wsStart;
429 && strspn( $accum, " \t", -$wsLength ) === $wsLength
431 $accum = substr( $accum, 0, -$wsLength );
434 // Dump all but the last comment to the accumulator
435 foreach ( $comments as $j => $com ) {
437 $endPos = $com[1] +
1;
438 if ( $j == ( count( $comments ) - 1 ) ) {
441 $inner = substr( $text, $startPos, $endPos - $startPos );
442 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
445 // Do a line-start run next time to look for headings after the comment
446 $fakeLineStart = true;
448 // No line to eat, just take the comment itself
454 $part = $stack->top
->getCurrentPart();
455 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
456 $part->visualEnd
= $wsStart;
458 // Else comments abutting, no change in visual end
459 $part->commentEnd
= $endPos;
462 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
463 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
468 $lowerName = strtolower( $name );
469 $attrStart = $i +
strlen( $name ) +
1;
472 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
473 if ( $tagEndPos === false ) {
474 // Infinite backtrack
475 // Disable tag search to prevent worst-case O(N^2) performance
482 // Handle ignored tags
483 if ( in_array( $lowerName, $ignoredTags ) ) {
485 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
492 if ( $text[$tagEndPos - 1] == '/' ) {
493 $attrEnd = $tagEndPos - 1;
498 $attrEnd = $tagEndPos;
500 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
501 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
503 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
504 $i = $matches[0][1] +
strlen( $matches[0][0] );
505 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
507 // No end tag -- let it run out to the end of the text.
508 $inner = substr( $text, $tagEndPos +
1 );
513 // <includeonly> and <noinclude> just become <ignore> tags
514 if ( in_array( $lowerName, $ignoredElements ) ) {
515 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
521 if ( $attrEnd <= $attrStart ) {
524 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
526 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
527 // Note that the attr element contains the whitespace between name and attribute,
528 // this is necessary for precise reconstruction during pre-save transform.
529 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
530 if ( $inner !== null ) {
531 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
533 $accum .= $close . '</ext>';
534 } elseif ( $found == 'line-start' ) {
535 // Is this the start of a heading?
536 // Line break belongs before the heading element in any case
537 if ( $fakeLineStart ) {
538 $fakeLineStart = false;
544 $count = strspn( $text, '=', $i, 6 );
545 if ( $count == 1 && $findEquals ) {
546 // DWIM: This looks kind of like a name/value separator.
547 // Let's let the equals handler have it and break the
548 // potential heading. This is heuristic, but AFAICT the
549 // methods for completely correct disambiguation are very
551 } elseif ( $count > 0 ) {
555 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
558 $stack->push( $piece );
559 $accum =& $stack->getAccum();
560 $flags = $stack->getFlags();
564 } elseif ( $found == 'line-end' ) {
565 $piece = $stack->top
;
566 // A heading must be open, otherwise \n wouldn't have been in the search list
567 assert( '$piece->open == "\n"' );
568 $part = $piece->getCurrentPart();
569 // Search back through the input to see if it has a proper close.
570 // Do this using the reversed string since the other solutions
571 // (end anchor, etc.) are inefficient.
572 $wsLength = strspn( $revText, " \t", $lengthText - $i );
573 $searchStart = $i - $wsLength;
574 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
575 // Comment found at line end
576 // Search for equals signs before the comment
577 $searchStart = $part->visualEnd
;
578 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
580 $count = $piece->count
;
581 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
582 if ( $equalsLength > 0 ) {
583 if ( $searchStart - $equalsLength == $piece->startPos
) {
584 // This is just a single string of equals signs on its own line
585 // Replicate the doHeadings behavior /={count}(.+)={count}/
586 // First find out how many equals signs there really are (don't stop at 6)
587 $count = $equalsLength;
591 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
594 $count = min( $equalsLength, $count );
597 // Normal match, output <h>
598 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
601 // Single equals sign on its own line, count=0
605 // No match, no <h>, just pass down the inner text
610 $accum =& $stack->getAccum();
611 $flags = $stack->getFlags();
614 // Append the result to the enclosing accumulator
616 // Note that we do NOT increment the input pointer.
617 // This is because the closing linebreak could be the opening linebreak of
618 // another heading. Infinite loops are avoided because the next iteration MUST
619 // hit the heading open case above, which unconditionally increments the
621 } elseif ( $found == 'open' ) {
622 # count opening brace characters
623 $count = strspn( $text, $curChar, $i );
625 # we need to add to stack only if opening brace count is enough for one of the rules
626 if ( $count >= $rule['min'] ) {
627 # Add it to the stack
630 'close' => $rule['end'],
632 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
635 $stack->push( $piece );
636 $accum =& $stack->getAccum();
637 $flags = $stack->getFlags();
640 # Add literal brace(s)
641 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
644 } elseif ( $found == 'close' ) {
645 $piece = $stack->top
;
646 # lets check if there are enough characters for closing brace
647 $maxCount = $piece->count
;
648 $count = strspn( $text, $curChar, $i, $maxCount );
650 # check for maximum matching characters (if there are 5 closing
651 # characters, we will probably need only 3 - depending on the rules)
652 $rule = $rules[$piece->open
];
653 if ( $count > $rule['max'] ) {
654 # The specified maximum exists in the callback array, unless the caller
656 $matchingCount = $rule['max'];
658 # Count is less than the maximum
659 # Skip any gaps in the callback array to find the true largest match
660 # Need to use array_key_exists not isset because the callback can be null
661 $matchingCount = $count;
662 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
667 if ( $matchingCount <= 0 ) {
668 # No matching element found in callback array
669 # Output a literal closing brace and continue
670 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
674 $name = $rule['names'][$matchingCount];
675 if ( $name === null ) {
676 // No element, just literal text
677 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
680 # Note: $parts is already XML, does not need to be encoded further
681 $parts = $piece->parts
;
682 $title = $parts[0]->out
;
685 # The invocation is at the start of the line if lineStart is set in
686 # the stack, and all opening brackets are used up.
687 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
688 $attr = ' lineStart="1"';
693 $element = "<$name$attr>";
694 $element .= "<title>$title</title>";
696 foreach ( $parts as $part ) {
697 if ( isset( $part->eqpos
) ) {
698 $argName = substr( $part->out
, 0, $part->eqpos
);
699 $argValue = substr( $part->out
, $part->eqpos +
1 );
700 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
702 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
706 $element .= "</$name>";
709 # Advance input pointer
710 $i +
= $matchingCount;
714 $accum =& $stack->getAccum();
716 # Re-add the old stack element if it still has unmatched opening characters remaining
717 if ( $matchingCount < $piece->count
) {
718 $piece->parts
= array( new PPDPart
);
719 $piece->count
-= $matchingCount;
720 # do we still qualify for any callback with remaining count?
721 $min = $rules[$piece->open
]['min'];
722 if ( $piece->count
>= $min ) {
723 $stack->push( $piece );
724 $accum =& $stack->getAccum();
726 $accum .= str_repeat( $piece->open
, $piece->count
);
729 $flags = $stack->getFlags();
732 # Add XML element to the enclosing accumulator
734 } elseif ( $found == 'pipe' ) {
735 $findEquals = true; // shortcut for getFlags()
737 $accum =& $stack->getAccum();
739 } elseif ( $found == 'equals' ) {
740 $findEquals = false; // shortcut for getFlags()
741 $stack->getCurrentPart()->eqpos
= strlen( $accum );
747 # Output any remaining unclosed brackets
748 foreach ( $stack->stack
as $piece ) {
749 $stack->rootAccum
.= $piece->breakSyntax();
751 $stack->rootAccum
.= '</root>';
752 $xml = $stack->rootAccum
;
759 * Stack class to help Preprocessor::preprocessToObj()
763 public $stack, $rootAccum;
770 public $elementClass = 'PPDStackElement';
772 public static $false = false;
774 public function __construct() {
775 $this->stack
= array();
777 $this->rootAccum
= '';
778 $this->accum
=& $this->rootAccum
;
784 public function count() {
785 return count( $this->stack
);
788 public function &getAccum() {
792 public function getCurrentPart() {
793 if ( $this->top
=== false ) {
796 return $this->top
->getCurrentPart();
800 public function push( $data ) {
801 if ( $data instanceof $this->elementClass
) {
802 $this->stack
[] = $data;
804 $class = $this->elementClass
;
805 $this->stack
[] = new $class( $data );
807 $this->top
= $this->stack
[count( $this->stack
) - 1];
808 $this->accum
=& $this->top
->getAccum();
811 public function pop() {
812 if ( !count( $this->stack
) ) {
813 throw new MWException( __METHOD__
. ': no elements remaining' );
815 $temp = array_pop( $this->stack
);
817 if ( count( $this->stack
) ) {
818 $this->top
= $this->stack
[count( $this->stack
) - 1];
819 $this->accum
=& $this->top
->getAccum();
821 $this->top
= self
::$false;
822 $this->accum
=& $this->rootAccum
;
827 public function addPart( $s = '' ) {
828 $this->top
->addPart( $s );
829 $this->accum
=& $this->top
->getAccum();
835 public function getFlags() {
836 if ( !count( $this->stack
) ) {
838 'findEquals' => false,
840 'inHeading' => false,
843 return $this->top
->getFlags();
851 class PPDStackElement
{
852 public $open, // Opening character (\n for heading)
853 $close, // Matching closing character
854 $count, // Number of opening characters found (number of "=" for heading)
855 $parts, // Array of PPDPart objects describing pipe-separated parts.
856 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
858 public $partClass = 'PPDPart';
860 public function __construct( $data = array() ) {
861 $class = $this->partClass
;
862 $this->parts
= array( new $class );
864 foreach ( $data as $name => $value ) {
865 $this->$name = $value;
869 public function &getAccum() {
870 return $this->parts
[count( $this->parts
) - 1]->out
;
873 public function addPart( $s = '' ) {
874 $class = $this->partClass
;
875 $this->parts
[] = new $class( $s );
878 public function getCurrentPart() {
879 return $this->parts
[count( $this->parts
) - 1];
885 public function getFlags() {
886 $partCount = count( $this->parts
);
887 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
889 'findPipe' => $findPipe,
890 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
891 'inHeading' => $this->open
== "\n",
896 * Get the output string that would result if the close is not found.
898 * @param bool|int $openingCount
901 public function breakSyntax( $openingCount = false ) {
902 if ( $this->open
== "\n" ) {
903 $s = $this->parts
[0]->out
;
905 if ( $openingCount === false ) {
906 $openingCount = $this->count
;
908 $s = str_repeat( $this->open
, $openingCount );
910 foreach ( $this->parts
as $part ) {
927 public $out; // Output accumulator string
929 // Optional member variables:
930 // eqpos Position of equals sign in output accumulator
931 // commentEnd Past-the-end input pointer for the last comment encountered
932 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
934 public function __construct( $out = '' ) {
940 * An expansion frame, used as a context to expand the result of preprocessToObj()
942 * @codingStandardsIgnoreStart
944 class PPFrame_DOM
implements PPFrame
{
945 // @codingStandardsIgnoreEnd
950 public $preprocessor;
964 * Hashtable listing templates which are disallowed for expansion in this frame,
965 * having been encountered previously in parent frames.
967 public $loopCheckHash;
970 * Recursion depth of this frame, top = 0
971 * Note that this is NOT the same as expansion depth in expand()
975 private $volatile = false;
981 protected $childExpansionCache;
984 * Construct a new preprocessor frame.
985 * @param Preprocessor $preprocessor The parent preprocessor
987 public function __construct( $preprocessor ) {
988 $this->preprocessor
= $preprocessor;
989 $this->parser
= $preprocessor->parser
;
990 $this->title
= $this->parser
->mTitle
;
991 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
992 $this->loopCheckHash
= array();
994 $this->childExpansionCache
= array();
998 * Create a new child frame
999 * $args is optionally a multi-root PPNode or array containing the template arguments
1001 * @param bool|array $args
1002 * @param Title|bool $title
1003 * @param int $indexOffset
1004 * @return PPTemplateFrame_DOM
1006 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1007 $namedArgs = array();
1008 $numberedArgs = array();
1009 if ( $title === false ) {
1010 $title = $this->title
;
1012 if ( $args !== false ) {
1014 if ( $args instanceof PPNode
) {
1015 $args = $args->node
;
1017 foreach ( $args as $arg ) {
1018 if ( $arg instanceof PPNode
) {
1021 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1022 $xpath = new DOMXPath( $arg->ownerDocument
);
1025 $nameNodes = $xpath->query( 'name', $arg );
1026 $value = $xpath->query( 'value', $arg );
1027 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1028 // Numbered parameter
1029 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1030 $index = $index - $indexOffset;
1031 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1032 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1034 $numberedArgs[$index] = $value->item( 0 );
1035 unset( $namedArgs[$index] );
1038 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1039 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1040 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1042 $namedArgs[$name] = $value->item( 0 );
1043 unset( $numberedArgs[$name] );
1047 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1051 * @throws MWException
1052 * @param string|int $key
1053 * @param string|PPNode_DOM|DOMDocument $root
1057 public function cachedExpand( $key, $root, $flags = 0 ) {
1058 // we don't have a parent, so we don't have a cache
1059 return $this->expand( $root, $flags );
1063 * @throws MWException
1064 * @param string|PPNode_DOM|DOMDocument $root
1068 public function expand( $root, $flags = 0 ) {
1069 static $expansionDepth = 0;
1070 if ( is_string( $root ) ) {
1074 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1075 $this->parser
->limitationWarn( 'node-count-exceeded',
1076 $this->parser
->mPPNodeCount
,
1077 $this->parser
->mOptions
->getMaxPPNodeCount()
1079 return '<span class="error">Node-count limit exceeded</span>';
1082 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1083 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1085 $this->parser
->mOptions
->getMaxPPExpandDepth()
1087 return '<span class="error">Expansion depth limit exceeded</span>';
1090 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1091 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1094 if ( $root instanceof PPNode_DOM
) {
1095 $root = $root->node
;
1097 if ( $root instanceof DOMDocument
) {
1098 $root = $root->documentElement
;
1101 $outStack = array( '', '' );
1102 $iteratorStack = array( false, $root );
1103 $indexStack = array( 0, 0 );
1105 while ( count( $iteratorStack ) > 1 ) {
1106 $level = count( $outStack ) - 1;
1107 $iteratorNode =& $iteratorStack[$level];
1108 $out =& $outStack[$level];
1109 $index =& $indexStack[$level];
1111 if ( $iteratorNode instanceof PPNode_DOM
) {
1112 $iteratorNode = $iteratorNode->node
;
1115 if ( is_array( $iteratorNode ) ) {
1116 if ( $index >= count( $iteratorNode ) ) {
1117 // All done with this iterator
1118 $iteratorStack[$level] = false;
1119 $contextNode = false;
1121 $contextNode = $iteratorNode[$index];
1124 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1125 if ( $index >= $iteratorNode->length
) {
1126 // All done with this iterator
1127 $iteratorStack[$level] = false;
1128 $contextNode = false;
1130 $contextNode = $iteratorNode->item( $index );
1134 // Copy to $contextNode and then delete from iterator stack,
1135 // because this is not an iterator but we do have to execute it once
1136 $contextNode = $iteratorStack[$level];
1137 $iteratorStack[$level] = false;
1140 if ( $contextNode instanceof PPNode_DOM
) {
1141 $contextNode = $contextNode->node
;
1144 $newIterator = false;
1146 if ( $contextNode === false ) {
1148 } elseif ( is_string( $contextNode ) ) {
1149 $out .= $contextNode;
1150 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1151 $newIterator = $contextNode;
1152 } elseif ( $contextNode instanceof DOMNode
) {
1153 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1154 $out .= $contextNode->nodeValue
;
1155 } elseif ( $contextNode->nodeName
== 'template' ) {
1156 # Double-brace expansion
1157 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1158 $titles = $xpath->query( 'title', $contextNode );
1159 $title = $titles->item( 0 );
1160 $parts = $xpath->query( 'part', $contextNode );
1161 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1162 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1164 $lineStart = $contextNode->getAttribute( 'lineStart' );
1166 'title' => new PPNode_DOM( $title ),
1167 'parts' => new PPNode_DOM( $parts ),
1168 'lineStart' => $lineStart );
1169 $ret = $this->parser
->braceSubstitution( $params, $this );
1170 if ( isset( $ret['object'] ) ) {
1171 $newIterator = $ret['object'];
1173 $out .= $ret['text'];
1176 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1177 # Triple-brace expansion
1178 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1179 $titles = $xpath->query( 'title', $contextNode );
1180 $title = $titles->item( 0 );
1181 $parts = $xpath->query( 'part', $contextNode );
1182 if ( $flags & PPFrame
::NO_ARGS
) {
1183 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1186 'title' => new PPNode_DOM( $title ),
1187 'parts' => new PPNode_DOM( $parts ) );
1188 $ret = $this->parser
->argSubstitution( $params, $this );
1189 if ( isset( $ret['object'] ) ) {
1190 $newIterator = $ret['object'];
1192 $out .= $ret['text'];
1195 } elseif ( $contextNode->nodeName
== 'comment' ) {
1196 # HTML-style comment
1197 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1198 if ( $this->parser
->ot
['html']
1199 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1200 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1203 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1204 # Add a strip marker in PST mode so that pstPass2() can
1205 # run some old-fashioned regexes on the result.
1206 # Not in RECOVER_COMMENTS mode (extractSections) though.
1207 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1209 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1210 $out .= $contextNode->textContent
;
1212 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1213 # Output suppression used by <includeonly> etc.
1214 # OT_WIKI will only respect <ignore> in substed templates.
1215 # The other output types respect it unless NO_IGNORE is set.
1216 # extractSections() sets NO_IGNORE and so never respects it.
1217 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1218 ||
( $flags & PPFrame
::NO_IGNORE
)
1220 $out .= $contextNode->textContent
;
1224 } elseif ( $contextNode->nodeName
== 'ext' ) {
1226 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1227 $names = $xpath->query( 'name', $contextNode );
1228 $attrs = $xpath->query( 'attr', $contextNode );
1229 $inners = $xpath->query( 'inner', $contextNode );
1230 $closes = $xpath->query( 'close', $contextNode );
1231 if ( $flags & PPFrame
::NO_TAGS
) {
1232 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1233 if ( $attrs->length
> 0 ) {
1234 $s .= $this->expand( $attrs->item( 0 ), $flags );
1236 if ( $inners->length
> 0 ) {
1237 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1238 if ( $closes->length
> 0 ) {
1239 $s .= $this->expand( $closes->item( 0 ), $flags );
1247 'name' => new PPNode_DOM( $names->item( 0 ) ),
1248 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1249 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1250 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1252 $out .= $this->parser
->extensionSubstitution( $params, $this );
1254 } elseif ( $contextNode->nodeName
== 'h' ) {
1256 $s = $this->expand( $contextNode->childNodes
, $flags );
1258 # Insert a heading marker only for <h> children of <root>
1259 # This is to stop extractSections from going over multiple tree levels
1260 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1261 # Insert heading index marker
1262 $headingIndex = $contextNode->getAttribute( 'i' );
1263 $titleText = $this->title
->getPrefixedDBkey();
1264 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1265 $serial = count( $this->parser
->mHeadings
) - 1;
1266 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1267 $count = $contextNode->getAttribute( 'level' );
1268 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1269 $this->parser
->mStripState
->addGeneral( $marker, '' );
1273 # Generic recursive expansion
1274 $newIterator = $contextNode->childNodes
;
1277 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1280 if ( $newIterator !== false ) {
1281 if ( $newIterator instanceof PPNode_DOM
) {
1282 $newIterator = $newIterator->node
;
1285 $iteratorStack[] = $newIterator;
1287 } elseif ( $iteratorStack[$level] === false ) {
1288 // Return accumulated value to parent
1289 // With tail recursion
1290 while ( $iteratorStack[$level] === false && $level > 0 ) {
1291 $outStack[$level - 1] .= $out;
1292 array_pop( $outStack );
1293 array_pop( $iteratorStack );
1294 array_pop( $indexStack );
1300 return $outStack[0];
1304 * @param string $sep
1306 * @param string|PPNode_DOM|DOMDocument $args,...
1309 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1310 $args = array_slice( func_get_args(), 2 );
1314 foreach ( $args as $root ) {
1315 if ( $root instanceof PPNode_DOM
) {
1316 $root = $root->node
;
1318 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1319 $root = array( $root );
1321 foreach ( $root as $node ) {
1327 $s .= $this->expand( $node, $flags );
1334 * Implode with no flags specified
1335 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1337 * @param string $sep
1338 * @param string|PPNode_DOM|DOMDocument $args,...
1341 public function implode( $sep /*, ... */ ) {
1342 $args = array_slice( func_get_args(), 1 );
1346 foreach ( $args as $root ) {
1347 if ( $root instanceof PPNode_DOM
) {
1348 $root = $root->node
;
1350 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1351 $root = array( $root );
1353 foreach ( $root as $node ) {
1359 $s .= $this->expand( $node );
1366 * Makes an object that, when expand()ed, will be the same as one obtained
1369 * @param string $sep
1370 * @param string|PPNode_DOM|DOMDocument $args,...
1373 public function virtualImplode( $sep /*, ... */ ) {
1374 $args = array_slice( func_get_args(), 1 );
1378 foreach ( $args as $root ) {
1379 if ( $root instanceof PPNode_DOM
) {
1380 $root = $root->node
;
1382 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1383 $root = array( $root );
1385 foreach ( $root as $node ) {
1398 * Virtual implode with brackets
1399 * @param string $start
1400 * @param string $sep
1401 * @param string $end
1402 * @param string|PPNode_DOM|DOMDocument $args,...
1405 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1406 $args = array_slice( func_get_args(), 3 );
1407 $out = array( $start );
1410 foreach ( $args as $root ) {
1411 if ( $root instanceof PPNode_DOM
) {
1412 $root = $root->node
;
1414 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1415 $root = array( $root );
1417 foreach ( $root as $node ) {
1430 public function __toString() {
1434 public function getPDBK( $level = false ) {
1435 if ( $level === false ) {
1436 return $this->title
->getPrefixedDBkey();
1438 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1445 public function getArguments() {
1452 public function getNumberedArguments() {
1459 public function getNamedArguments() {
1464 * Returns true if there are no arguments in this frame
1468 public function isEmpty() {
1472 public function getArgument( $name ) {
1477 * Returns true if the infinite loop check is OK, false if a loop is detected
1479 * @param Title $title
1482 public function loopCheck( $title ) {
1483 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1487 * Return true if the frame is a template frame
1491 public function isTemplate() {
1496 * Get a title of frame
1500 public function getTitle() {
1501 return $this->title
;
1505 * Set the volatile flag
1509 public function setVolatile( $flag = true ) {
1510 $this->volatile
= $flag;
1514 * Get the volatile flag
1518 public function isVolatile() {
1519 return $this->volatile
;
1527 public function setTTL( $ttl ) {
1528 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1538 public function getTTL() {
1544 * Expansion frame with template arguments
1546 * @codingStandardsIgnoreStart
1548 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1549 // @codingStandardsIgnoreEnd
1551 public $numberedArgs, $namedArgs;
1557 public $numberedExpansionCache, $namedExpansionCache;
1560 * @param Preprocessor $preprocessor
1561 * @param bool|PPFrame_DOM $parent
1562 * @param array $numberedArgs
1563 * @param array $namedArgs
1564 * @param bool|Title $title
1566 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1567 $namedArgs = array(), $title = false
1569 parent
::__construct( $preprocessor );
1571 $this->parent
= $parent;
1572 $this->numberedArgs
= $numberedArgs;
1573 $this->namedArgs
= $namedArgs;
1574 $this->title
= $title;
1575 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1576 $this->titleCache
= $parent->titleCache
;
1577 $this->titleCache
[] = $pdbk;
1578 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1579 if ( $pdbk !== false ) {
1580 $this->loopCheckHash
[$pdbk] = true;
1582 $this->depth
= $parent->depth +
1;
1583 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1586 public function __toString() {
1589 $args = $this->numberedArgs +
$this->namedArgs
;
1590 foreach ( $args as $name => $value ) {
1596 $s .= "\"$name\":\"" .
1597 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1604 * @throws MWException
1605 * @param string|int $key
1606 * @param string|PPNode_DOM|DOMDocument $root
1610 public function cachedExpand( $key, $root, $flags = 0 ) {
1611 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1612 return $this->parent
->childExpansionCache
[$key];
1614 $retval = $this->expand( $root, $flags );
1615 if ( !$this->isVolatile() ) {
1616 $this->parent
->childExpansionCache
[$key] = $retval;
1622 * Returns true if there are no arguments in this frame
1626 public function isEmpty() {
1627 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1630 public function getArguments() {
1631 $arguments = array();
1632 foreach ( array_merge(
1633 array_keys( $this->numberedArgs
),
1634 array_keys( $this->namedArgs
) ) as $key ) {
1635 $arguments[$key] = $this->getArgument( $key );
1640 public function getNumberedArguments() {
1641 $arguments = array();
1642 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1643 $arguments[$key] = $this->getArgument( $key );
1648 public function getNamedArguments() {
1649 $arguments = array();
1650 foreach ( array_keys( $this->namedArgs
) as $key ) {
1651 $arguments[$key] = $this->getArgument( $key );
1656 public function getNumberedArgument( $index ) {
1657 if ( !isset( $this->numberedArgs
[$index] ) ) {
1660 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1661 # No trimming for unnamed arguments
1662 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1663 $this->numberedArgs
[$index],
1664 PPFrame
::STRIP_COMMENTS
1667 return $this->numberedExpansionCache
[$index];
1670 public function getNamedArgument( $name ) {
1671 if ( !isset( $this->namedArgs
[$name] ) ) {
1674 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1675 # Trim named arguments post-expand, for backwards compatibility
1676 $this->namedExpansionCache
[$name] = trim(
1677 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1679 return $this->namedExpansionCache
[$name];
1682 public function getArgument( $name ) {
1683 $text = $this->getNumberedArgument( $name );
1684 if ( $text === false ) {
1685 $text = $this->getNamedArgument( $name );
1691 * Return true if the frame is a template frame
1695 public function isTemplate() {
1699 public function setVolatile( $flag = true ) {
1700 parent
::setVolatile( $flag );
1701 $this->parent
->setVolatile( $flag );
1704 public function setTTL( $ttl ) {
1705 parent
::setTTL( $ttl );
1706 $this->parent
->setTTL( $ttl );
1711 * Expansion frame with custom arguments
1713 * @codingStandardsIgnoreStart
1715 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1716 // @codingStandardsIgnoreEnd
1720 public function __construct( $preprocessor, $args ) {
1721 parent
::__construct( $preprocessor );
1722 $this->args
= $args;
1725 public function __toString() {
1728 foreach ( $this->args
as $name => $value ) {
1734 $s .= "\"$name\":\"" .
1735 str_replace( '"', '\\"', $value->__toString() ) . '"';
1744 public function isEmpty() {
1745 return !count( $this->args
);
1748 public function getArgument( $index ) {
1749 if ( !isset( $this->args
[$index] ) ) {
1752 return $this->args
[$index];
1755 public function getArguments() {
1762 * @codingStandardsIgnoreStart
1764 class PPNode_DOM
implements PPNode
{
1765 // @codingStandardsIgnoreEnd
1773 public function __construct( $node, $xpath = false ) {
1774 $this->node
= $node;
1780 public function getXPath() {
1781 if ( $this->xpath
=== null ) {
1782 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1784 return $this->xpath
;
1787 public function __toString() {
1788 if ( $this->node
instanceof DOMNodeList
) {
1790 foreach ( $this->node
as $node ) {
1791 $s .= $node->ownerDocument
->saveXML( $node );
1794 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1800 * @return bool|PPNode_DOM
1802 public function getChildren() {
1803 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1807 * @return bool|PPNode_DOM
1809 public function getFirstChild() {
1810 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1814 * @return bool|PPNode_DOM
1816 public function getNextSibling() {
1817 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1821 * @param string $type
1823 * @return bool|PPNode_DOM
1825 public function getChildrenOfType( $type ) {
1826 return new self( $this->getXPath()->query( $type, $this->node
) );
1832 public function getLength() {
1833 if ( $this->node
instanceof DOMNodeList
) {
1834 return $this->node
->length
;
1842 * @return bool|PPNode_DOM
1844 public function item( $i ) {
1845 $item = $this->node
->item( $i );
1846 return $item ?
new self( $item ) : false;
1852 public function getName() {
1853 if ( $this->node
instanceof DOMNodeList
) {
1856 return $this->node
->nodeName
;
1861 * Split a "<part>" node into an associative array containing:
1862 * - name PPNode name
1863 * - index String index
1864 * - value PPNode value
1866 * @throws MWException
1869 public function splitArg() {
1870 $xpath = $this->getXPath();
1871 $names = $xpath->query( 'name', $this->node
);
1872 $values = $xpath->query( 'value', $this->node
);
1873 if ( !$names->length ||
!$values->length
) {
1874 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1876 $name = $names->item( 0 );
1877 $index = $name->getAttribute( 'index' );
1879 'name' => new self( $name ),
1881 'value' => new self( $values->item( 0 ) ) );
1885 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1886 * All values in the resulting array are PPNodes. Inner and close are optional.
1888 * @throws MWException
1891 public function splitExt() {
1892 $xpath = $this->getXPath();
1893 $names = $xpath->query( 'name', $this->node
);
1894 $attrs = $xpath->query( 'attr', $this->node
);
1895 $inners = $xpath->query( 'inner', $this->node
);
1896 $closes = $xpath->query( 'close', $this->node
);
1897 if ( !$names->length ||
!$attrs->length
) {
1898 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1901 'name' => new self( $names->item( 0 ) ),
1902 'attr' => new self( $attrs->item( 0 ) ) );
1903 if ( $inners->length
) {
1904 $parts['inner'] = new self( $inners->item( 0 ) );
1906 if ( $closes->length
) {
1907 $parts['close'] = new self( $closes->item( 0 ) );
1913 * Split a "<h>" node
1914 * @throws MWException
1917 public function splitHeading() {
1918 if ( $this->getName() !== 'h' ) {
1919 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1922 'i' => $this->node
->getAttribute( 'i' ),
1923 'level' => $this->node
->getAttribute( 'level' ),
1924 'contents' => $this->getChildren()