3 * Preprocessor using PHP's dom extension
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
27 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
28 class Preprocessor_DOM
extends Preprocessor
{
29 // @codingStandardsIgnoreEnd
38 const CACHE_PREFIX
= 'preprocess-xml';
40 public function __construct( $parser ) {
41 $this->parser
= $parser;
42 $mem = ini_get( 'memory_limit' );
43 $this->memoryLimit
= false;
44 if ( strval( $mem ) !== '' && $mem != -1 ) {
45 if ( preg_match( '/^\d+$/', $mem ) ) {
46 $this->memoryLimit
= $mem;
47 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
48 $this->memoryLimit
= $m[1] * 1048576;
56 public function newFrame() {
57 return new PPFrame_DOM( $this );
62 * @return PPCustomFrame_DOM
64 public function newCustomFrame( $args ) {
65 return new PPCustomFrame_DOM( $this, $args );
69 * @param array $values
73 public function newPartNodeArray( $values ) {
74 // NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
77 foreach ( $values as $k => $val ) {
79 $xml .= "<part><name index=\"$k\"/><value>"
80 . htmlspecialchars( $val ) . "</value></part>";
82 $xml .= "<part><name>" . htmlspecialchars( $k )
83 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
89 $dom = new DOMDocument();
90 MediaWiki\
suppressWarnings();
91 $result = $dom->loadXML( $xml );
92 MediaWiki\restoreWarnings
();
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal\Validator
::cleanUp( $xml );
96 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
97 // don't barf when the XML is >256 levels deep
98 $result = $dom->loadXML( $xml, 1 << 19 );
102 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
105 $root = $dom->documentElement
;
106 $node = new PPNode_DOM( $root->childNodes
);
111 * @throws MWException
114 public function memCheck() {
115 if ( $this->memoryLimit
=== false ) {
118 $usage = memory_get_usage();
119 if ( $usage > $this->memoryLimit
* 0.9 ) {
120 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
121 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
123 return $usage <= $this->memoryLimit
* 0.8;
127 * Preprocess some wikitext and return the document tree.
128 * This is the ghost of Parser::replace_variables().
130 * @param string $text The text to parse
131 * @param int $flags Bitwise combination of:
132 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
133 * as if the text is being included. Default
134 * is to assume a direct page view.
136 * The generated DOM tree must depend only on the input text and the flags.
137 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
139 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
140 * change in the DOM tree for a given text, must be passed through the section identifier
141 * in the section edit link and thus back to extractSections().
143 * The output of this function is currently only cached in process memory, but a persistent
144 * cache may be implemented at a later date which takes further advantage of these strict
145 * dependency requirements.
147 * @throws MWException
150 public function preprocessToObj( $text, $flags = 0 ) {
152 $xml = $this->cacheGetTree( $text, $flags );
153 if ( $xml === false ) {
154 $xml = $this->preprocessToXml( $text, $flags );
155 $this->cacheSetTree( $text, $flags, $xml );
158 // Fail if the number of elements exceeds acceptable limits
159 // Do not attempt to generate the DOM
160 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
161 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
162 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
163 // if ( $cacheable ) { ... }
164 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
167 $dom = new DOMDocument
;
168 MediaWiki\
suppressWarnings();
169 $result = $dom->loadXML( $xml );
170 MediaWiki\restoreWarnings
();
172 // Try running the XML through UtfNormal to get rid of invalid characters
173 $xml = UtfNormal\Validator
::cleanUp( $xml );
174 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
175 // don't barf when the XML is >256 levels deep.
176 $result = $dom->loadXML( $xml, 1 << 19 );
179 $obj = new PPNode_DOM( $dom->documentElement
);
182 // if ( $cacheable ) { ... }
185 throw new MWException( __METHOD__
. ' generated invalid XML' );
191 * @param string $text
195 public function preprocessToXml( $text, $flags = 0 ) {
196 global $wgDisableLangConversion;
198 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
200 $xmlishElements = $this->parser
->getStripList();
201 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
202 $enableOnlyinclude = false;
203 if ( $forInclusion ) {
204 $ignoredTags = [ 'includeonly', '/includeonly' ];
205 $ignoredElements = [ 'noinclude' ];
206 $xmlishElements[] = 'noinclude';
207 if ( strpos( $text, '<onlyinclude>' ) !== false
208 && strpos( $text, '</onlyinclude>' ) !== false
210 $enableOnlyinclude = true;
213 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
214 $ignoredElements = [ 'includeonly' ];
215 $xmlishElements[] = 'includeonly';
217 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
219 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
220 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
222 $stack = new PPDStack
;
224 $searchBase = "[{<\n"; # }
225 if ( !$wgDisableLangConversion ) {
229 // For fast reverse searches
230 $revText = strrev( $text );
231 $lengthText = strlen( $text );
233 // Input pointer, starts out pointing to a pseudo-newline before the start
235 // Current accumulator
236 $accum =& $stack->getAccum();
238 // True to find equals signs in arguments
240 // True to take notice of pipe characters
243 // True if $i is inside a possible heading
245 // True if there are no more greater-than (>) signs right of $i
247 // Map of tag name => true if there are no more closing tags of given type right of $i
248 $noMoreClosingTag = [];
249 // True to ignore all input up to the next <onlyinclude>
250 $findOnlyinclude = $enableOnlyinclude;
251 // Do a line-start run without outputting an LF character
252 $fakeLineStart = true;
255 // $this->memCheck();
257 if ( $findOnlyinclude ) {
258 // Ignore all input up to the next <onlyinclude>
259 $startPos = strpos( $text, '<onlyinclude>', $i );
260 if ( $startPos === false ) {
261 // Ignored section runs to the end
262 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
265 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
266 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
268 $findOnlyinclude = false;
271 if ( $fakeLineStart ) {
272 $found = 'line-start';
275 # Find next opening brace, closing brace or pipe
276 $search = $searchBase;
277 if ( $stack->top
=== false ) {
278 $currentClosing = '';
280 $currentClosing = $stack->top
->close
;
281 $search .= $currentClosing;
287 // First equals will be for the template
291 # Output literal section, advance input counter
292 $literalLength = strcspn( $text, $search, $i );
293 if ( $literalLength > 0 ) {
294 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
295 $i +
= $literalLength;
297 if ( $i >= $lengthText ) {
298 if ( $currentClosing == "\n" ) {
299 // Do a past-the-end run to finish off the heading
307 $curChar = $curTwoChar = $text[$i];
308 if ( ( $i +
1 ) < $lengthText ) {
309 $curTwoChar .= $text[$i +
1];
311 if ( $curChar == '|' ) {
313 } elseif ( $curChar == '=' ) {
315 } elseif ( $curChar == '<' ) {
317 } elseif ( $curChar == "\n" ) {
321 $found = 'line-start';
323 } elseif ( $curTwoChar == $currentClosing ) {
325 $curChar = $curTwoChar;
326 } elseif ( $curChar == $currentClosing ) {
328 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
329 $curChar = $curTwoChar;
331 $rule = $this->rules
[$curChar];
332 } elseif ( isset( $this->rules
[$curChar] ) ) {
334 $rule = $this->rules
[$curChar];
335 } elseif ( $curChar == '-' ) {
338 # Some versions of PHP have a strcspn which stops on null characters
339 # Ignore and continue
346 if ( $found == 'angle' ) {
348 // Handle </onlyinclude>
349 if ( $enableOnlyinclude
350 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
352 $findOnlyinclude = true;
356 // Determine element name
357 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
358 // Element name missing or not listed
364 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
366 // To avoid leaving blank lines, when a sequence of
367 // space-separated comments is both preceded and followed by
368 // a newline (ignoring spaces), then
369 // trim leading and trailing spaces and the trailing newline.
372 $endPos = strpos( $text, '-->', $i +
4 );
373 if ( $endPos === false ) {
374 // Unclosed comment in input, runs to end
375 $inner = substr( $text, $i );
376 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
379 // Search backwards for leading whitespace
380 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
382 // Search forwards for trailing whitespace
383 // $wsEnd will be the position of the last space (or the '>' if there's none)
384 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
386 // Keep looking forward as long as we're finding more
388 $comments = [ [ $wsStart, $wsEnd ] ];
389 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
390 $c = strpos( $text, '-->', $wsEnd +
4 );
391 if ( $c === false ) {
394 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
395 $comments[] = [ $wsEnd +
1, $c ];
399 // Eat the line if possible
400 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
401 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
402 // it's a possible beneficial b/c break.
403 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
404 && substr( $text, $wsEnd +
1, 1 ) == "\n"
406 // Remove leading whitespace from the end of the accumulator
407 // Sanity check first though
408 $wsLength = $i - $wsStart;
410 && strspn( $accum, " \t", -$wsLength ) === $wsLength
412 $accum = substr( $accum, 0, -$wsLength );
415 // Dump all but the last comment to the accumulator
416 foreach ( $comments as $j => $com ) {
418 $endPos = $com[1] +
1;
419 if ( $j == ( count( $comments ) - 1 ) ) {
422 $inner = substr( $text, $startPos, $endPos - $startPos );
423 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
426 // Do a line-start run next time to look for headings after the comment
427 $fakeLineStart = true;
429 // No line to eat, just take the comment itself
435 $part = $stack->top
->getCurrentPart();
436 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
437 $part->visualEnd
= $wsStart;
439 // Else comments abutting, no change in visual end
440 $part->commentEnd
= $endPos;
443 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
444 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
449 $lowerName = strtolower( $name );
450 $attrStart = $i +
strlen( $name ) +
1;
453 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
454 if ( $tagEndPos === false ) {
455 // Infinite backtrack
456 // Disable tag search to prevent worst-case O(N^2) performance
463 // Handle ignored tags
464 if ( in_array( $lowerName, $ignoredTags ) ) {
466 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
473 if ( $text[$tagEndPos - 1] == '/' ) {
474 $attrEnd = $tagEndPos - 1;
479 $attrEnd = $tagEndPos;
482 !isset( $noMoreClosingTag[$name] ) &&
483 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
484 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
486 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
487 $i = $matches[0][1] +
strlen( $matches[0][0] );
488 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
491 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
492 // Let it run out to the end of the text.
493 $inner = substr( $text, $tagEndPos +
1 );
497 // Don't match the tag, treat opening tag as literal and resume parsing.
499 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
500 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
501 $noMoreClosingTag[$name] = true;
506 // <includeonly> and <noinclude> just become <ignore> tags
507 if ( in_array( $lowerName, $ignoredElements ) ) {
508 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
514 if ( $attrEnd <= $attrStart ) {
517 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
519 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
520 // Note that the attr element contains the whitespace between name and attribute,
521 // this is necessary for precise reconstruction during pre-save transform.
522 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
523 if ( $inner !== null ) {
524 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
526 $accum .= $close . '</ext>';
527 } elseif ( $found == 'line-start' ) {
528 // Is this the start of a heading?
529 // Line break belongs before the heading element in any case
530 if ( $fakeLineStart ) {
531 $fakeLineStart = false;
537 $count = strspn( $text, '=', $i, 6 );
538 if ( $count == 1 && $findEquals ) {
539 // DWIM: This looks kind of like a name/value separator.
540 // Let's let the equals handler have it and break the
541 // potential heading. This is heuristic, but AFAICT the
542 // methods for completely correct disambiguation are very
544 } elseif ( $count > 0 ) {
548 'parts' => [ new PPDPart( str_repeat( '=', $count ) ) ],
551 $stack->push( $piece );
552 $accum =& $stack->getAccum();
553 $flags = $stack->getFlags();
557 } elseif ( $found == 'line-end' ) {
558 $piece = $stack->top
;
559 // A heading must be open, otherwise \n wouldn't have been in the search list
560 assert( $piece->open
=== "\n" );
561 $part = $piece->getCurrentPart();
562 // Search back through the input to see if it has a proper close.
563 // Do this using the reversed string since the other solutions
564 // (end anchor, etc.) are inefficient.
565 $wsLength = strspn( $revText, " \t", $lengthText - $i );
566 $searchStart = $i - $wsLength;
567 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
568 // Comment found at line end
569 // Search for equals signs before the comment
570 $searchStart = $part->visualEnd
;
571 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
573 $count = $piece->count
;
574 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
575 if ( $equalsLength > 0 ) {
576 if ( $searchStart - $equalsLength == $piece->startPos
) {
577 // This is just a single string of equals signs on its own line
578 // Replicate the doHeadings behavior /={count}(.+)={count}/
579 // First find out how many equals signs there really are (don't stop at 6)
580 $count = $equalsLength;
584 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
587 $count = min( $equalsLength, $count );
590 // Normal match, output <h>
591 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
594 // Single equals sign on its own line, count=0
598 // No match, no <h>, just pass down the inner text
603 $accum =& $stack->getAccum();
604 $flags = $stack->getFlags();
607 // Append the result to the enclosing accumulator
609 // Note that we do NOT increment the input pointer.
610 // This is because the closing linebreak could be the opening linebreak of
611 // another heading. Infinite loops are avoided because the next iteration MUST
612 // hit the heading open case above, which unconditionally increments the
614 } elseif ( $found == 'open' ) {
615 # count opening brace characters
616 $curLen = strlen( $curChar );
617 $count = ( $curLen > 1 ) ?
1 : strspn( $text, $curChar, $i );
619 # we need to add to stack only if opening brace count is enough for one of the rules
620 if ( $count >= $rule['min'] ) {
621 # Add it to the stack
624 'close' => $rule['end'],
626 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
629 $stack->push( $piece );
630 $accum =& $stack->getAccum();
631 $flags = $stack->getFlags();
634 # Add literal brace(s)
635 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
637 $i +
= $curLen * $count;
638 } elseif ( $found == 'close' ) {
639 $piece = $stack->top
;
640 # lets check if there are enough characters for closing brace
641 $maxCount = $piece->count
;
642 $curLen = strlen( $curChar );
643 $count = ( $curLen > 1 ) ?
1 : strspn( $text, $curChar, $i, $maxCount );
645 # check for maximum matching characters (if there are 5 closing
646 # characters, we will probably need only 3 - depending on the rules)
647 $rule = $this->rules
[$piece->open
];
648 if ( $count > $rule['max'] ) {
649 # The specified maximum exists in the callback array, unless the caller
651 $matchingCount = $rule['max'];
653 # Count is less than the maximum
654 # Skip any gaps in the callback array to find the true largest match
655 # Need to use array_key_exists not isset because the callback can be null
656 $matchingCount = $count;
657 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
662 if ( $matchingCount <= 0 ) {
663 # No matching element found in callback array
664 # Output a literal closing brace and continue
665 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
666 $i +
= $curLen * $count;
669 $name = $rule['names'][$matchingCount];
670 if ( $name === null ) {
671 // No element, just literal text
672 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
675 # Note: $parts is already XML, does not need to be encoded further
676 $parts = $piece->parts
;
677 $title = $parts[0]->out
;
680 # The invocation is at the start of the line if lineStart is set in
681 # the stack, and all opening brackets are used up.
682 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
683 $attr = ' lineStart="1"';
688 $element = "<$name$attr>";
689 $element .= "<title>$title</title>";
691 foreach ( $parts as $part ) {
692 if ( isset( $part->eqpos
) ) {
693 $argName = substr( $part->out
, 0, $part->eqpos
);
694 $argValue = substr( $part->out
, $part->eqpos +
1 );
695 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
697 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
701 $element .= "</$name>";
704 # Advance input pointer
705 $i +
= $curLen * $matchingCount;
709 $accum =& $stack->getAccum();
711 # Re-add the old stack element if it still has unmatched opening characters remaining
712 if ( $matchingCount < $piece->count
) {
713 $piece->parts
= [ new PPDPart
];
714 $piece->count
-= $matchingCount;
715 # do we still qualify for any callback with remaining count?
716 $min = $this->rules
[$piece->open
]['min'];
717 if ( $piece->count
>= $min ) {
718 $stack->push( $piece );
719 $accum =& $stack->getAccum();
721 $accum .= str_repeat( $piece->open
, $piece->count
);
724 $flags = $stack->getFlags();
727 # Add XML element to the enclosing accumulator
729 } elseif ( $found == 'pipe' ) {
730 $findEquals = true; // shortcut for getFlags()
732 $accum =& $stack->getAccum();
734 } elseif ( $found == 'equals' ) {
735 $findEquals = false; // shortcut for getFlags()
736 $stack->getCurrentPart()->eqpos
= strlen( $accum );
739 } elseif ( $found == 'dash' ) {
745 # Output any remaining unclosed brackets
746 foreach ( $stack->stack
as $piece ) {
747 $stack->rootAccum
.= $piece->breakSyntax();
749 $stack->rootAccum
.= '</root>';
750 $xml = $stack->rootAccum
;
757 * Stack class to help Preprocessor::preprocessToObj()
761 public $stack, $rootAccum;
768 public $elementClass = 'PPDStackElement';
770 public static $false = false;
772 public function __construct() {
775 $this->rootAccum
= '';
776 $this->accum
=& $this->rootAccum
;
782 public function count() {
783 return count( $this->stack
);
786 public function &getAccum() {
790 public function getCurrentPart() {
791 if ( $this->top
=== false ) {
794 return $this->top
->getCurrentPart();
798 public function push( $data ) {
799 if ( $data instanceof $this->elementClass
) {
800 $this->stack
[] = $data;
802 $class = $this->elementClass
;
803 $this->stack
[] = new $class( $data );
805 $this->top
= $this->stack
[count( $this->stack
) - 1];
806 $this->accum
=& $this->top
->getAccum();
809 public function pop() {
810 if ( !count( $this->stack
) ) {
811 throw new MWException( __METHOD__
. ': no elements remaining' );
813 $temp = array_pop( $this->stack
);
815 if ( count( $this->stack
) ) {
816 $this->top
= $this->stack
[count( $this->stack
) - 1];
817 $this->accum
=& $this->top
->getAccum();
819 $this->top
= self
::$false;
820 $this->accum
=& $this->rootAccum
;
825 public function addPart( $s = '' ) {
826 $this->top
->addPart( $s );
827 $this->accum
=& $this->top
->getAccum();
833 public function getFlags() {
834 if ( !count( $this->stack
) ) {
836 'findEquals' => false,
838 'inHeading' => false,
841 return $this->top
->getFlags();
849 class PPDStackElement
{
851 * @var string Opening character (\n for heading)
856 * @var string Matching closing character
861 * @var int Number of opening characters found (number of "=" for heading)
866 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
871 * @var bool True if the open char appeared at the start of the input line.
872 * Not set for headings.
876 public $partClass = 'PPDPart';
878 public function __construct( $data = [] ) {
879 $class = $this->partClass
;
880 $this->parts
= [ new $class ];
882 foreach ( $data as $name => $value ) {
883 $this->$name = $value;
887 public function &getAccum() {
888 return $this->parts
[count( $this->parts
) - 1]->out
;
891 public function addPart( $s = '' ) {
892 $class = $this->partClass
;
893 $this->parts
[] = new $class( $s );
896 public function getCurrentPart() {
897 return $this->parts
[count( $this->parts
) - 1];
903 public function getFlags() {
904 $partCount = count( $this->parts
);
905 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
907 'findPipe' => $findPipe,
908 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
909 'inHeading' => $this->open
== "\n",
914 * Get the output string that would result if the close is not found.
916 * @param bool|int $openingCount
919 public function breakSyntax( $openingCount = false ) {
920 if ( $this->open
== "\n" ) {
921 $s = $this->parts
[0]->out
;
923 if ( $openingCount === false ) {
924 $openingCount = $this->count
;
926 $s = str_repeat( $this->open
, $openingCount );
928 foreach ( $this->parts
as $part ) {
946 * @var string Output accumulator string
950 // Optional member variables:
951 // eqpos Position of equals sign in output accumulator
952 // commentEnd Past-the-end input pointer for the last comment encountered
953 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
955 public function __construct( $out = '' ) {
961 * An expansion frame, used as a context to expand the result of preprocessToObj()
964 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
965 class PPFrame_DOM
implements PPFrame
{
966 // @codingStandardsIgnoreEnd
971 public $preprocessor;
985 * Hashtable listing templates which are disallowed for expansion in this frame,
986 * having been encountered previously in parent frames.
988 public $loopCheckHash;
991 * Recursion depth of this frame, top = 0
992 * Note that this is NOT the same as expansion depth in expand()
996 private $volatile = false;
1002 protected $childExpansionCache;
1005 * Construct a new preprocessor frame.
1006 * @param Preprocessor $preprocessor The parent preprocessor
1008 public function __construct( $preprocessor ) {
1009 $this->preprocessor
= $preprocessor;
1010 $this->parser
= $preprocessor->parser
;
1011 $this->title
= $this->parser
->mTitle
;
1012 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
1013 $this->loopCheckHash
= [];
1015 $this->childExpansionCache
= [];
1019 * Create a new child frame
1020 * $args is optionally a multi-root PPNode or array containing the template arguments
1022 * @param bool|array $args
1023 * @param Title|bool $title
1024 * @param int $indexOffset
1025 * @return PPTemplateFrame_DOM
1027 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1030 if ( $title === false ) {
1031 $title = $this->title
;
1033 if ( $args !== false ) {
1035 if ( $args instanceof PPNode
) {
1036 $args = $args->node
;
1038 foreach ( $args as $arg ) {
1039 if ( $arg instanceof PPNode
) {
1042 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1043 $xpath = new DOMXPath( $arg->ownerDocument
);
1046 $nameNodes = $xpath->query( 'name', $arg );
1047 $value = $xpath->query( 'value', $arg );
1048 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1049 // Numbered parameter
1050 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1051 $index = $index - $indexOffset;
1052 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1053 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1054 wfEscapeWikiText( $this->title
),
1055 wfEscapeWikiText( $title ),
1056 wfEscapeWikiText( $index ) )->text() );
1057 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1059 $numberedArgs[$index] = $value->item( 0 );
1060 unset( $namedArgs[$index] );
1063 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1064 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1065 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1066 wfEscapeWikiText( $this->title
),
1067 wfEscapeWikiText( $title ),
1068 wfEscapeWikiText( $name ) )->text() );
1069 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1071 $namedArgs[$name] = $value->item( 0 );
1072 unset( $numberedArgs[$name] );
1076 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1080 * @throws MWException
1081 * @param string|int $key
1082 * @param string|PPNode_DOM|DOMDocument $root
1086 public function cachedExpand( $key, $root, $flags = 0 ) {
1087 // we don't have a parent, so we don't have a cache
1088 return $this->expand( $root, $flags );
1092 * @throws MWException
1093 * @param string|PPNode_DOM|DOMDocument $root
1097 public function expand( $root, $flags = 0 ) {
1098 static $expansionDepth = 0;
1099 if ( is_string( $root ) ) {
1103 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1104 $this->parser
->limitationWarn( 'node-count-exceeded',
1105 $this->parser
->mPPNodeCount
,
1106 $this->parser
->mOptions
->getMaxPPNodeCount()
1108 return '<span class="error">Node-count limit exceeded</span>';
1111 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1112 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1114 $this->parser
->mOptions
->getMaxPPExpandDepth()
1116 return '<span class="error">Expansion depth limit exceeded</span>';
1119 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1120 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1123 if ( $root instanceof PPNode_DOM
) {
1124 $root = $root->node
;
1126 if ( $root instanceof DOMDocument
) {
1127 $root = $root->documentElement
;
1130 $outStack = [ '', '' ];
1131 $iteratorStack = [ false, $root ];
1132 $indexStack = [ 0, 0 ];
1134 while ( count( $iteratorStack ) > 1 ) {
1135 $level = count( $outStack ) - 1;
1136 $iteratorNode =& $iteratorStack[$level];
1137 $out =& $outStack[$level];
1138 $index =& $indexStack[$level];
1140 if ( $iteratorNode instanceof PPNode_DOM
) {
1141 $iteratorNode = $iteratorNode->node
;
1144 if ( is_array( $iteratorNode ) ) {
1145 if ( $index >= count( $iteratorNode ) ) {
1146 // All done with this iterator
1147 $iteratorStack[$level] = false;
1148 $contextNode = false;
1150 $contextNode = $iteratorNode[$index];
1153 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1154 if ( $index >= $iteratorNode->length
) {
1155 // All done with this iterator
1156 $iteratorStack[$level] = false;
1157 $contextNode = false;
1159 $contextNode = $iteratorNode->item( $index );
1163 // Copy to $contextNode and then delete from iterator stack,
1164 // because this is not an iterator but we do have to execute it once
1165 $contextNode = $iteratorStack[$level];
1166 $iteratorStack[$level] = false;
1169 if ( $contextNode instanceof PPNode_DOM
) {
1170 $contextNode = $contextNode->node
;
1173 $newIterator = false;
1175 if ( $contextNode === false ) {
1177 } elseif ( is_string( $contextNode ) ) {
1178 $out .= $contextNode;
1179 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1180 $newIterator = $contextNode;
1181 } elseif ( $contextNode instanceof DOMNode
) {
1182 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1183 $out .= $contextNode->nodeValue
;
1184 } elseif ( $contextNode->nodeName
== 'template' ) {
1185 # Double-brace expansion
1186 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1187 $titles = $xpath->query( 'title', $contextNode );
1188 $title = $titles->item( 0 );
1189 $parts = $xpath->query( 'part', $contextNode );
1190 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1191 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1193 $lineStart = $contextNode->getAttribute( 'lineStart' );
1195 'title' => new PPNode_DOM( $title ),
1196 'parts' => new PPNode_DOM( $parts ),
1197 'lineStart' => $lineStart ];
1198 $ret = $this->parser
->braceSubstitution( $params, $this );
1199 if ( isset( $ret['object'] ) ) {
1200 $newIterator = $ret['object'];
1202 $out .= $ret['text'];
1205 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1206 # Triple-brace expansion
1207 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1208 $titles = $xpath->query( 'title', $contextNode );
1209 $title = $titles->item( 0 );
1210 $parts = $xpath->query( 'part', $contextNode );
1211 if ( $flags & PPFrame
::NO_ARGS
) {
1212 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1215 'title' => new PPNode_DOM( $title ),
1216 'parts' => new PPNode_DOM( $parts ) ];
1217 $ret = $this->parser
->argSubstitution( $params, $this );
1218 if ( isset( $ret['object'] ) ) {
1219 $newIterator = $ret['object'];
1221 $out .= $ret['text'];
1224 } elseif ( $contextNode->nodeName
== 'comment' ) {
1225 # HTML-style comment
1226 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1227 # Not in RECOVER_COMMENTS mode (msgnw) though.
1228 if ( ( $this->parser
->ot
['html']
1229 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1230 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1231 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1234 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1235 # Add a strip marker in PST mode so that pstPass2() can
1236 # run some old-fashioned regexes on the result.
1237 # Not in RECOVER_COMMENTS mode (extractSections) though.
1238 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1240 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1241 $out .= $contextNode->textContent
;
1243 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1244 # Output suppression used by <includeonly> etc.
1245 # OT_WIKI will only respect <ignore> in substed templates.
1246 # The other output types respect it unless NO_IGNORE is set.
1247 # extractSections() sets NO_IGNORE and so never respects it.
1248 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1249 ||
( $flags & PPFrame
::NO_IGNORE
)
1251 $out .= $contextNode->textContent
;
1255 } elseif ( $contextNode->nodeName
== 'ext' ) {
1257 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1258 $names = $xpath->query( 'name', $contextNode );
1259 $attrs = $xpath->query( 'attr', $contextNode );
1260 $inners = $xpath->query( 'inner', $contextNode );
1261 $closes = $xpath->query( 'close', $contextNode );
1262 if ( $flags & PPFrame
::NO_TAGS
) {
1263 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1264 if ( $attrs->length
> 0 ) {
1265 $s .= $this->expand( $attrs->item( 0 ), $flags );
1267 if ( $inners->length
> 0 ) {
1268 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1269 if ( $closes->length
> 0 ) {
1270 $s .= $this->expand( $closes->item( 0 ), $flags );
1278 'name' => new PPNode_DOM( $names->item( 0 ) ),
1279 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1280 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1281 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1283 $out .= $this->parser
->extensionSubstitution( $params, $this );
1285 } elseif ( $contextNode->nodeName
== 'h' ) {
1287 $s = $this->expand( $contextNode->childNodes
, $flags );
1289 # Insert a heading marker only for <h> children of <root>
1290 # This is to stop extractSections from going over multiple tree levels
1291 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1292 # Insert heading index marker
1293 $headingIndex = $contextNode->getAttribute( 'i' );
1294 $titleText = $this->title
->getPrefixedDBkey();
1295 $this->parser
->mHeadings
[] = [ $titleText, $headingIndex ];
1296 $serial = count( $this->parser
->mHeadings
) - 1;
1297 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1298 $count = $contextNode->getAttribute( 'level' );
1299 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1300 $this->parser
->mStripState
->addGeneral( $marker, '' );
1304 # Generic recursive expansion
1305 $newIterator = $contextNode->childNodes
;
1308 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1311 if ( $newIterator !== false ) {
1312 if ( $newIterator instanceof PPNode_DOM
) {
1313 $newIterator = $newIterator->node
;
1316 $iteratorStack[] = $newIterator;
1318 } elseif ( $iteratorStack[$level] === false ) {
1319 // Return accumulated value to parent
1320 // With tail recursion
1321 while ( $iteratorStack[$level] === false && $level > 0 ) {
1322 $outStack[$level - 1] .= $out;
1323 array_pop( $outStack );
1324 array_pop( $iteratorStack );
1325 array_pop( $indexStack );
1331 return $outStack[0];
1335 * @param string $sep
1337 * @param string|PPNode_DOM|DOMDocument $args,...
1340 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1341 $args = array_slice( func_get_args(), 2 );
1345 foreach ( $args as $root ) {
1346 if ( $root instanceof PPNode_DOM
) {
1347 $root = $root->node
;
1349 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1352 foreach ( $root as $node ) {
1358 $s .= $this->expand( $node, $flags );
1365 * Implode with no flags specified
1366 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1368 * @param string $sep
1369 * @param string|PPNode_DOM|DOMDocument $args,...
1372 public function implode( $sep /*, ... */ ) {
1373 $args = array_slice( func_get_args(), 1 );
1377 foreach ( $args as $root ) {
1378 if ( $root instanceof PPNode_DOM
) {
1379 $root = $root->node
;
1381 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1384 foreach ( $root as $node ) {
1390 $s .= $this->expand( $node );
1397 * Makes an object that, when expand()ed, will be the same as one obtained
1400 * @param string $sep
1401 * @param string|PPNode_DOM|DOMDocument $args,...
1404 public function virtualImplode( $sep /*, ... */ ) {
1405 $args = array_slice( func_get_args(), 1 );
1409 foreach ( $args as $root ) {
1410 if ( $root instanceof PPNode_DOM
) {
1411 $root = $root->node
;
1413 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1416 foreach ( $root as $node ) {
1429 * Virtual implode with brackets
1430 * @param string $start
1431 * @param string $sep
1432 * @param string $end
1433 * @param string|PPNode_DOM|DOMDocument $args,...
1436 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1437 $args = array_slice( func_get_args(), 3 );
1441 foreach ( $args as $root ) {
1442 if ( $root instanceof PPNode_DOM
) {
1443 $root = $root->node
;
1445 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1448 foreach ( $root as $node ) {
1461 public function __toString() {
1465 public function getPDBK( $level = false ) {
1466 if ( $level === false ) {
1467 return $this->title
->getPrefixedDBkey();
1469 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1476 public function getArguments() {
1483 public function getNumberedArguments() {
1490 public function getNamedArguments() {
1495 * Returns true if there are no arguments in this frame
1499 public function isEmpty() {
1504 * @param int|string $name
1505 * @return bool Always false in this implementation.
1507 public function getArgument( $name ) {
1512 * Returns true if the infinite loop check is OK, false if a loop is detected
1514 * @param Title $title
1517 public function loopCheck( $title ) {
1518 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1522 * Return true if the frame is a template frame
1526 public function isTemplate() {
1531 * Get a title of frame
1535 public function getTitle() {
1536 return $this->title
;
1540 * Set the volatile flag
1544 public function setVolatile( $flag = true ) {
1545 $this->volatile
= $flag;
1549 * Get the volatile flag
1553 public function isVolatile() {
1554 return $this->volatile
;
1562 public function setTTL( $ttl ) {
1563 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1573 public function getTTL() {
1579 * Expansion frame with template arguments
1582 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1583 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1584 // @codingStandardsIgnoreEnd
1586 public $numberedArgs, $namedArgs;
1592 public $numberedExpansionCache, $namedExpansionCache;
1595 * @param Preprocessor $preprocessor
1596 * @param bool|PPFrame_DOM $parent
1597 * @param array $numberedArgs
1598 * @param array $namedArgs
1599 * @param bool|Title $title
1601 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1602 $namedArgs = [], $title = false
1604 parent
::__construct( $preprocessor );
1606 $this->parent
= $parent;
1607 $this->numberedArgs
= $numberedArgs;
1608 $this->namedArgs
= $namedArgs;
1609 $this->title
= $title;
1610 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1611 $this->titleCache
= $parent->titleCache
;
1612 $this->titleCache
[] = $pdbk;
1613 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1614 if ( $pdbk !== false ) {
1615 $this->loopCheckHash
[$pdbk] = true;
1617 $this->depth
= $parent->depth +
1;
1618 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1621 public function __toString() {
1624 $args = $this->numberedArgs +
$this->namedArgs
;
1625 foreach ( $args as $name => $value ) {
1631 $s .= "\"$name\":\"" .
1632 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1639 * @throws MWException
1640 * @param string|int $key
1641 * @param string|PPNode_DOM|DOMDocument $root
1645 public function cachedExpand( $key, $root, $flags = 0 ) {
1646 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1647 return $this->parent
->childExpansionCache
[$key];
1649 $retval = $this->expand( $root, $flags );
1650 if ( !$this->isVolatile() ) {
1651 $this->parent
->childExpansionCache
[$key] = $retval;
1657 * Returns true if there are no arguments in this frame
1661 public function isEmpty() {
1662 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1665 public function getArguments() {
1667 foreach ( array_merge(
1668 array_keys( $this->numberedArgs
),
1669 array_keys( $this->namedArgs
) ) as $key ) {
1670 $arguments[$key] = $this->getArgument( $key );
1675 public function getNumberedArguments() {
1677 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1678 $arguments[$key] = $this->getArgument( $key );
1683 public function getNamedArguments() {
1685 foreach ( array_keys( $this->namedArgs
) as $key ) {
1686 $arguments[$key] = $this->getArgument( $key );
1693 * @return string|bool
1695 public function getNumberedArgument( $index ) {
1696 if ( !isset( $this->numberedArgs
[$index] ) ) {
1699 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1700 # No trimming for unnamed arguments
1701 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1702 $this->numberedArgs
[$index],
1703 PPFrame
::STRIP_COMMENTS
1706 return $this->numberedExpansionCache
[$index];
1710 * @param string $name
1711 * @return string|bool
1713 public function getNamedArgument( $name ) {
1714 if ( !isset( $this->namedArgs
[$name] ) ) {
1717 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1718 # Trim named arguments post-expand, for backwards compatibility
1719 $this->namedExpansionCache
[$name] = trim(
1720 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1722 return $this->namedExpansionCache
[$name];
1726 * @param int|string $name
1727 * @return string|bool
1729 public function getArgument( $name ) {
1730 $text = $this->getNumberedArgument( $name );
1731 if ( $text === false ) {
1732 $text = $this->getNamedArgument( $name );
1738 * Return true if the frame is a template frame
1742 public function isTemplate() {
1746 public function setVolatile( $flag = true ) {
1747 parent
::setVolatile( $flag );
1748 $this->parent
->setVolatile( $flag );
1751 public function setTTL( $ttl ) {
1752 parent
::setTTL( $ttl );
1753 $this->parent
->setTTL( $ttl );
1758 * Expansion frame with custom arguments
1761 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1762 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1763 // @codingStandardsIgnoreEnd
1767 public function __construct( $preprocessor, $args ) {
1768 parent
::__construct( $preprocessor );
1769 $this->args
= $args;
1772 public function __toString() {
1775 foreach ( $this->args
as $name => $value ) {
1781 $s .= "\"$name\":\"" .
1782 str_replace( '"', '\\"', $value->__toString() ) . '"';
1791 public function isEmpty() {
1792 return !count( $this->args
);
1796 * @param int|string $index
1797 * @return string|bool
1799 public function getArgument( $index ) {
1800 if ( !isset( $this->args
[$index] ) ) {
1803 return $this->args
[$index];
1806 public function getArguments() {
1814 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1815 class PPNode_DOM
implements PPNode
{
1816 // @codingStandardsIgnoreEnd
1824 public function __construct( $node, $xpath = false ) {
1825 $this->node
= $node;
1831 public function getXPath() {
1832 if ( $this->xpath
=== null ) {
1833 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1835 return $this->xpath
;
1838 public function __toString() {
1839 if ( $this->node
instanceof DOMNodeList
) {
1841 foreach ( $this->node
as $node ) {
1842 $s .= $node->ownerDocument
->saveXML( $node );
1845 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1851 * @return bool|PPNode_DOM
1853 public function getChildren() {
1854 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1858 * @return bool|PPNode_DOM
1860 public function getFirstChild() {
1861 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1865 * @return bool|PPNode_DOM
1867 public function getNextSibling() {
1868 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1872 * @param string $type
1874 * @return bool|PPNode_DOM
1876 public function getChildrenOfType( $type ) {
1877 return new self( $this->getXPath()->query( $type, $this->node
) );
1883 public function getLength() {
1884 if ( $this->node
instanceof DOMNodeList
) {
1885 return $this->node
->length
;
1893 * @return bool|PPNode_DOM
1895 public function item( $i ) {
1896 $item = $this->node
->item( $i );
1897 return $item ?
new self( $item ) : false;
1903 public function getName() {
1904 if ( $this->node
instanceof DOMNodeList
) {
1907 return $this->node
->nodeName
;
1912 * Split a "<part>" node into an associative array containing:
1913 * - name PPNode name
1914 * - index String index
1915 * - value PPNode value
1917 * @throws MWException
1920 public function splitArg() {
1921 $xpath = $this->getXPath();
1922 $names = $xpath->query( 'name', $this->node
);
1923 $values = $xpath->query( 'value', $this->node
);
1924 if ( !$names->length ||
!$values->length
) {
1925 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1927 $name = $names->item( 0 );
1928 $index = $name->getAttribute( 'index' );
1930 'name' => new self( $name ),
1932 'value' => new self( $values->item( 0 ) ) ];
1936 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1937 * All values in the resulting array are PPNodes. Inner and close are optional.
1939 * @throws MWException
1942 public function splitExt() {
1943 $xpath = $this->getXPath();
1944 $names = $xpath->query( 'name', $this->node
);
1945 $attrs = $xpath->query( 'attr', $this->node
);
1946 $inners = $xpath->query( 'inner', $this->node
);
1947 $closes = $xpath->query( 'close', $this->node
);
1948 if ( !$names->length ||
!$attrs->length
) {
1949 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1952 'name' => new self( $names->item( 0 ) ),
1953 'attr' => new self( $attrs->item( 0 ) ) ];
1954 if ( $inners->length
) {
1955 $parts['inner'] = new self( $inners->item( 0 ) );
1957 if ( $closes->length
) {
1958 $parts['close'] = new self( $closes->item( 0 ) );
1964 * Split a "<h>" node
1965 * @throws MWException
1968 public function splitHeading() {
1969 if ( $this->getName() !== 'h' ) {
1970 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1973 'i' => $this->node
->getAttribute( 'i' ),
1974 'level' => $this->node
->getAttribute( 'level' ),
1975 'contents' => $this->getChildren()