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 ) {
151 $xml = $this->cacheGetTree( $text, $flags );
152 if ( $xml === false ) {
153 $xml = $this->preprocessToXml( $text, $flags );
154 $this->cacheSetTree( $text, $flags, $xml );
157 // Fail if the number of elements exceeds acceptable limits
158 // Do not attempt to generate the DOM
159 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
160 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
161 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
162 // if ( $cacheable ) { ... }
163 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
166 $dom = new DOMDocument
;
167 MediaWiki\
suppressWarnings();
168 $result = $dom->loadXML( $xml );
169 MediaWiki\restoreWarnings
();
171 // Try running the XML through UtfNormal to get rid of invalid characters
172 $xml = UtfNormal\Validator
::cleanUp( $xml );
173 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
174 // don't barf when the XML is >256 levels deep.
175 $result = $dom->loadXML( $xml, 1 << 19 );
178 $obj = new PPNode_DOM( $dom->documentElement
);
181 // if ( $cacheable ) { ... }
184 throw new MWException( __METHOD__
. ' generated invalid XML' );
190 * @param string $text
194 public function preprocessToXml( $text, $flags = 0 ) {
195 global $wgDisableLangConversion;
197 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
199 $xmlishElements = $this->parser
->getStripList();
200 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
201 $enableOnlyinclude = false;
202 if ( $forInclusion ) {
203 $ignoredTags = [ 'includeonly', '/includeonly' ];
204 $ignoredElements = [ 'noinclude' ];
205 $xmlishElements[] = 'noinclude';
206 if ( strpos( $text, '<onlyinclude>' ) !== false
207 && strpos( $text, '</onlyinclude>' ) !== false
209 $enableOnlyinclude = true;
212 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
213 $ignoredElements = [ 'includeonly' ];
214 $xmlishElements[] = 'includeonly';
216 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
218 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
219 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
221 $stack = new PPDStack
;
223 $searchBase = "[{<\n"; # }
224 if ( !$wgDisableLangConversion ) {
228 // For fast reverse searches
229 $revText = strrev( $text );
230 $lengthText = strlen( $text );
232 // Input pointer, starts out pointing to a pseudo-newline before the start
234 // Current accumulator
235 $accum =& $stack->getAccum();
237 // True to find equals signs in arguments
239 // True to take notice of pipe characters
242 // True if $i is inside a possible heading
244 // True if there are no more greater-than (>) signs right of $i
246 // Map of tag name => true if there are no more closing tags of given type right of $i
247 $noMoreClosingTag = [];
248 // True to ignore all input up to the next <onlyinclude>
249 $findOnlyinclude = $enableOnlyinclude;
250 // Do a line-start run without outputting an LF character
251 $fakeLineStart = true;
254 // $this->memCheck();
256 if ( $findOnlyinclude ) {
257 // Ignore all input up to the next <onlyinclude>
258 $startPos = strpos( $text, '<onlyinclude>', $i );
259 if ( $startPos === false ) {
260 // Ignored section runs to the end
261 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
264 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
265 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
267 $findOnlyinclude = false;
270 if ( $fakeLineStart ) {
271 $found = 'line-start';
274 # Find next opening brace, closing brace or pipe
275 $search = $searchBase;
276 if ( $stack->top
=== false ) {
277 $currentClosing = '';
279 $stack->top
->close
=== '}-' &&
280 $stack->top
->count
> 2
282 # adjust closing for -{{{...{{
283 $currentClosing = '}';
284 $search .= $currentClosing;
286 $currentClosing = $stack->top
->close
;
287 $search .= $currentClosing;
293 // First equals will be for the template
297 # Output literal section, advance input counter
298 $literalLength = strcspn( $text, $search, $i );
299 if ( $literalLength > 0 ) {
300 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
301 $i +
= $literalLength;
303 if ( $i >= $lengthText ) {
304 if ( $currentClosing == "\n" ) {
305 // Do a past-the-end run to finish off the heading
313 $curChar = $curTwoChar = $text[$i];
314 if ( ( $i +
1 ) < $lengthText ) {
315 $curTwoChar .= $text[$i +
1];
317 if ( $curChar == '|' ) {
319 } elseif ( $curChar == '=' ) {
321 } elseif ( $curChar == '<' ) {
323 } elseif ( $curChar == "\n" ) {
327 $found = 'line-start';
329 } elseif ( $curTwoChar == $currentClosing ) {
331 $curChar = $curTwoChar;
332 } elseif ( $curChar == $currentClosing ) {
334 } elseif ( isset( $this->rules
[$curTwoChar] ) ) {
335 $curChar = $curTwoChar;
337 $rule = $this->rules
[$curChar];
338 } elseif ( isset( $this->rules
[$curChar] ) ) {
340 $rule = $this->rules
[$curChar];
342 # Some versions of PHP have a strcspn which stops on
343 # null characters; ignore these and continue.
344 # We also may get '-' and '}' characters here which
345 # don't match -{ or $currentClosing. Add these to
346 # output and continue.
347 if ( $curChar == '-' ||
$curChar == '}' ) {
356 if ( $found == 'angle' ) {
358 // Handle </onlyinclude>
359 if ( $enableOnlyinclude
360 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
362 $findOnlyinclude = true;
366 // Determine element name
367 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
368 // Element name missing or not listed
374 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
375 // To avoid leaving blank lines, when a sequence of
376 // space-separated comments is both preceded and followed by
377 // a newline (ignoring spaces), then
378 // trim leading and trailing spaces and the trailing newline.
381 $endPos = strpos( $text, '-->', $i +
4 );
382 if ( $endPos === false ) {
383 // Unclosed comment in input, runs to end
384 $inner = substr( $text, $i );
385 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
388 // Search backwards for leading whitespace
389 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
391 // Search forwards for trailing whitespace
392 // $wsEnd will be the position of the last space (or the '>' if there's none)
393 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
395 // Keep looking forward as long as we're finding more
397 $comments = [ [ $wsStart, $wsEnd ] ];
398 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
399 $c = strpos( $text, '-->', $wsEnd +
4 );
400 if ( $c === false ) {
403 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
404 $comments[] = [ $wsEnd +
1, $c ];
408 // Eat the line if possible
409 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
410 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
411 // it's a possible beneficial b/c break.
412 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
413 && substr( $text, $wsEnd +
1, 1 ) == "\n"
415 // Remove leading whitespace from the end of the accumulator
416 // Sanity check first though
417 $wsLength = $i - $wsStart;
419 && strspn( $accum, " \t", -$wsLength ) === $wsLength
421 $accum = substr( $accum, 0, -$wsLength );
424 // Dump all but the last comment to the accumulator
425 foreach ( $comments as $j => $com ) {
427 $endPos = $com[1] +
1;
428 if ( $j == ( count( $comments ) - 1 ) ) {
431 $inner = substr( $text, $startPos, $endPos - $startPos );
432 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
435 // Do a line-start run next time to look for headings after the comment
436 $fakeLineStart = true;
438 // No line to eat, just take the comment itself
444 $part = $stack->top
->getCurrentPart();
445 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
446 $part->visualEnd
= $wsStart;
448 // Else comments abutting, no change in visual end
449 $part->commentEnd
= $endPos;
452 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
453 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
458 $lowerName = strtolower( $name );
459 $attrStart = $i +
strlen( $name ) +
1;
462 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
463 if ( $tagEndPos === false ) {
464 // Infinite backtrack
465 // Disable tag search to prevent worst-case O(N^2) performance
472 // Handle ignored tags
473 if ( in_array( $lowerName, $ignoredTags ) ) {
475 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
482 if ( $text[$tagEndPos - 1] == '/' ) {
483 $attrEnd = $tagEndPos - 1;
488 $attrEnd = $tagEndPos;
491 !isset( $noMoreClosingTag[$name] ) &&
492 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
493 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
495 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
496 $i = $matches[0][1] +
strlen( $matches[0][0] );
497 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
500 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
501 // Let it run out to the end of the text.
502 $inner = substr( $text, $tagEndPos +
1 );
506 // Don't match the tag, treat opening tag as literal and resume parsing.
508 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos +
1 - $tagStartPos ) );
509 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
510 $noMoreClosingTag[$name] = true;
515 // <includeonly> and <noinclude> just become <ignore> tags
516 if ( in_array( $lowerName, $ignoredElements ) ) {
517 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
523 if ( $attrEnd <= $attrStart ) {
526 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
528 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
529 // Note that the attr element contains the whitespace between name and attribute,
530 // this is necessary for precise reconstruction during pre-save transform.
531 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
532 if ( $inner !== null ) {
533 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
535 $accum .= $close . '</ext>';
536 } elseif ( $found == 'line-start' ) {
537 // Is this the start of a heading?
538 // Line break belongs before the heading element in any case
539 if ( $fakeLineStart ) {
540 $fakeLineStart = false;
546 $count = strspn( $text, '=', $i, 6 );
547 if ( $count == 1 && $findEquals ) {
548 // DWIM: This looks kind of like a name/value separator.
549 // Let's let the equals handler have it and break the
550 // potential heading. This is heuristic, but AFAICT the
551 // methods for completely correct disambiguation are very
553 } elseif ( $count > 0 ) {
557 'parts' => [ new PPDPart( str_repeat( '=', $count ) ) ],
560 $stack->push( $piece );
561 $accum =& $stack->getAccum();
562 $stackFlags = $stack->getFlags();
563 if ( isset( $stackFlags['findEquals'] ) ) {
564 $findEquals = $stackFlags['findEquals'];
566 if ( isset( $stackFlags['findPipe'] ) ) {
567 $findPipe = $stackFlags['findPipe'];
569 if ( isset( $stackFlags['inHeading'] ) ) {
570 $inHeading = $stackFlags['inHeading'];
574 } elseif ( $found == 'line-end' ) {
575 $piece = $stack->top
;
576 // A heading must be open, otherwise \n wouldn't have been in the search list
577 assert( $piece->open
=== "\n" );
578 $part = $piece->getCurrentPart();
579 // Search back through the input to see if it has a proper close.
580 // Do this using the reversed string since the other solutions
581 // (end anchor, etc.) are inefficient.
582 $wsLength = strspn( $revText, " \t", $lengthText - $i );
583 $searchStart = $i - $wsLength;
584 if ( isset( $part->commentEnd
) && $searchStart - 1 == $part->commentEnd
) {
585 // Comment found at line end
586 // Search for equals signs before the comment
587 $searchStart = $part->visualEnd
;
588 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
590 $count = $piece->count
;
591 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
592 if ( $equalsLength > 0 ) {
593 if ( $searchStart - $equalsLength == $piece->startPos
) {
594 // This is just a single string of equals signs on its own line
595 // Replicate the doHeadings behavior /={count}(.+)={count}/
596 // First find out how many equals signs there really are (don't stop at 6)
597 $count = $equalsLength;
601 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
604 $count = min( $equalsLength, $count );
607 // Normal match, output <h>
608 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
611 // Single equals sign on its own line, count=0
615 // No match, no <h>, just pass down the inner text
620 $accum =& $stack->getAccum();
621 $stackFlags = $stack->getFlags();
622 if ( isset( $stackFlags['findEquals'] ) ) {
623 $findEquals = $stackFlags['findEquals'];
625 if ( isset( $stackFlags['findPipe'] ) ) {
626 $findPipe = $stackFlags['findPipe'];
628 if ( isset( $stackFlags['inHeading'] ) ) {
629 $inHeading = $stackFlags['inHeading'];
632 // Append the result to the enclosing accumulator
634 // Note that we do NOT increment the input pointer.
635 // This is because the closing linebreak could be the opening linebreak of
636 // another heading. Infinite loops are avoided because the next iteration MUST
637 // hit the heading open case above, which unconditionally increments the
639 } elseif ( $found == 'open' ) {
640 # count opening brace characters
641 $curLen = strlen( $curChar );
642 $count = ( $curLen > 1 ) ?
643 # allow the final character to repeat
644 strspn( $text, $curChar[$curLen - 1], $i +
1 ) +
1 :
645 strspn( $text, $curChar, $i );
647 # we need to add to stack only if opening brace count is enough for one of the rules
648 if ( $count >= $rule['min'] ) {
649 # Add it to the stack
652 'close' => $rule['end'],
654 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
657 $stack->push( $piece );
658 $accum =& $stack->getAccum();
659 $stackFlags = $stack->getFlags();
660 if ( isset( $stackFlags['findEquals'] ) ) {
661 $findEquals = $stackFlags['findEquals'];
663 if ( isset( $stackFlags['findPipe'] ) ) {
664 $findPipe = $stackFlags['findPipe'];
666 if ( isset( $stackFlags['inHeading'] ) ) {
667 $inHeading = $stackFlags['inHeading'];
670 # Add literal brace(s)
671 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
674 } elseif ( $found == 'close' ) {
675 $piece = $stack->top
;
676 # lets check if there are enough characters for closing brace
677 $maxCount = $piece->count
;
678 if ( $piece->close
=== '}-' && $curChar === '}' ) {
679 $maxCount--; # don't try to match closing '-' as a '}'
681 $curLen = strlen( $curChar );
682 $count = ( $curLen > 1 ) ?
$curLen :
683 strspn( $text, $curChar, $i, $maxCount );
685 # check for maximum matching characters (if there are 5 closing
686 # characters, we will probably need only 3 - depending on the rules)
687 $rule = $this->rules
[$piece->open
];
688 if ( $piece->close
=== '}-' && $piece->count
> 2 ) {
689 # tweak for -{..{{ }}..}-
690 $rule = $this->rules
['{'];
692 if ( $count > $rule['max'] ) {
693 # The specified maximum exists in the callback array, unless the caller
695 $matchingCount = $rule['max'];
697 # Count is less than the maximum
698 # Skip any gaps in the callback array to find the true largest match
699 # Need to use array_key_exists not isset because the callback can be null
700 $matchingCount = $count;
701 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
706 if ( $matchingCount <= 0 ) {
707 # No matching element found in callback array
708 # Output a literal closing brace and continue
709 $endText = substr( $text, $i, $count );
710 $accum .= htmlspecialchars( $endText );
714 $name = $rule['names'][$matchingCount];
715 if ( $name === null ) {
716 // No element, just literal text
717 $endText = substr( $text, $i, $matchingCount );
718 $element = $piece->breakSyntax( $matchingCount ) . $endText;
721 # Note: $parts is already XML, does not need to be encoded further
722 $parts = $piece->parts
;
723 $title = $parts[0]->out
;
726 # The invocation is at the start of the line if lineStart is set in
727 # the stack, and all opening brackets are used up.
728 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
729 $attr = ' lineStart="1"';
734 $element = "<$name$attr>";
735 $element .= "<title>$title</title>";
737 foreach ( $parts as $part ) {
738 if ( isset( $part->eqpos
) ) {
739 $argName = substr( $part->out
, 0, $part->eqpos
);
740 $argValue = substr( $part->out
, $part->eqpos +
1 );
741 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
743 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
747 $element .= "</$name>";
750 # Advance input pointer
751 $i +
= $matchingCount;
755 $accum =& $stack->getAccum();
757 # Re-add the old stack element if it still has unmatched opening characters remaining
758 if ( $matchingCount < $piece->count
) {
759 $piece->parts
= [ new PPDPart
];
760 $piece->count
-= $matchingCount;
761 # do we still qualify for any callback with remaining count?
762 $min = $this->rules
[$piece->open
]['min'];
763 if ( $piece->count
>= $min ) {
764 $stack->push( $piece );
765 $accum =& $stack->getAccum();
767 $s = substr( $piece->open
, 0, -1 );
769 substr( $piece->open
, -1 ),
770 $piece->count
- strlen( $s )
775 $stackFlags = $stack->getFlags();
776 if ( isset( $stackFlags['findEquals'] ) ) {
777 $findEquals = $stackFlags['findEquals'];
779 if ( isset( $stackFlags['findPipe'] ) ) {
780 $findPipe = $stackFlags['findPipe'];
782 if ( isset( $stackFlags['inHeading'] ) ) {
783 $inHeading = $stackFlags['inHeading'];
786 # Add XML element to the enclosing accumulator
788 } elseif ( $found == 'pipe' ) {
789 $findEquals = true; // shortcut for getFlags()
791 $accum =& $stack->getAccum();
793 } elseif ( $found == 'equals' ) {
794 $findEquals = false; // shortcut for getFlags()
795 $stack->getCurrentPart()->eqpos
= strlen( $accum );
798 } elseif ( $found == 'dash' ) {
804 # Output any remaining unclosed brackets
805 foreach ( $stack->stack
as $piece ) {
806 $stack->rootAccum
.= $piece->breakSyntax();
808 $stack->rootAccum
.= '</root>';
809 $xml = $stack->rootAccum
;
816 * Stack class to help Preprocessor::preprocessToObj()
820 public $stack, $rootAccum;
827 public $elementClass = 'PPDStackElement';
829 public static $false = false;
831 public function __construct() {
834 $this->rootAccum
= '';
835 $this->accum
=& $this->rootAccum
;
841 public function count() {
842 return count( $this->stack
);
845 public function &getAccum() {
849 public function getCurrentPart() {
850 if ( $this->top
=== false ) {
853 return $this->top
->getCurrentPart();
857 public function push( $data ) {
858 if ( $data instanceof $this->elementClass
) {
859 $this->stack
[] = $data;
861 $class = $this->elementClass
;
862 $this->stack
[] = new $class( $data );
864 $this->top
= $this->stack
[count( $this->stack
) - 1];
865 $this->accum
=& $this->top
->getAccum();
868 public function pop() {
869 if ( !count( $this->stack
) ) {
870 throw new MWException( __METHOD__
. ': no elements remaining' );
872 $temp = array_pop( $this->stack
);
874 if ( count( $this->stack
) ) {
875 $this->top
= $this->stack
[count( $this->stack
) - 1];
876 $this->accum
=& $this->top
->getAccum();
878 $this->top
= self
::$false;
879 $this->accum
=& $this->rootAccum
;
884 public function addPart( $s = '' ) {
885 $this->top
->addPart( $s );
886 $this->accum
=& $this->top
->getAccum();
892 public function getFlags() {
893 if ( !count( $this->stack
) ) {
895 'findEquals' => false,
897 'inHeading' => false,
900 return $this->top
->getFlags();
908 class PPDStackElement
{
910 * @var string Opening character (\n for heading)
915 * @var string Matching closing character
920 * @var int Number of opening characters found (number of "=" for heading)
925 * @var PPDPart[] Array of PPDPart objects describing pipe-separated parts.
930 * @var bool True if the open char appeared at the start of the input line.
931 * Not set for headings.
935 public $partClass = 'PPDPart';
937 public function __construct( $data = [] ) {
938 $class = $this->partClass
;
939 $this->parts
= [ new $class ];
941 foreach ( $data as $name => $value ) {
942 $this->$name = $value;
946 public function &getAccum() {
947 return $this->parts
[count( $this->parts
) - 1]->out
;
950 public function addPart( $s = '' ) {
951 $class = $this->partClass
;
952 $this->parts
[] = new $class( $s );
955 public function getCurrentPart() {
956 return $this->parts
[count( $this->parts
) - 1];
962 public function getFlags() {
963 $partCount = count( $this->parts
);
964 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
966 'findPipe' => $findPipe,
967 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
968 'inHeading' => $this->open
== "\n",
973 * Get the output string that would result if the close is not found.
975 * @param bool|int $openingCount
978 public function breakSyntax( $openingCount = false ) {
979 if ( $this->open
== "\n" ) {
980 $s = $this->parts
[0]->out
;
982 if ( $openingCount === false ) {
983 $openingCount = $this->count
;
985 $s = substr( $this->open
, 0, -1 );
987 substr( $this->open
, -1 ),
988 $openingCount - strlen( $s )
991 foreach ( $this->parts
as $part ) {
1009 * @var string Output accumulator string
1013 // Optional member variables:
1014 // eqpos Position of equals sign in output accumulator
1015 // commentEnd Past-the-end input pointer for the last comment encountered
1016 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
1018 public function __construct( $out = '' ) {
1024 * An expansion frame, used as a context to expand the result of preprocessToObj()
1027 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1028 class PPFrame_DOM
implements PPFrame
{
1029 // @codingStandardsIgnoreEnd
1034 public $preprocessor;
1048 * Hashtable listing templates which are disallowed for expansion in this frame,
1049 * having been encountered previously in parent frames.
1051 public $loopCheckHash;
1054 * Recursion depth of this frame, top = 0
1055 * Note that this is NOT the same as expansion depth in expand()
1059 private $volatile = false;
1060 private $ttl = null;
1065 protected $childExpansionCache;
1068 * Construct a new preprocessor frame.
1069 * @param Preprocessor $preprocessor The parent preprocessor
1071 public function __construct( $preprocessor ) {
1072 $this->preprocessor
= $preprocessor;
1073 $this->parser
= $preprocessor->parser
;
1074 $this->title
= $this->parser
->mTitle
;
1075 $this->titleCache
= [ $this->title ?
$this->title
->getPrefixedDBkey() : false ];
1076 $this->loopCheckHash
= [];
1078 $this->childExpansionCache
= [];
1082 * Create a new child frame
1083 * $args is optionally a multi-root PPNode or array containing the template arguments
1085 * @param bool|array $args
1086 * @param Title|bool $title
1087 * @param int $indexOffset
1088 * @return PPTemplateFrame_DOM
1090 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1093 if ( $title === false ) {
1094 $title = $this->title
;
1096 if ( $args !== false ) {
1098 if ( $args instanceof PPNode
) {
1099 $args = $args->node
;
1101 foreach ( $args as $arg ) {
1102 if ( $arg instanceof PPNode
) {
1105 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1106 $xpath = new DOMXPath( $arg->ownerDocument
);
1109 $nameNodes = $xpath->query( 'name', $arg );
1110 $value = $xpath->query( 'value', $arg );
1111 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1112 // Numbered parameter
1113 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1114 $index = $index - $indexOffset;
1115 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1116 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1117 wfEscapeWikiText( $this->title
),
1118 wfEscapeWikiText( $title ),
1119 wfEscapeWikiText( $index ) )->text() );
1120 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1122 $numberedArgs[$index] = $value->item( 0 );
1123 unset( $namedArgs[$index] );
1126 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1127 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1128 $this->parser
->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
1129 wfEscapeWikiText( $this->title
),
1130 wfEscapeWikiText( $title ),
1131 wfEscapeWikiText( $name ) )->text() );
1132 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1134 $namedArgs[$name] = $value->item( 0 );
1135 unset( $numberedArgs[$name] );
1139 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1143 * @throws MWException
1144 * @param string|int $key
1145 * @param string|PPNode_DOM|DOMDocument $root
1149 public function cachedExpand( $key, $root, $flags = 0 ) {
1150 // we don't have a parent, so we don't have a cache
1151 return $this->expand( $root, $flags );
1155 * @throws MWException
1156 * @param string|PPNode_DOM|DOMDocument $root
1160 public function expand( $root, $flags = 0 ) {
1161 static $expansionDepth = 0;
1162 if ( is_string( $root ) ) {
1166 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1167 $this->parser
->limitationWarn( 'node-count-exceeded',
1168 $this->parser
->mPPNodeCount
,
1169 $this->parser
->mOptions
->getMaxPPNodeCount()
1171 return '<span class="error">Node-count limit exceeded</span>';
1174 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1175 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1177 $this->parser
->mOptions
->getMaxPPExpandDepth()
1179 return '<span class="error">Expansion depth limit exceeded</span>';
1182 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1183 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1186 if ( $root instanceof PPNode_DOM
) {
1187 $root = $root->node
;
1189 if ( $root instanceof DOMDocument
) {
1190 $root = $root->documentElement
;
1193 $outStack = [ '', '' ];
1194 $iteratorStack = [ false, $root ];
1195 $indexStack = [ 0, 0 ];
1197 while ( count( $iteratorStack ) > 1 ) {
1198 $level = count( $outStack ) - 1;
1199 $iteratorNode =& $iteratorStack[$level];
1200 $out =& $outStack[$level];
1201 $index =& $indexStack[$level];
1203 if ( $iteratorNode instanceof PPNode_DOM
) {
1204 $iteratorNode = $iteratorNode->node
;
1207 if ( is_array( $iteratorNode ) ) {
1208 if ( $index >= count( $iteratorNode ) ) {
1209 // All done with this iterator
1210 $iteratorStack[$level] = false;
1211 $contextNode = false;
1213 $contextNode = $iteratorNode[$index];
1216 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1217 if ( $index >= $iteratorNode->length
) {
1218 // All done with this iterator
1219 $iteratorStack[$level] = false;
1220 $contextNode = false;
1222 $contextNode = $iteratorNode->item( $index );
1226 // Copy to $contextNode and then delete from iterator stack,
1227 // because this is not an iterator but we do have to execute it once
1228 $contextNode = $iteratorStack[$level];
1229 $iteratorStack[$level] = false;
1232 if ( $contextNode instanceof PPNode_DOM
) {
1233 $contextNode = $contextNode->node
;
1236 $newIterator = false;
1238 if ( $contextNode === false ) {
1240 } elseif ( is_string( $contextNode ) ) {
1241 $out .= $contextNode;
1242 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1243 $newIterator = $contextNode;
1244 } elseif ( $contextNode instanceof DOMNode
) {
1245 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1246 $out .= $contextNode->nodeValue
;
1247 } elseif ( $contextNode->nodeName
== 'template' ) {
1248 # Double-brace expansion
1249 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1250 $titles = $xpath->query( 'title', $contextNode );
1251 $title = $titles->item( 0 );
1252 $parts = $xpath->query( 'part', $contextNode );
1253 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1254 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1256 $lineStart = $contextNode->getAttribute( 'lineStart' );
1258 'title' => new PPNode_DOM( $title ),
1259 'parts' => new PPNode_DOM( $parts ),
1260 'lineStart' => $lineStart ];
1261 $ret = $this->parser
->braceSubstitution( $params, $this );
1262 if ( isset( $ret['object'] ) ) {
1263 $newIterator = $ret['object'];
1265 $out .= $ret['text'];
1268 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1269 # Triple-brace expansion
1270 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1271 $titles = $xpath->query( 'title', $contextNode );
1272 $title = $titles->item( 0 );
1273 $parts = $xpath->query( 'part', $contextNode );
1274 if ( $flags & PPFrame
::NO_ARGS
) {
1275 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1278 'title' => new PPNode_DOM( $title ),
1279 'parts' => new PPNode_DOM( $parts ) ];
1280 $ret = $this->parser
->argSubstitution( $params, $this );
1281 if ( isset( $ret['object'] ) ) {
1282 $newIterator = $ret['object'];
1284 $out .= $ret['text'];
1287 } elseif ( $contextNode->nodeName
== 'comment' ) {
1288 # HTML-style comment
1289 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1290 # Not in RECOVER_COMMENTS mode (msgnw) though.
1291 if ( ( $this->parser
->ot
['html']
1292 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1293 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1294 ) && !( $flags & PPFrame
::RECOVER_COMMENTS
)
1297 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1298 # Add a strip marker in PST mode so that pstPass2() can
1299 # run some old-fashioned regexes on the result.
1300 # Not in RECOVER_COMMENTS mode (extractSections) though.
1301 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1303 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1304 $out .= $contextNode->textContent
;
1306 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1307 # Output suppression used by <includeonly> etc.
1308 # OT_WIKI will only respect <ignore> in substed templates.
1309 # The other output types respect it unless NO_IGNORE is set.
1310 # extractSections() sets NO_IGNORE and so never respects it.
1311 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1312 ||
( $flags & PPFrame
::NO_IGNORE
)
1314 $out .= $contextNode->textContent
;
1318 } elseif ( $contextNode->nodeName
== 'ext' ) {
1320 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1321 $names = $xpath->query( 'name', $contextNode );
1322 $attrs = $xpath->query( 'attr', $contextNode );
1323 $inners = $xpath->query( 'inner', $contextNode );
1324 $closes = $xpath->query( 'close', $contextNode );
1325 if ( $flags & PPFrame
::NO_TAGS
) {
1326 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1327 if ( $attrs->length
> 0 ) {
1328 $s .= $this->expand( $attrs->item( 0 ), $flags );
1330 if ( $inners->length
> 0 ) {
1331 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1332 if ( $closes->length
> 0 ) {
1333 $s .= $this->expand( $closes->item( 0 ), $flags );
1341 'name' => new PPNode_DOM( $names->item( 0 ) ),
1342 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1343 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1344 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1346 $out .= $this->parser
->extensionSubstitution( $params, $this );
1348 } elseif ( $contextNode->nodeName
== 'h' ) {
1350 $s = $this->expand( $contextNode->childNodes
, $flags );
1352 # Insert a heading marker only for <h> children of <root>
1353 # This is to stop extractSections from going over multiple tree levels
1354 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1355 # Insert heading index marker
1356 $headingIndex = $contextNode->getAttribute( 'i' );
1357 $titleText = $this->title
->getPrefixedDBkey();
1358 $this->parser
->mHeadings
[] = [ $titleText, $headingIndex ];
1359 $serial = count( $this->parser
->mHeadings
) - 1;
1360 $marker = Parser
::MARKER_PREFIX
. "-h-$serial-" . Parser
::MARKER_SUFFIX
;
1361 $count = $contextNode->getAttribute( 'level' );
1362 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1363 $this->parser
->mStripState
->addGeneral( $marker, '' );
1367 # Generic recursive expansion
1368 $newIterator = $contextNode->childNodes
;
1371 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1374 if ( $newIterator !== false ) {
1375 if ( $newIterator instanceof PPNode_DOM
) {
1376 $newIterator = $newIterator->node
;
1379 $iteratorStack[] = $newIterator;
1381 } elseif ( $iteratorStack[$level] === false ) {
1382 // Return accumulated value to parent
1383 // With tail recursion
1384 while ( $iteratorStack[$level] === false && $level > 0 ) {
1385 $outStack[$level - 1] .= $out;
1386 array_pop( $outStack );
1387 array_pop( $iteratorStack );
1388 array_pop( $indexStack );
1394 return $outStack[0];
1398 * @param string $sep
1400 * @param string|PPNode_DOM|DOMDocument $args,...
1403 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1404 $args = array_slice( func_get_args(), 2 );
1408 foreach ( $args as $root ) {
1409 if ( $root instanceof PPNode_DOM
) {
1410 $root = $root->node
;
1412 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1415 foreach ( $root as $node ) {
1421 $s .= $this->expand( $node, $flags );
1428 * Implode with no flags specified
1429 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1431 * @param string $sep
1432 * @param string|PPNode_DOM|DOMDocument $args,...
1435 public function implode( $sep /*, ... */ ) {
1436 $args = array_slice( func_get_args(), 1 );
1440 foreach ( $args as $root ) {
1441 if ( $root instanceof PPNode_DOM
) {
1442 $root = $root->node
;
1444 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1447 foreach ( $root as $node ) {
1453 $s .= $this->expand( $node );
1460 * Makes an object that, when expand()ed, will be the same as one obtained
1463 * @param string $sep
1464 * @param string|PPNode_DOM|DOMDocument $args,...
1467 public function virtualImplode( $sep /*, ... */ ) {
1468 $args = array_slice( func_get_args(), 1 );
1472 foreach ( $args as $root ) {
1473 if ( $root instanceof PPNode_DOM
) {
1474 $root = $root->node
;
1476 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1479 foreach ( $root as $node ) {
1492 * Virtual implode with brackets
1493 * @param string $start
1494 * @param string $sep
1495 * @param string $end
1496 * @param string|PPNode_DOM|DOMDocument $args,...
1499 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1500 $args = array_slice( func_get_args(), 3 );
1504 foreach ( $args as $root ) {
1505 if ( $root instanceof PPNode_DOM
) {
1506 $root = $root->node
;
1508 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1511 foreach ( $root as $node ) {
1524 public function __toString() {
1528 public function getPDBK( $level = false ) {
1529 if ( $level === false ) {
1530 return $this->title
->getPrefixedDBkey();
1532 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1539 public function getArguments() {
1546 public function getNumberedArguments() {
1553 public function getNamedArguments() {
1558 * Returns true if there are no arguments in this frame
1562 public function isEmpty() {
1567 * @param int|string $name
1568 * @return bool Always false in this implementation.
1570 public function getArgument( $name ) {
1575 * Returns true if the infinite loop check is OK, false if a loop is detected
1577 * @param Title $title
1580 public function loopCheck( $title ) {
1581 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1585 * Return true if the frame is a template frame
1589 public function isTemplate() {
1594 * Get a title of frame
1598 public function getTitle() {
1599 return $this->title
;
1603 * Set the volatile flag
1607 public function setVolatile( $flag = true ) {
1608 $this->volatile
= $flag;
1612 * Get the volatile flag
1616 public function isVolatile() {
1617 return $this->volatile
;
1625 public function setTTL( $ttl ) {
1626 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1636 public function getTTL() {
1642 * Expansion frame with template arguments
1645 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1646 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1647 // @codingStandardsIgnoreEnd
1649 public $numberedArgs, $namedArgs;
1655 public $numberedExpansionCache, $namedExpansionCache;
1658 * @param Preprocessor $preprocessor
1659 * @param bool|PPFrame_DOM $parent
1660 * @param array $numberedArgs
1661 * @param array $namedArgs
1662 * @param bool|Title $title
1664 public function __construct( $preprocessor, $parent = false, $numberedArgs = [],
1665 $namedArgs = [], $title = false
1667 parent
::__construct( $preprocessor );
1669 $this->parent
= $parent;
1670 $this->numberedArgs
= $numberedArgs;
1671 $this->namedArgs
= $namedArgs;
1672 $this->title
= $title;
1673 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1674 $this->titleCache
= $parent->titleCache
;
1675 $this->titleCache
[] = $pdbk;
1676 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1677 if ( $pdbk !== false ) {
1678 $this->loopCheckHash
[$pdbk] = true;
1680 $this->depth
= $parent->depth +
1;
1681 $this->numberedExpansionCache
= $this->namedExpansionCache
= [];
1684 public function __toString() {
1687 $args = $this->numberedArgs +
$this->namedArgs
;
1688 foreach ( $args as $name => $value ) {
1694 $s .= "\"$name\":\"" .
1695 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1702 * @throws MWException
1703 * @param string|int $key
1704 * @param string|PPNode_DOM|DOMDocument $root
1708 public function cachedExpand( $key, $root, $flags = 0 ) {
1709 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1710 return $this->parent
->childExpansionCache
[$key];
1712 $retval = $this->expand( $root, $flags );
1713 if ( !$this->isVolatile() ) {
1714 $this->parent
->childExpansionCache
[$key] = $retval;
1720 * Returns true if there are no arguments in this frame
1724 public function isEmpty() {
1725 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1728 public function getArguments() {
1730 foreach ( array_merge(
1731 array_keys( $this->numberedArgs
),
1732 array_keys( $this->namedArgs
) ) as $key ) {
1733 $arguments[$key] = $this->getArgument( $key );
1738 public function getNumberedArguments() {
1740 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1741 $arguments[$key] = $this->getArgument( $key );
1746 public function getNamedArguments() {
1748 foreach ( array_keys( $this->namedArgs
) as $key ) {
1749 $arguments[$key] = $this->getArgument( $key );
1756 * @return string|bool
1758 public function getNumberedArgument( $index ) {
1759 if ( !isset( $this->numberedArgs
[$index] ) ) {
1762 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1763 # No trimming for unnamed arguments
1764 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1765 $this->numberedArgs
[$index],
1766 PPFrame
::STRIP_COMMENTS
1769 return $this->numberedExpansionCache
[$index];
1773 * @param string $name
1774 * @return string|bool
1776 public function getNamedArgument( $name ) {
1777 if ( !isset( $this->namedArgs
[$name] ) ) {
1780 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1781 # Trim named arguments post-expand, for backwards compatibility
1782 $this->namedExpansionCache
[$name] = trim(
1783 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1785 return $this->namedExpansionCache
[$name];
1789 * @param int|string $name
1790 * @return string|bool
1792 public function getArgument( $name ) {
1793 $text = $this->getNumberedArgument( $name );
1794 if ( $text === false ) {
1795 $text = $this->getNamedArgument( $name );
1801 * Return true if the frame is a template frame
1805 public function isTemplate() {
1809 public function setVolatile( $flag = true ) {
1810 parent
::setVolatile( $flag );
1811 $this->parent
->setVolatile( $flag );
1814 public function setTTL( $ttl ) {
1815 parent
::setTTL( $ttl );
1816 $this->parent
->setTTL( $ttl );
1821 * Expansion frame with custom arguments
1824 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1825 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1826 // @codingStandardsIgnoreEnd
1830 public function __construct( $preprocessor, $args ) {
1831 parent
::__construct( $preprocessor );
1832 $this->args
= $args;
1835 public function __toString() {
1838 foreach ( $this->args
as $name => $value ) {
1844 $s .= "\"$name\":\"" .
1845 str_replace( '"', '\\"', $value->__toString() ) . '"';
1854 public function isEmpty() {
1855 return !count( $this->args
);
1859 * @param int|string $index
1860 * @return string|bool
1862 public function getArgument( $index ) {
1863 if ( !isset( $this->args
[$index] ) ) {
1866 return $this->args
[$index];
1869 public function getArguments() {
1877 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1878 class PPNode_DOM
implements PPNode
{
1879 // @codingStandardsIgnoreEnd
1887 public function __construct( $node, $xpath = false ) {
1888 $this->node
= $node;
1894 public function getXPath() {
1895 if ( $this->xpath
=== null ) {
1896 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1898 return $this->xpath
;
1901 public function __toString() {
1902 if ( $this->node
instanceof DOMNodeList
) {
1904 foreach ( $this->node
as $node ) {
1905 $s .= $node->ownerDocument
->saveXML( $node );
1908 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1914 * @return bool|PPNode_DOM
1916 public function getChildren() {
1917 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1921 * @return bool|PPNode_DOM
1923 public function getFirstChild() {
1924 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1928 * @return bool|PPNode_DOM
1930 public function getNextSibling() {
1931 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1935 * @param string $type
1937 * @return bool|PPNode_DOM
1939 public function getChildrenOfType( $type ) {
1940 return new self( $this->getXPath()->query( $type, $this->node
) );
1946 public function getLength() {
1947 if ( $this->node
instanceof DOMNodeList
) {
1948 return $this->node
->length
;
1956 * @return bool|PPNode_DOM
1958 public function item( $i ) {
1959 $item = $this->node
->item( $i );
1960 return $item ?
new self( $item ) : false;
1966 public function getName() {
1967 if ( $this->node
instanceof DOMNodeList
) {
1970 return $this->node
->nodeName
;
1975 * Split a "<part>" node into an associative array containing:
1976 * - name PPNode name
1977 * - index String index
1978 * - value PPNode value
1980 * @throws MWException
1983 public function splitArg() {
1984 $xpath = $this->getXPath();
1985 $names = $xpath->query( 'name', $this->node
);
1986 $values = $xpath->query( 'value', $this->node
);
1987 if ( !$names->length ||
!$values->length
) {
1988 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1990 $name = $names->item( 0 );
1991 $index = $name->getAttribute( 'index' );
1993 'name' => new self( $name ),
1995 'value' => new self( $values->item( 0 ) ) ];
1999 * Split an "<ext>" node into an associative array containing name, attr, inner and close
2000 * All values in the resulting array are PPNodes. Inner and close are optional.
2002 * @throws MWException
2005 public function splitExt() {
2006 $xpath = $this->getXPath();
2007 $names = $xpath->query( 'name', $this->node
);
2008 $attrs = $xpath->query( 'attr', $this->node
);
2009 $inners = $xpath->query( 'inner', $this->node
);
2010 $closes = $xpath->query( 'close', $this->node
);
2011 if ( !$names->length ||
!$attrs->length
) {
2012 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
2015 'name' => new self( $names->item( 0 ) ),
2016 'attr' => new self( $attrs->item( 0 ) ) ];
2017 if ( $inners->length
) {
2018 $parts['inner'] = new self( $inners->item( 0 ) );
2020 if ( $closes->length
) {
2021 $parts['close'] = new self( $closes->item( 0 ) );
2027 * Split a "<h>" node
2028 * @throws MWException
2031 public function splitHeading() {
2032 if ( $this->getName() !== 'h' ) {
2033 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
2036 'i' => $this->node
->getAttribute( 'i' ),
2037 'level' => $this->node
->getAttribute( 'level' ),
2038 'contents' => $this->getChildren()