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
72 public function newPartNodeArray( $values ) {
73 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
76 foreach ( $values as $k => $val ) {
78 $xml .= "<part><name index=\"$k\"/><value>"
79 . htmlspecialchars( $val ) . "</value></part>";
81 $xml .= "<part><name>" . htmlspecialchars( $k )
82 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
88 wfProfileIn( __METHOD__
. '-loadXML' );
89 $dom = new DOMDocument();
91 $result = $dom->loadXML( $xml );
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal
::cleanUp( $xml );
96 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
97 // don't barf when the XML is >256 levels deep
98 $result = $dom->loadXML( $xml, 1 << 19 );
100 wfProfileOut( __METHOD__
. '-loadXML' );
103 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
106 $root = $dom->documentElement
;
107 $node = new PPNode_DOM( $root->childNodes
);
112 * @throws MWException
115 public function memCheck() {
116 if ( $this->memoryLimit
=== false ) {
119 $usage = memory_get_usage();
120 if ( $usage > $this->memoryLimit
* 0.9 ) {
121 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
122 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
124 return $usage <= $this->memoryLimit
* 0.8;
128 * Preprocess some wikitext and return the document tree.
129 * This is the ghost of Parser::replace_variables().
131 * @param string $text The text to parse
132 * @param int $flags Bitwise combination of:
133 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
134 * as if the text is being included. Default
135 * is to assume a direct page view.
137 * The generated DOM tree must depend only on the input text and the flags.
138 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
140 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
141 * change in the DOM tree for a given text, must be passed through the section identifier
142 * in the section edit link and thus back to extractSections().
144 * The output of this function is currently only cached in process memory, but a persistent
145 * cache may be implemented at a later date which takes further advantage of these strict
146 * dependency requirements.
148 * @throws MWException
151 public function preprocessToObj( $text, $flags = 0 ) {
152 wfProfileIn( __METHOD__
);
153 global $wgMemc, $wgPreprocessorCacheThreshold;
156 $cacheable = ( $wgPreprocessorCacheThreshold !== false
157 && strlen( $text ) > $wgPreprocessorCacheThreshold );
159 wfProfileIn( __METHOD__
. '-cacheable' );
161 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
162 $cacheValue = $wgMemc->get( $cacheKey );
164 $version = substr( $cacheValue, 0, 8 );
165 if ( intval( $version ) == self
::CACHE_VERSION
) {
166 $xml = substr( $cacheValue, 8 );
168 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
171 if ( $xml === false ) {
172 wfProfileIn( __METHOD__
. '-cache-miss' );
173 $xml = $this->preprocessToXml( $text, $flags );
174 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
175 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
176 wfProfileOut( __METHOD__
. '-cache-miss' );
177 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
180 $xml = $this->preprocessToXml( $text, $flags );
183 // Fail if the number of elements exceeds acceptable limits
184 // Do not attempt to generate the DOM
185 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
186 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
187 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
189 wfProfileOut( __METHOD__
. '-cacheable' );
191 wfProfileOut( __METHOD__
);
192 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
195 wfProfileIn( __METHOD__
. '-loadXML' );
196 $dom = new DOMDocument
;
197 wfSuppressWarnings();
198 $result = $dom->loadXML( $xml );
201 // Try running the XML through UtfNormal to get rid of invalid characters
202 $xml = UtfNormal
::cleanUp( $xml );
203 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
204 // don't barf when the XML is >256 levels deep.
205 $result = $dom->loadXML( $xml, 1 << 19 );
208 $obj = new PPNode_DOM( $dom->documentElement
);
210 wfProfileOut( __METHOD__
. '-loadXML' );
213 wfProfileOut( __METHOD__
. '-cacheable' );
216 wfProfileOut( __METHOD__
);
219 throw new MWException( __METHOD__
. ' generated invalid XML' );
225 * @param string $text
229 public function preprocessToXml( $text, $flags = 0 ) {
230 wfProfileIn( __METHOD__
);
243 'names' => array( 2 => null ),
249 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
251 $xmlishElements = $this->parser
->getStripList();
252 $enableOnlyinclude = false;
253 if ( $forInclusion ) {
254 $ignoredTags = array( 'includeonly', '/includeonly' );
255 $ignoredElements = array( 'noinclude' );
256 $xmlishElements[] = 'noinclude';
257 if ( strpos( $text, '<onlyinclude>' ) !== false
258 && strpos( $text, '</onlyinclude>' ) !== false
260 $enableOnlyinclude = true;
263 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
264 $ignoredElements = array( 'includeonly' );
265 $xmlishElements[] = 'includeonly';
267 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
269 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
270 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
272 $stack = new PPDStack
;
274 $searchBase = "[{<\n"; #}
275 // For fast reverse searches
276 $revText = strrev( $text );
277 $lengthText = strlen( $text );
279 // Input pointer, starts out pointing to a pseudo-newline before the start
281 // Current accumulator
282 $accum =& $stack->getAccum();
284 // True to find equals signs in arguments
286 // True to take notice of pipe characters
289 // True if $i is inside a possible heading
291 // True if there are no more greater-than (>) signs right of $i
293 // True to ignore all input up to the next <onlyinclude>
294 $findOnlyinclude = $enableOnlyinclude;
295 // Do a line-start run without outputting an LF character
296 $fakeLineStart = true;
301 if ( $findOnlyinclude ) {
302 // Ignore all input up to the next <onlyinclude>
303 $startPos = strpos( $text, '<onlyinclude>', $i );
304 if ( $startPos === false ) {
305 // Ignored section runs to the end
306 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
309 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
310 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
312 $findOnlyinclude = false;
315 if ( $fakeLineStart ) {
316 $found = 'line-start';
319 # Find next opening brace, closing brace or pipe
320 $search = $searchBase;
321 if ( $stack->top
=== false ) {
322 $currentClosing = '';
324 $currentClosing = $stack->top
->close
;
325 $search .= $currentClosing;
331 // First equals will be for the template
335 # Output literal section, advance input counter
336 $literalLength = strcspn( $text, $search, $i );
337 if ( $literalLength > 0 ) {
338 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
339 $i +
= $literalLength;
341 if ( $i >= $lengthText ) {
342 if ( $currentClosing == "\n" ) {
343 // Do a past-the-end run to finish off the heading
351 $curChar = $text[$i];
352 if ( $curChar == '|' ) {
354 } elseif ( $curChar == '=' ) {
356 } elseif ( $curChar == '<' ) {
358 } elseif ( $curChar == "\n" ) {
362 $found = 'line-start';
364 } elseif ( $curChar == $currentClosing ) {
366 } elseif ( isset( $rules[$curChar] ) ) {
368 $rule = $rules[$curChar];
370 # Some versions of PHP have a strcspn which stops on null characters
371 # Ignore and continue
378 if ( $found == 'angle' ) {
380 // Handle </onlyinclude>
381 if ( $enableOnlyinclude
382 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
384 $findOnlyinclude = true;
388 // Determine element name
389 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
390 // Element name missing or not listed
396 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
398 // To avoid leaving blank lines, when a sequence of
399 // space-separated comments is both preceded and followed by
400 // a newline (ignoring spaces), then
401 // trim leading and trailing spaces and the trailing newline.
404 $endPos = strpos( $text, '-->', $i +
4 );
405 if ( $endPos === false ) {
406 // Unclosed comment in input, runs to end
407 $inner = substr( $text, $i );
408 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
411 // Search backwards for leading whitespace
412 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
414 // Search forwards for trailing whitespace
415 // $wsEnd will be the position of the last space (or the '>' if there's none)
416 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
418 // Keep looking forward as long as we're finding more
420 $comments = array( array( $wsStart, $wsEnd ) );
421 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
422 $c = strpos( $text, '-->', $wsEnd +
4 );
423 if ( $c === false ) {
426 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
427 $comments[] = array( $wsEnd +
1, $c );
431 // Eat the line if possible
432 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
433 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
434 // it's a possible beneficial b/c break.
435 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
436 && substr( $text, $wsEnd +
1, 1 ) == "\n"
438 // Remove leading whitespace from the end of the accumulator
439 // Sanity check first though
440 $wsLength = $i - $wsStart;
442 && strspn( $accum, " \t", -$wsLength ) === $wsLength
444 $accum = substr( $accum, 0, -$wsLength );
447 // Dump all but the last comment to the accumulator
448 foreach ( $comments as $j => $com ) {
450 $endPos = $com[1] +
1;
451 if ( $j == ( count( $comments ) - 1 ) ) {
454 $inner = substr( $text, $startPos, $endPos - $startPos );
455 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
458 // Do a line-start run next time to look for headings after the comment
459 $fakeLineStart = true;
461 // No line to eat, just take the comment itself
467 $part = $stack->top
->getCurrentPart();
468 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
469 $part->visualEnd
= $wsStart;
471 // Else comments abutting, no change in visual end
472 $part->commentEnd
= $endPos;
475 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
476 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
481 $lowerName = strtolower( $name );
482 $attrStart = $i +
strlen( $name ) +
1;
485 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
486 if ( $tagEndPos === false ) {
487 // Infinite backtrack
488 // Disable tag search to prevent worst-case O(N^2) performance
495 // Handle ignored tags
496 if ( in_array( $lowerName, $ignoredTags ) ) {
498 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
505 if ( $text[$tagEndPos - 1] == '/' ) {
506 $attrEnd = $tagEndPos - 1;
511 $attrEnd = $tagEndPos;
513 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
514 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
516 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
517 $i = $matches[0][1] +
strlen( $matches[0][0] );
518 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
520 // No end tag -- let it run out to the end of the text.
521 $inner = substr( $text, $tagEndPos +
1 );
526 // <includeonly> and <noinclude> just become <ignore> tags
527 if ( in_array( $lowerName, $ignoredElements ) ) {
528 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
534 if ( $attrEnd <= $attrStart ) {
537 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
539 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
540 // Note that the attr element contains the whitespace between name and attribute,
541 // this is necessary for precise reconstruction during pre-save transform.
542 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
543 if ( $inner !== null ) {
544 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
546 $accum .= $close . '</ext>';
547 } elseif ( $found == 'line-start' ) {
548 // Is this the start of a heading?
549 // Line break belongs before the heading element in any case
550 if ( $fakeLineStart ) {
551 $fakeLineStart = false;
557 $count = strspn( $text, '=', $i, 6 );
558 if ( $count == 1 && $findEquals ) {
559 // DWIM: This looks kind of like a name/value separator.
560 // Let's let the equals handler have it and break the
561 // potential heading. This is heuristic, but AFAICT the
562 // methods for completely correct disambiguation are very
564 } elseif ( $count > 0 ) {
568 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
571 $stack->push( $piece );
572 $accum =& $stack->getAccum();
573 $flags = $stack->getFlags();
577 } elseif ( $found == 'line-end' ) {
578 $piece = $stack->top
;
579 // A heading must be open, otherwise \n wouldn't have been in the search list
580 assert( '$piece->open == "\n"' );
581 $part = $piece->getCurrentPart();
582 // Search back through the input to see if it has a proper close.
583 // Do this using the reversed string since the other solutions
584 // (end anchor, etc.) are inefficient.
585 $wsLength = strspn( $revText, " \t", $lengthText - $i );
586 $searchStart = $i - $wsLength;
587 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
588 // Comment found at line end
589 // Search for equals signs before the comment
590 $searchStart = $part->visualEnd
;
591 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
593 $count = $piece->count
;
594 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
595 if ( $equalsLength > 0 ) {
596 if ( $searchStart - $equalsLength == $piece->startPos
) {
597 // This is just a single string of equals signs on its own line
598 // Replicate the doHeadings behavior /={count}(.+)={count}/
599 // First find out how many equals signs there really are (don't stop at 6)
600 $count = $equalsLength;
604 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
607 $count = min( $equalsLength, $count );
610 // Normal match, output <h>
611 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
614 // Single equals sign on its own line, count=0
618 // No match, no <h>, just pass down the inner text
623 $accum =& $stack->getAccum();
624 $flags = $stack->getFlags();
627 // Append the result to the enclosing accumulator
629 // Note that we do NOT increment the input pointer.
630 // This is because the closing linebreak could be the opening linebreak of
631 // another heading. Infinite loops are avoided because the next iteration MUST
632 // hit the heading open case above, which unconditionally increments the
634 } elseif ( $found == 'open' ) {
635 # count opening brace characters
636 $count = strspn( $text, $curChar, $i );
638 # we need to add to stack only if opening brace count is enough for one of the rules
639 if ( $count >= $rule['min'] ) {
640 # Add it to the stack
643 'close' => $rule['end'],
645 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
648 $stack->push( $piece );
649 $accum =& $stack->getAccum();
650 $flags = $stack->getFlags();
653 # Add literal brace(s)
654 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
657 } elseif ( $found == 'close' ) {
658 $piece = $stack->top
;
659 # lets check if there are enough characters for closing brace
660 $maxCount = $piece->count
;
661 $count = strspn( $text, $curChar, $i, $maxCount );
663 # check for maximum matching characters (if there are 5 closing
664 # characters, we will probably need only 3 - depending on the rules)
665 $rule = $rules[$piece->open
];
666 if ( $count > $rule['max'] ) {
667 # The specified maximum exists in the callback array, unless the caller
669 $matchingCount = $rule['max'];
671 # Count is less than the maximum
672 # Skip any gaps in the callback array to find the true largest match
673 # Need to use array_key_exists not isset because the callback can be null
674 $matchingCount = $count;
675 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
680 if ( $matchingCount <= 0 ) {
681 # No matching element found in callback array
682 # Output a literal closing brace and continue
683 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
687 $name = $rule['names'][$matchingCount];
688 if ( $name === null ) {
689 // No element, just literal text
690 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
693 # Note: $parts is already XML, does not need to be encoded further
694 $parts = $piece->parts
;
695 $title = $parts[0]->out
;
698 # The invocation is at the start of the line if lineStart is set in
699 # the stack, and all opening brackets are used up.
700 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
701 $attr = ' lineStart="1"';
706 $element = "<$name$attr>";
707 $element .= "<title>$title</title>";
709 foreach ( $parts as $part ) {
710 if ( isset( $part->eqpos
) ) {
711 $argName = substr( $part->out
, 0, $part->eqpos
);
712 $argValue = substr( $part->out
, $part->eqpos +
1 );
713 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
715 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
719 $element .= "</$name>";
722 # Advance input pointer
723 $i +
= $matchingCount;
727 $accum =& $stack->getAccum();
729 # Re-add the old stack element if it still has unmatched opening characters remaining
730 if ( $matchingCount < $piece->count
) {
731 $piece->parts
= array( new PPDPart
);
732 $piece->count
-= $matchingCount;
733 # do we still qualify for any callback with remaining count?
734 $min = $rules[$piece->open
]['min'];
735 if ( $piece->count
>= $min ) {
736 $stack->push( $piece );
737 $accum =& $stack->getAccum();
739 $accum .= str_repeat( $piece->open
, $piece->count
);
742 $flags = $stack->getFlags();
745 # Add XML element to the enclosing accumulator
747 } elseif ( $found == 'pipe' ) {
748 $findEquals = true; // shortcut for getFlags()
750 $accum =& $stack->getAccum();
752 } elseif ( $found == 'equals' ) {
753 $findEquals = false; // shortcut for getFlags()
754 $stack->getCurrentPart()->eqpos
= strlen( $accum );
760 # Output any remaining unclosed brackets
761 foreach ( $stack->stack
as $piece ) {
762 $stack->rootAccum
.= $piece->breakSyntax();
764 $stack->rootAccum
.= '</root>';
765 $xml = $stack->rootAccum
;
767 wfProfileOut( __METHOD__
);
774 * Stack class to help Preprocessor::preprocessToObj()
778 public $stack, $rootAccum;
785 public $elementClass = 'PPDStackElement';
787 public static $false = false;
789 public function __construct() {
790 $this->stack
= array();
792 $this->rootAccum
= '';
793 $this->accum
=& $this->rootAccum
;
799 public function count() {
800 return count( $this->stack
);
803 public function &getAccum() {
807 public function getCurrentPart() {
808 if ( $this->top
=== false ) {
811 return $this->top
->getCurrentPart();
815 public function push( $data ) {
816 if ( $data instanceof $this->elementClass
) {
817 $this->stack
[] = $data;
819 $class = $this->elementClass
;
820 $this->stack
[] = new $class( $data );
822 $this->top
= $this->stack
[count( $this->stack
) - 1];
823 $this->accum
=& $this->top
->getAccum();
826 public function pop() {
827 if ( !count( $this->stack
) ) {
828 throw new MWException( __METHOD__
. ': no elements remaining' );
830 $temp = array_pop( $this->stack
);
832 if ( count( $this->stack
) ) {
833 $this->top
= $this->stack
[count( $this->stack
) - 1];
834 $this->accum
=& $this->top
->getAccum();
836 $this->top
= self
::$false;
837 $this->accum
=& $this->rootAccum
;
842 public function addPart( $s = '' ) {
843 $this->top
->addPart( $s );
844 $this->accum
=& $this->top
->getAccum();
850 public function getFlags() {
851 if ( !count( $this->stack
) ) {
853 'findEquals' => false,
855 'inHeading' => false,
858 return $this->top
->getFlags();
866 class PPDStackElement
{
867 public $open, // Opening character (\n for heading)
868 $close, // Matching closing character
869 $count, // Number of opening characters found (number of "=" for heading)
870 $parts, // Array of PPDPart objects describing pipe-separated parts.
871 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
873 public $partClass = 'PPDPart';
875 public function __construct( $data = array() ) {
876 $class = $this->partClass
;
877 $this->parts
= array( new $class );
879 foreach ( $data as $name => $value ) {
880 $this->$name = $value;
884 public function &getAccum() {
885 return $this->parts
[count( $this->parts
) - 1]->out
;
888 public function addPart( $s = '' ) {
889 $class = $this->partClass
;
890 $this->parts
[] = new $class( $s );
893 public function getCurrentPart() {
894 return $this->parts
[count( $this->parts
) - 1];
900 public function getFlags() {
901 $partCount = count( $this->parts
);
902 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
904 'findPipe' => $findPipe,
905 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
906 'inHeading' => $this->open
== "\n",
911 * Get the output string that would result if the close is not found.
913 * @param bool|int $openingCount
916 public function breakSyntax( $openingCount = false ) {
917 if ( $this->open
== "\n" ) {
918 $s = $this->parts
[0]->out
;
920 if ( $openingCount === false ) {
921 $openingCount = $this->count
;
923 $s = str_repeat( $this->open
, $openingCount );
925 foreach ( $this->parts
as $part ) {
942 public $out; // Output accumulator string
944 // Optional member variables:
945 // eqpos Position of equals sign in output accumulator
946 // commentEnd Past-the-end input pointer for the last comment encountered
947 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
949 public function __construct( $out = '' ) {
955 * An expansion frame, used as a context to expand the result of preprocessToObj()
957 * @codingStandardsIgnoreStart
959 class PPFrame_DOM
implements PPFrame
{
960 // @codingStandardsIgnoreEnd
965 public $preprocessor;
979 * Hashtable listing templates which are disallowed for expansion in this frame,
980 * having been encountered previously in parent frames.
982 public $loopCheckHash;
985 * Recursion depth of this frame, top = 0
986 * Note that this is NOT the same as expansion depth in expand()
990 private $volatile = false;
996 protected $childExpansionCache;
999 * Construct a new preprocessor frame.
1000 * @param Preprocessor $preprocessor The parent preprocessor
1002 public function __construct( $preprocessor ) {
1003 $this->preprocessor
= $preprocessor;
1004 $this->parser
= $preprocessor->parser
;
1005 $this->title
= $this->parser
->mTitle
;
1006 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
1007 $this->loopCheckHash
= array();
1009 $this->childExpansionCache
= array();
1013 * Create a new child frame
1014 * $args is optionally a multi-root PPNode or array containing the template arguments
1016 * @param bool|array $args
1017 * @param Title|bool $title
1018 * @param int $indexOffset
1019 * @return PPTemplateFrame_DOM
1021 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1022 $namedArgs = array();
1023 $numberedArgs = array();
1024 if ( $title === false ) {
1025 $title = $this->title
;
1027 if ( $args !== false ) {
1029 if ( $args instanceof PPNode
) {
1030 $args = $args->node
;
1032 foreach ( $args as $arg ) {
1033 if ( $arg instanceof PPNode
) {
1036 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1037 $xpath = new DOMXPath( $arg->ownerDocument
);
1040 $nameNodes = $xpath->query( 'name', $arg );
1041 $value = $xpath->query( 'value', $arg );
1042 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1043 // Numbered parameter
1044 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1045 $index = $index - $indexOffset;
1046 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1047 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1049 $numberedArgs[$index] = $value->item( 0 );
1050 unset( $namedArgs[$index] );
1053 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1054 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1055 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1057 $namedArgs[$name] = $value->item( 0 );
1058 unset( $numberedArgs[$name] );
1062 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1066 * @throws MWException
1067 * @param string|int $key
1068 * @param string|PPNode_DOM|DOMDocument $root
1072 public function cachedExpand( $key, $root, $flags = 0 ) {
1073 // we don't have a parent, so we don't have a cache
1074 return $this->expand( $root, $flags );
1078 * @throws MWException
1079 * @param string|PPNode_DOM|DOMDocument $root
1083 public function expand( $root, $flags = 0 ) {
1084 static $expansionDepth = 0;
1085 if ( is_string( $root ) ) {
1089 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1090 $this->parser
->limitationWarn( 'node-count-exceeded',
1091 $this->parser
->mPPNodeCount
,
1092 $this->parser
->mOptions
->getMaxPPNodeCount()
1094 return '<span class="error">Node-count limit exceeded</span>';
1097 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1098 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1100 $this->parser
->mOptions
->getMaxPPExpandDepth()
1102 return '<span class="error">Expansion depth limit exceeded</span>';
1104 wfProfileIn( __METHOD__
);
1106 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1107 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1110 if ( $root instanceof PPNode_DOM
) {
1111 $root = $root->node
;
1113 if ( $root instanceof DOMDocument
) {
1114 $root = $root->documentElement
;
1117 $outStack = array( '', '' );
1118 $iteratorStack = array( false, $root );
1119 $indexStack = array( 0, 0 );
1121 while ( count( $iteratorStack ) > 1 ) {
1122 $level = count( $outStack ) - 1;
1123 $iteratorNode =& $iteratorStack[$level];
1124 $out =& $outStack[$level];
1125 $index =& $indexStack[$level];
1127 if ( $iteratorNode instanceof PPNode_DOM
) {
1128 $iteratorNode = $iteratorNode->node
;
1131 if ( is_array( $iteratorNode ) ) {
1132 if ( $index >= count( $iteratorNode ) ) {
1133 // All done with this iterator
1134 $iteratorStack[$level] = false;
1135 $contextNode = false;
1137 $contextNode = $iteratorNode[$index];
1140 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1141 if ( $index >= $iteratorNode->length
) {
1142 // All done with this iterator
1143 $iteratorStack[$level] = false;
1144 $contextNode = false;
1146 $contextNode = $iteratorNode->item( $index );
1150 // Copy to $contextNode and then delete from iterator stack,
1151 // because this is not an iterator but we do have to execute it once
1152 $contextNode = $iteratorStack[$level];
1153 $iteratorStack[$level] = false;
1156 if ( $contextNode instanceof PPNode_DOM
) {
1157 $contextNode = $contextNode->node
;
1160 $newIterator = false;
1162 if ( $contextNode === false ) {
1164 } elseif ( is_string( $contextNode ) ) {
1165 $out .= $contextNode;
1166 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1167 $newIterator = $contextNode;
1168 } elseif ( $contextNode instanceof DOMNode
) {
1169 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1170 $out .= $contextNode->nodeValue
;
1171 } elseif ( $contextNode->nodeName
== 'template' ) {
1172 # Double-brace expansion
1173 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1174 $titles = $xpath->query( 'title', $contextNode );
1175 $title = $titles->item( 0 );
1176 $parts = $xpath->query( 'part', $contextNode );
1177 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1178 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1180 $lineStart = $contextNode->getAttribute( 'lineStart' );
1182 'title' => new PPNode_DOM( $title ),
1183 'parts' => new PPNode_DOM( $parts ),
1184 'lineStart' => $lineStart );
1185 $ret = $this->parser
->braceSubstitution( $params, $this );
1186 if ( isset( $ret['object'] ) ) {
1187 $newIterator = $ret['object'];
1189 $out .= $ret['text'];
1192 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1193 # Triple-brace expansion
1194 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1195 $titles = $xpath->query( 'title', $contextNode );
1196 $title = $titles->item( 0 );
1197 $parts = $xpath->query( 'part', $contextNode );
1198 if ( $flags & PPFrame
::NO_ARGS
) {
1199 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1202 'title' => new PPNode_DOM( $title ),
1203 'parts' => new PPNode_DOM( $parts ) );
1204 $ret = $this->parser
->argSubstitution( $params, $this );
1205 if ( isset( $ret['object'] ) ) {
1206 $newIterator = $ret['object'];
1208 $out .= $ret['text'];
1211 } elseif ( $contextNode->nodeName
== 'comment' ) {
1212 # HTML-style comment
1213 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1214 if ( $this->parser
->ot
['html']
1215 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1216 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1219 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1220 # Add a strip marker in PST mode so that pstPass2() can
1221 # run some old-fashioned regexes on the result.
1222 # Not in RECOVER_COMMENTS mode (extractSections) though.
1223 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1225 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1226 $out .= $contextNode->textContent
;
1228 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1229 # Output suppression used by <includeonly> etc.
1230 # OT_WIKI will only respect <ignore> in substed templates.
1231 # The other output types respect it unless NO_IGNORE is set.
1232 # extractSections() sets NO_IGNORE and so never respects it.
1233 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1234 ||
( $flags & PPFrame
::NO_IGNORE
)
1236 $out .= $contextNode->textContent
;
1240 } elseif ( $contextNode->nodeName
== 'ext' ) {
1242 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1243 $names = $xpath->query( 'name', $contextNode );
1244 $attrs = $xpath->query( 'attr', $contextNode );
1245 $inners = $xpath->query( 'inner', $contextNode );
1246 $closes = $xpath->query( 'close', $contextNode );
1247 if ( $flags & PPFrame
::NO_TAGS
) {
1248 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1249 if ( $attrs->length
> 0 ) {
1250 $s .= $this->expand( $attrs->item( 0 ), $flags );
1252 if ( $inners->length
> 0 ) {
1253 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1254 if ( $closes->length
> 0 ) {
1255 $s .= $this->expand( $closes->item( 0 ), $flags );
1263 'name' => new PPNode_DOM( $names->item( 0 ) ),
1264 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1265 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1266 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1268 $out .= $this->parser
->extensionSubstitution( $params, $this );
1270 } elseif ( $contextNode->nodeName
== 'h' ) {
1272 $s = $this->expand( $contextNode->childNodes
, $flags );
1274 # Insert a heading marker only for <h> children of <root>
1275 # This is to stop extractSections from going over multiple tree levels
1276 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1277 # Insert heading index marker
1278 $headingIndex = $contextNode->getAttribute( 'i' );
1279 $titleText = $this->title
->getPrefixedDBkey();
1280 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1281 $serial = count( $this->parser
->mHeadings
) - 1;
1282 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1283 $count = $contextNode->getAttribute( 'level' );
1284 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1285 $this->parser
->mStripState
->addGeneral( $marker, '' );
1289 # Generic recursive expansion
1290 $newIterator = $contextNode->childNodes
;
1293 wfProfileOut( __METHOD__
);
1294 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1297 if ( $newIterator !== false ) {
1298 if ( $newIterator instanceof PPNode_DOM
) {
1299 $newIterator = $newIterator->node
;
1302 $iteratorStack[] = $newIterator;
1304 } elseif ( $iteratorStack[$level] === false ) {
1305 // Return accumulated value to parent
1306 // With tail recursion
1307 while ( $iteratorStack[$level] === false && $level > 0 ) {
1308 $outStack[$level - 1] .= $out;
1309 array_pop( $outStack );
1310 array_pop( $iteratorStack );
1311 array_pop( $indexStack );
1317 wfProfileOut( __METHOD__
);
1318 return $outStack[0];
1322 * @param string $sep
1324 * @param string|PPNode_DOM|DOMDocument $args,...
1327 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1328 $args = array_slice( func_get_args(), 2 );
1332 foreach ( $args as $root ) {
1333 if ( $root instanceof PPNode_DOM
) {
1334 $root = $root->node
;
1336 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1337 $root = array( $root );
1339 foreach ( $root as $node ) {
1345 $s .= $this->expand( $node, $flags );
1352 * Implode with no flags specified
1353 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1355 * @param string $sep
1356 * @param string|PPNode_DOM|DOMDocument $args,...
1359 public function implode( $sep /*, ... */ ) {
1360 $args = array_slice( func_get_args(), 1 );
1364 foreach ( $args as $root ) {
1365 if ( $root instanceof PPNode_DOM
) {
1366 $root = $root->node
;
1368 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1369 $root = array( $root );
1371 foreach ( $root as $node ) {
1377 $s .= $this->expand( $node );
1384 * Makes an object that, when expand()ed, will be the same as one obtained
1387 * @param string $sep
1388 * @param string|PPNode_DOM|DOMDocument $args,...
1391 public function virtualImplode( $sep /*, ... */ ) {
1392 $args = array_slice( func_get_args(), 1 );
1396 foreach ( $args as $root ) {
1397 if ( $root instanceof PPNode_DOM
) {
1398 $root = $root->node
;
1400 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1401 $root = array( $root );
1403 foreach ( $root as $node ) {
1416 * Virtual implode with brackets
1417 * @param string $start
1418 * @param string $sep
1419 * @param string $end
1420 * @param string|PPNode_DOM|DOMDocument $args,...
1423 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1424 $args = array_slice( func_get_args(), 3 );
1425 $out = array( $start );
1428 foreach ( $args as $root ) {
1429 if ( $root instanceof PPNode_DOM
) {
1430 $root = $root->node
;
1432 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1433 $root = array( $root );
1435 foreach ( $root as $node ) {
1448 public function __toString() {
1452 public function getPDBK( $level = false ) {
1453 if ( $level === false ) {
1454 return $this->title
->getPrefixedDBkey();
1456 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1463 public function getArguments() {
1470 public function getNumberedArguments() {
1477 public function getNamedArguments() {
1482 * Returns true if there are no arguments in this frame
1486 public function isEmpty() {
1490 public function getArgument( $name ) {
1495 * Returns true if the infinite loop check is OK, false if a loop is detected
1497 * @param Title $title
1500 public function loopCheck( $title ) {
1501 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1505 * Return true if the frame is a template frame
1509 public function isTemplate() {
1514 * Get a title of frame
1518 public function getTitle() {
1519 return $this->title
;
1523 * Set the volatile flag
1527 public function setVolatile( $flag = true ) {
1528 $this->volatile
= $flag;
1532 * Get the volatile flag
1536 public function isVolatile() {
1537 return $this->volatile
;
1545 public function setTTL( $ttl ) {
1546 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1556 public function getTTL() {
1562 * Expansion frame with template arguments
1564 * @codingStandardsIgnoreStart
1566 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1567 // @codingStandardsIgnoreEnd
1569 public $numberedArgs, $namedArgs;
1575 public $numberedExpansionCache, $namedExpansionCache;
1578 * @param Preprocessor $preprocessor
1579 * @param bool|PPFrame_DOM $parent
1580 * @param array $numberedArgs
1581 * @param array $namedArgs
1582 * @param bool|Title $title
1584 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1585 $namedArgs = array(), $title = false
1587 parent
::__construct( $preprocessor );
1589 $this->parent
= $parent;
1590 $this->numberedArgs
= $numberedArgs;
1591 $this->namedArgs
= $namedArgs;
1592 $this->title
= $title;
1593 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1594 $this->titleCache
= $parent->titleCache
;
1595 $this->titleCache
[] = $pdbk;
1596 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1597 if ( $pdbk !== false ) {
1598 $this->loopCheckHash
[$pdbk] = true;
1600 $this->depth
= $parent->depth +
1;
1601 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1604 public function __toString() {
1607 $args = $this->numberedArgs +
$this->namedArgs
;
1608 foreach ( $args as $name => $value ) {
1614 $s .= "\"$name\":\"" .
1615 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1622 * @throws MWException
1623 * @param string|int $key
1624 * @param string|PPNode_DOM|DOMDocument $root
1628 public function cachedExpand( $key, $root, $flags = 0 ) {
1629 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1630 return $this->parent
->childExpansionCache
[$key];
1632 $retval = $this->expand( $root, $flags );
1633 if ( !$this->isVolatile() ) {
1634 $this->parent
->childExpansionCache
[$key] = $retval;
1640 * Returns true if there are no arguments in this frame
1644 public function isEmpty() {
1645 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1648 public function getArguments() {
1649 $arguments = array();
1650 foreach ( array_merge(
1651 array_keys( $this->numberedArgs
),
1652 array_keys( $this->namedArgs
) ) as $key ) {
1653 $arguments[$key] = $this->getArgument( $key );
1658 public function getNumberedArguments() {
1659 $arguments = array();
1660 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1661 $arguments[$key] = $this->getArgument( $key );
1666 public function getNamedArguments() {
1667 $arguments = array();
1668 foreach ( array_keys( $this->namedArgs
) as $key ) {
1669 $arguments[$key] = $this->getArgument( $key );
1674 public function getNumberedArgument( $index ) {
1675 if ( !isset( $this->numberedArgs
[$index] ) ) {
1678 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1679 # No trimming for unnamed arguments
1680 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1681 $this->numberedArgs
[$index],
1682 PPFrame
::STRIP_COMMENTS
1685 return $this->numberedExpansionCache
[$index];
1688 public function getNamedArgument( $name ) {
1689 if ( !isset( $this->namedArgs
[$name] ) ) {
1692 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1693 # Trim named arguments post-expand, for backwards compatibility
1694 $this->namedExpansionCache
[$name] = trim(
1695 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1697 return $this->namedExpansionCache
[$name];
1700 public function getArgument( $name ) {
1701 $text = $this->getNumberedArgument( $name );
1702 if ( $text === false ) {
1703 $text = $this->getNamedArgument( $name );
1709 * Return true if the frame is a template frame
1713 public function isTemplate() {
1717 public function setVolatile( $flag = true ) {
1718 parent
::setVolatile( $flag );
1719 $this->parent
->setVolatile( $flag );
1722 public function setTTL( $ttl ) {
1723 parent
::setTTL( $ttl );
1724 $this->parent
->setTTL( $ttl );
1729 * Expansion frame with custom arguments
1731 * @codingStandardsIgnoreStart
1733 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1734 // @codingStandardsIgnoreEnd
1738 public function __construct( $preprocessor, $args ) {
1739 parent
::__construct( $preprocessor );
1740 $this->args
= $args;
1743 public function __toString() {
1746 foreach ( $this->args
as $name => $value ) {
1752 $s .= "\"$name\":\"" .
1753 str_replace( '"', '\\"', $value->__toString() ) . '"';
1762 public function isEmpty() {
1763 return !count( $this->args
);
1766 public function getArgument( $index ) {
1767 if ( !isset( $this->args
[$index] ) ) {
1770 return $this->args
[$index];
1773 public function getArguments() {
1780 * @codingStandardsIgnoreStart
1782 class PPNode_DOM
implements PPNode
{
1783 // @codingStandardsIgnoreEnd
1791 public function __construct( $node, $xpath = false ) {
1792 $this->node
= $node;
1798 public function getXPath() {
1799 if ( $this->xpath
=== null ) {
1800 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1802 return $this->xpath
;
1805 public function __toString() {
1806 if ( $this->node
instanceof DOMNodeList
) {
1808 foreach ( $this->node
as $node ) {
1809 $s .= $node->ownerDocument
->saveXML( $node );
1812 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1818 * @return bool|PPNode_DOM
1820 public function getChildren() {
1821 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1825 * @return bool|PPNode_DOM
1827 public function getFirstChild() {
1828 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1832 * @return bool|PPNode_DOM
1834 public function getNextSibling() {
1835 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1839 * @param string $type
1841 * @return bool|PPNode_DOM
1843 public function getChildrenOfType( $type ) {
1844 return new self( $this->getXPath()->query( $type, $this->node
) );
1850 public function getLength() {
1851 if ( $this->node
instanceof DOMNodeList
) {
1852 return $this->node
->length
;
1860 * @return bool|PPNode_DOM
1862 public function item( $i ) {
1863 $item = $this->node
->item( $i );
1864 return $item ?
new self( $item ) : false;
1870 public function getName() {
1871 if ( $this->node
instanceof DOMNodeList
) {
1874 return $this->node
->nodeName
;
1879 * Split a "<part>" node into an associative array containing:
1880 * - name PPNode name
1881 * - index String index
1882 * - value PPNode value
1884 * @throws MWException
1887 public function splitArg() {
1888 $xpath = $this->getXPath();
1889 $names = $xpath->query( 'name', $this->node
);
1890 $values = $xpath->query( 'value', $this->node
);
1891 if ( !$names->length ||
!$values->length
) {
1892 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1894 $name = $names->item( 0 );
1895 $index = $name->getAttribute( 'index' );
1897 'name' => new self( $name ),
1899 'value' => new self( $values->item( 0 ) ) );
1903 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1904 * All values in the resulting array are PPNodes. Inner and close are optional.
1906 * @throws MWException
1909 public function splitExt() {
1910 $xpath = $this->getXPath();
1911 $names = $xpath->query( 'name', $this->node
);
1912 $attrs = $xpath->query( 'attr', $this->node
);
1913 $inners = $xpath->query( 'inner', $this->node
);
1914 $closes = $xpath->query( 'close', $this->node
);
1915 if ( !$names->length ||
!$attrs->length
) {
1916 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1919 'name' => new self( $names->item( 0 ) ),
1920 'attr' => new self( $attrs->item( 0 ) ) );
1921 if ( $inners->length
) {
1922 $parts['inner'] = new self( $inners->item( 0 ) );
1924 if ( $closes->length
) {
1925 $parts['close'] = new self( $closes->item( 0 ) );
1931 * Split a "<h>" node
1932 * @throws MWException
1935 public function splitHeading() {
1936 if ( $this->getName() !== 'h' ) {
1937 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1940 'i' => $this->node
->getAttribute( 'i' ),
1941 'level' => $this->node
->getAttribute( 'level' ),
1942 'contents' => $this->getChildren()