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 ) {
208 'names' => array( 2 => null ),
214 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
216 $xmlishElements = $this->parser
->getStripList();
217 $enableOnlyinclude = false;
218 if ( $forInclusion ) {
219 $ignoredTags = array( 'includeonly', '/includeonly' );
220 $ignoredElements = array( 'noinclude' );
221 $xmlishElements[] = 'noinclude';
222 if ( strpos( $text, '<onlyinclude>' ) !== false
223 && strpos( $text, '</onlyinclude>' ) !== false
225 $enableOnlyinclude = true;
228 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
229 $ignoredElements = array( 'includeonly' );
230 $xmlishElements[] = 'includeonly';
232 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
234 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
235 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
237 $stack = new PPDStack
;
239 $searchBase = "[{<\n"; # }
240 // For fast reverse searches
241 $revText = strrev( $text );
242 $lengthText = strlen( $text );
244 // Input pointer, starts out pointing to a pseudo-newline before the start
246 // Current accumulator
247 $accum =& $stack->getAccum();
249 // True to find equals signs in arguments
251 // True to take notice of pipe characters
254 // True if $i is inside a possible heading
256 // True if there are no more greater-than (>) signs right of $i
258 // True to ignore all input up to the next <onlyinclude>
259 $findOnlyinclude = $enableOnlyinclude;
260 // Do a line-start run without outputting an LF character
261 $fakeLineStart = true;
264 // $this->memCheck();
266 if ( $findOnlyinclude ) {
267 // Ignore all input up to the next <onlyinclude>
268 $startPos = strpos( $text, '<onlyinclude>', $i );
269 if ( $startPos === false ) {
270 // Ignored section runs to the end
271 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
274 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
275 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
277 $findOnlyinclude = false;
280 if ( $fakeLineStart ) {
281 $found = 'line-start';
284 # Find next opening brace, closing brace or pipe
285 $search = $searchBase;
286 if ( $stack->top
=== false ) {
287 $currentClosing = '';
289 $currentClosing = $stack->top
->close
;
290 $search .= $currentClosing;
296 // First equals will be for the template
300 # Output literal section, advance input counter
301 $literalLength = strcspn( $text, $search, $i );
302 if ( $literalLength > 0 ) {
303 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
304 $i +
= $literalLength;
306 if ( $i >= $lengthText ) {
307 if ( $currentClosing == "\n" ) {
308 // Do a past-the-end run to finish off the heading
316 $curChar = $text[$i];
317 if ( $curChar == '|' ) {
319 } elseif ( $curChar == '=' ) {
321 } elseif ( $curChar == '<' ) {
323 } elseif ( $curChar == "\n" ) {
327 $found = 'line-start';
329 } elseif ( $curChar == $currentClosing ) {
331 } elseif ( isset( $rules[$curChar] ) ) {
333 $rule = $rules[$curChar];
335 # Some versions of PHP have a strcspn which stops on null characters
336 # Ignore and continue
343 if ( $found == 'angle' ) {
345 // Handle </onlyinclude>
346 if ( $enableOnlyinclude
347 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
349 $findOnlyinclude = true;
353 // Determine element name
354 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
355 // Element name missing or not listed
361 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
363 // To avoid leaving blank lines, when a sequence of
364 // space-separated comments is both preceded and followed by
365 // a newline (ignoring spaces), then
366 // trim leading and trailing spaces and the trailing newline.
369 $endPos = strpos( $text, '-->', $i +
4 );
370 if ( $endPos === false ) {
371 // Unclosed comment in input, runs to end
372 $inner = substr( $text, $i );
373 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
376 // Search backwards for leading whitespace
377 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
379 // Search forwards for trailing whitespace
380 // $wsEnd will be the position of the last space (or the '>' if there's none)
381 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
383 // Keep looking forward as long as we're finding more
385 $comments = array( array( $wsStart, $wsEnd ) );
386 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
387 $c = strpos( $text, '-->', $wsEnd +
4 );
388 if ( $c === false ) {
391 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
392 $comments[] = array( $wsEnd +
1, $c );
396 // Eat the line if possible
397 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
398 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
399 // it's a possible beneficial b/c break.
400 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
401 && substr( $text, $wsEnd +
1, 1 ) == "\n"
403 // Remove leading whitespace from the end of the accumulator
404 // Sanity check first though
405 $wsLength = $i - $wsStart;
407 && strspn( $accum, " \t", -$wsLength ) === $wsLength
409 $accum = substr( $accum, 0, -$wsLength );
412 // Dump all but the last comment to the accumulator
413 foreach ( $comments as $j => $com ) {
415 $endPos = $com[1] +
1;
416 if ( $j == ( count( $comments ) - 1 ) ) {
419 $inner = substr( $text, $startPos, $endPos - $startPos );
420 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
423 // Do a line-start run next time to look for headings after the comment
424 $fakeLineStart = true;
426 // No line to eat, just take the comment itself
432 $part = $stack->top
->getCurrentPart();
433 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
434 $part->visualEnd
= $wsStart;
436 // Else comments abutting, no change in visual end
437 $part->commentEnd
= $endPos;
440 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
441 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
446 $lowerName = strtolower( $name );
447 $attrStart = $i +
strlen( $name ) +
1;
450 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
451 if ( $tagEndPos === false ) {
452 // Infinite backtrack
453 // Disable tag search to prevent worst-case O(N^2) performance
460 // Handle ignored tags
461 if ( in_array( $lowerName, $ignoredTags ) ) {
463 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
470 if ( $text[$tagEndPos - 1] == '/' ) {
471 $attrEnd = $tagEndPos - 1;
476 $attrEnd = $tagEndPos;
478 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
479 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
481 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
482 $i = $matches[0][1] +
strlen( $matches[0][0] );
483 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
485 // No end tag -- let it run out to the end of the text.
486 $inner = substr( $text, $tagEndPos +
1 );
491 // <includeonly> and <noinclude> just become <ignore> tags
492 if ( in_array( $lowerName, $ignoredElements ) ) {
493 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
499 if ( $attrEnd <= $attrStart ) {
502 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
504 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
505 // Note that the attr element contains the whitespace between name and attribute,
506 // this is necessary for precise reconstruction during pre-save transform.
507 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
508 if ( $inner !== null ) {
509 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
511 $accum .= $close . '</ext>';
512 } elseif ( $found == 'line-start' ) {
513 // Is this the start of a heading?
514 // Line break belongs before the heading element in any case
515 if ( $fakeLineStart ) {
516 $fakeLineStart = false;
522 $count = strspn( $text, '=', $i, 6 );
523 if ( $count == 1 && $findEquals ) {
524 // DWIM: This looks kind of like a name/value separator.
525 // Let's let the equals handler have it and break the
526 // potential heading. This is heuristic, but AFAICT the
527 // methods for completely correct disambiguation are very
529 } elseif ( $count > 0 ) {
533 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
536 $stack->push( $piece );
537 $accum =& $stack->getAccum();
538 $flags = $stack->getFlags();
542 } elseif ( $found == 'line-end' ) {
543 $piece = $stack->top
;
544 // A heading must be open, otherwise \n wouldn't have been in the search list
545 assert( '$piece->open == "\n"' );
546 $part = $piece->getCurrentPart();
547 // Search back through the input to see if it has a proper close.
548 // Do this using the reversed string since the other solutions
549 // (end anchor, etc.) are inefficient.
550 $wsLength = strspn( $revText, " \t", $lengthText - $i );
551 $searchStart = $i - $wsLength;
552 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
553 // Comment found at line end
554 // Search for equals signs before the comment
555 $searchStart = $part->visualEnd
;
556 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
558 $count = $piece->count
;
559 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
560 if ( $equalsLength > 0 ) {
561 if ( $searchStart - $equalsLength == $piece->startPos
) {
562 // This is just a single string of equals signs on its own line
563 // Replicate the doHeadings behavior /={count}(.+)={count}/
564 // First find out how many equals signs there really are (don't stop at 6)
565 $count = $equalsLength;
569 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
572 $count = min( $equalsLength, $count );
575 // Normal match, output <h>
576 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
579 // Single equals sign on its own line, count=0
583 // No match, no <h>, just pass down the inner text
588 $accum =& $stack->getAccum();
589 $flags = $stack->getFlags();
592 // Append the result to the enclosing accumulator
594 // Note that we do NOT increment the input pointer.
595 // This is because the closing linebreak could be the opening linebreak of
596 // another heading. Infinite loops are avoided because the next iteration MUST
597 // hit the heading open case above, which unconditionally increments the
599 } elseif ( $found == 'open' ) {
600 # count opening brace characters
601 $count = strspn( $text, $curChar, $i );
603 # we need to add to stack only if opening brace count is enough for one of the rules
604 if ( $count >= $rule['min'] ) {
605 # Add it to the stack
608 'close' => $rule['end'],
610 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
613 $stack->push( $piece );
614 $accum =& $stack->getAccum();
615 $flags = $stack->getFlags();
618 # Add literal brace(s)
619 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
622 } elseif ( $found == 'close' ) {
623 $piece = $stack->top
;
624 # lets check if there are enough characters for closing brace
625 $maxCount = $piece->count
;
626 $count = strspn( $text, $curChar, $i, $maxCount );
628 # check for maximum matching characters (if there are 5 closing
629 # characters, we will probably need only 3 - depending on the rules)
630 $rule = $rules[$piece->open
];
631 if ( $count > $rule['max'] ) {
632 # The specified maximum exists in the callback array, unless the caller
634 $matchingCount = $rule['max'];
636 # Count is less than the maximum
637 # Skip any gaps in the callback array to find the true largest match
638 # Need to use array_key_exists not isset because the callback can be null
639 $matchingCount = $count;
640 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
645 if ( $matchingCount <= 0 ) {
646 # No matching element found in callback array
647 # Output a literal closing brace and continue
648 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
652 $name = $rule['names'][$matchingCount];
653 if ( $name === null ) {
654 // No element, just literal text
655 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
658 # Note: $parts is already XML, does not need to be encoded further
659 $parts = $piece->parts
;
660 $title = $parts[0]->out
;
663 # The invocation is at the start of the line if lineStart is set in
664 # the stack, and all opening brackets are used up.
665 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
666 $attr = ' lineStart="1"';
671 $element = "<$name$attr>";
672 $element .= "<title>$title</title>";
674 foreach ( $parts as $part ) {
675 if ( isset( $part->eqpos
) ) {
676 $argName = substr( $part->out
, 0, $part->eqpos
);
677 $argValue = substr( $part->out
, $part->eqpos +
1 );
678 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
680 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
684 $element .= "</$name>";
687 # Advance input pointer
688 $i +
= $matchingCount;
692 $accum =& $stack->getAccum();
694 # Re-add the old stack element if it still has unmatched opening characters remaining
695 if ( $matchingCount < $piece->count
) {
696 $piece->parts
= array( new PPDPart
);
697 $piece->count
-= $matchingCount;
698 # do we still qualify for any callback with remaining count?
699 $min = $rules[$piece->open
]['min'];
700 if ( $piece->count
>= $min ) {
701 $stack->push( $piece );
702 $accum =& $stack->getAccum();
704 $accum .= str_repeat( $piece->open
, $piece->count
);
707 $flags = $stack->getFlags();
710 # Add XML element to the enclosing accumulator
712 } elseif ( $found == 'pipe' ) {
713 $findEquals = true; // shortcut for getFlags()
715 $accum =& $stack->getAccum();
717 } elseif ( $found == 'equals' ) {
718 $findEquals = false; // shortcut for getFlags()
719 $stack->getCurrentPart()->eqpos
= strlen( $accum );
725 # Output any remaining unclosed brackets
726 foreach ( $stack->stack
as $piece ) {
727 $stack->rootAccum
.= $piece->breakSyntax();
729 $stack->rootAccum
.= '</root>';
730 $xml = $stack->rootAccum
;
737 * Stack class to help Preprocessor::preprocessToObj()
741 public $stack, $rootAccum;
748 public $elementClass = 'PPDStackElement';
750 public static $false = false;
752 public function __construct() {
753 $this->stack
= array();
755 $this->rootAccum
= '';
756 $this->accum
=& $this->rootAccum
;
762 public function count() {
763 return count( $this->stack
);
766 public function &getAccum() {
770 public function getCurrentPart() {
771 if ( $this->top
=== false ) {
774 return $this->top
->getCurrentPart();
778 public function push( $data ) {
779 if ( $data instanceof $this->elementClass
) {
780 $this->stack
[] = $data;
782 $class = $this->elementClass
;
783 $this->stack
[] = new $class( $data );
785 $this->top
= $this->stack
[count( $this->stack
) - 1];
786 $this->accum
=& $this->top
->getAccum();
789 public function pop() {
790 if ( !count( $this->stack
) ) {
791 throw new MWException( __METHOD__
. ': no elements remaining' );
793 $temp = array_pop( $this->stack
);
795 if ( count( $this->stack
) ) {
796 $this->top
= $this->stack
[count( $this->stack
) - 1];
797 $this->accum
=& $this->top
->getAccum();
799 $this->top
= self
::$false;
800 $this->accum
=& $this->rootAccum
;
805 public function addPart( $s = '' ) {
806 $this->top
->addPart( $s );
807 $this->accum
=& $this->top
->getAccum();
813 public function getFlags() {
814 if ( !count( $this->stack
) ) {
816 'findEquals' => false,
818 'inHeading' => false,
821 return $this->top
->getFlags();
829 class PPDStackElement
{
831 * @var string Opening character (\n for heading)
836 * @var string Matching closing character
841 * @var int Number of opening characters found (number of "=" for heading)
846 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
851 * @var bool True if the open char appeared at the start of the input line.
852 * Not set for headings.
856 public $partClass = 'PPDPart';
858 public function __construct( $data = array() ) {
859 $class = $this->partClass
;
860 $this->parts
= array( new $class );
862 foreach ( $data as $name => $value ) {
863 $this->$name = $value;
867 public function &getAccum() {
868 return $this->parts
[count( $this->parts
) - 1]->out
;
871 public function addPart( $s = '' ) {
872 $class = $this->partClass
;
873 $this->parts
[] = new $class( $s );
876 public function getCurrentPart() {
877 return $this->parts
[count( $this->parts
) - 1];
883 public function getFlags() {
884 $partCount = count( $this->parts
);
885 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
887 'findPipe' => $findPipe,
888 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
889 'inHeading' => $this->open
== "\n",
894 * Get the output string that would result if the close is not found.
896 * @param bool|int $openingCount
899 public function breakSyntax( $openingCount = false ) {
900 if ( $this->open
== "\n" ) {
901 $s = $this->parts
[0]->out
;
903 if ( $openingCount === false ) {
904 $openingCount = $this->count
;
906 $s = str_repeat( $this->open
, $openingCount );
908 foreach ( $this->parts
as $part ) {
926 * @var string Output accumulator string
930 // Optional member variables:
931 // eqpos Position of equals sign in output accumulator
932 // commentEnd Past-the-end input pointer for the last comment encountered
933 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
935 public function __construct( $out = '' ) {
941 * An expansion frame, used as a context to expand the result of preprocessToObj()
944 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
945 class PPFrame_DOM
implements PPFrame
{
946 // @codingStandardsIgnoreEnd
951 public $preprocessor;
965 * Hashtable listing templates which are disallowed for expansion in this frame,
966 * having been encountered previously in parent frames.
968 public $loopCheckHash;
971 * Recursion depth of this frame, top = 0
972 * Note that this is NOT the same as expansion depth in expand()
976 private $volatile = false;
982 protected $childExpansionCache;
985 * Construct a new preprocessor frame.
986 * @param Preprocessor $preprocessor The parent preprocessor
988 public function __construct( $preprocessor ) {
989 $this->preprocessor
= $preprocessor;
990 $this->parser
= $preprocessor->parser
;
991 $this->title
= $this->parser
->mTitle
;
992 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
993 $this->loopCheckHash
= array();
995 $this->childExpansionCache
= array();
999 * Create a new child frame
1000 * $args is optionally a multi-root PPNode or array containing the template arguments
1002 * @param bool|array $args
1003 * @param Title|bool $title
1004 * @param int $indexOffset
1005 * @return PPTemplateFrame_DOM
1007 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1008 $namedArgs = array();
1009 $numberedArgs = array();
1010 if ( $title === false ) {
1011 $title = $this->title
;
1013 if ( $args !== false ) {
1015 if ( $args instanceof PPNode
) {
1016 $args = $args->node
;
1018 foreach ( $args as $arg ) {
1019 if ( $arg instanceof PPNode
) {
1022 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1023 $xpath = new DOMXPath( $arg->ownerDocument
);
1026 $nameNodes = $xpath->query( 'name', $arg );
1027 $value = $xpath->query( 'value', $arg );
1028 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1029 // Numbered parameter
1030 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1031 $index = $index - $indexOffset;
1032 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1033 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1034 wfEscapeWikiText( $this->title
),
1035 wfEscapeWikiText( $title ),
1036 wfEscapeWikiText( $index ) )->text() );
1037 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1039 $numberedArgs[$index] = $value->item( 0 );
1040 unset( $namedArgs[$index] );
1043 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1044 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1045 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1046 wfEscapeWikiText( $this->title
),
1047 wfEscapeWikiText( $title ),
1048 wfEscapeWikiText( $name ) )->text() );
1049 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1051 $namedArgs[$name] = $value->item( 0 );
1052 unset( $numberedArgs[$name] );
1056 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1060 * @throws MWException
1061 * @param string|int $key
1062 * @param string|PPNode_DOM|DOMDocument $root
1066 public function cachedExpand( $key, $root, $flags = 0 ) {
1067 // we don't have a parent, so we don't have a cache
1068 return $this->expand( $root, $flags );
1072 * @throws MWException
1073 * @param string|PPNode_DOM|DOMDocument $root
1077 public function expand( $root, $flags = 0 ) {
1078 static $expansionDepth = 0;
1079 if ( is_string( $root ) ) {
1083 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1084 $this->parser
->limitationWarn( 'node-count-exceeded',
1085 $this->parser
->mPPNodeCount
,
1086 $this->parser
->mOptions
->getMaxPPNodeCount()
1088 return '<span class="error">Node-count limit exceeded</span>';
1091 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1092 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1094 $this->parser
->mOptions
->getMaxPPExpandDepth()
1096 return '<span class="error">Expansion depth limit exceeded</span>';
1099 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1100 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1103 if ( $root instanceof PPNode_DOM
) {
1104 $root = $root->node
;
1106 if ( $root instanceof DOMDocument
) {
1107 $root = $root->documentElement
;
1110 $outStack = array( '', '' );
1111 $iteratorStack = array( false, $root );
1112 $indexStack = array( 0, 0 );
1114 while ( count( $iteratorStack ) > 1 ) {
1115 $level = count( $outStack ) - 1;
1116 $iteratorNode =& $iteratorStack[$level];
1117 $out =& $outStack[$level];
1118 $index =& $indexStack[$level];
1120 if ( $iteratorNode instanceof PPNode_DOM
) {
1121 $iteratorNode = $iteratorNode->node
;
1124 if ( is_array( $iteratorNode ) ) {
1125 if ( $index >= count( $iteratorNode ) ) {
1126 // All done with this iterator
1127 $iteratorStack[$level] = false;
1128 $contextNode = false;
1130 $contextNode = $iteratorNode[$index];
1133 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1134 if ( $index >= $iteratorNode->length
) {
1135 // All done with this iterator
1136 $iteratorStack[$level] = false;
1137 $contextNode = false;
1139 $contextNode = $iteratorNode->item( $index );
1143 // Copy to $contextNode and then delete from iterator stack,
1144 // because this is not an iterator but we do have to execute it once
1145 $contextNode = $iteratorStack[$level];
1146 $iteratorStack[$level] = false;
1149 if ( $contextNode instanceof PPNode_DOM
) {
1150 $contextNode = $contextNode->node
;
1153 $newIterator = false;
1155 if ( $contextNode === false ) {
1157 } elseif ( is_string( $contextNode ) ) {
1158 $out .= $contextNode;
1159 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1160 $newIterator = $contextNode;
1161 } elseif ( $contextNode instanceof DOMNode
) {
1162 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1163 $out .= $contextNode->nodeValue
;
1164 } elseif ( $contextNode->nodeName
== 'template' ) {
1165 # Double-brace expansion
1166 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1167 $titles = $xpath->query( 'title', $contextNode );
1168 $title = $titles->item( 0 );
1169 $parts = $xpath->query( 'part', $contextNode );
1170 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1171 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1173 $lineStart = $contextNode->getAttribute( 'lineStart' );
1175 'title' => new PPNode_DOM( $title ),
1176 'parts' => new PPNode_DOM( $parts ),
1177 'lineStart' => $lineStart );
1178 $ret = $this->parser
->braceSubstitution( $params, $this );
1179 if ( isset( $ret['object'] ) ) {
1180 $newIterator = $ret['object'];
1182 $out .= $ret['text'];
1185 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1186 # Triple-brace expansion
1187 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1188 $titles = $xpath->query( 'title', $contextNode );
1189 $title = $titles->item( 0 );
1190 $parts = $xpath->query( 'part', $contextNode );
1191 if ( $flags & PPFrame
::NO_ARGS
) {
1192 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1195 'title' => new PPNode_DOM( $title ),
1196 'parts' => new PPNode_DOM( $parts ) );
1197 $ret = $this->parser
->argSubstitution( $params, $this );
1198 if ( isset( $ret['object'] ) ) {
1199 $newIterator = $ret['object'];
1201 $out .= $ret['text'];
1204 } elseif ( $contextNode->nodeName
== 'comment' ) {
1205 # HTML-style comment
1206 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1207 # Not in RECOVER_COMMENTS mode (msgnw) though.
1208 if ( ( $this->parser
->ot
['html']
1209 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1210 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1211 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1214 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1215 # Add a strip marker in PST mode so that pstPass2() can
1216 # run some old-fashioned regexes on the result.
1217 # Not in RECOVER_COMMENTS mode (extractSections) though.
1218 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1220 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1221 $out .= $contextNode->textContent
;
1223 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1224 # Output suppression used by <includeonly> etc.
1225 # OT_WIKI will only respect <ignore> in substed templates.
1226 # The other output types respect it unless NO_IGNORE is set.
1227 # extractSections() sets NO_IGNORE and so never respects it.
1228 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1229 ||
( $flags & PPFrame
::NO_IGNORE
)
1231 $out .= $contextNode->textContent
;
1235 } elseif ( $contextNode->nodeName
== 'ext' ) {
1237 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1238 $names = $xpath->query( 'name', $contextNode );
1239 $attrs = $xpath->query( 'attr', $contextNode );
1240 $inners = $xpath->query( 'inner', $contextNode );
1241 $closes = $xpath->query( 'close', $contextNode );
1242 if ( $flags & PPFrame
::NO_TAGS
) {
1243 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1244 if ( $attrs->length
> 0 ) {
1245 $s .= $this->expand( $attrs->item( 0 ), $flags );
1247 if ( $inners->length
> 0 ) {
1248 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1249 if ( $closes->length
> 0 ) {
1250 $s .= $this->expand( $closes->item( 0 ), $flags );
1258 'name' => new PPNode_DOM( $names->item( 0 ) ),
1259 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1260 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1261 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1263 $out .= $this->parser
->extensionSubstitution( $params, $this );
1265 } elseif ( $contextNode->nodeName
== 'h' ) {
1267 $s = $this->expand( $contextNode->childNodes
, $flags );
1269 # Insert a heading marker only for <h> children of <root>
1270 # This is to stop extractSections from going over multiple tree levels
1271 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1272 # Insert heading index marker
1273 $headingIndex = $contextNode->getAttribute( 'i' );
1274 $titleText = $this->title
->getPrefixedDBkey();
1275 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1276 $serial = count( $this->parser
->mHeadings
) - 1;
1277 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1278 $count = $contextNode->getAttribute( 'level' );
1279 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1280 $this->parser
->mStripState
->addGeneral( $marker, '' );
1284 # Generic recursive expansion
1285 $newIterator = $contextNode->childNodes
;
1288 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1291 if ( $newIterator !== false ) {
1292 if ( $newIterator instanceof PPNode_DOM
) {
1293 $newIterator = $newIterator->node
;
1296 $iteratorStack[] = $newIterator;
1298 } elseif ( $iteratorStack[$level] === false ) {
1299 // Return accumulated value to parent
1300 // With tail recursion
1301 while ( $iteratorStack[$level] === false && $level > 0 ) {
1302 $outStack[$level - 1] .= $out;
1303 array_pop( $outStack );
1304 array_pop( $iteratorStack );
1305 array_pop( $indexStack );
1311 return $outStack[0];
1315 * @param string $sep
1317 * @param string|PPNode_DOM|DOMDocument $args,...
1320 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1321 $args = array_slice( func_get_args(), 2 );
1325 foreach ( $args as $root ) {
1326 if ( $root instanceof PPNode_DOM
) {
1327 $root = $root->node
;
1329 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1330 $root = array( $root );
1332 foreach ( $root as $node ) {
1338 $s .= $this->expand( $node, $flags );
1345 * Implode with no flags specified
1346 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1348 * @param string $sep
1349 * @param string|PPNode_DOM|DOMDocument $args,...
1352 public function implode( $sep /*, ... */ ) {
1353 $args = array_slice( func_get_args(), 1 );
1357 foreach ( $args as $root ) {
1358 if ( $root instanceof PPNode_DOM
) {
1359 $root = $root->node
;
1361 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1362 $root = array( $root );
1364 foreach ( $root as $node ) {
1370 $s .= $this->expand( $node );
1377 * Makes an object that, when expand()ed, will be the same as one obtained
1380 * @param string $sep
1381 * @param string|PPNode_DOM|DOMDocument $args,...
1384 public function virtualImplode( $sep /*, ... */ ) {
1385 $args = array_slice( func_get_args(), 1 );
1389 foreach ( $args as $root ) {
1390 if ( $root instanceof PPNode_DOM
) {
1391 $root = $root->node
;
1393 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1394 $root = array( $root );
1396 foreach ( $root as $node ) {
1409 * Virtual implode with brackets
1410 * @param string $start
1411 * @param string $sep
1412 * @param string $end
1413 * @param string|PPNode_DOM|DOMDocument $args,...
1416 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1417 $args = array_slice( func_get_args(), 3 );
1418 $out = array( $start );
1421 foreach ( $args as $root ) {
1422 if ( $root instanceof PPNode_DOM
) {
1423 $root = $root->node
;
1425 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1426 $root = array( $root );
1428 foreach ( $root as $node ) {
1441 public function __toString() {
1445 public function getPDBK( $level = false ) {
1446 if ( $level === false ) {
1447 return $this->title
->getPrefixedDBkey();
1449 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1456 public function getArguments() {
1463 public function getNumberedArguments() {
1470 public function getNamedArguments() {
1475 * Returns true if there are no arguments in this frame
1479 public function isEmpty() {
1483 public function getArgument( $name ) {
1488 * Returns true if the infinite loop check is OK, false if a loop is detected
1490 * @param Title $title
1493 public function loopCheck( $title ) {
1494 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1498 * Return true if the frame is a template frame
1502 public function isTemplate() {
1507 * Get a title of frame
1511 public function getTitle() {
1512 return $this->title
;
1516 * Set the volatile flag
1520 public function setVolatile( $flag = true ) {
1521 $this->volatile
= $flag;
1525 * Get the volatile flag
1529 public function isVolatile() {
1530 return $this->volatile
;
1538 public function setTTL( $ttl ) {
1539 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1549 public function getTTL() {
1555 * Expansion frame with template arguments
1558 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1559 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1560 // @codingStandardsIgnoreEnd
1562 public $numberedArgs, $namedArgs;
1568 public $numberedExpansionCache, $namedExpansionCache;
1571 * @param Preprocessor $preprocessor
1572 * @param bool|PPFrame_DOM $parent
1573 * @param array $numberedArgs
1574 * @param array $namedArgs
1575 * @param bool|Title $title
1577 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1578 $namedArgs = array(), $title = false
1580 parent
::__construct( $preprocessor );
1582 $this->parent
= $parent;
1583 $this->numberedArgs
= $numberedArgs;
1584 $this->namedArgs
= $namedArgs;
1585 $this->title
= $title;
1586 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1587 $this->titleCache
= $parent->titleCache
;
1588 $this->titleCache
[] = $pdbk;
1589 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1590 if ( $pdbk !== false ) {
1591 $this->loopCheckHash
[$pdbk] = true;
1593 $this->depth
= $parent->depth +
1;
1594 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1597 public function __toString() {
1600 $args = $this->numberedArgs +
$this->namedArgs
;
1601 foreach ( $args as $name => $value ) {
1607 $s .= "\"$name\":\"" .
1608 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1615 * @throws MWException
1616 * @param string|int $key
1617 * @param string|PPNode_DOM|DOMDocument $root
1621 public function cachedExpand( $key, $root, $flags = 0 ) {
1622 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1623 return $this->parent
->childExpansionCache
[$key];
1625 $retval = $this->expand( $root, $flags );
1626 if ( !$this->isVolatile() ) {
1627 $this->parent
->childExpansionCache
[$key] = $retval;
1633 * Returns true if there are no arguments in this frame
1637 public function isEmpty() {
1638 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1641 public function getArguments() {
1642 $arguments = array();
1643 foreach ( array_merge(
1644 array_keys( $this->numberedArgs
),
1645 array_keys( $this->namedArgs
) ) as $key ) {
1646 $arguments[$key] = $this->getArgument( $key );
1651 public function getNumberedArguments() {
1652 $arguments = array();
1653 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1654 $arguments[$key] = $this->getArgument( $key );
1659 public function getNamedArguments() {
1660 $arguments = array();
1661 foreach ( array_keys( $this->namedArgs
) as $key ) {
1662 $arguments[$key] = $this->getArgument( $key );
1667 public function getNumberedArgument( $index ) {
1668 if ( !isset( $this->numberedArgs
[$index] ) ) {
1671 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1672 # No trimming for unnamed arguments
1673 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1674 $this->numberedArgs
[$index],
1675 PPFrame
::STRIP_COMMENTS
1678 return $this->numberedExpansionCache
[$index];
1681 public function getNamedArgument( $name ) {
1682 if ( !isset( $this->namedArgs
[$name] ) ) {
1685 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1686 # Trim named arguments post-expand, for backwards compatibility
1687 $this->namedExpansionCache
[$name] = trim(
1688 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1690 return $this->namedExpansionCache
[$name];
1693 public function getArgument( $name ) {
1694 $text = $this->getNumberedArgument( $name );
1695 if ( $text === false ) {
1696 $text = $this->getNamedArgument( $name );
1702 * Return true if the frame is a template frame
1706 public function isTemplate() {
1710 public function setVolatile( $flag = true ) {
1711 parent
::setVolatile( $flag );
1712 $this->parent
->setVolatile( $flag );
1715 public function setTTL( $ttl ) {
1716 parent
::setTTL( $ttl );
1717 $this->parent
->setTTL( $ttl );
1722 * Expansion frame with custom arguments
1725 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1726 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1727 // @codingStandardsIgnoreEnd
1731 public function __construct( $preprocessor, $args ) {
1732 parent
::__construct( $preprocessor );
1733 $this->args
= $args;
1736 public function __toString() {
1739 foreach ( $this->args
as $name => $value ) {
1745 $s .= "\"$name\":\"" .
1746 str_replace( '"', '\\"', $value->__toString() ) . '"';
1755 public function isEmpty() {
1756 return !count( $this->args
);
1759 public function getArgument( $index ) {
1760 if ( !isset( $this->args
[$index] ) ) {
1763 return $this->args
[$index];
1766 public function getArguments() {
1774 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1775 class PPNode_DOM
implements PPNode
{
1776 // @codingStandardsIgnoreEnd
1784 public function __construct( $node, $xpath = false ) {
1785 $this->node
= $node;
1791 public function getXPath() {
1792 if ( $this->xpath
=== null ) {
1793 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1795 return $this->xpath
;
1798 public function __toString() {
1799 if ( $this->node
instanceof DOMNodeList
) {
1801 foreach ( $this->node
as $node ) {
1802 $s .= $node->ownerDocument
->saveXML( $node );
1805 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1811 * @return bool|PPNode_DOM
1813 public function getChildren() {
1814 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1818 * @return bool|PPNode_DOM
1820 public function getFirstChild() {
1821 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1825 * @return bool|PPNode_DOM
1827 public function getNextSibling() {
1828 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1832 * @param string $type
1834 * @return bool|PPNode_DOM
1836 public function getChildrenOfType( $type ) {
1837 return new self( $this->getXPath()->query( $type, $this->node
) );
1843 public function getLength() {
1844 if ( $this->node
instanceof DOMNodeList
) {
1845 return $this->node
->length
;
1853 * @return bool|PPNode_DOM
1855 public function item( $i ) {
1856 $item = $this->node
->item( $i );
1857 return $item ?
new self( $item ) : false;
1863 public function getName() {
1864 if ( $this->node
instanceof DOMNodeList
) {
1867 return $this->node
->nodeName
;
1872 * Split a "<part>" node into an associative array containing:
1873 * - name PPNode name
1874 * - index String index
1875 * - value PPNode value
1877 * @throws MWException
1880 public function splitArg() {
1881 $xpath = $this->getXPath();
1882 $names = $xpath->query( 'name', $this->node
);
1883 $values = $xpath->query( 'value', $this->node
);
1884 if ( !$names->length ||
!$values->length
) {
1885 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1887 $name = $names->item( 0 );
1888 $index = $name->getAttribute( 'index' );
1890 'name' => new self( $name ),
1892 'value' => new self( $values->item( 0 ) ) );
1896 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1897 * All values in the resulting array are PPNodes. Inner and close are optional.
1899 * @throws MWException
1902 public function splitExt() {
1903 $xpath = $this->getXPath();
1904 $names = $xpath->query( 'name', $this->node
);
1905 $attrs = $xpath->query( 'attr', $this->node
);
1906 $inners = $xpath->query( 'inner', $this->node
);
1907 $closes = $xpath->query( 'close', $this->node
);
1908 if ( !$names->length ||
!$attrs->length
) {
1909 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1912 'name' => new self( $names->item( 0 ) ),
1913 'attr' => new self( $attrs->item( 0 ) ) );
1914 if ( $inners->length
) {
1915 $parts['inner'] = new self( $inners->item( 0 ) );
1917 if ( $closes->length
) {
1918 $parts['close'] = new self( $closes->item( 0 ) );
1924 * Split a "<h>" node
1925 * @throws MWException
1928 public function splitHeading() {
1929 if ( $this->getName() !== 'h' ) {
1930 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1933 'i' => $this->node
->getAttribute( 'i' ),
1934 'level' => $this->node
->getAttribute( 'level' ),
1935 'contents' => $this->getChildren()