3 * Preprocessor using PHP's dom extension
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
27 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
28 class Preprocessor_DOM
extends Preprocessor
{
29 // @codingStandardsIgnoreEnd
38 const CACHE_PREFIX
= 'preprocess-xml';
40 public function __construct( $parser ) {
41 $this->parser
= $parser;
42 $mem = ini_get( 'memory_limit' );
43 $this->memoryLimit
= false;
44 if ( strval( $mem ) !== '' && $mem != -1 ) {
45 if ( preg_match( '/^\d+$/', $mem ) ) {
46 $this->memoryLimit
= $mem;
47 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
48 $this->memoryLimit
= $m[1] * 1048576;
56 public function newFrame() {
57 return new PPFrame_DOM( $this );
62 * @return PPCustomFrame_DOM
64 public function newCustomFrame( $args ) {
65 return new PPCustomFrame_DOM( $this, $args );
69 * @param array $values
73 public function newPartNodeArray( $values ) {
74 // NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
77 foreach ( $values as $k => $val ) {
79 $xml .= "<part><name index=\"$k\"/><value>"
80 . htmlspecialchars( $val ) . "</value></part>";
82 $xml .= "<part><name>" . htmlspecialchars( $k )
83 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
89 $dom = new DOMDocument();
90 MediaWiki\
suppressWarnings();
91 $result = $dom->loadXML( $xml );
92 MediaWiki\restoreWarnings
();
94 // Try running the XML through UtfNormal to get rid of invalid characters
95 $xml = UtfNormal\Validator
::cleanUp( $xml );
96 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
97 // don't barf when the XML is >256 levels deep
98 $result = $dom->loadXML( $xml, 1 << 19 );
102 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
105 $root = $dom->documentElement
;
106 $node = new PPNode_DOM( $root->childNodes
);
111 * @throws MWException
114 public function memCheck() {
115 if ( $this->memoryLimit
=== false ) {
118 $usage = memory_get_usage();
119 if ( $usage > $this->memoryLimit
* 0.9 ) {
120 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
121 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
123 return $usage <= $this->memoryLimit
* 0.8;
127 * Preprocess some wikitext and return the document tree.
128 * This is the ghost of Parser::replace_variables().
130 * @param string $text The text to parse
131 * @param int $flags Bitwise combination of:
132 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
133 * as if the text is being included. Default
134 * is to assume a direct page view.
136 * The generated DOM tree must depend only on the input text and the flags.
137 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
139 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
140 * change in the DOM tree for a given text, must be passed through the section identifier
141 * in the section edit link and thus back to extractSections().
143 * The output of this function is currently only cached in process memory, but a persistent
144 * cache may be implemented at a later date which takes further advantage of these strict
145 * dependency requirements.
147 * @throws MWException
150 public function preprocessToObj( $text, $flags = 0 ) {
152 $xml = $this->cacheGetTree( $text, $flags );
153 if ( $xml === false ) {
154 $xml = $this->preprocessToXml( $text, $flags );
155 $this->cacheSetTree( $text, $flags, $xml );
158 // Fail if the number of elements exceeds acceptable limits
159 // Do not attempt to generate the DOM
160 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
161 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
162 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
163 // if ( $cacheable ) { ... }
164 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
167 $dom = new DOMDocument
;
168 MediaWiki\
suppressWarnings();
169 $result = $dom->loadXML( $xml );
170 MediaWiki\restoreWarnings
();
172 // Try running the XML through UtfNormal to get rid of invalid characters
173 $xml = UtfNormal\Validator
::cleanUp( $xml );
174 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
175 // don't barf when the XML is >256 levels deep.
176 $result = $dom->loadXML( $xml, 1 << 19 );
179 $obj = new PPNode_DOM( $dom->documentElement
);
182 // if ( $cacheable ) { ... }
185 throw new MWException( __METHOD__
. ' generated invalid XML' );
191 * @param string $text
195 public function preprocessToXml( $text, $flags = 0 ) {
196 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
198 $xmlishElements = $this->parser
->getStripList();
199 $enableOnlyinclude = false;
200 if ( $forInclusion ) {
201 $ignoredTags = array( 'includeonly', '/includeonly' );
202 $ignoredElements = array( 'noinclude' );
203 $xmlishElements[] = 'noinclude';
204 if ( strpos( $text, '<onlyinclude>' ) !== false
205 && strpos( $text, '</onlyinclude>' ) !== false
207 $enableOnlyinclude = true;
210 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
211 $ignoredElements = array( 'includeonly' );
212 $xmlishElements[] = 'includeonly';
214 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
216 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
217 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
219 $stack = new PPDStack
;
221 $searchBase = "[{<\n"; # }
222 // For fast reverse searches
223 $revText = strrev( $text );
224 $lengthText = strlen( $text );
226 // Input pointer, starts out pointing to a pseudo-newline before the start
228 // Current accumulator
229 $accum =& $stack->getAccum();
231 // True to find equals signs in arguments
233 // True to take notice of pipe characters
236 // True if $i is inside a possible heading
238 // True if there are no more greater-than (>) signs right of $i
240 // True to ignore all input up to the next <onlyinclude>
241 $findOnlyinclude = $enableOnlyinclude;
242 // Do a line-start run without outputting an LF character
243 $fakeLineStart = true;
246 // $this->memCheck();
248 if ( $findOnlyinclude ) {
249 // Ignore all input up to the next <onlyinclude>
250 $startPos = strpos( $text, '<onlyinclude>', $i );
251 if ( $startPos === false ) {
252 // Ignored section runs to the end
253 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
256 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
257 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
259 $findOnlyinclude = false;
262 if ( $fakeLineStart ) {
263 $found = 'line-start';
266 # Find next opening brace, closing brace or pipe
267 $search = $searchBase;
268 if ( $stack->top
=== false ) {
269 $currentClosing = '';
271 $currentClosing = $stack->top
->close
;
272 $search .= $currentClosing;
278 // First equals will be for the template
282 # Output literal section, advance input counter
283 $literalLength = strcspn( $text, $search, $i );
284 if ( $literalLength > 0 ) {
285 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
286 $i +
= $literalLength;
288 if ( $i >= $lengthText ) {
289 if ( $currentClosing == "\n" ) {
290 // Do a past-the-end run to finish off the heading
298 $curChar = $text[$i];
299 if ( $curChar == '|' ) {
301 } elseif ( $curChar == '=' ) {
303 } elseif ( $curChar == '<' ) {
305 } elseif ( $curChar == "\n" ) {
309 $found = 'line-start';
311 } elseif ( $curChar == $currentClosing ) {
313 } elseif ( isset( $this->rules
[$curChar] ) ) {
315 $rule = $this->rules
[$curChar];
317 # Some versions of PHP have a strcspn which stops on null characters
318 # Ignore and continue
325 if ( $found == 'angle' ) {
327 // Handle </onlyinclude>
328 if ( $enableOnlyinclude
329 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
331 $findOnlyinclude = true;
335 // Determine element name
336 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
337 // Element name missing or not listed
343 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
345 // To avoid leaving blank lines, when a sequence of
346 // space-separated comments is both preceded and followed by
347 // a newline (ignoring spaces), then
348 // trim leading and trailing spaces and the trailing newline.
351 $endPos = strpos( $text, '-->', $i +
4 );
352 if ( $endPos === false ) {
353 // Unclosed comment in input, runs to end
354 $inner = substr( $text, $i );
355 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
358 // Search backwards for leading whitespace
359 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
361 // Search forwards for trailing whitespace
362 // $wsEnd will be the position of the last space (or the '>' if there's none)
363 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
365 // Keep looking forward as long as we're finding more
367 $comments = array( array( $wsStart, $wsEnd ) );
368 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
369 $c = strpos( $text, '-->', $wsEnd +
4 );
370 if ( $c === false ) {
373 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
374 $comments[] = array( $wsEnd +
1, $c );
378 // Eat the line if possible
379 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
380 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
381 // it's a possible beneficial b/c break.
382 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
383 && substr( $text, $wsEnd +
1, 1 ) == "\n"
385 // Remove leading whitespace from the end of the accumulator
386 // Sanity check first though
387 $wsLength = $i - $wsStart;
389 && strspn( $accum, " \t", -$wsLength ) === $wsLength
391 $accum = substr( $accum, 0, -$wsLength );
394 // Dump all but the last comment to the accumulator
395 foreach ( $comments as $j => $com ) {
397 $endPos = $com[1] +
1;
398 if ( $j == ( count( $comments ) - 1 ) ) {
401 $inner = substr( $text, $startPos, $endPos - $startPos );
402 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
405 // Do a line-start run next time to look for headings after the comment
406 $fakeLineStart = true;
408 // No line to eat, just take the comment itself
414 $part = $stack->top
->getCurrentPart();
415 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
416 $part->visualEnd
= $wsStart;
418 // Else comments abutting, no change in visual end
419 $part->commentEnd
= $endPos;
422 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
423 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
428 $lowerName = strtolower( $name );
429 $attrStart = $i +
strlen( $name ) +
1;
432 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
433 if ( $tagEndPos === false ) {
434 // Infinite backtrack
435 // Disable tag search to prevent worst-case O(N^2) performance
442 // Handle ignored tags
443 if ( in_array( $lowerName, $ignoredTags ) ) {
445 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
452 if ( $text[$tagEndPos - 1] == '/' ) {
453 $attrEnd = $tagEndPos - 1;
458 $attrEnd = $tagEndPos;
460 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
461 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
463 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
464 $i = $matches[0][1] +
strlen( $matches[0][0] );
465 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
467 // No end tag -- let it run out to the end of the text.
468 $inner = substr( $text, $tagEndPos +
1 );
473 // <includeonly> and <noinclude> just become <ignore> tags
474 if ( in_array( $lowerName, $ignoredElements ) ) {
475 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
481 if ( $attrEnd <= $attrStart ) {
484 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
486 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
487 // Note that the attr element contains the whitespace between name and attribute,
488 // this is necessary for precise reconstruction during pre-save transform.
489 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
490 if ( $inner !== null ) {
491 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
493 $accum .= $close . '</ext>';
494 } elseif ( $found == 'line-start' ) {
495 // Is this the start of a heading?
496 // Line break belongs before the heading element in any case
497 if ( $fakeLineStart ) {
498 $fakeLineStart = false;
504 $count = strspn( $text, '=', $i, 6 );
505 if ( $count == 1 && $findEquals ) {
506 // DWIM: This looks kind of like a name/value separator.
507 // Let's let the equals handler have it and break the
508 // potential heading. This is heuristic, but AFAICT the
509 // methods for completely correct disambiguation are very
511 } elseif ( $count > 0 ) {
515 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
518 $stack->push( $piece );
519 $accum =& $stack->getAccum();
520 $flags = $stack->getFlags();
524 } elseif ( $found == 'line-end' ) {
525 $piece = $stack->top
;
526 // A heading must be open, otherwise \n wouldn't have been in the search list
527 assert( '$piece->open == "\n"' );
528 $part = $piece->getCurrentPart();
529 // Search back through the input to see if it has a proper close.
530 // Do this using the reversed string since the other solutions
531 // (end anchor, etc.) are inefficient.
532 $wsLength = strspn( $revText, " \t", $lengthText - $i );
533 $searchStart = $i - $wsLength;
534 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
535 // Comment found at line end
536 // Search for equals signs before the comment
537 $searchStart = $part->visualEnd
;
538 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
540 $count = $piece->count
;
541 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
542 if ( $equalsLength > 0 ) {
543 if ( $searchStart - $equalsLength == $piece->startPos
) {
544 // This is just a single string of equals signs on its own line
545 // Replicate the doHeadings behavior /={count}(.+)={count}/
546 // First find out how many equals signs there really are (don't stop at 6)
547 $count = $equalsLength;
551 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
554 $count = min( $equalsLength, $count );
557 // Normal match, output <h>
558 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
561 // Single equals sign on its own line, count=0
565 // No match, no <h>, just pass down the inner text
570 $accum =& $stack->getAccum();
571 $flags = $stack->getFlags();
574 // Append the result to the enclosing accumulator
576 // Note that we do NOT increment the input pointer.
577 // This is because the closing linebreak could be the opening linebreak of
578 // another heading. Infinite loops are avoided because the next iteration MUST
579 // hit the heading open case above, which unconditionally increments the
581 } elseif ( $found == 'open' ) {
582 # count opening brace characters
583 $count = strspn( $text, $curChar, $i );
585 # we need to add to stack only if opening brace count is enough for one of the rules
586 if ( $count >= $rule['min'] ) {
587 # Add it to the stack
590 'close' => $rule['end'],
592 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
595 $stack->push( $piece );
596 $accum =& $stack->getAccum();
597 $flags = $stack->getFlags();
600 # Add literal brace(s)
601 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
604 } elseif ( $found == 'close' ) {
605 $piece = $stack->top
;
606 # lets check if there are enough characters for closing brace
607 $maxCount = $piece->count
;
608 $count = strspn( $text, $curChar, $i, $maxCount );
610 # check for maximum matching characters (if there are 5 closing
611 # characters, we will probably need only 3 - depending on the rules)
612 $rule = $this->rules
[$piece->open
];
613 if ( $count > $rule['max'] ) {
614 # The specified maximum exists in the callback array, unless the caller
616 $matchingCount = $rule['max'];
618 # Count is less than the maximum
619 # Skip any gaps in the callback array to find the true largest match
620 # Need to use array_key_exists not isset because the callback can be null
621 $matchingCount = $count;
622 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
627 if ( $matchingCount <= 0 ) {
628 # No matching element found in callback array
629 # Output a literal closing brace and continue
630 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
634 $name = $rule['names'][$matchingCount];
635 if ( $name === null ) {
636 // No element, just literal text
637 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
640 # Note: $parts is already XML, does not need to be encoded further
641 $parts = $piece->parts
;
642 $title = $parts[0]->out
;
645 # The invocation is at the start of the line if lineStart is set in
646 # the stack, and all opening brackets are used up.
647 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
648 $attr = ' lineStart="1"';
653 $element = "<$name$attr>";
654 $element .= "<title>$title</title>";
656 foreach ( $parts as $part ) {
657 if ( isset( $part->eqpos
) ) {
658 $argName = substr( $part->out
, 0, $part->eqpos
);
659 $argValue = substr( $part->out
, $part->eqpos +
1 );
660 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
662 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
666 $element .= "</$name>";
669 # Advance input pointer
670 $i +
= $matchingCount;
674 $accum =& $stack->getAccum();
676 # Re-add the old stack element if it still has unmatched opening characters remaining
677 if ( $matchingCount < $piece->count
) {
678 $piece->parts
= array( new PPDPart
);
679 $piece->count
-= $matchingCount;
680 # do we still qualify for any callback with remaining count?
681 $min = $this->rules
[$piece->open
]['min'];
682 if ( $piece->count
>= $min ) {
683 $stack->push( $piece );
684 $accum =& $stack->getAccum();
686 $accum .= str_repeat( $piece->open
, $piece->count
);
689 $flags = $stack->getFlags();
692 # Add XML element to the enclosing accumulator
694 } elseif ( $found == 'pipe' ) {
695 $findEquals = true; // shortcut for getFlags()
697 $accum =& $stack->getAccum();
699 } elseif ( $found == 'equals' ) {
700 $findEquals = false; // shortcut for getFlags()
701 $stack->getCurrentPart()->eqpos
= strlen( $accum );
707 # Output any remaining unclosed brackets
708 foreach ( $stack->stack
as $piece ) {
709 $stack->rootAccum
.= $piece->breakSyntax();
711 $stack->rootAccum
.= '</root>';
712 $xml = $stack->rootAccum
;
719 * Stack class to help Preprocessor::preprocessToObj()
723 public $stack, $rootAccum;
730 public $elementClass = 'PPDStackElement';
732 public static $false = false;
734 public function __construct() {
735 $this->stack
= array();
737 $this->rootAccum
= '';
738 $this->accum
=& $this->rootAccum
;
744 public function count() {
745 return count( $this->stack
);
748 public function &getAccum() {
752 public function getCurrentPart() {
753 if ( $this->top
=== false ) {
756 return $this->top
->getCurrentPart();
760 public function push( $data ) {
761 if ( $data instanceof $this->elementClass
) {
762 $this->stack
[] = $data;
764 $class = $this->elementClass
;
765 $this->stack
[] = new $class( $data );
767 $this->top
= $this->stack
[count( $this->stack
) - 1];
768 $this->accum
=& $this->top
->getAccum();
771 public function pop() {
772 if ( !count( $this->stack
) ) {
773 throw new MWException( __METHOD__
. ': no elements remaining' );
775 $temp = array_pop( $this->stack
);
777 if ( count( $this->stack
) ) {
778 $this->top
= $this->stack
[count( $this->stack
) - 1];
779 $this->accum
=& $this->top
->getAccum();
781 $this->top
= self
::$false;
782 $this->accum
=& $this->rootAccum
;
787 public function addPart( $s = '' ) {
788 $this->top
->addPart( $s );
789 $this->accum
=& $this->top
->getAccum();
795 public function getFlags() {
796 if ( !count( $this->stack
) ) {
798 'findEquals' => false,
800 'inHeading' => false,
803 return $this->top
->getFlags();
811 class PPDStackElement
{
813 * @var string Opening character (\n for heading)
818 * @var string Matching closing character
823 * @var int Number of opening characters found (number of "=" for heading)
828 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
833 * @var bool True if the open char appeared at the start of the input line.
834 * Not set for headings.
838 public $partClass = 'PPDPart';
840 public function __construct( $data = array() ) {
841 $class = $this->partClass
;
842 $this->parts
= array( new $class );
844 foreach ( $data as $name => $value ) {
845 $this->$name = $value;
849 public function &getAccum() {
850 return $this->parts
[count( $this->parts
) - 1]->out
;
853 public function addPart( $s = '' ) {
854 $class = $this->partClass
;
855 $this->parts
[] = new $class( $s );
858 public function getCurrentPart() {
859 return $this->parts
[count( $this->parts
) - 1];
865 public function getFlags() {
866 $partCount = count( $this->parts
);
867 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
869 'findPipe' => $findPipe,
870 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
871 'inHeading' => $this->open
== "\n",
876 * Get the output string that would result if the close is not found.
878 * @param bool|int $openingCount
881 public function breakSyntax( $openingCount = false ) {
882 if ( $this->open
== "\n" ) {
883 $s = $this->parts
[0]->out
;
885 if ( $openingCount === false ) {
886 $openingCount = $this->count
;
888 $s = str_repeat( $this->open
, $openingCount );
890 foreach ( $this->parts
as $part ) {
908 * @var string Output accumulator string
912 // Optional member variables:
913 // eqpos Position of equals sign in output accumulator
914 // commentEnd Past-the-end input pointer for the last comment encountered
915 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
917 public function __construct( $out = '' ) {
923 * An expansion frame, used as a context to expand the result of preprocessToObj()
926 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
927 class PPFrame_DOM
implements PPFrame
{
928 // @codingStandardsIgnoreEnd
933 public $preprocessor;
947 * Hashtable listing templates which are disallowed for expansion in this frame,
948 * having been encountered previously in parent frames.
950 public $loopCheckHash;
953 * Recursion depth of this frame, top = 0
954 * Note that this is NOT the same as expansion depth in expand()
958 private $volatile = false;
964 protected $childExpansionCache;
967 * Construct a new preprocessor frame.
968 * @param Preprocessor $preprocessor The parent preprocessor
970 public function __construct( $preprocessor ) {
971 $this->preprocessor
= $preprocessor;
972 $this->parser
= $preprocessor->parser
;
973 $this->title
= $this->parser
->mTitle
;
974 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
975 $this->loopCheckHash
= array();
977 $this->childExpansionCache
= array();
981 * Create a new child frame
982 * $args is optionally a multi-root PPNode or array containing the template arguments
984 * @param bool|array $args
985 * @param Title|bool $title
986 * @param int $indexOffset
987 * @return PPTemplateFrame_DOM
989 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
990 $namedArgs = array();
991 $numberedArgs = array();
992 if ( $title === false ) {
993 $title = $this->title
;
995 if ( $args !== false ) {
997 if ( $args instanceof PPNode
) {
1000 foreach ( $args as $arg ) {
1001 if ( $arg instanceof PPNode
) {
1004 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1005 $xpath = new DOMXPath( $arg->ownerDocument
);
1008 $nameNodes = $xpath->query( 'name', $arg );
1009 $value = $xpath->query( 'value', $arg );
1010 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1011 // Numbered parameter
1012 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1013 $index = $index - $indexOffset;
1014 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1015 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1016 wfEscapeWikiText( $this->title
),
1017 wfEscapeWikiText( $title ),
1018 wfEscapeWikiText( $index ) )->text() );
1019 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1021 $numberedArgs[$index] = $value->item( 0 );
1022 unset( $namedArgs[$index] );
1025 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1026 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1027 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1028 wfEscapeWikiText( $this->title
),
1029 wfEscapeWikiText( $title ),
1030 wfEscapeWikiText( $name ) )->text() );
1031 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1033 $namedArgs[$name] = $value->item( 0 );
1034 unset( $numberedArgs[$name] );
1038 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1042 * @throws MWException
1043 * @param string|int $key
1044 * @param string|PPNode_DOM|DOMDocument $root
1048 public function cachedExpand( $key, $root, $flags = 0 ) {
1049 // we don't have a parent, so we don't have a cache
1050 return $this->expand( $root, $flags );
1054 * @throws MWException
1055 * @param string|PPNode_DOM|DOMDocument $root
1059 public function expand( $root, $flags = 0 ) {
1060 static $expansionDepth = 0;
1061 if ( is_string( $root ) ) {
1065 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1066 $this->parser
->limitationWarn( 'node-count-exceeded',
1067 $this->parser
->mPPNodeCount
,
1068 $this->parser
->mOptions
->getMaxPPNodeCount()
1070 return '<span class="error">Node-count limit exceeded</span>';
1073 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1074 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1076 $this->parser
->mOptions
->getMaxPPExpandDepth()
1078 return '<span class="error">Expansion depth limit exceeded</span>';
1081 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1082 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1085 if ( $root instanceof PPNode_DOM
) {
1086 $root = $root->node
;
1088 if ( $root instanceof DOMDocument
) {
1089 $root = $root->documentElement
;
1092 $outStack = array( '', '' );
1093 $iteratorStack = array( false, $root );
1094 $indexStack = array( 0, 0 );
1096 while ( count( $iteratorStack ) > 1 ) {
1097 $level = count( $outStack ) - 1;
1098 $iteratorNode =& $iteratorStack[$level];
1099 $out =& $outStack[$level];
1100 $index =& $indexStack[$level];
1102 if ( $iteratorNode instanceof PPNode_DOM
) {
1103 $iteratorNode = $iteratorNode->node
;
1106 if ( is_array( $iteratorNode ) ) {
1107 if ( $index >= count( $iteratorNode ) ) {
1108 // All done with this iterator
1109 $iteratorStack[$level] = false;
1110 $contextNode = false;
1112 $contextNode = $iteratorNode[$index];
1115 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1116 if ( $index >= $iteratorNode->length
) {
1117 // All done with this iterator
1118 $iteratorStack[$level] = false;
1119 $contextNode = false;
1121 $contextNode = $iteratorNode->item( $index );
1125 // Copy to $contextNode and then delete from iterator stack,
1126 // because this is not an iterator but we do have to execute it once
1127 $contextNode = $iteratorStack[$level];
1128 $iteratorStack[$level] = false;
1131 if ( $contextNode instanceof PPNode_DOM
) {
1132 $contextNode = $contextNode->node
;
1135 $newIterator = false;
1137 if ( $contextNode === false ) {
1139 } elseif ( is_string( $contextNode ) ) {
1140 $out .= $contextNode;
1141 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1142 $newIterator = $contextNode;
1143 } elseif ( $contextNode instanceof DOMNode
) {
1144 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1145 $out .= $contextNode->nodeValue
;
1146 } elseif ( $contextNode->nodeName
== 'template' ) {
1147 # Double-brace expansion
1148 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1149 $titles = $xpath->query( 'title', $contextNode );
1150 $title = $titles->item( 0 );
1151 $parts = $xpath->query( 'part', $contextNode );
1152 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1153 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1155 $lineStart = $contextNode->getAttribute( 'lineStart' );
1157 'title' => new PPNode_DOM( $title ),
1158 'parts' => new PPNode_DOM( $parts ),
1159 'lineStart' => $lineStart );
1160 $ret = $this->parser
->braceSubstitution( $params, $this );
1161 if ( isset( $ret['object'] ) ) {
1162 $newIterator = $ret['object'];
1164 $out .= $ret['text'];
1167 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1168 # Triple-brace expansion
1169 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1170 $titles = $xpath->query( 'title', $contextNode );
1171 $title = $titles->item( 0 );
1172 $parts = $xpath->query( 'part', $contextNode );
1173 if ( $flags & PPFrame
::NO_ARGS
) {
1174 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1177 'title' => new PPNode_DOM( $title ),
1178 'parts' => new PPNode_DOM( $parts ) );
1179 $ret = $this->parser
->argSubstitution( $params, $this );
1180 if ( isset( $ret['object'] ) ) {
1181 $newIterator = $ret['object'];
1183 $out .= $ret['text'];
1186 } elseif ( $contextNode->nodeName
== 'comment' ) {
1187 # HTML-style comment
1188 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1189 # Not in RECOVER_COMMENTS mode (msgnw) though.
1190 if ( ( $this->parser
->ot
['html']
1191 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1192 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1193 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1196 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1197 # Add a strip marker in PST mode so that pstPass2() can
1198 # run some old-fashioned regexes on the result.
1199 # Not in RECOVER_COMMENTS mode (extractSections) though.
1200 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1202 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1203 $out .= $contextNode->textContent
;
1205 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1206 # Output suppression used by <includeonly> etc.
1207 # OT_WIKI will only respect <ignore> in substed templates.
1208 # The other output types respect it unless NO_IGNORE is set.
1209 # extractSections() sets NO_IGNORE and so never respects it.
1210 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1211 ||
( $flags & PPFrame
::NO_IGNORE
)
1213 $out .= $contextNode->textContent
;
1217 } elseif ( $contextNode->nodeName
== 'ext' ) {
1219 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1220 $names = $xpath->query( 'name', $contextNode );
1221 $attrs = $xpath->query( 'attr', $contextNode );
1222 $inners = $xpath->query( 'inner', $contextNode );
1223 $closes = $xpath->query( 'close', $contextNode );
1224 if ( $flags & PPFrame
::NO_TAGS
) {
1225 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1226 if ( $attrs->length
> 0 ) {
1227 $s .= $this->expand( $attrs->item( 0 ), $flags );
1229 if ( $inners->length
> 0 ) {
1230 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1231 if ( $closes->length
> 0 ) {
1232 $s .= $this->expand( $closes->item( 0 ), $flags );
1240 'name' => new PPNode_DOM( $names->item( 0 ) ),
1241 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1242 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1243 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1245 $out .= $this->parser
->extensionSubstitution( $params, $this );
1247 } elseif ( $contextNode->nodeName
== 'h' ) {
1249 $s = $this->expand( $contextNode->childNodes
, $flags );
1251 # Insert a heading marker only for <h> children of <root>
1252 # This is to stop extractSections from going over multiple tree levels
1253 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1254 # Insert heading index marker
1255 $headingIndex = $contextNode->getAttribute( 'i' );
1256 $titleText = $this->title
->getPrefixedDBkey();
1257 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1258 $serial = count( $this->parser
->mHeadings
) - 1;
1259 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1260 $count = $contextNode->getAttribute( 'level' );
1261 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1262 $this->parser
->mStripState
->addGeneral( $marker, '' );
1266 # Generic recursive expansion
1267 $newIterator = $contextNode->childNodes
;
1270 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1273 if ( $newIterator !== false ) {
1274 if ( $newIterator instanceof PPNode_DOM
) {
1275 $newIterator = $newIterator->node
;
1278 $iteratorStack[] = $newIterator;
1280 } elseif ( $iteratorStack[$level] === false ) {
1281 // Return accumulated value to parent
1282 // With tail recursion
1283 while ( $iteratorStack[$level] === false && $level > 0 ) {
1284 $outStack[$level - 1] .= $out;
1285 array_pop( $outStack );
1286 array_pop( $iteratorStack );
1287 array_pop( $indexStack );
1293 return $outStack[0];
1297 * @param string $sep
1299 * @param string|PPNode_DOM|DOMDocument $args,...
1302 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1303 $args = array_slice( func_get_args(), 2 );
1307 foreach ( $args as $root ) {
1308 if ( $root instanceof PPNode_DOM
) {
1309 $root = $root->node
;
1311 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1312 $root = array( $root );
1314 foreach ( $root as $node ) {
1320 $s .= $this->expand( $node, $flags );
1327 * Implode with no flags specified
1328 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1330 * @param string $sep
1331 * @param string|PPNode_DOM|DOMDocument $args,...
1334 public function implode( $sep /*, ... */ ) {
1335 $args = array_slice( func_get_args(), 1 );
1339 foreach ( $args as $root ) {
1340 if ( $root instanceof PPNode_DOM
) {
1341 $root = $root->node
;
1343 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1344 $root = array( $root );
1346 foreach ( $root as $node ) {
1352 $s .= $this->expand( $node );
1359 * Makes an object that, when expand()ed, will be the same as one obtained
1362 * @param string $sep
1363 * @param string|PPNode_DOM|DOMDocument $args,...
1366 public function virtualImplode( $sep /*, ... */ ) {
1367 $args = array_slice( func_get_args(), 1 );
1371 foreach ( $args as $root ) {
1372 if ( $root instanceof PPNode_DOM
) {
1373 $root = $root->node
;
1375 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1376 $root = array( $root );
1378 foreach ( $root as $node ) {
1391 * Virtual implode with brackets
1392 * @param string $start
1393 * @param string $sep
1394 * @param string $end
1395 * @param string|PPNode_DOM|DOMDocument $args,...
1398 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1399 $args = array_slice( func_get_args(), 3 );
1400 $out = array( $start );
1403 foreach ( $args as $root ) {
1404 if ( $root instanceof PPNode_DOM
) {
1405 $root = $root->node
;
1407 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1408 $root = array( $root );
1410 foreach ( $root as $node ) {
1423 public function __toString() {
1427 public function getPDBK( $level = false ) {
1428 if ( $level === false ) {
1429 return $this->title
->getPrefixedDBkey();
1431 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1438 public function getArguments() {
1445 public function getNumberedArguments() {
1452 public function getNamedArguments() {
1457 * Returns true if there are no arguments in this frame
1461 public function isEmpty() {
1465 public function getArgument( $name ) {
1470 * Returns true if the infinite loop check is OK, false if a loop is detected
1472 * @param Title $title
1475 public function loopCheck( $title ) {
1476 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1480 * Return true if the frame is a template frame
1484 public function isTemplate() {
1489 * Get a title of frame
1493 public function getTitle() {
1494 return $this->title
;
1498 * Set the volatile flag
1502 public function setVolatile( $flag = true ) {
1503 $this->volatile
= $flag;
1507 * Get the volatile flag
1511 public function isVolatile() {
1512 return $this->volatile
;
1520 public function setTTL( $ttl ) {
1521 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1531 public function getTTL() {
1537 * Expansion frame with template arguments
1540 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1541 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1542 // @codingStandardsIgnoreEnd
1544 public $numberedArgs, $namedArgs;
1550 public $numberedExpansionCache, $namedExpansionCache;
1553 * @param Preprocessor $preprocessor
1554 * @param bool|PPFrame_DOM $parent
1555 * @param array $numberedArgs
1556 * @param array $namedArgs
1557 * @param bool|Title $title
1559 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1560 $namedArgs = array(), $title = false
1562 parent
::__construct( $preprocessor );
1564 $this->parent
= $parent;
1565 $this->numberedArgs
= $numberedArgs;
1566 $this->namedArgs
= $namedArgs;
1567 $this->title
= $title;
1568 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1569 $this->titleCache
= $parent->titleCache
;
1570 $this->titleCache
[] = $pdbk;
1571 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1572 if ( $pdbk !== false ) {
1573 $this->loopCheckHash
[$pdbk] = true;
1575 $this->depth
= $parent->depth +
1;
1576 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1579 public function __toString() {
1582 $args = $this->numberedArgs +
$this->namedArgs
;
1583 foreach ( $args as $name => $value ) {
1589 $s .= "\"$name\":\"" .
1590 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1597 * @throws MWException
1598 * @param string|int $key
1599 * @param string|PPNode_DOM|DOMDocument $root
1603 public function cachedExpand( $key, $root, $flags = 0 ) {
1604 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1605 return $this->parent
->childExpansionCache
[$key];
1607 $retval = $this->expand( $root, $flags );
1608 if ( !$this->isVolatile() ) {
1609 $this->parent
->childExpansionCache
[$key] = $retval;
1615 * Returns true if there are no arguments in this frame
1619 public function isEmpty() {
1620 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1623 public function getArguments() {
1624 $arguments = array();
1625 foreach ( array_merge(
1626 array_keys( $this->numberedArgs
),
1627 array_keys( $this->namedArgs
) ) as $key ) {
1628 $arguments[$key] = $this->getArgument( $key );
1633 public function getNumberedArguments() {
1634 $arguments = array();
1635 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1636 $arguments[$key] = $this->getArgument( $key );
1641 public function getNamedArguments() {
1642 $arguments = array();
1643 foreach ( array_keys( $this->namedArgs
) as $key ) {
1644 $arguments[$key] = $this->getArgument( $key );
1649 public function getNumberedArgument( $index ) {
1650 if ( !isset( $this->numberedArgs
[$index] ) ) {
1653 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1654 # No trimming for unnamed arguments
1655 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1656 $this->numberedArgs
[$index],
1657 PPFrame
::STRIP_COMMENTS
1660 return $this->numberedExpansionCache
[$index];
1663 public function getNamedArgument( $name ) {
1664 if ( !isset( $this->namedArgs
[$name] ) ) {
1667 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1668 # Trim named arguments post-expand, for backwards compatibility
1669 $this->namedExpansionCache
[$name] = trim(
1670 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1672 return $this->namedExpansionCache
[$name];
1675 public function getArgument( $name ) {
1676 $text = $this->getNumberedArgument( $name );
1677 if ( $text === false ) {
1678 $text = $this->getNamedArgument( $name );
1684 * Return true if the frame is a template frame
1688 public function isTemplate() {
1692 public function setVolatile( $flag = true ) {
1693 parent
::setVolatile( $flag );
1694 $this->parent
->setVolatile( $flag );
1697 public function setTTL( $ttl ) {
1698 parent
::setTTL( $ttl );
1699 $this->parent
->setTTL( $ttl );
1704 * Expansion frame with custom arguments
1707 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1708 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1709 // @codingStandardsIgnoreEnd
1713 public function __construct( $preprocessor, $args ) {
1714 parent
::__construct( $preprocessor );
1715 $this->args
= $args;
1718 public function __toString() {
1721 foreach ( $this->args
as $name => $value ) {
1727 $s .= "\"$name\":\"" .
1728 str_replace( '"', '\\"', $value->__toString() ) . '"';
1737 public function isEmpty() {
1738 return !count( $this->args
);
1741 public function getArgument( $index ) {
1742 if ( !isset( $this->args
[$index] ) ) {
1745 return $this->args
[$index];
1748 public function getArguments() {
1756 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1757 class PPNode_DOM
implements PPNode
{
1758 // @codingStandardsIgnoreEnd
1766 public function __construct( $node, $xpath = false ) {
1767 $this->node
= $node;
1773 public function getXPath() {
1774 if ( $this->xpath
=== null ) {
1775 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1777 return $this->xpath
;
1780 public function __toString() {
1781 if ( $this->node
instanceof DOMNodeList
) {
1783 foreach ( $this->node
as $node ) {
1784 $s .= $node->ownerDocument
->saveXML( $node );
1787 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1793 * @return bool|PPNode_DOM
1795 public function getChildren() {
1796 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1800 * @return bool|PPNode_DOM
1802 public function getFirstChild() {
1803 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1807 * @return bool|PPNode_DOM
1809 public function getNextSibling() {
1810 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1814 * @param string $type
1816 * @return bool|PPNode_DOM
1818 public function getChildrenOfType( $type ) {
1819 return new self( $this->getXPath()->query( $type, $this->node
) );
1825 public function getLength() {
1826 if ( $this->node
instanceof DOMNodeList
) {
1827 return $this->node
->length
;
1835 * @return bool|PPNode_DOM
1837 public function item( $i ) {
1838 $item = $this->node
->item( $i );
1839 return $item ?
new self( $item ) : false;
1845 public function getName() {
1846 if ( $this->node
instanceof DOMNodeList
) {
1849 return $this->node
->nodeName
;
1854 * Split a "<part>" node into an associative array containing:
1855 * - name PPNode name
1856 * - index String index
1857 * - value PPNode value
1859 * @throws MWException
1862 public function splitArg() {
1863 $xpath = $this->getXPath();
1864 $names = $xpath->query( 'name', $this->node
);
1865 $values = $xpath->query( 'value', $this->node
);
1866 if ( !$names->length ||
!$values->length
) {
1867 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1869 $name = $names->item( 0 );
1870 $index = $name->getAttribute( 'index' );
1872 'name' => new self( $name ),
1874 'value' => new self( $values->item( 0 ) ) );
1878 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1879 * All values in the resulting array are PPNodes. Inner and close are optional.
1881 * @throws MWException
1884 public function splitExt() {
1885 $xpath = $this->getXPath();
1886 $names = $xpath->query( 'name', $this->node
);
1887 $attrs = $xpath->query( 'attr', $this->node
);
1888 $inners = $xpath->query( 'inner', $this->node
);
1889 $closes = $xpath->query( 'close', $this->node
);
1890 if ( !$names->length ||
!$attrs->length
) {
1891 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1894 'name' => new self( $names->item( 0 ) ),
1895 'attr' => new self( $attrs->item( 0 ) ) );
1896 if ( $inners->length
) {
1897 $parts['inner'] = new self( $inners->item( 0 ) );
1899 if ( $closes->length
) {
1900 $parts['close'] = new self( $closes->item( 0 ) );
1906 * Split a "<h>" node
1907 * @throws MWException
1910 public function splitHeading() {
1911 if ( $this->getName() !== 'h' ) {
1912 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1915 'i' => $this->node
->getAttribute( 'i' ),
1916 'level' => $this->node
->getAttribute( 'level' ),
1917 'contents' => $this->getChildren()