7e0405c1bcba5a0a87ffe5a520834c1d5cd6bce7
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 wfProfileIn( __METHOD__
. '-loadXML' );
90 $dom = new DOMDocument();
92 $result = $dom->loadXML( $xml );
95 // Try running the XML through UtfNormal to get rid of invalid characters
96 $xml = UtfNormal
::cleanUp( $xml );
97 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
98 // don't barf when the XML is >256 levels deep
99 $result = $dom->loadXML( $xml, 1 << 19 );
101 wfProfileOut( __METHOD__
. '-loadXML' );
104 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
107 $root = $dom->documentElement
;
108 $node = new PPNode_DOM( $root->childNodes
);
113 * @throws MWException
116 public function memCheck() {
117 if ( $this->memoryLimit
=== false ) {
120 $usage = memory_get_usage();
121 if ( $usage > $this->memoryLimit
* 0.9 ) {
122 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
123 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
125 return $usage <= $this->memoryLimit
* 0.8;
129 * Preprocess some wikitext and return the document tree.
130 * This is the ghost of Parser::replace_variables().
132 * @param string $text The text to parse
133 * @param int $flags Bitwise combination of:
134 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
135 * as if the text is being included. Default
136 * is to assume a direct page view.
138 * The generated DOM tree must depend only on the input text and the flags.
139 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
141 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
142 * change in the DOM tree for a given text, must be passed through the section identifier
143 * in the section edit link and thus back to extractSections().
145 * The output of this function is currently only cached in process memory, but a persistent
146 * cache may be implemented at a later date which takes further advantage of these strict
147 * dependency requirements.
149 * @throws MWException
152 public function preprocessToObj( $text, $flags = 0 ) {
153 wfProfileIn( __METHOD__
);
154 global $wgMemc, $wgPreprocessorCacheThreshold;
157 $cacheable = ( $wgPreprocessorCacheThreshold !== false
158 && strlen( $text ) > $wgPreprocessorCacheThreshold );
160 wfProfileIn( __METHOD__
. '-cacheable' );
162 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
163 $cacheValue = $wgMemc->get( $cacheKey );
165 $version = substr( $cacheValue, 0, 8 );
166 if ( intval( $version ) == self
::CACHE_VERSION
) {
167 $xml = substr( $cacheValue, 8 );
169 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
172 if ( $xml === false ) {
173 wfProfileIn( __METHOD__
. '-cache-miss' );
174 $xml = $this->preprocessToXml( $text, $flags );
175 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
176 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
177 wfProfileOut( __METHOD__
. '-cache-miss' );
178 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
181 $xml = $this->preprocessToXml( $text, $flags );
184 // Fail if the number of elements exceeds acceptable limits
185 // Do not attempt to generate the DOM
186 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
187 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
188 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
190 wfProfileOut( __METHOD__
. '-cacheable' );
192 wfProfileOut( __METHOD__
);
193 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
196 wfProfileIn( __METHOD__
. '-loadXML' );
197 $dom = new DOMDocument
;
198 wfSuppressWarnings();
199 $result = $dom->loadXML( $xml );
202 // Try running the XML through UtfNormal to get rid of invalid characters
203 $xml = UtfNormal
::cleanUp( $xml );
204 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
205 // don't barf when the XML is >256 levels deep.
206 $result = $dom->loadXML( $xml, 1 << 19 );
209 $obj = new PPNode_DOM( $dom->documentElement
);
211 wfProfileOut( __METHOD__
. '-loadXML' );
214 wfProfileOut( __METHOD__
. '-cacheable' );
217 wfProfileOut( __METHOD__
);
220 throw new MWException( __METHOD__
. ' generated invalid XML' );
226 * @param string $text
230 public function preprocessToXml( $text, $flags = 0 ) {
231 wfProfileIn( __METHOD__
);
244 'names' => array( 2 => null ),
250 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
252 $xmlishElements = $this->parser
->getStripList();
253 $enableOnlyinclude = false;
254 if ( $forInclusion ) {
255 $ignoredTags = array( 'includeonly', '/includeonly' );
256 $ignoredElements = array( 'noinclude' );
257 $xmlishElements[] = 'noinclude';
258 if ( strpos( $text, '<onlyinclude>' ) !== false
259 && strpos( $text, '</onlyinclude>' ) !== false
261 $enableOnlyinclude = true;
264 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
265 $ignoredElements = array( 'includeonly' );
266 $xmlishElements[] = 'includeonly';
268 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
270 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
271 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
273 $stack = new PPDStack
;
275 $searchBase = "[{<\n"; #}
276 // For fast reverse searches
277 $revText = strrev( $text );
278 $lengthText = strlen( $text );
280 // Input pointer, starts out pointing to a pseudo-newline before the start
282 // Current accumulator
283 $accum =& $stack->getAccum();
285 // True to find equals signs in arguments
287 // True to take notice of pipe characters
290 // True if $i is inside a possible heading
292 // True if there are no more greater-than (>) signs right of $i
294 // True to ignore all input up to the next <onlyinclude>
295 $findOnlyinclude = $enableOnlyinclude;
296 // Do a line-start run without outputting an LF character
297 $fakeLineStart = true;
302 if ( $findOnlyinclude ) {
303 // Ignore all input up to the next <onlyinclude>
304 $startPos = strpos( $text, '<onlyinclude>', $i );
305 if ( $startPos === false ) {
306 // Ignored section runs to the end
307 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
310 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
311 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
313 $findOnlyinclude = false;
316 if ( $fakeLineStart ) {
317 $found = 'line-start';
320 # Find next opening brace, closing brace or pipe
321 $search = $searchBase;
322 if ( $stack->top
=== false ) {
323 $currentClosing = '';
325 $currentClosing = $stack->top
->close
;
326 $search .= $currentClosing;
332 // First equals will be for the template
336 # Output literal section, advance input counter
337 $literalLength = strcspn( $text, $search, $i );
338 if ( $literalLength > 0 ) {
339 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
340 $i +
= $literalLength;
342 if ( $i >= $lengthText ) {
343 if ( $currentClosing == "\n" ) {
344 // Do a past-the-end run to finish off the heading
352 $curChar = $text[$i];
353 if ( $curChar == '|' ) {
355 } elseif ( $curChar == '=' ) {
357 } elseif ( $curChar == '<' ) {
359 } elseif ( $curChar == "\n" ) {
363 $found = 'line-start';
365 } elseif ( $curChar == $currentClosing ) {
367 } elseif ( isset( $rules[$curChar] ) ) {
369 $rule = $rules[$curChar];
371 # Some versions of PHP have a strcspn which stops on null characters
372 # Ignore and continue
379 if ( $found == 'angle' ) {
381 // Handle </onlyinclude>
382 if ( $enableOnlyinclude
383 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
385 $findOnlyinclude = true;
389 // Determine element name
390 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
391 // Element name missing or not listed
397 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
399 // To avoid leaving blank lines, when a sequence of
400 // space-separated comments is both preceded and followed by
401 // a newline (ignoring spaces), then
402 // trim leading and trailing spaces and the trailing newline.
405 $endPos = strpos( $text, '-->', $i +
4 );
406 if ( $endPos === false ) {
407 // Unclosed comment in input, runs to end
408 $inner = substr( $text, $i );
409 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
412 // Search backwards for leading whitespace
413 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
415 // Search forwards for trailing whitespace
416 // $wsEnd will be the position of the last space (or the '>' if there's none)
417 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
419 // Keep looking forward as long as we're finding more
421 $comments = array( array( $wsStart, $wsEnd ) );
422 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
423 $c = strpos( $text, '-->', $wsEnd +
4 );
424 if ( $c === false ) {
427 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
428 $comments[] = array( $wsEnd +
1, $c );
432 // Eat the line if possible
433 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
434 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
435 // it's a possible beneficial b/c break.
436 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
437 && substr( $text, $wsEnd +
1, 1 ) == "\n"
439 // Remove leading whitespace from the end of the accumulator
440 // Sanity check first though
441 $wsLength = $i - $wsStart;
443 && strspn( $accum, " \t", -$wsLength ) === $wsLength
445 $accum = substr( $accum, 0, -$wsLength );
448 // Dump all but the last comment to the accumulator
449 foreach ( $comments as $j => $com ) {
451 $endPos = $com[1] +
1;
452 if ( $j == ( count( $comments ) - 1 ) ) {
455 $inner = substr( $text, $startPos, $endPos - $startPos );
456 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
459 // Do a line-start run next time to look for headings after the comment
460 $fakeLineStart = true;
462 // No line to eat, just take the comment itself
468 $part = $stack->top
->getCurrentPart();
469 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
470 $part->visualEnd
= $wsStart;
472 // Else comments abutting, no change in visual end
473 $part->commentEnd
= $endPos;
476 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
477 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
482 $lowerName = strtolower( $name );
483 $attrStart = $i +
strlen( $name ) +
1;
486 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
487 if ( $tagEndPos === false ) {
488 // Infinite backtrack
489 // Disable tag search to prevent worst-case O(N^2) performance
496 // Handle ignored tags
497 if ( in_array( $lowerName, $ignoredTags ) ) {
499 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
506 if ( $text[$tagEndPos - 1] == '/' ) {
507 $attrEnd = $tagEndPos - 1;
512 $attrEnd = $tagEndPos;
514 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
515 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
517 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
518 $i = $matches[0][1] +
strlen( $matches[0][0] );
519 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
521 // No end tag -- let it run out to the end of the text.
522 $inner = substr( $text, $tagEndPos +
1 );
527 // <includeonly> and <noinclude> just become <ignore> tags
528 if ( in_array( $lowerName, $ignoredElements ) ) {
529 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
535 if ( $attrEnd <= $attrStart ) {
538 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
540 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
541 // Note that the attr element contains the whitespace between name and attribute,
542 // this is necessary for precise reconstruction during pre-save transform.
543 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
544 if ( $inner !== null ) {
545 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
547 $accum .= $close . '</ext>';
548 } elseif ( $found == 'line-start' ) {
549 // Is this the start of a heading?
550 // Line break belongs before the heading element in any case
551 if ( $fakeLineStart ) {
552 $fakeLineStart = false;
558 $count = strspn( $text, '=', $i, 6 );
559 if ( $count == 1 && $findEquals ) {
560 // DWIM: This looks kind of like a name/value separator.
561 // Let's let the equals handler have it and break the
562 // potential heading. This is heuristic, but AFAICT the
563 // methods for completely correct disambiguation are very
565 } elseif ( $count > 0 ) {
569 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
572 $stack->push( $piece );
573 $accum =& $stack->getAccum();
574 $flags = $stack->getFlags();
578 } elseif ( $found == 'line-end' ) {
579 $piece = $stack->top
;
580 // A heading must be open, otherwise \n wouldn't have been in the search list
581 assert( '$piece->open == "\n"' );
582 $part = $piece->getCurrentPart();
583 // Search back through the input to see if it has a proper close.
584 // Do this using the reversed string since the other solutions
585 // (end anchor, etc.) are inefficient.
586 $wsLength = strspn( $revText, " \t", $lengthText - $i );
587 $searchStart = $i - $wsLength;
588 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
589 // Comment found at line end
590 // Search for equals signs before the comment
591 $searchStart = $part->visualEnd
;
592 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
594 $count = $piece->count
;
595 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
596 if ( $equalsLength > 0 ) {
597 if ( $searchStart - $equalsLength == $piece->startPos
) {
598 // This is just a single string of equals signs on its own line
599 // Replicate the doHeadings behavior /={count}(.+)={count}/
600 // First find out how many equals signs there really are (don't stop at 6)
601 $count = $equalsLength;
605 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
608 $count = min( $equalsLength, $count );
611 // Normal match, output <h>
612 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
615 // Single equals sign on its own line, count=0
619 // No match, no <h>, just pass down the inner text
624 $accum =& $stack->getAccum();
625 $flags = $stack->getFlags();
628 // Append the result to the enclosing accumulator
630 // Note that we do NOT increment the input pointer.
631 // This is because the closing linebreak could be the opening linebreak of
632 // another heading. Infinite loops are avoided because the next iteration MUST
633 // hit the heading open case above, which unconditionally increments the
635 } elseif ( $found == 'open' ) {
636 # count opening brace characters
637 $count = strspn( $text, $curChar, $i );
639 # we need to add to stack only if opening brace count is enough for one of the rules
640 if ( $count >= $rule['min'] ) {
641 # Add it to the stack
644 'close' => $rule['end'],
646 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
649 $stack->push( $piece );
650 $accum =& $stack->getAccum();
651 $flags = $stack->getFlags();
654 # Add literal brace(s)
655 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
658 } elseif ( $found == 'close' ) {
659 $piece = $stack->top
;
660 # lets check if there are enough characters for closing brace
661 $maxCount = $piece->count
;
662 $count = strspn( $text, $curChar, $i, $maxCount );
664 # check for maximum matching characters (if there are 5 closing
665 # characters, we will probably need only 3 - depending on the rules)
666 $rule = $rules[$piece->open
];
667 if ( $count > $rule['max'] ) {
668 # The specified maximum exists in the callback array, unless the caller
670 $matchingCount = $rule['max'];
672 # Count is less than the maximum
673 # Skip any gaps in the callback array to find the true largest match
674 # Need to use array_key_exists not isset because the callback can be null
675 $matchingCount = $count;
676 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
681 if ( $matchingCount <= 0 ) {
682 # No matching element found in callback array
683 # Output a literal closing brace and continue
684 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
688 $name = $rule['names'][$matchingCount];
689 if ( $name === null ) {
690 // No element, just literal text
691 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
694 # Note: $parts is already XML, does not need to be encoded further
695 $parts = $piece->parts
;
696 $title = $parts[0]->out
;
699 # The invocation is at the start of the line if lineStart is set in
700 # the stack, and all opening brackets are used up.
701 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
702 $attr = ' lineStart="1"';
707 $element = "<$name$attr>";
708 $element .= "<title>$title</title>";
710 foreach ( $parts as $part ) {
711 if ( isset( $part->eqpos
) ) {
712 $argName = substr( $part->out
, 0, $part->eqpos
);
713 $argValue = substr( $part->out
, $part->eqpos +
1 );
714 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
716 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
720 $element .= "</$name>";
723 # Advance input pointer
724 $i +
= $matchingCount;
728 $accum =& $stack->getAccum();
730 # Re-add the old stack element if it still has unmatched opening characters remaining
731 if ( $matchingCount < $piece->count
) {
732 $piece->parts
= array( new PPDPart
);
733 $piece->count
-= $matchingCount;
734 # do we still qualify for any callback with remaining count?
735 $min = $rules[$piece->open
]['min'];
736 if ( $piece->count
>= $min ) {
737 $stack->push( $piece );
738 $accum =& $stack->getAccum();
740 $accum .= str_repeat( $piece->open
, $piece->count
);
743 $flags = $stack->getFlags();
746 # Add XML element to the enclosing accumulator
748 } elseif ( $found == 'pipe' ) {
749 $findEquals = true; // shortcut for getFlags()
751 $accum =& $stack->getAccum();
753 } elseif ( $found == 'equals' ) {
754 $findEquals = false; // shortcut for getFlags()
755 $stack->getCurrentPart()->eqpos
= strlen( $accum );
761 # Output any remaining unclosed brackets
762 foreach ( $stack->stack
as $piece ) {
763 $stack->rootAccum
.= $piece->breakSyntax();
765 $stack->rootAccum
.= '</root>';
766 $xml = $stack->rootAccum
;
768 wfProfileOut( __METHOD__
);
775 * Stack class to help Preprocessor::preprocessToObj()
779 public $stack, $rootAccum;
786 public $elementClass = 'PPDStackElement';
788 public static $false = false;
790 public function __construct() {
791 $this->stack
= array();
793 $this->rootAccum
= '';
794 $this->accum
=& $this->rootAccum
;
800 public function count() {
801 return count( $this->stack
);
804 public function &getAccum() {
808 public function getCurrentPart() {
809 if ( $this->top
=== false ) {
812 return $this->top
->getCurrentPart();
816 public function push( $data ) {
817 if ( $data instanceof $this->elementClass
) {
818 $this->stack
[] = $data;
820 $class = $this->elementClass
;
821 $this->stack
[] = new $class( $data );
823 $this->top
= $this->stack
[count( $this->stack
) - 1];
824 $this->accum
=& $this->top
->getAccum();
827 public function pop() {
828 if ( !count( $this->stack
) ) {
829 throw new MWException( __METHOD__
. ': no elements remaining' );
831 $temp = array_pop( $this->stack
);
833 if ( count( $this->stack
) ) {
834 $this->top
= $this->stack
[count( $this->stack
) - 1];
835 $this->accum
=& $this->top
->getAccum();
837 $this->top
= self
::$false;
838 $this->accum
=& $this->rootAccum
;
843 public function addPart( $s = '' ) {
844 $this->top
->addPart( $s );
845 $this->accum
=& $this->top
->getAccum();
851 public function getFlags() {
852 if ( !count( $this->stack
) ) {
854 'findEquals' => false,
856 'inHeading' => false,
859 return $this->top
->getFlags();
867 class PPDStackElement
{
868 public $open, // Opening character (\n for heading)
869 $close, // Matching closing character
870 $count, // Number of opening characters found (number of "=" for heading)
871 $parts, // Array of PPDPart objects describing pipe-separated parts.
872 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
874 public $partClass = 'PPDPart';
876 public function __construct( $data = array() ) {
877 $class = $this->partClass
;
878 $this->parts
= array( new $class );
880 foreach ( $data as $name => $value ) {
881 $this->$name = $value;
885 public function &getAccum() {
886 return $this->parts
[count( $this->parts
) - 1]->out
;
889 public function addPart( $s = '' ) {
890 $class = $this->partClass
;
891 $this->parts
[] = new $class( $s );
894 public function getCurrentPart() {
895 return $this->parts
[count( $this->parts
) - 1];
901 public function getFlags() {
902 $partCount = count( $this->parts
);
903 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
905 'findPipe' => $findPipe,
906 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
907 'inHeading' => $this->open
== "\n",
912 * Get the output string that would result if the close is not found.
914 * @param bool|int $openingCount
917 public function breakSyntax( $openingCount = false ) {
918 if ( $this->open
== "\n" ) {
919 $s = $this->parts
[0]->out
;
921 if ( $openingCount === false ) {
922 $openingCount = $this->count
;
924 $s = str_repeat( $this->open
, $openingCount );
926 foreach ( $this->parts
as $part ) {
943 public $out; // Output accumulator string
945 // Optional member variables:
946 // eqpos Position of equals sign in output accumulator
947 // commentEnd Past-the-end input pointer for the last comment encountered
948 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
950 public function __construct( $out = '' ) {
956 * An expansion frame, used as a context to expand the result of preprocessToObj()
958 * @codingStandardsIgnoreStart
960 class PPFrame_DOM
implements PPFrame
{
961 // @codingStandardsIgnoreEnd
966 public $preprocessor;
980 * Hashtable listing templates which are disallowed for expansion in this frame,
981 * having been encountered previously in parent frames.
983 public $loopCheckHash;
986 * Recursion depth of this frame, top = 0
987 * Note that this is NOT the same as expansion depth in expand()
991 private $volatile = false;
997 protected $childExpansionCache;
1000 * Construct a new preprocessor frame.
1001 * @param Preprocessor $preprocessor The parent preprocessor
1003 public function __construct( $preprocessor ) {
1004 $this->preprocessor
= $preprocessor;
1005 $this->parser
= $preprocessor->parser
;
1006 $this->title
= $this->parser
->mTitle
;
1007 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
1008 $this->loopCheckHash
= array();
1010 $this->childExpansionCache
= array();
1014 * Create a new child frame
1015 * $args is optionally a multi-root PPNode or array containing the template arguments
1017 * @param bool|array $args
1018 * @param Title|bool $title
1019 * @param int $indexOffset
1020 * @return PPTemplateFrame_DOM
1022 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1023 $namedArgs = array();
1024 $numberedArgs = array();
1025 if ( $title === false ) {
1026 $title = $this->title
;
1028 if ( $args !== false ) {
1030 if ( $args instanceof PPNode
) {
1031 $args = $args->node
;
1033 foreach ( $args as $arg ) {
1034 if ( $arg instanceof PPNode
) {
1037 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1038 $xpath = new DOMXPath( $arg->ownerDocument
);
1041 $nameNodes = $xpath->query( 'name', $arg );
1042 $value = $xpath->query( 'value', $arg );
1043 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1044 // Numbered parameter
1045 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1046 $index = $index - $indexOffset;
1047 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1048 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1050 $numberedArgs[$index] = $value->item( 0 );
1051 unset( $namedArgs[$index] );
1054 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1055 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1056 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1058 $namedArgs[$name] = $value->item( 0 );
1059 unset( $numberedArgs[$name] );
1063 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1067 * @throws MWException
1068 * @param string|int $key
1069 * @param string|PPNode_DOM|DOMDocument $root
1073 public function cachedExpand( $key, $root, $flags = 0 ) {
1074 // we don't have a parent, so we don't have a cache
1075 return $this->expand( $root, $flags );
1079 * @throws MWException
1080 * @param string|PPNode_DOM|DOMDocument $root
1084 public function expand( $root, $flags = 0 ) {
1085 static $expansionDepth = 0;
1086 if ( is_string( $root ) ) {
1090 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1091 $this->parser
->limitationWarn( 'node-count-exceeded',
1092 $this->parser
->mPPNodeCount
,
1093 $this->parser
->mOptions
->getMaxPPNodeCount()
1095 return '<span class="error">Node-count limit exceeded</span>';
1098 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1099 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1101 $this->parser
->mOptions
->getMaxPPExpandDepth()
1103 return '<span class="error">Expansion depth limit exceeded</span>';
1105 wfProfileIn( __METHOD__
);
1107 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1108 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1111 if ( $root instanceof PPNode_DOM
) {
1112 $root = $root->node
;
1114 if ( $root instanceof DOMDocument
) {
1115 $root = $root->documentElement
;
1118 $outStack = array( '', '' );
1119 $iteratorStack = array( false, $root );
1120 $indexStack = array( 0, 0 );
1122 while ( count( $iteratorStack ) > 1 ) {
1123 $level = count( $outStack ) - 1;
1124 $iteratorNode =& $iteratorStack[$level];
1125 $out =& $outStack[$level];
1126 $index =& $indexStack[$level];
1128 if ( $iteratorNode instanceof PPNode_DOM
) {
1129 $iteratorNode = $iteratorNode->node
;
1132 if ( is_array( $iteratorNode ) ) {
1133 if ( $index >= count( $iteratorNode ) ) {
1134 // All done with this iterator
1135 $iteratorStack[$level] = false;
1136 $contextNode = false;
1138 $contextNode = $iteratorNode[$index];
1141 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1142 if ( $index >= $iteratorNode->length
) {
1143 // All done with this iterator
1144 $iteratorStack[$level] = false;
1145 $contextNode = false;
1147 $contextNode = $iteratorNode->item( $index );
1151 // Copy to $contextNode and then delete from iterator stack,
1152 // because this is not an iterator but we do have to execute it once
1153 $contextNode = $iteratorStack[$level];
1154 $iteratorStack[$level] = false;
1157 if ( $contextNode instanceof PPNode_DOM
) {
1158 $contextNode = $contextNode->node
;
1161 $newIterator = false;
1163 if ( $contextNode === false ) {
1165 } elseif ( is_string( $contextNode ) ) {
1166 $out .= $contextNode;
1167 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1168 $newIterator = $contextNode;
1169 } elseif ( $contextNode instanceof DOMNode
) {
1170 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1171 $out .= $contextNode->nodeValue
;
1172 } elseif ( $contextNode->nodeName
== 'template' ) {
1173 # Double-brace expansion
1174 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1175 $titles = $xpath->query( 'title', $contextNode );
1176 $title = $titles->item( 0 );
1177 $parts = $xpath->query( 'part', $contextNode );
1178 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1179 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1181 $lineStart = $contextNode->getAttribute( 'lineStart' );
1183 'title' => new PPNode_DOM( $title ),
1184 'parts' => new PPNode_DOM( $parts ),
1185 'lineStart' => $lineStart );
1186 $ret = $this->parser
->braceSubstitution( $params, $this );
1187 if ( isset( $ret['object'] ) ) {
1188 $newIterator = $ret['object'];
1190 $out .= $ret['text'];
1193 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1194 # Triple-brace expansion
1195 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1196 $titles = $xpath->query( 'title', $contextNode );
1197 $title = $titles->item( 0 );
1198 $parts = $xpath->query( 'part', $contextNode );
1199 if ( $flags & PPFrame
::NO_ARGS
) {
1200 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1203 'title' => new PPNode_DOM( $title ),
1204 'parts' => new PPNode_DOM( $parts ) );
1205 $ret = $this->parser
->argSubstitution( $params, $this );
1206 if ( isset( $ret['object'] ) ) {
1207 $newIterator = $ret['object'];
1209 $out .= $ret['text'];
1212 } elseif ( $contextNode->nodeName
== 'comment' ) {
1213 # HTML-style comment
1214 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1215 if ( $this->parser
->ot
['html']
1216 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1217 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1220 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1221 # Add a strip marker in PST mode so that pstPass2() can
1222 # run some old-fashioned regexes on the result.
1223 # Not in RECOVER_COMMENTS mode (extractSections) though.
1224 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1226 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1227 $out .= $contextNode->textContent
;
1229 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1230 # Output suppression used by <includeonly> etc.
1231 # OT_WIKI will only respect <ignore> in substed templates.
1232 # The other output types respect it unless NO_IGNORE is set.
1233 # extractSections() sets NO_IGNORE and so never respects it.
1234 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1235 ||
( $flags & PPFrame
::NO_IGNORE
)
1237 $out .= $contextNode->textContent
;
1241 } elseif ( $contextNode->nodeName
== 'ext' ) {
1243 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1244 $names = $xpath->query( 'name', $contextNode );
1245 $attrs = $xpath->query( 'attr', $contextNode );
1246 $inners = $xpath->query( 'inner', $contextNode );
1247 $closes = $xpath->query( 'close', $contextNode );
1248 if ( $flags & PPFrame
::NO_TAGS
) {
1249 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1250 if ( $attrs->length
> 0 ) {
1251 $s .= $this->expand( $attrs->item( 0 ), $flags );
1253 if ( $inners->length
> 0 ) {
1254 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1255 if ( $closes->length
> 0 ) {
1256 $s .= $this->expand( $closes->item( 0 ), $flags );
1264 'name' => new PPNode_DOM( $names->item( 0 ) ),
1265 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1266 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1267 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1269 $out .= $this->parser
->extensionSubstitution( $params, $this );
1271 } elseif ( $contextNode->nodeName
== 'h' ) {
1273 $s = $this->expand( $contextNode->childNodes
, $flags );
1275 # Insert a heading marker only for <h> children of <root>
1276 # This is to stop extractSections from going over multiple tree levels
1277 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1278 # Insert heading index marker
1279 $headingIndex = $contextNode->getAttribute( 'i' );
1280 $titleText = $this->title
->getPrefixedDBkey();
1281 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1282 $serial = count( $this->parser
->mHeadings
) - 1;
1283 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1284 $count = $contextNode->getAttribute( 'level' );
1285 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1286 $this->parser
->mStripState
->addGeneral( $marker, '' );
1290 # Generic recursive expansion
1291 $newIterator = $contextNode->childNodes
;
1294 wfProfileOut( __METHOD__
);
1295 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1298 if ( $newIterator !== false ) {
1299 if ( $newIterator instanceof PPNode_DOM
) {
1300 $newIterator = $newIterator->node
;
1303 $iteratorStack[] = $newIterator;
1305 } elseif ( $iteratorStack[$level] === false ) {
1306 // Return accumulated value to parent
1307 // With tail recursion
1308 while ( $iteratorStack[$level] === false && $level > 0 ) {
1309 $outStack[$level - 1] .= $out;
1310 array_pop( $outStack );
1311 array_pop( $iteratorStack );
1312 array_pop( $indexStack );
1318 wfProfileOut( __METHOD__
);
1319 return $outStack[0];
1323 * @param string $sep
1325 * @param string|PPNode_DOM|DOMDocument $args,...
1328 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1329 $args = array_slice( func_get_args(), 2 );
1333 foreach ( $args as $root ) {
1334 if ( $root instanceof PPNode_DOM
) {
1335 $root = $root->node
;
1337 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1338 $root = array( $root );
1340 foreach ( $root as $node ) {
1346 $s .= $this->expand( $node, $flags );
1353 * Implode with no flags specified
1354 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1356 * @param string $sep
1357 * @param string|PPNode_DOM|DOMDocument $args,...
1360 public function implode( $sep /*, ... */ ) {
1361 $args = array_slice( func_get_args(), 1 );
1365 foreach ( $args as $root ) {
1366 if ( $root instanceof PPNode_DOM
) {
1367 $root = $root->node
;
1369 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1370 $root = array( $root );
1372 foreach ( $root as $node ) {
1378 $s .= $this->expand( $node );
1385 * Makes an object that, when expand()ed, will be the same as one obtained
1388 * @param string $sep
1389 * @param string|PPNode_DOM|DOMDocument $args,...
1392 public function virtualImplode( $sep /*, ... */ ) {
1393 $args = array_slice( func_get_args(), 1 );
1397 foreach ( $args as $root ) {
1398 if ( $root instanceof PPNode_DOM
) {
1399 $root = $root->node
;
1401 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1402 $root = array( $root );
1404 foreach ( $root as $node ) {
1417 * Virtual implode with brackets
1418 * @param string $start
1419 * @param string $sep
1420 * @param string $end
1421 * @param string|PPNode_DOM|DOMDocument $args,...
1424 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1425 $args = array_slice( func_get_args(), 3 );
1426 $out = array( $start );
1429 foreach ( $args as $root ) {
1430 if ( $root instanceof PPNode_DOM
) {
1431 $root = $root->node
;
1433 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1434 $root = array( $root );
1436 foreach ( $root as $node ) {
1449 public function __toString() {
1453 public function getPDBK( $level = false ) {
1454 if ( $level === false ) {
1455 return $this->title
->getPrefixedDBkey();
1457 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1464 public function getArguments() {
1471 public function getNumberedArguments() {
1478 public function getNamedArguments() {
1483 * Returns true if there are no arguments in this frame
1487 public function isEmpty() {
1491 public function getArgument( $name ) {
1496 * Returns true if the infinite loop check is OK, false if a loop is detected
1498 * @param Title $title
1501 public function loopCheck( $title ) {
1502 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1506 * Return true if the frame is a template frame
1510 public function isTemplate() {
1515 * Get a title of frame
1519 public function getTitle() {
1520 return $this->title
;
1524 * Set the volatile flag
1528 public function setVolatile( $flag = true ) {
1529 $this->volatile
= $flag;
1533 * Get the volatile flag
1537 public function isVolatile() {
1538 return $this->volatile
;
1546 public function setTTL( $ttl ) {
1547 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1557 public function getTTL() {
1563 * Expansion frame with template arguments
1565 * @codingStandardsIgnoreStart
1567 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1568 // @codingStandardsIgnoreEnd
1570 public $numberedArgs, $namedArgs;
1576 public $numberedExpansionCache, $namedExpansionCache;
1579 * @param Preprocessor $preprocessor
1580 * @param bool|PPFrame_DOM $parent
1581 * @param array $numberedArgs
1582 * @param array $namedArgs
1583 * @param bool|Title $title
1585 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1586 $namedArgs = array(), $title = false
1588 parent
::__construct( $preprocessor );
1590 $this->parent
= $parent;
1591 $this->numberedArgs
= $numberedArgs;
1592 $this->namedArgs
= $namedArgs;
1593 $this->title
= $title;
1594 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1595 $this->titleCache
= $parent->titleCache
;
1596 $this->titleCache
[] = $pdbk;
1597 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1598 if ( $pdbk !== false ) {
1599 $this->loopCheckHash
[$pdbk] = true;
1601 $this->depth
= $parent->depth +
1;
1602 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1605 public function __toString() {
1608 $args = $this->numberedArgs +
$this->namedArgs
;
1609 foreach ( $args as $name => $value ) {
1615 $s .= "\"$name\":\"" .
1616 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1623 * @throws MWException
1624 * @param string|int $key
1625 * @param string|PPNode_DOM|DOMDocument $root
1629 public function cachedExpand( $key, $root, $flags = 0 ) {
1630 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1631 return $this->parent
->childExpansionCache
[$key];
1633 $retval = $this->expand( $root, $flags );
1634 if ( !$this->isVolatile() ) {
1635 $this->parent
->childExpansionCache
[$key] = $retval;
1641 * Returns true if there are no arguments in this frame
1645 public function isEmpty() {
1646 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1649 public function getArguments() {
1650 $arguments = array();
1651 foreach ( array_merge(
1652 array_keys( $this->numberedArgs
),
1653 array_keys( $this->namedArgs
) ) as $key ) {
1654 $arguments[$key] = $this->getArgument( $key );
1659 public function getNumberedArguments() {
1660 $arguments = array();
1661 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1662 $arguments[$key] = $this->getArgument( $key );
1667 public function getNamedArguments() {
1668 $arguments = array();
1669 foreach ( array_keys( $this->namedArgs
) as $key ) {
1670 $arguments[$key] = $this->getArgument( $key );
1675 public function getNumberedArgument( $index ) {
1676 if ( !isset( $this->numberedArgs
[$index] ) ) {
1679 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1680 # No trimming for unnamed arguments
1681 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1682 $this->numberedArgs
[$index],
1683 PPFrame
::STRIP_COMMENTS
1686 return $this->numberedExpansionCache
[$index];
1689 public function getNamedArgument( $name ) {
1690 if ( !isset( $this->namedArgs
[$name] ) ) {
1693 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1694 # Trim named arguments post-expand, for backwards compatibility
1695 $this->namedExpansionCache
[$name] = trim(
1696 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1698 return $this->namedExpansionCache
[$name];
1701 public function getArgument( $name ) {
1702 $text = $this->getNumberedArgument( $name );
1703 if ( $text === false ) {
1704 $text = $this->getNamedArgument( $name );
1710 * Return true if the frame is a template frame
1714 public function isTemplate() {
1718 public function setVolatile( $flag = true ) {
1719 parent
::setVolatile( $flag );
1720 $this->parent
->setVolatile( $flag );
1723 public function setTTL( $ttl ) {
1724 parent
::setTTL( $ttl );
1725 $this->parent
->setTTL( $ttl );
1730 * Expansion frame with custom arguments
1732 * @codingStandardsIgnoreStart
1734 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1735 // @codingStandardsIgnoreEnd
1739 public function __construct( $preprocessor, $args ) {
1740 parent
::__construct( $preprocessor );
1741 $this->args
= $args;
1744 public function __toString() {
1747 foreach ( $this->args
as $name => $value ) {
1753 $s .= "\"$name\":\"" .
1754 str_replace( '"', '\\"', $value->__toString() ) . '"';
1763 public function isEmpty() {
1764 return !count( $this->args
);
1767 public function getArgument( $index ) {
1768 if ( !isset( $this->args
[$index] ) ) {
1771 return $this->args
[$index];
1774 public function getArguments() {
1781 * @codingStandardsIgnoreStart
1783 class PPNode_DOM
implements PPNode
{
1784 // @codingStandardsIgnoreEnd
1792 public function __construct( $node, $xpath = false ) {
1793 $this->node
= $node;
1799 public function getXPath() {
1800 if ( $this->xpath
=== null ) {
1801 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1803 return $this->xpath
;
1806 public function __toString() {
1807 if ( $this->node
instanceof DOMNodeList
) {
1809 foreach ( $this->node
as $node ) {
1810 $s .= $node->ownerDocument
->saveXML( $node );
1813 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1819 * @return bool|PPNode_DOM
1821 public function getChildren() {
1822 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1826 * @return bool|PPNode_DOM
1828 public function getFirstChild() {
1829 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1833 * @return bool|PPNode_DOM
1835 public function getNextSibling() {
1836 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1840 * @param string $type
1842 * @return bool|PPNode_DOM
1844 public function getChildrenOfType( $type ) {
1845 return new self( $this->getXPath()->query( $type, $this->node
) );
1851 public function getLength() {
1852 if ( $this->node
instanceof DOMNodeList
) {
1853 return $this->node
->length
;
1861 * @return bool|PPNode_DOM
1863 public function item( $i ) {
1864 $item = $this->node
->item( $i );
1865 return $item ?
new self( $item ) : false;
1871 public function getName() {
1872 if ( $this->node
instanceof DOMNodeList
) {
1875 return $this->node
->nodeName
;
1880 * Split a "<part>" node into an associative array containing:
1881 * - name PPNode name
1882 * - index String index
1883 * - value PPNode value
1885 * @throws MWException
1888 public function splitArg() {
1889 $xpath = $this->getXPath();
1890 $names = $xpath->query( 'name', $this->node
);
1891 $values = $xpath->query( 'value', $this->node
);
1892 if ( !$names->length ||
!$values->length
) {
1893 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1895 $name = $names->item( 0 );
1896 $index = $name->getAttribute( 'index' );
1898 'name' => new self( $name ),
1900 'value' => new self( $values->item( 0 ) ) );
1904 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1905 * All values in the resulting array are PPNodes. Inner and close are optional.
1907 * @throws MWException
1910 public function splitExt() {
1911 $xpath = $this->getXPath();
1912 $names = $xpath->query( 'name', $this->node
);
1913 $attrs = $xpath->query( 'attr', $this->node
);
1914 $inners = $xpath->query( 'inner', $this->node
);
1915 $closes = $xpath->query( 'close', $this->node
);
1916 if ( !$names->length ||
!$attrs->length
) {
1917 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1920 'name' => new self( $names->item( 0 ) ),
1921 'attr' => new self( $attrs->item( 0 ) ) );
1922 if ( $inners->length
) {
1923 $parts['inner'] = new self( $inners->item( 0 ) );
1925 if ( $closes->length
) {
1926 $parts['close'] = new self( $closes->item( 0 ) );
1932 * Split a "<h>" node
1933 * @throws MWException
1936 public function splitHeading() {
1937 if ( $this->getName() !== 'h' ) {
1938 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1941 'i' => $this->node
->getAttribute( 'i' ),
1942 'level' => $this->node
->getAttribute( 'level' ),
1943 'contents' => $this->getChildren()