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
27 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
28 class Preprocessor_DOM
extends Preprocessor
{
29 // @codingStandardsIgnoreEnd
38 const CACHE_PREFIX
= 'preprocess-xml';
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 ) {
152 $xml = $this->cacheGetTree( $text, $flags );
153 if ( $xml === false ) {
154 $xml = $this->preprocessToXml( $text, $flags );
155 $this->cacheSetTree( $text, $flags, $xml );
158 // Fail if the number of elements exceeds acceptable limits
159 // Do not attempt to generate the DOM
160 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
161 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
162 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
163 // if ( $cacheable ) { ... }
164 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
167 $dom = new DOMDocument
;
168 MediaWiki\
suppressWarnings();
169 $result = $dom->loadXML( $xml );
170 MediaWiki\restoreWarnings
();
172 // Try running the XML through UtfNormal to get rid of invalid characters
173 $xml = UtfNormal\Validator
::cleanUp( $xml );
174 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
175 // don't barf when the XML is >256 levels deep.
176 $result = $dom->loadXML( $xml, 1 << 19 );
179 $obj = new PPNode_DOM( $dom->documentElement
);
182 // if ( $cacheable ) { ... }
185 throw new MWException( __METHOD__
. ' generated invalid XML' );
191 * @param string $text
195 public function preprocessToXml( $text, $flags = 0 ) {
196 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
198 $xmlishElements = $this->parser
->getStripList();
199 $enableOnlyinclude = false;
200 if ( $forInclusion ) {
201 $ignoredTags = array( 'includeonly', '/includeonly' );
202 $ignoredElements = array( 'noinclude' );
203 $xmlishElements[] = 'noinclude';
204 if ( strpos( $text, '<onlyinclude>' ) !== false
205 && strpos( $text, '</onlyinclude>' ) !== false
207 $enableOnlyinclude = true;
210 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
211 $ignoredElements = array( 'includeonly' );
212 $xmlishElements[] = 'includeonly';
214 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
216 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
217 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
219 $stack = new PPDStack
;
221 $searchBase = "[{<\n"; # }
222 // For fast reverse searches
223 $revText = strrev( $text );
224 $lengthText = strlen( $text );
226 // Input pointer, starts out pointing to a pseudo-newline before the start
228 // Current accumulator
229 $accum =& $stack->getAccum();
231 // True to find equals signs in arguments
233 // True to take notice of pipe characters
236 // True if $i is inside a possible heading
238 // True if there are no more greater-than (>) signs right of $i
240 // Map of tag name => true if there are no more closing tags of given type right of $i
241 $noMoreClosingTag = array();
242 // True to ignore all input up to the next <onlyinclude>
243 $findOnlyinclude = $enableOnlyinclude;
244 // Do a line-start run without outputting an LF character
245 $fakeLineStart = true;
248 // $this->memCheck();
250 if ( $findOnlyinclude ) {
251 // Ignore all input up to the next <onlyinclude>
252 $startPos = strpos( $text, '<onlyinclude>', $i );
253 if ( $startPos === false ) {
254 // Ignored section runs to the end
255 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
258 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
259 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
261 $findOnlyinclude = false;
264 if ( $fakeLineStart ) {
265 $found = 'line-start';
268 # Find next opening brace, closing brace or pipe
269 $search = $searchBase;
270 if ( $stack->top
=== false ) {
271 $currentClosing = '';
273 $currentClosing = $stack->top
->close
;
274 $search .= $currentClosing;
280 // First equals will be for the template
284 # Output literal section, advance input counter
285 $literalLength = strcspn( $text, $search, $i );
286 if ( $literalLength > 0 ) {
287 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
288 $i +
= $literalLength;
290 if ( $i >= $lengthText ) {
291 if ( $currentClosing == "\n" ) {
292 // Do a past-the-end run to finish off the heading
300 $curChar = $text[$i];
301 if ( $curChar == '|' ) {
303 } elseif ( $curChar == '=' ) {
305 } elseif ( $curChar == '<' ) {
307 } elseif ( $curChar == "\n" ) {
311 $found = 'line-start';
313 } elseif ( $curChar == $currentClosing ) {
315 } elseif ( isset( $this->rules
[$curChar] ) ) {
317 $rule = $this->rules
[$curChar];
319 # Some versions of PHP have a strcspn which stops on null characters
320 # Ignore and continue
327 if ( $found == 'angle' ) {
329 // Handle </onlyinclude>
330 if ( $enableOnlyinclude
331 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
333 $findOnlyinclude = true;
337 // Determine element name
338 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
339 // Element name missing or not listed
345 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
347 // To avoid leaving blank lines, when a sequence of
348 // space-separated comments is both preceded and followed by
349 // a newline (ignoring spaces), then
350 // trim leading and trailing spaces and the trailing newline.
353 $endPos = strpos( $text, '-->', $i +
4 );
354 if ( $endPos === false ) {
355 // Unclosed comment in input, runs to end
356 $inner = substr( $text, $i );
357 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
360 // Search backwards for leading whitespace
361 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
363 // Search forwards for trailing whitespace
364 // $wsEnd will be the position of the last space (or the '>' if there's none)
365 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
367 // Keep looking forward as long as we're finding more
369 $comments = array( array( $wsStart, $wsEnd ) );
370 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
371 $c = strpos( $text, '-->', $wsEnd +
4 );
372 if ( $c === false ) {
375 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
376 $comments[] = array( $wsEnd +
1, $c );
380 // Eat the line if possible
381 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
382 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
383 // it's a possible beneficial b/c break.
384 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
385 && substr( $text, $wsEnd +
1, 1 ) == "\n"
387 // Remove leading whitespace from the end of the accumulator
388 // Sanity check first though
389 $wsLength = $i - $wsStart;
391 && strspn( $accum, " \t", -$wsLength ) === $wsLength
393 $accum = substr( $accum, 0, -$wsLength );
396 // Dump all but the last comment to the accumulator
397 foreach ( $comments as $j => $com ) {
399 $endPos = $com[1] +
1;
400 if ( $j == ( count( $comments ) - 1 ) ) {
403 $inner = substr( $text, $startPos, $endPos - $startPos );
404 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
407 // Do a line-start run next time to look for headings after the comment
408 $fakeLineStart = true;
410 // No line to eat, just take the comment itself
416 $part = $stack->top
->getCurrentPart();
417 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
418 $part->visualEnd
= $wsStart;
420 // Else comments abutting, no change in visual end
421 $part->commentEnd
= $endPos;
424 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
425 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
430 $lowerName = strtolower( $name );
431 $attrStart = $i +
strlen( $name ) +
1;
434 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
435 if ( $tagEndPos === false ) {
436 // Infinite backtrack
437 // Disable tag search to prevent worst-case O(N^2) performance
444 // Handle ignored tags
445 if ( in_array( $lowerName, $ignoredTags ) ) {
447 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
454 if ( $text[$tagEndPos - 1] == '/' ) {
455 $attrEnd = $tagEndPos - 1;
460 $attrEnd = $tagEndPos;
463 !isset( $noMoreClosingTag[$name] ) &&
464 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
465 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
467 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
468 $i = $matches[0][1] +
strlen( $matches[0][0] );
469 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
471 // No end tag -- don't match the tag, treat opening tag as literal and resume parsing.
473 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
474 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
475 $noMoreClosingTag[$name] = true;
479 // <includeonly> and <noinclude> just become <ignore> tags
480 if ( in_array( $lowerName, $ignoredElements ) ) {
481 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
487 if ( $attrEnd <= $attrStart ) {
490 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
492 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
493 // Note that the attr element contains the whitespace between name and attribute,
494 // this is necessary for precise reconstruction during pre-save transform.
495 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
496 if ( $inner !== null ) {
497 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
499 $accum .= $close . '</ext>';
500 } elseif ( $found == 'line-start' ) {
501 // Is this the start of a heading?
502 // Line break belongs before the heading element in any case
503 if ( $fakeLineStart ) {
504 $fakeLineStart = false;
510 $count = strspn( $text, '=', $i, 6 );
511 if ( $count == 1 && $findEquals ) {
512 // DWIM: This looks kind of like a name/value separator.
513 // Let's let the equals handler have it and break the
514 // potential heading. This is heuristic, but AFAICT the
515 // methods for completely correct disambiguation are very
517 } elseif ( $count > 0 ) {
521 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
524 $stack->push( $piece );
525 $accum =& $stack->getAccum();
526 $flags = $stack->getFlags();
530 } elseif ( $found == 'line-end' ) {
531 $piece = $stack->top
;
532 // A heading must be open, otherwise \n wouldn't have been in the search list
533 assert( '$piece->open == "\n"' );
534 $part = $piece->getCurrentPart();
535 // Search back through the input to see if it has a proper close.
536 // Do this using the reversed string since the other solutions
537 // (end anchor, etc.) are inefficient.
538 $wsLength = strspn( $revText, " \t", $lengthText - $i );
539 $searchStart = $i - $wsLength;
540 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
541 // Comment found at line end
542 // Search for equals signs before the comment
543 $searchStart = $part->visualEnd
;
544 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
546 $count = $piece->count
;
547 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
548 if ( $equalsLength > 0 ) {
549 if ( $searchStart - $equalsLength == $piece->startPos
) {
550 // This is just a single string of equals signs on its own line
551 // Replicate the doHeadings behavior /={count}(.+)={count}/
552 // First find out how many equals signs there really are (don't stop at 6)
553 $count = $equalsLength;
557 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
560 $count = min( $equalsLength, $count );
563 // Normal match, output <h>
564 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
567 // Single equals sign on its own line, count=0
571 // No match, no <h>, just pass down the inner text
576 $accum =& $stack->getAccum();
577 $flags = $stack->getFlags();
580 // Append the result to the enclosing accumulator
582 // Note that we do NOT increment the input pointer.
583 // This is because the closing linebreak could be the opening linebreak of
584 // another heading. Infinite loops are avoided because the next iteration MUST
585 // hit the heading open case above, which unconditionally increments the
587 } elseif ( $found == 'open' ) {
588 # count opening brace characters
589 $count = strspn( $text, $curChar, $i );
591 # we need to add to stack only if opening brace count is enough for one of the rules
592 if ( $count >= $rule['min'] ) {
593 # Add it to the stack
596 'close' => $rule['end'],
598 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
601 $stack->push( $piece );
602 $accum =& $stack->getAccum();
603 $flags = $stack->getFlags();
606 # Add literal brace(s)
607 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
610 } elseif ( $found == 'close' ) {
611 $piece = $stack->top
;
612 # lets check if there are enough characters for closing brace
613 $maxCount = $piece->count
;
614 $count = strspn( $text, $curChar, $i, $maxCount );
616 # check for maximum matching characters (if there are 5 closing
617 # characters, we will probably need only 3 - depending on the rules)
618 $rule = $this->rules
[$piece->open
];
619 if ( $count > $rule['max'] ) {
620 # The specified maximum exists in the callback array, unless the caller
622 $matchingCount = $rule['max'];
624 # Count is less than the maximum
625 # Skip any gaps in the callback array to find the true largest match
626 # Need to use array_key_exists not isset because the callback can be null
627 $matchingCount = $count;
628 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
633 if ( $matchingCount <= 0 ) {
634 # No matching element found in callback array
635 # Output a literal closing brace and continue
636 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
640 $name = $rule['names'][$matchingCount];
641 if ( $name === null ) {
642 // No element, just literal text
643 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
646 # Note: $parts is already XML, does not need to be encoded further
647 $parts = $piece->parts
;
648 $title = $parts[0]->out
;
651 # The invocation is at the start of the line if lineStart is set in
652 # the stack, and all opening brackets are used up.
653 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
654 $attr = ' lineStart="1"';
659 $element = "<$name$attr>";
660 $element .= "<title>$title</title>";
662 foreach ( $parts as $part ) {
663 if ( isset( $part->eqpos
) ) {
664 $argName = substr( $part->out
, 0, $part->eqpos
);
665 $argValue = substr( $part->out
, $part->eqpos +
1 );
666 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
668 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
672 $element .= "</$name>";
675 # Advance input pointer
676 $i +
= $matchingCount;
680 $accum =& $stack->getAccum();
682 # Re-add the old stack element if it still has unmatched opening characters remaining
683 if ( $matchingCount < $piece->count
) {
684 $piece->parts
= array( new PPDPart
);
685 $piece->count
-= $matchingCount;
686 # do we still qualify for any callback with remaining count?
687 $min = $this->rules
[$piece->open
]['min'];
688 if ( $piece->count
>= $min ) {
689 $stack->push( $piece );
690 $accum =& $stack->getAccum();
692 $accum .= str_repeat( $piece->open
, $piece->count
);
695 $flags = $stack->getFlags();
698 # Add XML element to the enclosing accumulator
700 } elseif ( $found == 'pipe' ) {
701 $findEquals = true; // shortcut for getFlags()
703 $accum =& $stack->getAccum();
705 } elseif ( $found == 'equals' ) {
706 $findEquals = false; // shortcut for getFlags()
707 $stack->getCurrentPart()->eqpos
= strlen( $accum );
713 # Output any remaining unclosed brackets
714 foreach ( $stack->stack
as $piece ) {
715 $stack->rootAccum
.= $piece->breakSyntax();
717 $stack->rootAccum
.= '</root>';
718 $xml = $stack->rootAccum
;
725 * Stack class to help Preprocessor::preprocessToObj()
729 public $stack, $rootAccum;
736 public $elementClass = 'PPDStackElement';
738 public static $false = false;
740 public function __construct() {
741 $this->stack
= array();
743 $this->rootAccum
= '';
744 $this->accum
=& $this->rootAccum
;
750 public function count() {
751 return count( $this->stack
);
754 public function &getAccum() {
758 public function getCurrentPart() {
759 if ( $this->top
=== false ) {
762 return $this->top
->getCurrentPart();
766 public function push( $data ) {
767 if ( $data instanceof $this->elementClass
) {
768 $this->stack
[] = $data;
770 $class = $this->elementClass
;
771 $this->stack
[] = new $class( $data );
773 $this->top
= $this->stack
[count( $this->stack
) - 1];
774 $this->accum
=& $this->top
->getAccum();
777 public function pop() {
778 if ( !count( $this->stack
) ) {
779 throw new MWException( __METHOD__
. ': no elements remaining' );
781 $temp = array_pop( $this->stack
);
783 if ( count( $this->stack
) ) {
784 $this->top
= $this->stack
[count( $this->stack
) - 1];
785 $this->accum
=& $this->top
->getAccum();
787 $this->top
= self
::$false;
788 $this->accum
=& $this->rootAccum
;
793 public function addPart( $s = '' ) {
794 $this->top
->addPart( $s );
795 $this->accum
=& $this->top
->getAccum();
801 public function getFlags() {
802 if ( !count( $this->stack
) ) {
804 'findEquals' => false,
806 'inHeading' => false,
809 return $this->top
->getFlags();
817 class PPDStackElement
{
819 * @var string Opening character (\n for heading)
824 * @var string Matching closing character
829 * @var int Number of opening characters found (number of "=" for heading)
834 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
839 * @var bool True if the open char appeared at the start of the input line.
840 * Not set for headings.
844 public $partClass = 'PPDPart';
846 public function __construct( $data = array() ) {
847 $class = $this->partClass
;
848 $this->parts
= array( new $class );
850 foreach ( $data as $name => $value ) {
851 $this->$name = $value;
855 public function &getAccum() {
856 return $this->parts
[count( $this->parts
) - 1]->out
;
859 public function addPart( $s = '' ) {
860 $class = $this->partClass
;
861 $this->parts
[] = new $class( $s );
864 public function getCurrentPart() {
865 return $this->parts
[count( $this->parts
) - 1];
871 public function getFlags() {
872 $partCount = count( $this->parts
);
873 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
875 'findPipe' => $findPipe,
876 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
877 'inHeading' => $this->open
== "\n",
882 * Get the output string that would result if the close is not found.
884 * @param bool|int $openingCount
887 public function breakSyntax( $openingCount = false ) {
888 if ( $this->open
== "\n" ) {
889 $s = $this->parts
[0]->out
;
891 if ( $openingCount === false ) {
892 $openingCount = $this->count
;
894 $s = str_repeat( $this->open
, $openingCount );
896 foreach ( $this->parts
as $part ) {
914 * @var string Output accumulator string
918 // Optional member variables:
919 // eqpos Position of equals sign in output accumulator
920 // commentEnd Past-the-end input pointer for the last comment encountered
921 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
923 public function __construct( $out = '' ) {
929 * An expansion frame, used as a context to expand the result of preprocessToObj()
932 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
933 class PPFrame_DOM
implements PPFrame
{
934 // @codingStandardsIgnoreEnd
939 public $preprocessor;
953 * Hashtable listing templates which are disallowed for expansion in this frame,
954 * having been encountered previously in parent frames.
956 public $loopCheckHash;
959 * Recursion depth of this frame, top = 0
960 * Note that this is NOT the same as expansion depth in expand()
964 private $volatile = false;
970 protected $childExpansionCache;
973 * Construct a new preprocessor frame.
974 * @param Preprocessor $preprocessor The parent preprocessor
976 public function __construct( $preprocessor ) {
977 $this->preprocessor
= $preprocessor;
978 $this->parser
= $preprocessor->parser
;
979 $this->title
= $this->parser
->mTitle
;
980 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
981 $this->loopCheckHash
= array();
983 $this->childExpansionCache
= array();
987 * Create a new child frame
988 * $args is optionally a multi-root PPNode or array containing the template arguments
990 * @param bool|array $args
991 * @param Title|bool $title
992 * @param int $indexOffset
993 * @return PPTemplateFrame_DOM
995 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
996 $namedArgs = array();
997 $numberedArgs = array();
998 if ( $title === false ) {
999 $title = $this->title
;
1001 if ( $args !== false ) {
1003 if ( $args instanceof PPNode
) {
1004 $args = $args->node
;
1006 foreach ( $args as $arg ) {
1007 if ( $arg instanceof PPNode
) {
1010 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1011 $xpath = new DOMXPath( $arg->ownerDocument
);
1014 $nameNodes = $xpath->query( 'name', $arg );
1015 $value = $xpath->query( 'value', $arg );
1016 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1017 // Numbered parameter
1018 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1019 $index = $index - $indexOffset;
1020 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1021 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1022 wfEscapeWikiText( $this->title
),
1023 wfEscapeWikiText( $title ),
1024 wfEscapeWikiText( $index ) )->text() );
1025 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1027 $numberedArgs[$index] = $value->item( 0 );
1028 unset( $namedArgs[$index] );
1031 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1032 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1033 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1034 wfEscapeWikiText( $this->title
),
1035 wfEscapeWikiText( $title ),
1036 wfEscapeWikiText( $name ) )->text() );
1037 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1039 $namedArgs[$name] = $value->item( 0 );
1040 unset( $numberedArgs[$name] );
1044 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1048 * @throws MWException
1049 * @param string|int $key
1050 * @param string|PPNode_DOM|DOMDocument $root
1054 public function cachedExpand( $key, $root, $flags = 0 ) {
1055 // we don't have a parent, so we don't have a cache
1056 return $this->expand( $root, $flags );
1060 * @throws MWException
1061 * @param string|PPNode_DOM|DOMDocument $root
1065 public function expand( $root, $flags = 0 ) {
1066 static $expansionDepth = 0;
1067 if ( is_string( $root ) ) {
1071 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1072 $this->parser
->limitationWarn( 'node-count-exceeded',
1073 $this->parser
->mPPNodeCount
,
1074 $this->parser
->mOptions
->getMaxPPNodeCount()
1076 return '<span class="error">Node-count limit exceeded</span>';
1079 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1080 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1082 $this->parser
->mOptions
->getMaxPPExpandDepth()
1084 return '<span class="error">Expansion depth limit exceeded</span>';
1087 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1088 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1091 if ( $root instanceof PPNode_DOM
) {
1092 $root = $root->node
;
1094 if ( $root instanceof DOMDocument
) {
1095 $root = $root->documentElement
;
1098 $outStack = array( '', '' );
1099 $iteratorStack = array( false, $root );
1100 $indexStack = array( 0, 0 );
1102 while ( count( $iteratorStack ) > 1 ) {
1103 $level = count( $outStack ) - 1;
1104 $iteratorNode =& $iteratorStack[$level];
1105 $out =& $outStack[$level];
1106 $index =& $indexStack[$level];
1108 if ( $iteratorNode instanceof PPNode_DOM
) {
1109 $iteratorNode = $iteratorNode->node
;
1112 if ( is_array( $iteratorNode ) ) {
1113 if ( $index >= count( $iteratorNode ) ) {
1114 // All done with this iterator
1115 $iteratorStack[$level] = false;
1116 $contextNode = false;
1118 $contextNode = $iteratorNode[$index];
1121 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1122 if ( $index >= $iteratorNode->length
) {
1123 // All done with this iterator
1124 $iteratorStack[$level] = false;
1125 $contextNode = false;
1127 $contextNode = $iteratorNode->item( $index );
1131 // Copy to $contextNode and then delete from iterator stack,
1132 // because this is not an iterator but we do have to execute it once
1133 $contextNode = $iteratorStack[$level];
1134 $iteratorStack[$level] = false;
1137 if ( $contextNode instanceof PPNode_DOM
) {
1138 $contextNode = $contextNode->node
;
1141 $newIterator = false;
1143 if ( $contextNode === false ) {
1145 } elseif ( is_string( $contextNode ) ) {
1146 $out .= $contextNode;
1147 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1148 $newIterator = $contextNode;
1149 } elseif ( $contextNode instanceof DOMNode
) {
1150 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1151 $out .= $contextNode->nodeValue
;
1152 } elseif ( $contextNode->nodeName
== 'template' ) {
1153 # Double-brace expansion
1154 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1155 $titles = $xpath->query( 'title', $contextNode );
1156 $title = $titles->item( 0 );
1157 $parts = $xpath->query( 'part', $contextNode );
1158 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1159 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1161 $lineStart = $contextNode->getAttribute( 'lineStart' );
1163 'title' => new PPNode_DOM( $title ),
1164 'parts' => new PPNode_DOM( $parts ),
1165 'lineStart' => $lineStart );
1166 $ret = $this->parser
->braceSubstitution( $params, $this );
1167 if ( isset( $ret['object'] ) ) {
1168 $newIterator = $ret['object'];
1170 $out .= $ret['text'];
1173 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1174 # Triple-brace expansion
1175 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1176 $titles = $xpath->query( 'title', $contextNode );
1177 $title = $titles->item( 0 );
1178 $parts = $xpath->query( 'part', $contextNode );
1179 if ( $flags & PPFrame
::NO_ARGS
) {
1180 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1183 'title' => new PPNode_DOM( $title ),
1184 'parts' => new PPNode_DOM( $parts ) );
1185 $ret = $this->parser
->argSubstitution( $params, $this );
1186 if ( isset( $ret['object'] ) ) {
1187 $newIterator = $ret['object'];
1189 $out .= $ret['text'];
1192 } elseif ( $contextNode->nodeName
== 'comment' ) {
1193 # HTML-style comment
1194 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1195 # Not in RECOVER_COMMENTS mode (msgnw) though.
1196 if ( ( $this->parser
->ot
['html']
1197 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1198 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1199 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1202 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1203 # Add a strip marker in PST mode so that pstPass2() can
1204 # run some old-fashioned regexes on the result.
1205 # Not in RECOVER_COMMENTS mode (extractSections) though.
1206 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1208 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1209 $out .= $contextNode->textContent
;
1211 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1212 # Output suppression used by <includeonly> etc.
1213 # OT_WIKI will only respect <ignore> in substed templates.
1214 # The other output types respect it unless NO_IGNORE is set.
1215 # extractSections() sets NO_IGNORE and so never respects it.
1216 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1217 ||
( $flags & PPFrame
::NO_IGNORE
)
1219 $out .= $contextNode->textContent
;
1223 } elseif ( $contextNode->nodeName
== 'ext' ) {
1225 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1226 $names = $xpath->query( 'name', $contextNode );
1227 $attrs = $xpath->query( 'attr', $contextNode );
1228 $inners = $xpath->query( 'inner', $contextNode );
1229 $closes = $xpath->query( 'close', $contextNode );
1230 if ( $flags & PPFrame
::NO_TAGS
) {
1231 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1232 if ( $attrs->length
> 0 ) {
1233 $s .= $this->expand( $attrs->item( 0 ), $flags );
1235 if ( $inners->length
> 0 ) {
1236 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1237 if ( $closes->length
> 0 ) {
1238 $s .= $this->expand( $closes->item( 0 ), $flags );
1246 'name' => new PPNode_DOM( $names->item( 0 ) ),
1247 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1248 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1249 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1251 $out .= $this->parser
->extensionSubstitution( $params, $this );
1253 } elseif ( $contextNode->nodeName
== 'h' ) {
1255 $s = $this->expand( $contextNode->childNodes
, $flags );
1257 # Insert a heading marker only for <h> children of <root>
1258 # This is to stop extractSections from going over multiple tree levels
1259 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1260 # Insert heading index marker
1261 $headingIndex = $contextNode->getAttribute( 'i' );
1262 $titleText = $this->title
->getPrefixedDBkey();
1263 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1264 $serial = count( $this->parser
->mHeadings
) - 1;
1265 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1266 $count = $contextNode->getAttribute( 'level' );
1267 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1268 $this->parser
->mStripState
->addGeneral( $marker, '' );
1272 # Generic recursive expansion
1273 $newIterator = $contextNode->childNodes
;
1276 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1279 if ( $newIterator !== false ) {
1280 if ( $newIterator instanceof PPNode_DOM
) {
1281 $newIterator = $newIterator->node
;
1284 $iteratorStack[] = $newIterator;
1286 } elseif ( $iteratorStack[$level] === false ) {
1287 // Return accumulated value to parent
1288 // With tail recursion
1289 while ( $iteratorStack[$level] === false && $level > 0 ) {
1290 $outStack[$level - 1] .= $out;
1291 array_pop( $outStack );
1292 array_pop( $iteratorStack );
1293 array_pop( $indexStack );
1299 return $outStack[0];
1303 * @param string $sep
1305 * @param string|PPNode_DOM|DOMDocument $args,...
1308 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1309 $args = array_slice( func_get_args(), 2 );
1313 foreach ( $args as $root ) {
1314 if ( $root instanceof PPNode_DOM
) {
1315 $root = $root->node
;
1317 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1318 $root = array( $root );
1320 foreach ( $root as $node ) {
1326 $s .= $this->expand( $node, $flags );
1333 * Implode with no flags specified
1334 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1336 * @param string $sep
1337 * @param string|PPNode_DOM|DOMDocument $args,...
1340 public function implode( $sep /*, ... */ ) {
1341 $args = array_slice( func_get_args(), 1 );
1345 foreach ( $args as $root ) {
1346 if ( $root instanceof PPNode_DOM
) {
1347 $root = $root->node
;
1349 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1350 $root = array( $root );
1352 foreach ( $root as $node ) {
1358 $s .= $this->expand( $node );
1365 * Makes an object that, when expand()ed, will be the same as one obtained
1368 * @param string $sep
1369 * @param string|PPNode_DOM|DOMDocument $args,...
1372 public function virtualImplode( $sep /*, ... */ ) {
1373 $args = array_slice( func_get_args(), 1 );
1377 foreach ( $args as $root ) {
1378 if ( $root instanceof PPNode_DOM
) {
1379 $root = $root->node
;
1381 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1382 $root = array( $root );
1384 foreach ( $root as $node ) {
1397 * Virtual implode with brackets
1398 * @param string $start
1399 * @param string $sep
1400 * @param string $end
1401 * @param string|PPNode_DOM|DOMDocument $args,...
1404 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1405 $args = array_slice( func_get_args(), 3 );
1406 $out = array( $start );
1409 foreach ( $args as $root ) {
1410 if ( $root instanceof PPNode_DOM
) {
1411 $root = $root->node
;
1413 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1414 $root = array( $root );
1416 foreach ( $root as $node ) {
1429 public function __toString() {
1433 public function getPDBK( $level = false ) {
1434 if ( $level === false ) {
1435 return $this->title
->getPrefixedDBkey();
1437 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1444 public function getArguments() {
1451 public function getNumberedArguments() {
1458 public function getNamedArguments() {
1463 * Returns true if there are no arguments in this frame
1467 public function isEmpty() {
1471 public function getArgument( $name ) {
1476 * Returns true if the infinite loop check is OK, false if a loop is detected
1478 * @param Title $title
1481 public function loopCheck( $title ) {
1482 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1486 * Return true if the frame is a template frame
1490 public function isTemplate() {
1495 * Get a title of frame
1499 public function getTitle() {
1500 return $this->title
;
1504 * Set the volatile flag
1508 public function setVolatile( $flag = true ) {
1509 $this->volatile
= $flag;
1513 * Get the volatile flag
1517 public function isVolatile() {
1518 return $this->volatile
;
1526 public function setTTL( $ttl ) {
1527 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1537 public function getTTL() {
1543 * Expansion frame with template arguments
1546 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1547 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1548 // @codingStandardsIgnoreEnd
1550 public $numberedArgs, $namedArgs;
1556 public $numberedExpansionCache, $namedExpansionCache;
1559 * @param Preprocessor $preprocessor
1560 * @param bool|PPFrame_DOM $parent
1561 * @param array $numberedArgs
1562 * @param array $namedArgs
1563 * @param bool|Title $title
1565 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1566 $namedArgs = array(), $title = false
1568 parent
::__construct( $preprocessor );
1570 $this->parent
= $parent;
1571 $this->numberedArgs
= $numberedArgs;
1572 $this->namedArgs
= $namedArgs;
1573 $this->title
= $title;
1574 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1575 $this->titleCache
= $parent->titleCache
;
1576 $this->titleCache
[] = $pdbk;
1577 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1578 if ( $pdbk !== false ) {
1579 $this->loopCheckHash
[$pdbk] = true;
1581 $this->depth
= $parent->depth +
1;
1582 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1585 public function __toString() {
1588 $args = $this->numberedArgs +
$this->namedArgs
;
1589 foreach ( $args as $name => $value ) {
1595 $s .= "\"$name\":\"" .
1596 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1603 * @throws MWException
1604 * @param string|int $key
1605 * @param string|PPNode_DOM|DOMDocument $root
1609 public function cachedExpand( $key, $root, $flags = 0 ) {
1610 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1611 return $this->parent
->childExpansionCache
[$key];
1613 $retval = $this->expand( $root, $flags );
1614 if ( !$this->isVolatile() ) {
1615 $this->parent
->childExpansionCache
[$key] = $retval;
1621 * Returns true if there are no arguments in this frame
1625 public function isEmpty() {
1626 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1629 public function getArguments() {
1630 $arguments = array();
1631 foreach ( array_merge(
1632 array_keys( $this->numberedArgs
),
1633 array_keys( $this->namedArgs
) ) as $key ) {
1634 $arguments[$key] = $this->getArgument( $key );
1639 public function getNumberedArguments() {
1640 $arguments = array();
1641 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1642 $arguments[$key] = $this->getArgument( $key );
1647 public function getNamedArguments() {
1648 $arguments = array();
1649 foreach ( array_keys( $this->namedArgs
) as $key ) {
1650 $arguments[$key] = $this->getArgument( $key );
1655 public function getNumberedArgument( $index ) {
1656 if ( !isset( $this->numberedArgs
[$index] ) ) {
1659 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1660 # No trimming for unnamed arguments
1661 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1662 $this->numberedArgs
[$index],
1663 PPFrame
::STRIP_COMMENTS
1666 return $this->numberedExpansionCache
[$index];
1669 public function getNamedArgument( $name ) {
1670 if ( !isset( $this->namedArgs
[$name] ) ) {
1673 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1674 # Trim named arguments post-expand, for backwards compatibility
1675 $this->namedExpansionCache
[$name] = trim(
1676 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1678 return $this->namedExpansionCache
[$name];
1681 public function getArgument( $name ) {
1682 $text = $this->getNumberedArgument( $name );
1683 if ( $text === false ) {
1684 $text = $this->getNamedArgument( $name );
1690 * Return true if the frame is a template frame
1694 public function isTemplate() {
1698 public function setVolatile( $flag = true ) {
1699 parent
::setVolatile( $flag );
1700 $this->parent
->setVolatile( $flag );
1703 public function setTTL( $ttl ) {
1704 parent
::setTTL( $ttl );
1705 $this->parent
->setTTL( $ttl );
1710 * Expansion frame with custom arguments
1713 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1714 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1715 // @codingStandardsIgnoreEnd
1719 public function __construct( $preprocessor, $args ) {
1720 parent
::__construct( $preprocessor );
1721 $this->args
= $args;
1724 public function __toString() {
1727 foreach ( $this->args
as $name => $value ) {
1733 $s .= "\"$name\":\"" .
1734 str_replace( '"', '\\"', $value->__toString() ) . '"';
1743 public function isEmpty() {
1744 return !count( $this->args
);
1747 public function getArgument( $index ) {
1748 if ( !isset( $this->args
[$index] ) ) {
1751 return $this->args
[$index];
1754 public function getArguments() {
1762 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1763 class PPNode_DOM
implements PPNode
{
1764 // @codingStandardsIgnoreEnd
1772 public function __construct( $node, $xpath = false ) {
1773 $this->node
= $node;
1779 public function getXPath() {
1780 if ( $this->xpath
=== null ) {
1781 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1783 return $this->xpath
;
1786 public function __toString() {
1787 if ( $this->node
instanceof DOMNodeList
) {
1789 foreach ( $this->node
as $node ) {
1790 $s .= $node->ownerDocument
->saveXML( $node );
1793 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1799 * @return bool|PPNode_DOM
1801 public function getChildren() {
1802 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1806 * @return bool|PPNode_DOM
1808 public function getFirstChild() {
1809 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1813 * @return bool|PPNode_DOM
1815 public function getNextSibling() {
1816 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1820 * @param string $type
1822 * @return bool|PPNode_DOM
1824 public function getChildrenOfType( $type ) {
1825 return new self( $this->getXPath()->query( $type, $this->node
) );
1831 public function getLength() {
1832 if ( $this->node
instanceof DOMNodeList
) {
1833 return $this->node
->length
;
1841 * @return bool|PPNode_DOM
1843 public function item( $i ) {
1844 $item = $this->node
->item( $i );
1845 return $item ?
new self( $item ) : false;
1851 public function getName() {
1852 if ( $this->node
instanceof DOMNodeList
) {
1855 return $this->node
->nodeName
;
1860 * Split a "<part>" node into an associative array containing:
1861 * - name PPNode name
1862 * - index String index
1863 * - value PPNode value
1865 * @throws MWException
1868 public function splitArg() {
1869 $xpath = $this->getXPath();
1870 $names = $xpath->query( 'name', $this->node
);
1871 $values = $xpath->query( 'value', $this->node
);
1872 if ( !$names->length ||
!$values->length
) {
1873 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1875 $name = $names->item( 0 );
1876 $index = $name->getAttribute( 'index' );
1878 'name' => new self( $name ),
1880 'value' => new self( $values->item( 0 ) ) );
1884 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1885 * All values in the resulting array are PPNodes. Inner and close are optional.
1887 * @throws MWException
1890 public function splitExt() {
1891 $xpath = $this->getXPath();
1892 $names = $xpath->query( 'name', $this->node
);
1893 $attrs = $xpath->query( 'attr', $this->node
);
1894 $inners = $xpath->query( 'inner', $this->node
);
1895 $closes = $xpath->query( 'close', $this->node
);
1896 if ( !$names->length ||
!$attrs->length
) {
1897 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1900 'name' => new self( $names->item( 0 ) ),
1901 'attr' => new self( $attrs->item( 0 ) ) );
1902 if ( $inners->length
) {
1903 $parts['inner'] = new self( $inners->item( 0 ) );
1905 if ( $closes->length
) {
1906 $parts['close'] = new self( $closes->item( 0 ) );
1912 * Split a "<h>" node
1913 * @throws MWException
1916 public function splitHeading() {
1917 if ( $this->getName() !== 'h' ) {
1918 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1921 'i' => $this->node
->getAttribute( 'i' ),
1922 'level' => $this->node
->getAttribute( 'level' ),
1923 'contents' => $this->getChildren()