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 T6899.
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 $stack->top
->close
=== '}-' &&
281 $stack->top
->count
> 2
283 # adjust closing for -{{{...{{
284 $currentClosing = '}';
285 $search .= $currentClosing;
287 $currentClosing = $stack->top
->close
;
288 $search .= $currentClosing;
294 // First equals will be for the template
298 # Output literal section, advance input counter
299 $literalLength = strcspn( $text, $search, $i );
300 if ( $literalLength > 0 ) {
301 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
302 $i +
= $literalLength;
304 if ( $i >= $lengthText ) {
305 if ( $currentClosing == "\n" ) {
306 // Do a past-the-end run to finish off the heading
314 $curChar = $curTwoChar = $text[$i];
315 if ( ( $i +
1 ) < $lengthText ) {
316 $curTwoChar .= $text[$i +
1];
318 if ( $curChar == '|' ) {
320 } elseif ( $curChar == '=' ) {
322 } elseif ( $curChar == '<' ) {
324 } elseif ( $curChar == "\n" ) {
328 $found = 'line-start';
330 } elseif ( $curTwoChar == $currentClosing ) {
332 $curChar = $curTwoChar;
333 } elseif ( $curChar == $currentClosing ) {
335 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
336 $curChar = $curTwoChar;
338 $rule = $this->rules
[$curChar];
339 } elseif ( isset( $this->rules
[$curChar] ) ) {
341 $rule = $this->rules
[$curChar];
343 # Some versions of PHP have a strcspn which stops on
344 # null characters; ignore these and continue.
345 # We also may get '-' and '}' characters here which
346 # don't match -{ or $currentClosing. Add these to
347 # output and continue.
348 if ( $curChar == '-' ||
$curChar == '}' ) {
357 if ( $found == 'angle' ) {
359 // Handle </onlyinclude>
360 if ( $enableOnlyinclude
361 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
363 $findOnlyinclude = true;
367 // Determine element name
368 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
369 // Element name missing or not listed
375 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
377 // To avoid leaving blank lines, when a sequence of
378 // space-separated comments is both preceded and followed by
379 // a newline (ignoring spaces), then
380 // trim leading and trailing spaces and the trailing newline.
383 $endPos = strpos( $text, '-->', $i +
4 );
384 if ( $endPos === false ) {
385 // Unclosed comment in input, runs to end
386 $inner = substr( $text, $i );
387 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
390 // Search backwards for leading whitespace
391 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
393 // Search forwards for trailing whitespace
394 // $wsEnd will be the position of the last space (or the '>' if there's none)
395 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
397 // Keep looking forward as long as we're finding more
399 $comments = [ [ $wsStart, $wsEnd ] ];
400 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
401 $c = strpos( $text, '-->', $wsEnd +
4 );
402 if ( $c === false ) {
405 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
406 $comments[] = [ $wsEnd +
1, $c ];
410 // Eat the line if possible
411 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
412 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
413 // it's a possible beneficial b/c break.
414 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
415 && substr( $text, $wsEnd +
1, 1 ) == "\n"
417 // Remove leading whitespace from the end of the accumulator
418 // Sanity check first though
419 $wsLength = $i - $wsStart;
421 && strspn( $accum, " \t", -$wsLength ) === $wsLength
423 $accum = substr( $accum, 0, -$wsLength );
426 // Dump all but the last comment to the accumulator
427 foreach ( $comments as $j => $com ) {
429 $endPos = $com[1] +
1;
430 if ( $j == ( count( $comments ) - 1 ) ) {
433 $inner = substr( $text, $startPos, $endPos - $startPos );
434 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
437 // Do a line-start run next time to look for headings after the comment
438 $fakeLineStart = true;
440 // No line to eat, just take the comment itself
446 $part = $stack->top
->getCurrentPart();
447 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
448 $part->visualEnd
= $wsStart;
450 // Else comments abutting, no change in visual end
451 $part->commentEnd
= $endPos;
454 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
455 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
460 $lowerName = strtolower( $name );
461 $attrStart = $i +
strlen( $name ) +
1;
464 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
465 if ( $tagEndPos === false ) {
466 // Infinite backtrack
467 // Disable tag search to prevent worst-case O(N^2) performance
474 // Handle ignored tags
475 if ( in_array( $lowerName, $ignoredTags ) ) {
477 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
484 if ( $text[$tagEndPos - 1] == '/' ) {
485 $attrEnd = $tagEndPos - 1;
490 $attrEnd = $tagEndPos;
493 !isset( $noMoreClosingTag[$name] ) &&
494 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
495 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
497 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
498 $i = $matches[0][1] +
strlen( $matches[0][0] );
499 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
502 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
503 // Let it run out to the end of the text.
504 $inner = substr( $text, $tagEndPos +
1 );
508 // Don't match the tag, treat opening tag as literal and resume parsing.
510 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
511 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
512 $noMoreClosingTag[$name] = true;
517 // <includeonly> and <noinclude> just become <ignore> tags
518 if ( in_array( $lowerName, $ignoredElements ) ) {
519 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
525 if ( $attrEnd <= $attrStart ) {
528 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
530 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
531 // Note that the attr element contains the whitespace between name and attribute,
532 // this is necessary for precise reconstruction during pre-save transform.
533 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
534 if ( $inner !== null ) {
535 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
537 $accum .= $close . '</ext>';
538 } elseif ( $found == 'line-start' ) {
539 // Is this the start of a heading?
540 // Line break belongs before the heading element in any case
541 if ( $fakeLineStart ) {
542 $fakeLineStart = false;
548 $count = strspn( $text, '=', $i, 6 );
549 if ( $count == 1 && $findEquals ) {
550 // DWIM: This looks kind of like a name/value separator.
551 // Let's let the equals handler have it and break the
552 // potential heading. This is heuristic, but AFAICT the
553 // methods for completely correct disambiguation are very
555 } elseif ( $count > 0 ) {
559 'parts' => [ new PPDPart( str_repeat( '=', $count ) ) ],
562 $stack->push( $piece );
563 $accum =& $stack->getAccum();
564 $flags = $stack->getFlags();
568 } elseif ( $found == 'line-end' ) {
569 $piece = $stack->top
;
570 // A heading must be open, otherwise \n wouldn't have been in the search list
571 assert( $piece->open
=== "\n" );
572 $part = $piece->getCurrentPart();
573 // Search back through the input to see if it has a proper close.
574 // Do this using the reversed string since the other solutions
575 // (end anchor, etc.) are inefficient.
576 $wsLength = strspn( $revText, " \t", $lengthText - $i );
577 $searchStart = $i - $wsLength;
578 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
579 // Comment found at line end
580 // Search for equals signs before the comment
581 $searchStart = $part->visualEnd
;
582 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
584 $count = $piece->count
;
585 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
586 if ( $equalsLength > 0 ) {
587 if ( $searchStart - $equalsLength == $piece->startPos
) {
588 // This is just a single string of equals signs on its own line
589 // Replicate the doHeadings behavior /={count}(.+)={count}/
590 // First find out how many equals signs there really are (don't stop at 6)
591 $count = $equalsLength;
595 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
598 $count = min( $equalsLength, $count );
601 // Normal match, output <h>
602 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
605 // Single equals sign on its own line, count=0
609 // No match, no <h>, just pass down the inner text
614 $accum =& $stack->getAccum();
615 $flags = $stack->getFlags();
618 // Append the result to the enclosing accumulator
620 // Note that we do NOT increment the input pointer.
621 // This is because the closing linebreak could be the opening linebreak of
622 // another heading. Infinite loops are avoided because the next iteration MUST
623 // hit the heading open case above, which unconditionally increments the
625 } elseif ( $found == 'open' ) {
626 # count opening brace characters
627 $curLen = strlen( $curChar );
628 $count = ( $curLen > 1 ) ?
629 # allow the final character to repeat
630 strspn( $text, $curChar[$curLen-1], $i+
1 ) +
1 :
631 strspn( $text, $curChar, $i );
633 # we need to add to stack only if opening brace count is enough for one of the rules
634 if ( $count >= $rule['min'] ) {
635 # Add it to the stack
638 'close' => $rule['end'],
640 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
643 $stack->push( $piece );
644 $accum =& $stack->getAccum();
645 $flags = $stack->getFlags();
648 # Add literal brace(s)
649 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
652 } elseif ( $found == 'close' ) {
653 $piece = $stack->top
;
654 # lets check if there are enough characters for closing brace
655 $maxCount = $piece->count
;
656 if ( $piece->close
=== '}-' && $curChar === '}' ) {
657 $maxCount--; # don't try to match closing '-' as a '}'
659 $curLen = strlen( $curChar );
660 $count = ( $curLen > 1 ) ?
$curLen :
661 strspn( $text, $curChar, $i, $maxCount );
663 # check for maximum matching characters (if there are 5 closing
664 # characters, we will probably need only 3 - depending on the rules)
665 $rule = $this->rules
[$piece->open
];
666 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
667 # tweak for -{..{{ }}..}-
668 $rule = $this->rules
['{'];
670 if ( $count > $rule['max'] ) {
671 # The specified maximum exists in the callback array, unless the caller
673 $matchingCount = $rule['max'];
675 # Count is less than the maximum
676 # Skip any gaps in the callback array to find the true largest match
677 # Need to use array_key_exists not isset because the callback can be null
678 $matchingCount = $count;
679 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
684 if ( $matchingCount <= 0 ) {
685 # No matching element found in callback array
686 # Output a literal closing brace and continue
687 $endText = substr( $text, $i, $count );
688 $accum .= htmlspecialchars( $endText );
692 $name = $rule['names'][$matchingCount];
693 if ( $name === null ) {
694 // No element, just literal text
695 $endText = substr( $text, $i, $matchingCount );
696 $element = $piece->breakSyntax( $matchingCount ) . $endText;
699 # Note: $parts is already XML, does not need to be encoded further
700 $parts = $piece->parts
;
701 $title = $parts[0]->out
;
704 # The invocation is at the start of the line if lineStart is set in
705 # the stack, and all opening brackets are used up.
706 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
707 $attr = ' lineStart="1"';
712 $element = "<$name$attr>";
713 $element .= "<title>$title</title>";
715 foreach ( $parts as $part ) {
716 if ( isset( $part->eqpos
) ) {
717 $argName = substr( $part->out
, 0, $part->eqpos
);
718 $argValue = substr( $part->out
, $part->eqpos +
1 );
719 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
721 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
725 $element .= "</$name>";
728 # Advance input pointer
729 $i +
= $matchingCount;
733 $accum =& $stack->getAccum();
735 # Re-add the old stack element if it still has unmatched opening characters remaining
736 if ( $matchingCount < $piece->count
) {
737 $piece->parts
= [ new PPDPart
];
738 $piece->count
-= $matchingCount;
739 # do we still qualify for any callback with remaining count?
740 $min = $this->rules
[$piece->open
]['min'];
741 if ( $piece->count
>= $min ) {
742 $stack->push( $piece );
743 $accum =& $stack->getAccum();
745 $s = substr( $piece->open
, 0, -1 );
747 substr( $piece->open
, -1 ),
748 $piece->count
- strlen( $s )
753 $flags = $stack->getFlags();
756 # Add XML element to the enclosing accumulator
758 } elseif ( $found == 'pipe' ) {
759 $findEquals = true; // shortcut for getFlags()
761 $accum =& $stack->getAccum();
763 } elseif ( $found == 'equals' ) {
764 $findEquals = false; // shortcut for getFlags()
765 $stack->getCurrentPart()->eqpos
= strlen( $accum );
768 } elseif ( $found == 'dash' ) {
774 # Output any remaining unclosed brackets
775 foreach ( $stack->stack
as $piece ) {
776 $stack->rootAccum
.= $piece->breakSyntax();
778 $stack->rootAccum
.= '</root>';
779 $xml = $stack->rootAccum
;
786 * Stack class to help Preprocessor::preprocessToObj()
790 public $stack, $rootAccum;
797 public $elementClass = 'PPDStackElement';
799 public static $false = false;
801 public function __construct() {
804 $this->rootAccum
= '';
805 $this->accum
=& $this->rootAccum
;
811 public function count() {
812 return count( $this->stack
);
815 public function &getAccum() {
819 public function getCurrentPart() {
820 if ( $this->top
=== false ) {
823 return $this->top
->getCurrentPart();
827 public function push( $data ) {
828 if ( $data instanceof $this->elementClass
) {
829 $this->stack
[] = $data;
831 $class = $this->elementClass
;
832 $this->stack
[] = new $class( $data );
834 $this->top
= $this->stack
[count( $this->stack
) - 1];
835 $this->accum
=& $this->top
->getAccum();
838 public function pop() {
839 if ( !count( $this->stack
) ) {
840 throw new MWException( __METHOD__
. ': no elements remaining' );
842 $temp = array_pop( $this->stack
);
844 if ( count( $this->stack
) ) {
845 $this->top
= $this->stack
[count( $this->stack
) - 1];
846 $this->accum
=& $this->top
->getAccum();
848 $this->top
= self
::$false;
849 $this->accum
=& $this->rootAccum
;
854 public function addPart( $s = '' ) {
855 $this->top
->addPart( $s );
856 $this->accum
=& $this->top
->getAccum();
862 public function getFlags() {
863 if ( !count( $this->stack
) ) {
865 'findEquals' => false,
867 'inHeading' => false,
870 return $this->top
->getFlags();
878 class PPDStackElement
{
880 * @var string Opening character (\n for heading)
885 * @var string Matching closing character
890 * @var int Number of opening characters found (number of "=" for heading)
895 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
900 * @var bool True if the open char appeared at the start of the input line.
901 * Not set for headings.
905 public $partClass = 'PPDPart';
907 public function __construct( $data = [] ) {
908 $class = $this->partClass
;
909 $this->parts
= [ new $class ];
911 foreach ( $data as $name => $value ) {
912 $this->$name = $value;
916 public function &getAccum() {
917 return $this->parts
[count( $this->parts
) - 1]->out
;
920 public function addPart( $s = '' ) {
921 $class = $this->partClass
;
922 $this->parts
[] = new $class( $s );
925 public function getCurrentPart() {
926 return $this->parts
[count( $this->parts
) - 1];
932 public function getFlags() {
933 $partCount = count( $this->parts
);
934 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
936 'findPipe' => $findPipe,
937 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
938 'inHeading' => $this->open
== "\n",
943 * Get the output string that would result if the close is not found.
945 * @param bool|int $openingCount
948 public function breakSyntax( $openingCount = false ) {
949 if ( $this->open
== "\n" ) {
950 $s = $this->parts
[0]->out
;
952 if ( $openingCount === false ) {
953 $openingCount = $this->count
;
955 $s = substr( $this->open
, 0, -1 );
957 substr( $this->open
, -1 ),
958 $openingCount - strlen( $s )
961 foreach ( $this->parts
as $part ) {
979 * @var string Output accumulator string
983 // Optional member variables:
984 // eqpos Position of equals sign in output accumulator
985 // commentEnd Past-the-end input pointer for the last comment encountered
986 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
988 public function __construct( $out = '' ) {
994 * An expansion frame, used as a context to expand the result of preprocessToObj()
997 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
998 class PPFrame_DOM
implements PPFrame
{
999 // @codingStandardsIgnoreEnd
1004 public $preprocessor;
1018 * Hashtable listing templates which are disallowed for expansion in this frame,
1019 * having been encountered previously in parent frames.
1021 public $loopCheckHash;
1024 * Recursion depth of this frame, top = 0
1025 * Note that this is NOT the same as expansion depth in expand()
1029 private $volatile = false;
1030 private $ttl = null;
1035 protected $childExpansionCache;
1038 * Construct a new preprocessor frame.
1039 * @param Preprocessor $preprocessor The parent preprocessor
1041 public function __construct( $preprocessor ) {
1042 $this->preprocessor
= $preprocessor;
1043 $this->parser
= $preprocessor->parser
;
1044 $this->title
= $this->parser
->mTitle
;
1045 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
1046 $this->loopCheckHash
= [];
1048 $this->childExpansionCache
= [];
1052 * Create a new child frame
1053 * $args is optionally a multi-root PPNode or array containing the template arguments
1055 * @param bool|array $args
1056 * @param Title|bool $title
1057 * @param int $indexOffset
1058 * @return PPTemplateFrame_DOM
1060 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1063 if ( $title === false ) {
1064 $title = $this->title
;
1066 if ( $args !== false ) {
1068 if ( $args instanceof PPNode
) {
1069 $args = $args->node
;
1071 foreach ( $args as $arg ) {
1072 if ( $arg instanceof PPNode
) {
1075 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1076 $xpath = new DOMXPath( $arg->ownerDocument
);
1079 $nameNodes = $xpath->query( 'name', $arg );
1080 $value = $xpath->query( 'value', $arg );
1081 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1082 // Numbered parameter
1083 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1084 $index = $index - $indexOffset;
1085 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1086 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1087 wfEscapeWikiText( $this->title
),
1088 wfEscapeWikiText( $title ),
1089 wfEscapeWikiText( $index ) )->text() );
1090 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1092 $numberedArgs[$index] = $value->item( 0 );
1093 unset( $namedArgs[$index] );
1096 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1097 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1098 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1099 wfEscapeWikiText( $this->title
),
1100 wfEscapeWikiText( $title ),
1101 wfEscapeWikiText( $name ) )->text() );
1102 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1104 $namedArgs[$name] = $value->item( 0 );
1105 unset( $numberedArgs[$name] );
1109 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1113 * @throws MWException
1114 * @param string|int $key
1115 * @param string|PPNode_DOM|DOMDocument $root
1119 public function cachedExpand( $key, $root, $flags = 0 ) {
1120 // we don't have a parent, so we don't have a cache
1121 return $this->expand( $root, $flags );
1125 * @throws MWException
1126 * @param string|PPNode_DOM|DOMDocument $root
1130 public function expand( $root, $flags = 0 ) {
1131 static $expansionDepth = 0;
1132 if ( is_string( $root ) ) {
1136 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1137 $this->parser
->limitationWarn( 'node-count-exceeded',
1138 $this->parser
->mPPNodeCount
,
1139 $this->parser
->mOptions
->getMaxPPNodeCount()
1141 return '<span class="error">Node-count limit exceeded</span>';
1144 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1145 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1147 $this->parser
->mOptions
->getMaxPPExpandDepth()
1149 return '<span class="error">Expansion depth limit exceeded</span>';
1152 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1153 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1156 if ( $root instanceof PPNode_DOM
) {
1157 $root = $root->node
;
1159 if ( $root instanceof DOMDocument
) {
1160 $root = $root->documentElement
;
1163 $outStack = [ '', '' ];
1164 $iteratorStack = [ false, $root ];
1165 $indexStack = [ 0, 0 ];
1167 while ( count( $iteratorStack ) > 1 ) {
1168 $level = count( $outStack ) - 1;
1169 $iteratorNode =& $iteratorStack[$level];
1170 $out =& $outStack[$level];
1171 $index =& $indexStack[$level];
1173 if ( $iteratorNode instanceof PPNode_DOM
) {
1174 $iteratorNode = $iteratorNode->node
;
1177 if ( is_array( $iteratorNode ) ) {
1178 if ( $index >= count( $iteratorNode ) ) {
1179 // All done with this iterator
1180 $iteratorStack[$level] = false;
1181 $contextNode = false;
1183 $contextNode = $iteratorNode[$index];
1186 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1187 if ( $index >= $iteratorNode->length
) {
1188 // All done with this iterator
1189 $iteratorStack[$level] = false;
1190 $contextNode = false;
1192 $contextNode = $iteratorNode->item( $index );
1196 // Copy to $contextNode and then delete from iterator stack,
1197 // because this is not an iterator but we do have to execute it once
1198 $contextNode = $iteratorStack[$level];
1199 $iteratorStack[$level] = false;
1202 if ( $contextNode instanceof PPNode_DOM
) {
1203 $contextNode = $contextNode->node
;
1206 $newIterator = false;
1208 if ( $contextNode === false ) {
1210 } elseif ( is_string( $contextNode ) ) {
1211 $out .= $contextNode;
1212 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1213 $newIterator = $contextNode;
1214 } elseif ( $contextNode instanceof DOMNode
) {
1215 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1216 $out .= $contextNode->nodeValue
;
1217 } elseif ( $contextNode->nodeName
== 'template' ) {
1218 # Double-brace expansion
1219 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1220 $titles = $xpath->query( 'title', $contextNode );
1221 $title = $titles->item( 0 );
1222 $parts = $xpath->query( 'part', $contextNode );
1223 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1224 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1226 $lineStart = $contextNode->getAttribute( 'lineStart' );
1228 'title' => new PPNode_DOM( $title ),
1229 'parts' => new PPNode_DOM( $parts ),
1230 'lineStart' => $lineStart ];
1231 $ret = $this->parser
->braceSubstitution( $params, $this );
1232 if ( isset( $ret['object'] ) ) {
1233 $newIterator = $ret['object'];
1235 $out .= $ret['text'];
1238 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1239 # Triple-brace expansion
1240 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1241 $titles = $xpath->query( 'title', $contextNode );
1242 $title = $titles->item( 0 );
1243 $parts = $xpath->query( 'part', $contextNode );
1244 if ( $flags & PPFrame
::NO_ARGS
) {
1245 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1248 'title' => new PPNode_DOM( $title ),
1249 'parts' => new PPNode_DOM( $parts ) ];
1250 $ret = $this->parser
->argSubstitution( $params, $this );
1251 if ( isset( $ret['object'] ) ) {
1252 $newIterator = $ret['object'];
1254 $out .= $ret['text'];
1257 } elseif ( $contextNode->nodeName
== 'comment' ) {
1258 # HTML-style comment
1259 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1260 # Not in RECOVER_COMMENTS mode (msgnw) though.
1261 if ( ( $this->parser
->ot
['html']
1262 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1263 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1264 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1267 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1268 # Add a strip marker in PST mode so that pstPass2() can
1269 # run some old-fashioned regexes on the result.
1270 # Not in RECOVER_COMMENTS mode (extractSections) though.
1271 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1273 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1274 $out .= $contextNode->textContent
;
1276 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1277 # Output suppression used by <includeonly> etc.
1278 # OT_WIKI will only respect <ignore> in substed templates.
1279 # The other output types respect it unless NO_IGNORE is set.
1280 # extractSections() sets NO_IGNORE and so never respects it.
1281 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1282 ||
( $flags & PPFrame
::NO_IGNORE
)
1284 $out .= $contextNode->textContent
;
1288 } elseif ( $contextNode->nodeName
== 'ext' ) {
1290 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1291 $names = $xpath->query( 'name', $contextNode );
1292 $attrs = $xpath->query( 'attr', $contextNode );
1293 $inners = $xpath->query( 'inner', $contextNode );
1294 $closes = $xpath->query( 'close', $contextNode );
1295 if ( $flags & PPFrame
::NO_TAGS
) {
1296 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1297 if ( $attrs->length
> 0 ) {
1298 $s .= $this->expand( $attrs->item( 0 ), $flags );
1300 if ( $inners->length
> 0 ) {
1301 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1302 if ( $closes->length
> 0 ) {
1303 $s .= $this->expand( $closes->item( 0 ), $flags );
1311 'name' => new PPNode_DOM( $names->item( 0 ) ),
1312 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1313 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1314 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1316 $out .= $this->parser
->extensionSubstitution( $params, $this );
1318 } elseif ( $contextNode->nodeName
== 'h' ) {
1320 $s = $this->expand( $contextNode->childNodes
, $flags );
1322 # Insert a heading marker only for <h> children of <root>
1323 # This is to stop extractSections from going over multiple tree levels
1324 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1325 # Insert heading index marker
1326 $headingIndex = $contextNode->getAttribute( 'i' );
1327 $titleText = $this->title
->getPrefixedDBkey();
1328 $this->parser
->mHeadings
[] = [ $titleText, $headingIndex ];
1329 $serial = count( $this->parser
->mHeadings
) - 1;
1330 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1331 $count = $contextNode->getAttribute( 'level' );
1332 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1333 $this->parser
->mStripState
->addGeneral( $marker, '' );
1337 # Generic recursive expansion
1338 $newIterator = $contextNode->childNodes
;
1341 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1344 if ( $newIterator !== false ) {
1345 if ( $newIterator instanceof PPNode_DOM
) {
1346 $newIterator = $newIterator->node
;
1349 $iteratorStack[] = $newIterator;
1351 } elseif ( $iteratorStack[$level] === false ) {
1352 // Return accumulated value to parent
1353 // With tail recursion
1354 while ( $iteratorStack[$level] === false && $level > 0 ) {
1355 $outStack[$level - 1] .= $out;
1356 array_pop( $outStack );
1357 array_pop( $iteratorStack );
1358 array_pop( $indexStack );
1364 return $outStack[0];
1368 * @param string $sep
1370 * @param string|PPNode_DOM|DOMDocument $args,...
1373 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1374 $args = array_slice( func_get_args(), 2 );
1378 foreach ( $args as $root ) {
1379 if ( $root instanceof PPNode_DOM
) {
1380 $root = $root->node
;
1382 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1385 foreach ( $root as $node ) {
1391 $s .= $this->expand( $node, $flags );
1398 * Implode with no flags specified
1399 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1401 * @param string $sep
1402 * @param string|PPNode_DOM|DOMDocument $args,...
1405 public function implode( $sep /*, ... */ ) {
1406 $args = array_slice( func_get_args(), 1 );
1410 foreach ( $args as $root ) {
1411 if ( $root instanceof PPNode_DOM
) {
1412 $root = $root->node
;
1414 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1417 foreach ( $root as $node ) {
1423 $s .= $this->expand( $node );
1430 * Makes an object that, when expand()ed, will be the same as one obtained
1433 * @param string $sep
1434 * @param string|PPNode_DOM|DOMDocument $args,...
1437 public function virtualImplode( $sep /*, ... */ ) {
1438 $args = array_slice( func_get_args(), 1 );
1442 foreach ( $args as $root ) {
1443 if ( $root instanceof PPNode_DOM
) {
1444 $root = $root->node
;
1446 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1449 foreach ( $root as $node ) {
1462 * Virtual implode with brackets
1463 * @param string $start
1464 * @param string $sep
1465 * @param string $end
1466 * @param string|PPNode_DOM|DOMDocument $args,...
1469 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1470 $args = array_slice( func_get_args(), 3 );
1474 foreach ( $args as $root ) {
1475 if ( $root instanceof PPNode_DOM
) {
1476 $root = $root->node
;
1478 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1481 foreach ( $root as $node ) {
1494 public function __toString() {
1498 public function getPDBK( $level = false ) {
1499 if ( $level === false ) {
1500 return $this->title
->getPrefixedDBkey();
1502 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1509 public function getArguments() {
1516 public function getNumberedArguments() {
1523 public function getNamedArguments() {
1528 * Returns true if there are no arguments in this frame
1532 public function isEmpty() {
1537 * @param int|string $name
1538 * @return bool Always false in this implementation.
1540 public function getArgument( $name ) {
1545 * Returns true if the infinite loop check is OK, false if a loop is detected
1547 * @param Title $title
1550 public function loopCheck( $title ) {
1551 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1555 * Return true if the frame is a template frame
1559 public function isTemplate() {
1564 * Get a title of frame
1568 public function getTitle() {
1569 return $this->title
;
1573 * Set the volatile flag
1577 public function setVolatile( $flag = true ) {
1578 $this->volatile
= $flag;
1582 * Get the volatile flag
1586 public function isVolatile() {
1587 return $this->volatile
;
1595 public function setTTL( $ttl ) {
1596 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1606 public function getTTL() {
1612 * Expansion frame with template arguments
1615 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1616 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1617 // @codingStandardsIgnoreEnd
1619 public $numberedArgs, $namedArgs;
1625 public $numberedExpansionCache, $namedExpansionCache;
1628 * @param Preprocessor $preprocessor
1629 * @param bool|PPFrame_DOM $parent
1630 * @param array $numberedArgs
1631 * @param array $namedArgs
1632 * @param bool|Title $title
1634 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1635 $namedArgs = [], $title = false
1637 parent
::__construct( $preprocessor );
1639 $this->parent
= $parent;
1640 $this->numberedArgs
= $numberedArgs;
1641 $this->namedArgs
= $namedArgs;
1642 $this->title
= $title;
1643 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1644 $this->titleCache
= $parent->titleCache
;
1645 $this->titleCache
[] = $pdbk;
1646 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1647 if ( $pdbk !== false ) {
1648 $this->loopCheckHash
[$pdbk] = true;
1650 $this->depth
= $parent->depth +
1;
1651 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1654 public function __toString() {
1657 $args = $this->numberedArgs +
$this->namedArgs
;
1658 foreach ( $args as $name => $value ) {
1664 $s .= "\"$name\":\"" .
1665 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1672 * @throws MWException
1673 * @param string|int $key
1674 * @param string|PPNode_DOM|DOMDocument $root
1678 public function cachedExpand( $key, $root, $flags = 0 ) {
1679 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1680 return $this->parent
->childExpansionCache
[$key];
1682 $retval = $this->expand( $root, $flags );
1683 if ( !$this->isVolatile() ) {
1684 $this->parent
->childExpansionCache
[$key] = $retval;
1690 * Returns true if there are no arguments in this frame
1694 public function isEmpty() {
1695 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1698 public function getArguments() {
1700 foreach ( array_merge(
1701 array_keys( $this->numberedArgs
),
1702 array_keys( $this->namedArgs
) ) as $key ) {
1703 $arguments[$key] = $this->getArgument( $key );
1708 public function getNumberedArguments() {
1710 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1711 $arguments[$key] = $this->getArgument( $key );
1716 public function getNamedArguments() {
1718 foreach ( array_keys( $this->namedArgs
) as $key ) {
1719 $arguments[$key] = $this->getArgument( $key );
1726 * @return string|bool
1728 public function getNumberedArgument( $index ) {
1729 if ( !isset( $this->numberedArgs
[$index] ) ) {
1732 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1733 # No trimming for unnamed arguments
1734 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1735 $this->numberedArgs
[$index],
1736 PPFrame
::STRIP_COMMENTS
1739 return $this->numberedExpansionCache
[$index];
1743 * @param string $name
1744 * @return string|bool
1746 public function getNamedArgument( $name ) {
1747 if ( !isset( $this->namedArgs
[$name] ) ) {
1750 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1751 # Trim named arguments post-expand, for backwards compatibility
1752 $this->namedExpansionCache
[$name] = trim(
1753 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1755 return $this->namedExpansionCache
[$name];
1759 * @param int|string $name
1760 * @return string|bool
1762 public function getArgument( $name ) {
1763 $text = $this->getNumberedArgument( $name );
1764 if ( $text === false ) {
1765 $text = $this->getNamedArgument( $name );
1771 * Return true if the frame is a template frame
1775 public function isTemplate() {
1779 public function setVolatile( $flag = true ) {
1780 parent
::setVolatile( $flag );
1781 $this->parent
->setVolatile( $flag );
1784 public function setTTL( $ttl ) {
1785 parent
::setTTL( $ttl );
1786 $this->parent
->setTTL( $ttl );
1791 * Expansion frame with custom arguments
1794 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1795 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1796 // @codingStandardsIgnoreEnd
1800 public function __construct( $preprocessor, $args ) {
1801 parent
::__construct( $preprocessor );
1802 $this->args
= $args;
1805 public function __toString() {
1808 foreach ( $this->args
as $name => $value ) {
1814 $s .= "\"$name\":\"" .
1815 str_replace( '"', '\\"', $value->__toString() ) . '"';
1824 public function isEmpty() {
1825 return !count( $this->args
);
1829 * @param int|string $index
1830 * @return string|bool
1832 public function getArgument( $index ) {
1833 if ( !isset( $this->args
[$index] ) ) {
1836 return $this->args
[$index];
1839 public function getArguments() {
1847 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1848 class PPNode_DOM
implements PPNode
{
1849 // @codingStandardsIgnoreEnd
1857 public function __construct( $node, $xpath = false ) {
1858 $this->node
= $node;
1864 public function getXPath() {
1865 if ( $this->xpath
=== null ) {
1866 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1868 return $this->xpath
;
1871 public function __toString() {
1872 if ( $this->node
instanceof DOMNodeList
) {
1874 foreach ( $this->node
as $node ) {
1875 $s .= $node->ownerDocument
->saveXML( $node );
1878 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1884 * @return bool|PPNode_DOM
1886 public function getChildren() {
1887 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1891 * @return bool|PPNode_DOM
1893 public function getFirstChild() {
1894 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1898 * @return bool|PPNode_DOM
1900 public function getNextSibling() {
1901 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1905 * @param string $type
1907 * @return bool|PPNode_DOM
1909 public function getChildrenOfType( $type ) {
1910 return new self( $this->getXPath()->query( $type, $this->node
) );
1916 public function getLength() {
1917 if ( $this->node
instanceof DOMNodeList
) {
1918 return $this->node
->length
;
1926 * @return bool|PPNode_DOM
1928 public function item( $i ) {
1929 $item = $this->node
->item( $i );
1930 return $item ?
new self( $item ) : false;
1936 public function getName() {
1937 if ( $this->node
instanceof DOMNodeList
) {
1940 return $this->node
->nodeName
;
1945 * Split a "<part>" node into an associative array containing:
1946 * - name PPNode name
1947 * - index String index
1948 * - value PPNode value
1950 * @throws MWException
1953 public function splitArg() {
1954 $xpath = $this->getXPath();
1955 $names = $xpath->query( 'name', $this->node
);
1956 $values = $xpath->query( 'value', $this->node
);
1957 if ( !$names->length ||
!$values->length
) {
1958 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1960 $name = $names->item( 0 );
1961 $index = $name->getAttribute( 'index' );
1963 'name' => new self( $name ),
1965 'value' => new self( $values->item( 0 ) ) ];
1969 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1970 * All values in the resulting array are PPNodes. Inner and close are optional.
1972 * @throws MWException
1975 public function splitExt() {
1976 $xpath = $this->getXPath();
1977 $names = $xpath->query( 'name', $this->node
);
1978 $attrs = $xpath->query( 'attr', $this->node
);
1979 $inners = $xpath->query( 'inner', $this->node
);
1980 $closes = $xpath->query( 'close', $this->node
);
1981 if ( !$names->length ||
!$attrs->length
) {
1982 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1985 'name' => new self( $names->item( 0 ) ),
1986 'attr' => new self( $attrs->item( 0 ) ) ];
1987 if ( $inners->length
) {
1988 $parts['inner'] = new self( $inners->item( 0 ) );
1990 if ( $closes->length
) {
1991 $parts['close'] = new self( $closes->item( 0 ) );
1997 * Split a "<h>" node
1998 * @throws MWException
2001 public function splitHeading() {
2002 if ( $this->getName() !== 'h' ) {
2003 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2006 'i' => $this->node
->getAttribute( 'i' ),
2007 'level' => $this->node
->getAttribute( 'level' ),
2008 'contents' => $this->getChildren()