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();
90 MediaWiki\
suppressWarnings();
91 $result = $dom->loadXML( $xml );
92 MediaWiki\restoreWarnings
();
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal\Validator
::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 );
157 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
158 $cacheValue = $wgMemc->get( $cacheKey );
160 $version = substr( $cacheValue, 0, 8 );
161 if ( intval( $version ) == self
::CACHE_VERSION
) {
162 $xml = substr( $cacheValue, 8 );
164 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
167 if ( $xml === false ) {
168 $xml = $this->preprocessToXml( $text, $flags );
169 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
170 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
171 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
174 $xml = $this->preprocessToXml( $text, $flags );
177 // Fail if the number of elements exceeds acceptable limits
178 // Do not attempt to generate the DOM
179 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
180 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
181 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
184 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
187 $dom = new DOMDocument
;
188 MediaWiki\
suppressWarnings();
189 $result = $dom->loadXML( $xml );
190 MediaWiki\restoreWarnings
();
192 // Try running the XML through UtfNormal to get rid of invalid characters
193 $xml = UtfNormal\Validator
::cleanUp( $xml );
194 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
195 // don't barf when the XML is >256 levels deep.
196 $result = $dom->loadXML( $xml, 1 << 19 );
199 $obj = new PPNode_DOM( $dom->documentElement
);
206 throw new MWException( __METHOD__
. ' generated invalid XML' );
212 * @param string $text
216 public function preprocessToXml( $text, $flags = 0 ) {
229 'names' => array( 2 => null ),
235 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
237 $xmlishElements = $this->parser
->getStripList();
238 $enableOnlyinclude = false;
239 if ( $forInclusion ) {
240 $ignoredTags = array( 'includeonly', '/includeonly' );
241 $ignoredElements = array( 'noinclude' );
242 $xmlishElements[] = 'noinclude';
243 if ( strpos( $text, '<onlyinclude>' ) !== false
244 && strpos( $text, '</onlyinclude>' ) !== false
246 $enableOnlyinclude = true;
249 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
250 $ignoredElements = array( 'includeonly' );
251 $xmlishElements[] = 'includeonly';
253 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
255 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
256 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
258 $stack = new PPDStack
;
260 $searchBase = "[{<\n"; #}
261 // For fast reverse searches
262 $revText = strrev( $text );
263 $lengthText = strlen( $text );
265 // Input pointer, starts out pointing to a pseudo-newline before the start
267 // Current accumulator
268 $accum =& $stack->getAccum();
270 // True to find equals signs in arguments
272 // True to take notice of pipe characters
275 // True if $i is inside a possible heading
277 // True if there are no more greater-than (>) signs right of $i
279 // True to ignore all input up to the next <onlyinclude>
280 $findOnlyinclude = $enableOnlyinclude;
281 // Do a line-start run without outputting an LF character
282 $fakeLineStart = true;
287 if ( $findOnlyinclude ) {
288 // Ignore all input up to the next <onlyinclude>
289 $startPos = strpos( $text, '<onlyinclude>', $i );
290 if ( $startPos === false ) {
291 // Ignored section runs to the end
292 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
295 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
296 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
298 $findOnlyinclude = false;
301 if ( $fakeLineStart ) {
302 $found = 'line-start';
305 # Find next opening brace, closing brace or pipe
306 $search = $searchBase;
307 if ( $stack->top
=== false ) {
308 $currentClosing = '';
310 $currentClosing = $stack->top
->close
;
311 $search .= $currentClosing;
317 // First equals will be for the template
321 # Output literal section, advance input counter
322 $literalLength = strcspn( $text, $search, $i );
323 if ( $literalLength > 0 ) {
324 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
325 $i +
= $literalLength;
327 if ( $i >= $lengthText ) {
328 if ( $currentClosing == "\n" ) {
329 // Do a past-the-end run to finish off the heading
337 $curChar = $text[$i];
338 if ( $curChar == '|' ) {
340 } elseif ( $curChar == '=' ) {
342 } elseif ( $curChar == '<' ) {
344 } elseif ( $curChar == "\n" ) {
348 $found = 'line-start';
350 } elseif ( $curChar == $currentClosing ) {
352 } elseif ( isset( $rules[$curChar] ) ) {
354 $rule = $rules[$curChar];
356 # Some versions of PHP have a strcspn which stops on null characters
357 # Ignore and continue
364 if ( $found == 'angle' ) {
366 // Handle </onlyinclude>
367 if ( $enableOnlyinclude
368 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
370 $findOnlyinclude = true;
374 // Determine element name
375 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
376 // Element name missing or not listed
382 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
384 // To avoid leaving blank lines, when a sequence of
385 // space-separated comments is both preceded and followed by
386 // a newline (ignoring spaces), then
387 // trim leading and trailing spaces and the trailing newline.
390 $endPos = strpos( $text, '-->', $i +
4 );
391 if ( $endPos === false ) {
392 // Unclosed comment in input, runs to end
393 $inner = substr( $text, $i );
394 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
397 // Search backwards for leading whitespace
398 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
400 // Search forwards for trailing whitespace
401 // $wsEnd will be the position of the last space (or the '>' if there's none)
402 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
404 // Keep looking forward as long as we're finding more
406 $comments = array( array( $wsStart, $wsEnd ) );
407 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
408 $c = strpos( $text, '-->', $wsEnd +
4 );
409 if ( $c === false ) {
412 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
413 $comments[] = array( $wsEnd +
1, $c );
417 // Eat the line if possible
418 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
419 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
420 // it's a possible beneficial b/c break.
421 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
422 && substr( $text, $wsEnd +
1, 1 ) == "\n"
424 // Remove leading whitespace from the end of the accumulator
425 // Sanity check first though
426 $wsLength = $i - $wsStart;
428 && strspn( $accum, " \t", -$wsLength ) === $wsLength
430 $accum = substr( $accum, 0, -$wsLength );
433 // Dump all but the last comment to the accumulator
434 foreach ( $comments as $j => $com ) {
436 $endPos = $com[1] +
1;
437 if ( $j == ( count( $comments ) - 1 ) ) {
440 $inner = substr( $text, $startPos, $endPos - $startPos );
441 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
444 // Do a line-start run next time to look for headings after the comment
445 $fakeLineStart = true;
447 // No line to eat, just take the comment itself
453 $part = $stack->top
->getCurrentPart();
454 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
455 $part->visualEnd
= $wsStart;
457 // Else comments abutting, no change in visual end
458 $part->commentEnd
= $endPos;
461 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
462 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
467 $lowerName = strtolower( $name );
468 $attrStart = $i +
strlen( $name ) +
1;
471 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
472 if ( $tagEndPos === false ) {
473 // Infinite backtrack
474 // Disable tag search to prevent worst-case O(N^2) performance
481 // Handle ignored tags
482 if ( in_array( $lowerName, $ignoredTags ) ) {
484 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
491 if ( $text[$tagEndPos - 1] == '/' ) {
492 $attrEnd = $tagEndPos - 1;
497 $attrEnd = $tagEndPos;
499 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
500 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
502 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
503 $i = $matches[0][1] +
strlen( $matches[0][0] );
504 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
506 // No end tag -- let it run out to the end of the text.
507 $inner = substr( $text, $tagEndPos +
1 );
512 // <includeonly> and <noinclude> just become <ignore> tags
513 if ( in_array( $lowerName, $ignoredElements ) ) {
514 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
520 if ( $attrEnd <= $attrStart ) {
523 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
525 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
526 // Note that the attr element contains the whitespace between name and attribute,
527 // this is necessary for precise reconstruction during pre-save transform.
528 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
529 if ( $inner !== null ) {
530 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
532 $accum .= $close . '</ext>';
533 } elseif ( $found == 'line-start' ) {
534 // Is this the start of a heading?
535 // Line break belongs before the heading element in any case
536 if ( $fakeLineStart ) {
537 $fakeLineStart = false;
543 $count = strspn( $text, '=', $i, 6 );
544 if ( $count == 1 && $findEquals ) {
545 // DWIM: This looks kind of like a name/value separator.
546 // Let's let the equals handler have it and break the
547 // potential heading. This is heuristic, but AFAICT the
548 // methods for completely correct disambiguation are very
550 } elseif ( $count > 0 ) {
554 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
557 $stack->push( $piece );
558 $accum =& $stack->getAccum();
559 $flags = $stack->getFlags();
563 } elseif ( $found == 'line-end' ) {
564 $piece = $stack->top
;
565 // A heading must be open, otherwise \n wouldn't have been in the search list
566 assert( '$piece->open == "\n"' );
567 $part = $piece->getCurrentPart();
568 // Search back through the input to see if it has a proper close.
569 // Do this using the reversed string since the other solutions
570 // (end anchor, etc.) are inefficient.
571 $wsLength = strspn( $revText, " \t", $lengthText - $i );
572 $searchStart = $i - $wsLength;
573 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
574 // Comment found at line end
575 // Search for equals signs before the comment
576 $searchStart = $part->visualEnd
;
577 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
579 $count = $piece->count
;
580 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
581 if ( $equalsLength > 0 ) {
582 if ( $searchStart - $equalsLength == $piece->startPos
) {
583 // This is just a single string of equals signs on its own line
584 // Replicate the doHeadings behavior /={count}(.+)={count}/
585 // First find out how many equals signs there really are (don't stop at 6)
586 $count = $equalsLength;
590 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
593 $count = min( $equalsLength, $count );
596 // Normal match, output <h>
597 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
600 // Single equals sign on its own line, count=0
604 // No match, no <h>, just pass down the inner text
609 $accum =& $stack->getAccum();
610 $flags = $stack->getFlags();
613 // Append the result to the enclosing accumulator
615 // Note that we do NOT increment the input pointer.
616 // This is because the closing linebreak could be the opening linebreak of
617 // another heading. Infinite loops are avoided because the next iteration MUST
618 // hit the heading open case above, which unconditionally increments the
620 } elseif ( $found == 'open' ) {
621 # count opening brace characters
622 $count = strspn( $text, $curChar, $i );
624 # we need to add to stack only if opening brace count is enough for one of the rules
625 if ( $count >= $rule['min'] ) {
626 # Add it to the stack
629 'close' => $rule['end'],
631 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
634 $stack->push( $piece );
635 $accum =& $stack->getAccum();
636 $flags = $stack->getFlags();
639 # Add literal brace(s)
640 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
643 } elseif ( $found == 'close' ) {
644 $piece = $stack->top
;
645 # lets check if there are enough characters for closing brace
646 $maxCount = $piece->count
;
647 $count = strspn( $text, $curChar, $i, $maxCount );
649 # check for maximum matching characters (if there are 5 closing
650 # characters, we will probably need only 3 - depending on the rules)
651 $rule = $rules[$piece->open
];
652 if ( $count > $rule['max'] ) {
653 # The specified maximum exists in the callback array, unless the caller
655 $matchingCount = $rule['max'];
657 # Count is less than the maximum
658 # Skip any gaps in the callback array to find the true largest match
659 # Need to use array_key_exists not isset because the callback can be null
660 $matchingCount = $count;
661 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
666 if ( $matchingCount <= 0 ) {
667 # No matching element found in callback array
668 # Output a literal closing brace and continue
669 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
673 $name = $rule['names'][$matchingCount];
674 if ( $name === null ) {
675 // No element, just literal text
676 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
679 # Note: $parts is already XML, does not need to be encoded further
680 $parts = $piece->parts
;
681 $title = $parts[0]->out
;
684 # The invocation is at the start of the line if lineStart is set in
685 # the stack, and all opening brackets are used up.
686 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
687 $attr = ' lineStart="1"';
692 $element = "<$name$attr>";
693 $element .= "<title>$title</title>";
695 foreach ( $parts as $part ) {
696 if ( isset( $part->eqpos
) ) {
697 $argName = substr( $part->out
, 0, $part->eqpos
);
698 $argValue = substr( $part->out
, $part->eqpos +
1 );
699 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
701 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
705 $element .= "</$name>";
708 # Advance input pointer
709 $i +
= $matchingCount;
713 $accum =& $stack->getAccum();
715 # Re-add the old stack element if it still has unmatched opening characters remaining
716 if ( $matchingCount < $piece->count
) {
717 $piece->parts
= array( new PPDPart
);
718 $piece->count
-= $matchingCount;
719 # do we still qualify for any callback with remaining count?
720 $min = $rules[$piece->open
]['min'];
721 if ( $piece->count
>= $min ) {
722 $stack->push( $piece );
723 $accum =& $stack->getAccum();
725 $accum .= str_repeat( $piece->open
, $piece->count
);
728 $flags = $stack->getFlags();
731 # Add XML element to the enclosing accumulator
733 } elseif ( $found == 'pipe' ) {
734 $findEquals = true; // shortcut for getFlags()
736 $accum =& $stack->getAccum();
738 } elseif ( $found == 'equals' ) {
739 $findEquals = false; // shortcut for getFlags()
740 $stack->getCurrentPart()->eqpos
= strlen( $accum );
746 # Output any remaining unclosed brackets
747 foreach ( $stack->stack
as $piece ) {
748 $stack->rootAccum
.= $piece->breakSyntax();
750 $stack->rootAccum
.= '</root>';
751 $xml = $stack->rootAccum
;
758 * Stack class to help Preprocessor::preprocessToObj()
762 public $stack, $rootAccum;
769 public $elementClass = 'PPDStackElement';
771 public static $false = false;
773 public function __construct() {
774 $this->stack
= array();
776 $this->rootAccum
= '';
777 $this->accum
=& $this->rootAccum
;
783 public function count() {
784 return count( $this->stack
);
787 public function &getAccum() {
791 public function getCurrentPart() {
792 if ( $this->top
=== false ) {
795 return $this->top
->getCurrentPart();
799 public function push( $data ) {
800 if ( $data instanceof $this->elementClass
) {
801 $this->stack
[] = $data;
803 $class = $this->elementClass
;
804 $this->stack
[] = new $class( $data );
806 $this->top
= $this->stack
[count( $this->stack
) - 1];
807 $this->accum
=& $this->top
->getAccum();
810 public function pop() {
811 if ( !count( $this->stack
) ) {
812 throw new MWException( __METHOD__
. ': no elements remaining' );
814 $temp = array_pop( $this->stack
);
816 if ( count( $this->stack
) ) {
817 $this->top
= $this->stack
[count( $this->stack
) - 1];
818 $this->accum
=& $this->top
->getAccum();
820 $this->top
= self
::$false;
821 $this->accum
=& $this->rootAccum
;
826 public function addPart( $s = '' ) {
827 $this->top
->addPart( $s );
828 $this->accum
=& $this->top
->getAccum();
834 public function getFlags() {
835 if ( !count( $this->stack
) ) {
837 'findEquals' => false,
839 'inHeading' => false,
842 return $this->top
->getFlags();
850 class PPDStackElement
{
851 public $open, // Opening character (\n for heading)
852 $close, // Matching closing character
853 $count, // Number of opening characters found (number of "=" for heading)
854 $parts, // Array of PPDPart objects describing pipe-separated parts.
855 $lineStart; // True if the open char appeared at the start of the input line.
856 // 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
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1033 wfEscapeWikiText( $this->title
),
1034 wfEscapeWikiText( $title ),
1035 wfEscapeWikiText( $index ) )->text() );
1036 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1038 $numberedArgs[$index] = $value->item( 0 );
1039 unset( $namedArgs[$index] );
1042 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1043 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1044 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1045 wfEscapeWikiText( $this->title
),
1046 wfEscapeWikiText( $title ),
1047 wfEscapeWikiText( $name ) )->text() );
1048 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1050 $namedArgs[$name] = $value->item( 0 );
1051 unset( $numberedArgs[$name] );
1055 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1059 * @throws MWException
1060 * @param string|int $key
1061 * @param string|PPNode_DOM|DOMDocument $root
1065 public function cachedExpand( $key, $root, $flags = 0 ) {
1066 // we don't have a parent, so we don't have a cache
1067 return $this->expand( $root, $flags );
1071 * @throws MWException
1072 * @param string|PPNode_DOM|DOMDocument $root
1076 public function expand( $root, $flags = 0 ) {
1077 static $expansionDepth = 0;
1078 if ( is_string( $root ) ) {
1082 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1083 $this->parser
->limitationWarn( 'node-count-exceeded',
1084 $this->parser
->mPPNodeCount
,
1085 $this->parser
->mOptions
->getMaxPPNodeCount()
1087 return '<span class="error">Node-count limit exceeded</span>';
1090 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1091 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1093 $this->parser
->mOptions
->getMaxPPExpandDepth()
1095 return '<span class="error">Expansion depth limit exceeded</span>';
1098 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1099 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1102 if ( $root instanceof PPNode_DOM
) {
1103 $root = $root->node
;
1105 if ( $root instanceof DOMDocument
) {
1106 $root = $root->documentElement
;
1109 $outStack = array( '', '' );
1110 $iteratorStack = array( false, $root );
1111 $indexStack = array( 0, 0 );
1113 while ( count( $iteratorStack ) > 1 ) {
1114 $level = count( $outStack ) - 1;
1115 $iteratorNode =& $iteratorStack[$level];
1116 $out =& $outStack[$level];
1117 $index =& $indexStack[$level];
1119 if ( $iteratorNode instanceof PPNode_DOM
) {
1120 $iteratorNode = $iteratorNode->node
;
1123 if ( is_array( $iteratorNode ) ) {
1124 if ( $index >= count( $iteratorNode ) ) {
1125 // All done with this iterator
1126 $iteratorStack[$level] = false;
1127 $contextNode = false;
1129 $contextNode = $iteratorNode[$index];
1132 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1133 if ( $index >= $iteratorNode->length
) {
1134 // All done with this iterator
1135 $iteratorStack[$level] = false;
1136 $contextNode = false;
1138 $contextNode = $iteratorNode->item( $index );
1142 // Copy to $contextNode and then delete from iterator stack,
1143 // because this is not an iterator but we do have to execute it once
1144 $contextNode = $iteratorStack[$level];
1145 $iteratorStack[$level] = false;
1148 if ( $contextNode instanceof PPNode_DOM
) {
1149 $contextNode = $contextNode->node
;
1152 $newIterator = false;
1154 if ( $contextNode === false ) {
1156 } elseif ( is_string( $contextNode ) ) {
1157 $out .= $contextNode;
1158 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1159 $newIterator = $contextNode;
1160 } elseif ( $contextNode instanceof DOMNode
) {
1161 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1162 $out .= $contextNode->nodeValue
;
1163 } elseif ( $contextNode->nodeName
== 'template' ) {
1164 # Double-brace expansion
1165 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1166 $titles = $xpath->query( 'title', $contextNode );
1167 $title = $titles->item( 0 );
1168 $parts = $xpath->query( 'part', $contextNode );
1169 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1170 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1172 $lineStart = $contextNode->getAttribute( 'lineStart' );
1174 'title' => new PPNode_DOM( $title ),
1175 'parts' => new PPNode_DOM( $parts ),
1176 'lineStart' => $lineStart );
1177 $ret = $this->parser
->braceSubstitution( $params, $this );
1178 if ( isset( $ret['object'] ) ) {
1179 $newIterator = $ret['object'];
1181 $out .= $ret['text'];
1184 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1185 # Triple-brace expansion
1186 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1187 $titles = $xpath->query( 'title', $contextNode );
1188 $title = $titles->item( 0 );
1189 $parts = $xpath->query( 'part', $contextNode );
1190 if ( $flags & PPFrame
::NO_ARGS
) {
1191 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1194 'title' => new PPNode_DOM( $title ),
1195 'parts' => new PPNode_DOM( $parts ) );
1196 $ret = $this->parser
->argSubstitution( $params, $this );
1197 if ( isset( $ret['object'] ) ) {
1198 $newIterator = $ret['object'];
1200 $out .= $ret['text'];
1203 } elseif ( $contextNode->nodeName
== 'comment' ) {
1204 # HTML-style comment
1205 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1206 if ( $this->parser
->ot
['html']
1207 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1208 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1211 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1212 # Add a strip marker in PST mode so that pstPass2() can
1213 # run some old-fashioned regexes on the result.
1214 # Not in RECOVER_COMMENTS mode (extractSections) though.
1215 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1217 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1218 $out .= $contextNode->textContent
;
1220 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1221 # Output suppression used by <includeonly> etc.
1222 # OT_WIKI will only respect <ignore> in substed templates.
1223 # The other output types respect it unless NO_IGNORE is set.
1224 # extractSections() sets NO_IGNORE and so never respects it.
1225 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1226 ||
( $flags & PPFrame
::NO_IGNORE
)
1228 $out .= $contextNode->textContent
;
1232 } elseif ( $contextNode->nodeName
== 'ext' ) {
1234 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1235 $names = $xpath->query( 'name', $contextNode );
1236 $attrs = $xpath->query( 'attr', $contextNode );
1237 $inners = $xpath->query( 'inner', $contextNode );
1238 $closes = $xpath->query( 'close', $contextNode );
1239 if ( $flags & PPFrame
::NO_TAGS
) {
1240 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1241 if ( $attrs->length
> 0 ) {
1242 $s .= $this->expand( $attrs->item( 0 ), $flags );
1244 if ( $inners->length
> 0 ) {
1245 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1246 if ( $closes->length
> 0 ) {
1247 $s .= $this->expand( $closes->item( 0 ), $flags );
1255 'name' => new PPNode_DOM( $names->item( 0 ) ),
1256 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1257 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1258 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1260 $out .= $this->parser
->extensionSubstitution( $params, $this );
1262 } elseif ( $contextNode->nodeName
== 'h' ) {
1264 $s = $this->expand( $contextNode->childNodes
, $flags );
1266 # Insert a heading marker only for <h> children of <root>
1267 # This is to stop extractSections from going over multiple tree levels
1268 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1269 # Insert heading index marker
1270 $headingIndex = $contextNode->getAttribute( 'i' );
1271 $titleText = $this->title
->getPrefixedDBkey();
1272 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1273 $serial = count( $this->parser
->mHeadings
) - 1;
1274 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1275 $count = $contextNode->getAttribute( 'level' );
1276 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1277 $this->parser
->mStripState
->addGeneral( $marker, '' );
1281 # Generic recursive expansion
1282 $newIterator = $contextNode->childNodes
;
1285 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1288 if ( $newIterator !== false ) {
1289 if ( $newIterator instanceof PPNode_DOM
) {
1290 $newIterator = $newIterator->node
;
1293 $iteratorStack[] = $newIterator;
1295 } elseif ( $iteratorStack[$level] === false ) {
1296 // Return accumulated value to parent
1297 // With tail recursion
1298 while ( $iteratorStack[$level] === false && $level > 0 ) {
1299 $outStack[$level - 1] .= $out;
1300 array_pop( $outStack );
1301 array_pop( $iteratorStack );
1302 array_pop( $indexStack );
1308 return $outStack[0];
1312 * @param string $sep
1314 * @param string|PPNode_DOM|DOMDocument $args,...
1317 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1318 $args = array_slice( func_get_args(), 2 );
1322 foreach ( $args as $root ) {
1323 if ( $root instanceof PPNode_DOM
) {
1324 $root = $root->node
;
1326 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1327 $root = array( $root );
1329 foreach ( $root as $node ) {
1335 $s .= $this->expand( $node, $flags );
1342 * Implode with no flags specified
1343 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1345 * @param string $sep
1346 * @param string|PPNode_DOM|DOMDocument $args,...
1349 public function implode( $sep /*, ... */ ) {
1350 $args = array_slice( func_get_args(), 1 );
1354 foreach ( $args as $root ) {
1355 if ( $root instanceof PPNode_DOM
) {
1356 $root = $root->node
;
1358 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1359 $root = array( $root );
1361 foreach ( $root as $node ) {
1367 $s .= $this->expand( $node );
1374 * Makes an object that, when expand()ed, will be the same as one obtained
1377 * @param string $sep
1378 * @param string|PPNode_DOM|DOMDocument $args,...
1381 public function virtualImplode( $sep /*, ... */ ) {
1382 $args = array_slice( func_get_args(), 1 );
1386 foreach ( $args as $root ) {
1387 if ( $root instanceof PPNode_DOM
) {
1388 $root = $root->node
;
1390 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1391 $root = array( $root );
1393 foreach ( $root as $node ) {
1406 * Virtual implode with brackets
1407 * @param string $start
1408 * @param string $sep
1409 * @param string $end
1410 * @param string|PPNode_DOM|DOMDocument $args,...
1413 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1414 $args = array_slice( func_get_args(), 3 );
1415 $out = array( $start );
1418 foreach ( $args as $root ) {
1419 if ( $root instanceof PPNode_DOM
) {
1420 $root = $root->node
;
1422 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1423 $root = array( $root );
1425 foreach ( $root as $node ) {
1438 public function __toString() {
1442 public function getPDBK( $level = false ) {
1443 if ( $level === false ) {
1444 return $this->title
->getPrefixedDBkey();
1446 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1453 public function getArguments() {
1460 public function getNumberedArguments() {
1467 public function getNamedArguments() {
1472 * Returns true if there are no arguments in this frame
1476 public function isEmpty() {
1480 public function getArgument( $name ) {
1485 * Returns true if the infinite loop check is OK, false if a loop is detected
1487 * @param Title $title
1490 public function loopCheck( $title ) {
1491 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1495 * Return true if the frame is a template frame
1499 public function isTemplate() {
1504 * Get a title of frame
1508 public function getTitle() {
1509 return $this->title
;
1513 * Set the volatile flag
1517 public function setVolatile( $flag = true ) {
1518 $this->volatile
= $flag;
1522 * Get the volatile flag
1526 public function isVolatile() {
1527 return $this->volatile
;
1535 public function setTTL( $ttl ) {
1536 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1546 public function getTTL() {
1552 * Expansion frame with template arguments
1554 * @codingStandardsIgnoreStart
1556 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1557 // @codingStandardsIgnoreEnd
1559 public $numberedArgs, $namedArgs;
1565 public $numberedExpansionCache, $namedExpansionCache;
1568 * @param Preprocessor $preprocessor
1569 * @param bool|PPFrame_DOM $parent
1570 * @param array $numberedArgs
1571 * @param array $namedArgs
1572 * @param bool|Title $title
1574 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1575 $namedArgs = array(), $title = false
1577 parent
::__construct( $preprocessor );
1579 $this->parent
= $parent;
1580 $this->numberedArgs
= $numberedArgs;
1581 $this->namedArgs
= $namedArgs;
1582 $this->title
= $title;
1583 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1584 $this->titleCache
= $parent->titleCache
;
1585 $this->titleCache
[] = $pdbk;
1586 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1587 if ( $pdbk !== false ) {
1588 $this->loopCheckHash
[$pdbk] = true;
1590 $this->depth
= $parent->depth +
1;
1591 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1594 public function __toString() {
1597 $args = $this->numberedArgs +
$this->namedArgs
;
1598 foreach ( $args as $name => $value ) {
1604 $s .= "\"$name\":\"" .
1605 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1612 * @throws MWException
1613 * @param string|int $key
1614 * @param string|PPNode_DOM|DOMDocument $root
1618 public function cachedExpand( $key, $root, $flags = 0 ) {
1619 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1620 return $this->parent
->childExpansionCache
[$key];
1622 $retval = $this->expand( $root, $flags );
1623 if ( !$this->isVolatile() ) {
1624 $this->parent
->childExpansionCache
[$key] = $retval;
1630 * Returns true if there are no arguments in this frame
1634 public function isEmpty() {
1635 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1638 public function getArguments() {
1639 $arguments = array();
1640 foreach ( array_merge(
1641 array_keys( $this->numberedArgs
),
1642 array_keys( $this->namedArgs
) ) as $key ) {
1643 $arguments[$key] = $this->getArgument( $key );
1648 public function getNumberedArguments() {
1649 $arguments = array();
1650 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1651 $arguments[$key] = $this->getArgument( $key );
1656 public function getNamedArguments() {
1657 $arguments = array();
1658 foreach ( array_keys( $this->namedArgs
) as $key ) {
1659 $arguments[$key] = $this->getArgument( $key );
1664 public function getNumberedArgument( $index ) {
1665 if ( !isset( $this->numberedArgs
[$index] ) ) {
1668 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1669 # No trimming for unnamed arguments
1670 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1671 $this->numberedArgs
[$index],
1672 PPFrame
::STRIP_COMMENTS
1675 return $this->numberedExpansionCache
[$index];
1678 public function getNamedArgument( $name ) {
1679 if ( !isset( $this->namedArgs
[$name] ) ) {
1682 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1683 # Trim named arguments post-expand, for backwards compatibility
1684 $this->namedExpansionCache
[$name] = trim(
1685 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1687 return $this->namedExpansionCache
[$name];
1690 public function getArgument( $name ) {
1691 $text = $this->getNumberedArgument( $name );
1692 if ( $text === false ) {
1693 $text = $this->getNamedArgument( $name );
1699 * Return true if the frame is a template frame
1703 public function isTemplate() {
1707 public function setVolatile( $flag = true ) {
1708 parent
::setVolatile( $flag );
1709 $this->parent
->setVolatile( $flag );
1712 public function setTTL( $ttl ) {
1713 parent
::setTTL( $ttl );
1714 $this->parent
->setTTL( $ttl );
1719 * Expansion frame with custom arguments
1721 * @codingStandardsIgnoreStart
1723 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1724 // @codingStandardsIgnoreEnd
1728 public function __construct( $preprocessor, $args ) {
1729 parent
::__construct( $preprocessor );
1730 $this->args
= $args;
1733 public function __toString() {
1736 foreach ( $this->args
as $name => $value ) {
1742 $s .= "\"$name\":\"" .
1743 str_replace( '"', '\\"', $value->__toString() ) . '"';
1752 public function isEmpty() {
1753 return !count( $this->args
);
1756 public function getArgument( $index ) {
1757 if ( !isset( $this->args
[$index] ) ) {
1760 return $this->args
[$index];
1763 public function getArguments() {
1770 * @codingStandardsIgnoreStart
1772 class PPNode_DOM
implements PPNode
{
1773 // @codingStandardsIgnoreEnd
1781 public function __construct( $node, $xpath = false ) {
1782 $this->node
= $node;
1788 public function getXPath() {
1789 if ( $this->xpath
=== null ) {
1790 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1792 return $this->xpath
;
1795 public function __toString() {
1796 if ( $this->node
instanceof DOMNodeList
) {
1798 foreach ( $this->node
as $node ) {
1799 $s .= $node->ownerDocument
->saveXML( $node );
1802 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1808 * @return bool|PPNode_DOM
1810 public function getChildren() {
1811 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1815 * @return bool|PPNode_DOM
1817 public function getFirstChild() {
1818 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1822 * @return bool|PPNode_DOM
1824 public function getNextSibling() {
1825 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1829 * @param string $type
1831 * @return bool|PPNode_DOM
1833 public function getChildrenOfType( $type ) {
1834 return new self( $this->getXPath()->query( $type, $this->node
) );
1840 public function getLength() {
1841 if ( $this->node
instanceof DOMNodeList
) {
1842 return $this->node
->length
;
1850 * @return bool|PPNode_DOM
1852 public function item( $i ) {
1853 $item = $this->node
->item( $i );
1854 return $item ?
new self( $item ) : false;
1860 public function getName() {
1861 if ( $this->node
instanceof DOMNodeList
) {
1864 return $this->node
->nodeName
;
1869 * Split a "<part>" node into an associative array containing:
1870 * - name PPNode name
1871 * - index String index
1872 * - value PPNode value
1874 * @throws MWException
1877 public function splitArg() {
1878 $xpath = $this->getXPath();
1879 $names = $xpath->query( 'name', $this->node
);
1880 $values = $xpath->query( 'value', $this->node
);
1881 if ( !$names->length ||
!$values->length
) {
1882 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1884 $name = $names->item( 0 );
1885 $index = $name->getAttribute( 'index' );
1887 'name' => new self( $name ),
1889 'value' => new self( $values->item( 0 ) ) );
1893 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1894 * All values in the resulting array are PPNodes. Inner and close are optional.
1896 * @throws MWException
1899 public function splitExt() {
1900 $xpath = $this->getXPath();
1901 $names = $xpath->query( 'name', $this->node
);
1902 $attrs = $xpath->query( 'attr', $this->node
);
1903 $inners = $xpath->query( 'inner', $this->node
);
1904 $closes = $xpath->query( 'close', $this->node
);
1905 if ( !$names->length ||
!$attrs->length
) {
1906 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1909 'name' => new self( $names->item( 0 ) ),
1910 'attr' => new self( $attrs->item( 0 ) ) );
1911 if ( $inners->length
) {
1912 $parts['inner'] = new self( $inners->item( 0 ) );
1914 if ( $closes->length
) {
1915 $parts['close'] = new self( $closes->item( 0 ) );
1921 * Split a "<h>" node
1922 * @throws MWException
1925 public function splitHeading() {
1926 if ( $this->getName() !== 'h' ) {
1927 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1930 'i' => $this->node
->getAttribute( 'i' ),
1931 'level' => $this->node
->getAttribute( 'level' ),
1932 'contents' => $this->getChildren()