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
26 * @codingStandardsIgnoreStart
28 class Preprocessor_DOM
implements Preprocessor
{
29 // @codingStandardsIgnoreEnd
38 const CACHE_VERSION
= 1;
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 wfProfileIn( __METHOD__
. '-loadXML' );
90 $dom = new DOMDocument();
92 $result = $dom->loadXML( $xml );
95 // Try running the XML through UtfNormal to get rid of invalid characters
96 $xml = UtfNormal
::cleanUp( $xml );
97 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
98 // don't barf when the XML is >256 levels deep
99 $result = $dom->loadXML( $xml, 1 << 19 );
101 wfProfileOut( __METHOD__
. '-loadXML' );
104 throw new MWException( 'Parameters passed to ' . __METHOD__
. ' result in invalid XML' );
107 $root = $dom->documentElement
;
108 $node = new PPNode_DOM( $root->childNodes
);
113 * @throws MWException
116 public function memCheck() {
117 if ( $this->memoryLimit
=== false ) {
120 $usage = memory_get_usage();
121 if ( $usage > $this->memoryLimit
* 0.9 ) {
122 $limit = intval( $this->memoryLimit
* 0.9 / 1048576 +
0.5 );
123 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
125 return $usage <= $this->memoryLimit
* 0.8;
129 * Preprocess some wikitext and return the document tree.
130 * This is the ghost of Parser::replace_variables().
132 * @param string $text The text to parse
133 * @param int $flags Bitwise combination of:
134 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
135 * as if the text is being included. Default
136 * is to assume a direct page view.
138 * The generated DOM tree must depend only on the input text and the flags.
139 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
141 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
142 * change in the DOM tree for a given text, must be passed through the section identifier
143 * in the section edit link and thus back to extractSections().
145 * The output of this function is currently only cached in process memory, but a persistent
146 * cache may be implemented at a later date which takes further advantage of these strict
147 * dependency requirements.
149 * @throws MWException
152 public function preprocessToObj( $text, $flags = 0 ) {
153 global $wgMemc, $wgPreprocessorCacheThreshold;
156 $cacheable = ( $wgPreprocessorCacheThreshold !== false
157 && strlen( $text ) > $wgPreprocessorCacheThreshold );
159 wfProfileIn( __METHOD__
. '-cacheable' );
161 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
162 $cacheValue = $wgMemc->get( $cacheKey );
164 $version = substr( $cacheValue, 0, 8 );
165 if ( intval( $version ) == self
::CACHE_VERSION
) {
166 $xml = substr( $cacheValue, 8 );
168 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
171 if ( $xml === false ) {
172 wfProfileIn( __METHOD__
. '-cache-miss' );
173 $xml = $this->preprocessToXml( $text, $flags );
174 $cacheValue = sprintf( "%08d", self
::CACHE_VERSION
) . $xml;
175 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
176 wfProfileOut( __METHOD__
. '-cache-miss' );
177 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
180 $xml = $this->preprocessToXml( $text, $flags );
183 // Fail if the number of elements exceeds acceptable limits
184 // Do not attempt to generate the DOM
185 $this->parser
->mGeneratedPPNodeCount +
= substr_count( $xml, '<' );
186 $max = $this->parser
->mOptions
->getMaxGeneratedPPNodeCount();
187 if ( $this->parser
->mGeneratedPPNodeCount
> $max ) {
189 wfProfileOut( __METHOD__
. '-cacheable' );
191 throw new MWException( __METHOD__
. ': generated node count limit exceeded' );
194 wfProfileIn( __METHOD__
. '-loadXML' );
195 $dom = new DOMDocument
;
196 wfSuppressWarnings();
197 $result = $dom->loadXML( $xml );
200 // Try running the XML through UtfNormal to get rid of invalid characters
201 $xml = UtfNormal
::cleanUp( $xml );
202 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
203 // don't barf when the XML is >256 levels deep.
204 $result = $dom->loadXML( $xml, 1 << 19 );
207 $obj = new PPNode_DOM( $dom->documentElement
);
209 wfProfileOut( __METHOD__
. '-loadXML' );
212 wfProfileOut( __METHOD__
. '-cacheable' );
217 throw new MWException( __METHOD__
. ' generated invalid XML' );
223 * @param string $text
227 public function preprocessToXml( $text, $flags = 0 ) {
240 'names' => array( 2 => null ),
246 $forInclusion = $flags & Parser
::PTD_FOR_INCLUSION
;
248 $xmlishElements = $this->parser
->getStripList();
249 $enableOnlyinclude = false;
250 if ( $forInclusion ) {
251 $ignoredTags = array( 'includeonly', '/includeonly' );
252 $ignoredElements = array( 'noinclude' );
253 $xmlishElements[] = 'noinclude';
254 if ( strpos( $text, '<onlyinclude>' ) !== false
255 && strpos( $text, '</onlyinclude>' ) !== false
257 $enableOnlyinclude = true;
260 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
261 $ignoredElements = array( 'includeonly' );
262 $xmlishElements[] = 'includeonly';
264 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
266 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
267 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
269 $stack = new PPDStack
;
271 $searchBase = "[{<\n"; #}
272 // For fast reverse searches
273 $revText = strrev( $text );
274 $lengthText = strlen( $text );
276 // Input pointer, starts out pointing to a pseudo-newline before the start
278 // Current accumulator
279 $accum =& $stack->getAccum();
281 // True to find equals signs in arguments
283 // True to take notice of pipe characters
286 // True if $i is inside a possible heading
288 // True if there are no more greater-than (>) signs right of $i
290 // True to ignore all input up to the next <onlyinclude>
291 $findOnlyinclude = $enableOnlyinclude;
292 // Do a line-start run without outputting an LF character
293 $fakeLineStart = true;
298 if ( $findOnlyinclude ) {
299 // Ignore all input up to the next <onlyinclude>
300 $startPos = strpos( $text, '<onlyinclude>', $i );
301 if ( $startPos === false ) {
302 // Ignored section runs to the end
303 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
306 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
307 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
309 $findOnlyinclude = false;
312 if ( $fakeLineStart ) {
313 $found = 'line-start';
316 # Find next opening brace, closing brace or pipe
317 $search = $searchBase;
318 if ( $stack->top
=== false ) {
319 $currentClosing = '';
321 $currentClosing = $stack->top
->close
;
322 $search .= $currentClosing;
328 // First equals will be for the template
332 # Output literal section, advance input counter
333 $literalLength = strcspn( $text, $search, $i );
334 if ( $literalLength > 0 ) {
335 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
336 $i +
= $literalLength;
338 if ( $i >= $lengthText ) {
339 if ( $currentClosing == "\n" ) {
340 // Do a past-the-end run to finish off the heading
348 $curChar = $text[$i];
349 if ( $curChar == '|' ) {
351 } elseif ( $curChar == '=' ) {
353 } elseif ( $curChar == '<' ) {
355 } elseif ( $curChar == "\n" ) {
359 $found = 'line-start';
361 } elseif ( $curChar == $currentClosing ) {
363 } elseif ( isset( $rules[$curChar] ) ) {
365 $rule = $rules[$curChar];
367 # Some versions of PHP have a strcspn which stops on null characters
368 # Ignore and continue
375 if ( $found == 'angle' ) {
377 // Handle </onlyinclude>
378 if ( $enableOnlyinclude
379 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
381 $findOnlyinclude = true;
385 // Determine element name
386 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
387 // Element name missing or not listed
393 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
395 // To avoid leaving blank lines, when a sequence of
396 // space-separated comments is both preceded and followed by
397 // a newline (ignoring spaces), then
398 // trim leading and trailing spaces and the trailing newline.
401 $endPos = strpos( $text, '-->', $i +
4 );
402 if ( $endPos === false ) {
403 // Unclosed comment in input, runs to end
404 $inner = substr( $text, $i );
405 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
408 // Search backwards for leading whitespace
409 $wsStart = $i ?
( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
411 // Search forwards for trailing whitespace
412 // $wsEnd will be the position of the last space (or the '>' if there's none)
413 $wsEnd = $endPos +
2 +
strspn( $text, " \t", $endPos +
3 );
415 // Keep looking forward as long as we're finding more
417 $comments = array( array( $wsStart, $wsEnd ) );
418 while ( substr( $text, $wsEnd +
1, 4 ) == '<!--' ) {
419 $c = strpos( $text, '-->', $wsEnd +
4 );
420 if ( $c === false ) {
423 $c = $c +
2 +
strspn( $text, " \t", $c +
3 );
424 $comments[] = array( $wsEnd +
1, $c );
428 // Eat the line if possible
429 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
430 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
431 // it's a possible beneficial b/c break.
432 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
433 && substr( $text, $wsEnd +
1, 1 ) == "\n"
435 // Remove leading whitespace from the end of the accumulator
436 // Sanity check first though
437 $wsLength = $i - $wsStart;
439 && strspn( $accum, " \t", -$wsLength ) === $wsLength
441 $accum = substr( $accum, 0, -$wsLength );
444 // Dump all but the last comment to the accumulator
445 foreach ( $comments as $j => $com ) {
447 $endPos = $com[1] +
1;
448 if ( $j == ( count( $comments ) - 1 ) ) {
451 $inner = substr( $text, $startPos, $endPos - $startPos );
452 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
455 // Do a line-start run next time to look for headings after the comment
456 $fakeLineStart = true;
458 // No line to eat, just take the comment itself
464 $part = $stack->top
->getCurrentPart();
465 if ( !( isset( $part->commentEnd
) && $part->commentEnd
== $wsStart - 1 ) ) {
466 $part->visualEnd
= $wsStart;
468 // Else comments abutting, no change in visual end
469 $part->commentEnd
= $endPos;
472 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
473 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
478 $lowerName = strtolower( $name );
479 $attrStart = $i +
strlen( $name ) +
1;
482 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
483 if ( $tagEndPos === false ) {
484 // Infinite backtrack
485 // Disable tag search to prevent worst-case O(N^2) performance
492 // Handle ignored tags
493 if ( in_array( $lowerName, $ignoredTags ) ) {
495 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) )
502 if ( $text[$tagEndPos - 1] == '/' ) {
503 $attrEnd = $tagEndPos - 1;
508 $attrEnd = $tagEndPos;
510 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
511 $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 )
513 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
514 $i = $matches[0][1] +
strlen( $matches[0][0] );
515 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
517 // No end tag -- let it run out to the end of the text.
518 $inner = substr( $text, $tagEndPos +
1 );
523 // <includeonly> and <noinclude> just become <ignore> tags
524 if ( in_array( $lowerName, $ignoredElements ) ) {
525 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
531 if ( $attrEnd <= $attrStart ) {
534 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
536 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
537 // Note that the attr element contains the whitespace between name and attribute,
538 // this is necessary for precise reconstruction during pre-save transform.
539 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
540 if ( $inner !== null ) {
541 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
543 $accum .= $close . '</ext>';
544 } elseif ( $found == 'line-start' ) {
545 // Is this the start of a heading?
546 // Line break belongs before the heading element in any case
547 if ( $fakeLineStart ) {
548 $fakeLineStart = false;
554 $count = strspn( $text, '=', $i, 6 );
555 if ( $count == 1 && $findEquals ) {
556 // DWIM: This looks kind of like a name/value separator.
557 // Let's let the equals handler have it and break the
558 // potential heading. This is heuristic, but AFAICT the
559 // methods for completely correct disambiguation are very
561 } elseif ( $count > 0 ) {
565 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
568 $stack->push( $piece );
569 $accum =& $stack->getAccum();
570 $flags = $stack->getFlags();
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 $flags = $stack->getFlags();
624 // Append the result to the enclosing accumulator
626 // Note that we do NOT increment the input pointer.
627 // This is because the closing linebreak could be the opening linebreak of
628 // another heading. Infinite loops are avoided because the next iteration MUST
629 // hit the heading open case above, which unconditionally increments the
631 } elseif ( $found == 'open' ) {
632 # count opening brace characters
633 $count = strspn( $text, $curChar, $i );
635 # we need to add to stack only if opening brace count is enough for one of the rules
636 if ( $count >= $rule['min'] ) {
637 # Add it to the stack
640 'close' => $rule['end'],
642 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
645 $stack->push( $piece );
646 $accum =& $stack->getAccum();
647 $flags = $stack->getFlags();
650 # Add literal brace(s)
651 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
654 } elseif ( $found == 'close' ) {
655 $piece = $stack->top
;
656 # lets check if there are enough characters for closing brace
657 $maxCount = $piece->count
;
658 $count = strspn( $text, $curChar, $i, $maxCount );
660 # check for maximum matching characters (if there are 5 closing
661 # characters, we will probably need only 3 - depending on the rules)
662 $rule = $rules[$piece->open
];
663 if ( $count > $rule['max'] ) {
664 # The specified maximum exists in the callback array, unless the caller
666 $matchingCount = $rule['max'];
668 # Count is less than the maximum
669 # Skip any gaps in the callback array to find the true largest match
670 # Need to use array_key_exists not isset because the callback can be null
671 $matchingCount = $count;
672 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
677 if ( $matchingCount <= 0 ) {
678 # No matching element found in callback array
679 # Output a literal closing brace and continue
680 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
684 $name = $rule['names'][$matchingCount];
685 if ( $name === null ) {
686 // No element, just literal text
687 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
690 # Note: $parts is already XML, does not need to be encoded further
691 $parts = $piece->parts
;
692 $title = $parts[0]->out
;
695 # The invocation is at the start of the line if lineStart is set in
696 # the stack, and all opening brackets are used up.
697 if ( $maxCount == $matchingCount && !empty( $piece->lineStart
) ) {
698 $attr = ' lineStart="1"';
703 $element = "<$name$attr>";
704 $element .= "<title>$title</title>";
706 foreach ( $parts as $part ) {
707 if ( isset( $part->eqpos
) ) {
708 $argName = substr( $part->out
, 0, $part->eqpos
);
709 $argValue = substr( $part->out
, $part->eqpos +
1 );
710 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
712 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
716 $element .= "</$name>";
719 # Advance input pointer
720 $i +
= $matchingCount;
724 $accum =& $stack->getAccum();
726 # Re-add the old stack element if it still has unmatched opening characters remaining
727 if ( $matchingCount < $piece->count
) {
728 $piece->parts
= array( new PPDPart
);
729 $piece->count
-= $matchingCount;
730 # do we still qualify for any callback with remaining count?
731 $min = $rules[$piece->open
]['min'];
732 if ( $piece->count
>= $min ) {
733 $stack->push( $piece );
734 $accum =& $stack->getAccum();
736 $accum .= str_repeat( $piece->open
, $piece->count
);
739 $flags = $stack->getFlags();
742 # Add XML element to the enclosing accumulator
744 } elseif ( $found == 'pipe' ) {
745 $findEquals = true; // shortcut for getFlags()
747 $accum =& $stack->getAccum();
749 } elseif ( $found == 'equals' ) {
750 $findEquals = false; // shortcut for getFlags()
751 $stack->getCurrentPart()->eqpos
= strlen( $accum );
757 # Output any remaining unclosed brackets
758 foreach ( $stack->stack
as $piece ) {
759 $stack->rootAccum
.= $piece->breakSyntax();
761 $stack->rootAccum
.= '</root>';
762 $xml = $stack->rootAccum
;
770 * Stack class to help Preprocessor::preprocessToObj()
774 public $stack, $rootAccum;
781 public $elementClass = 'PPDStackElement';
783 public static $false = false;
785 public function __construct() {
786 $this->stack
= array();
788 $this->rootAccum
= '';
789 $this->accum
=& $this->rootAccum
;
795 public function count() {
796 return count( $this->stack
);
799 public function &getAccum() {
803 public function getCurrentPart() {
804 if ( $this->top
=== false ) {
807 return $this->top
->getCurrentPart();
811 public function push( $data ) {
812 if ( $data instanceof $this->elementClass
) {
813 $this->stack
[] = $data;
815 $class = $this->elementClass
;
816 $this->stack
[] = new $class( $data );
818 $this->top
= $this->stack
[count( $this->stack
) - 1];
819 $this->accum
=& $this->top
->getAccum();
822 public function pop() {
823 if ( !count( $this->stack
) ) {
824 throw new MWException( __METHOD__
. ': no elements remaining' );
826 $temp = array_pop( $this->stack
);
828 if ( count( $this->stack
) ) {
829 $this->top
= $this->stack
[count( $this->stack
) - 1];
830 $this->accum
=& $this->top
->getAccum();
832 $this->top
= self
::$false;
833 $this->accum
=& $this->rootAccum
;
838 public function addPart( $s = '' ) {
839 $this->top
->addPart( $s );
840 $this->accum
=& $this->top
->getAccum();
846 public function getFlags() {
847 if ( !count( $this->stack
) ) {
849 'findEquals' => false,
851 'inHeading' => false,
854 return $this->top
->getFlags();
862 class PPDStackElement
{
863 public $open, // Opening character (\n for heading)
864 $close, // Matching closing character
865 $count, // Number of opening characters found (number of "=" for heading)
866 $parts, // Array of PPDPart objects describing pipe-separated parts.
867 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
869 public $partClass = 'PPDPart';
871 public function __construct( $data = array() ) {
872 $class = $this->partClass
;
873 $this->parts
= array( new $class );
875 foreach ( $data as $name => $value ) {
876 $this->$name = $value;
880 public function &getAccum() {
881 return $this->parts
[count( $this->parts
) - 1]->out
;
884 public function addPart( $s = '' ) {
885 $class = $this->partClass
;
886 $this->parts
[] = new $class( $s );
889 public function getCurrentPart() {
890 return $this->parts
[count( $this->parts
) - 1];
896 public function getFlags() {
897 $partCount = count( $this->parts
);
898 $findPipe = $this->open
!= "\n" && $this->open
!= '[';
900 'findPipe' => $findPipe,
901 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts
[$partCount - 1]->eqpos
),
902 'inHeading' => $this->open
== "\n",
907 * Get the output string that would result if the close is not found.
909 * @param bool|int $openingCount
912 public function breakSyntax( $openingCount = false ) {
913 if ( $this->open
== "\n" ) {
914 $s = $this->parts
[0]->out
;
916 if ( $openingCount === false ) {
917 $openingCount = $this->count
;
919 $s = str_repeat( $this->open
, $openingCount );
921 foreach ( $this->parts
as $part ) {
938 public $out; // Output accumulator string
940 // Optional member variables:
941 // eqpos Position of equals sign in output accumulator
942 // commentEnd Past-the-end input pointer for the last comment encountered
943 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
945 public function __construct( $out = '' ) {
951 * An expansion frame, used as a context to expand the result of preprocessToObj()
953 * @codingStandardsIgnoreStart
955 class PPFrame_DOM
implements PPFrame
{
956 // @codingStandardsIgnoreEnd
961 public $preprocessor;
975 * Hashtable listing templates which are disallowed for expansion in this frame,
976 * having been encountered previously in parent frames.
978 public $loopCheckHash;
981 * Recursion depth of this frame, top = 0
982 * Note that this is NOT the same as expansion depth in expand()
986 private $volatile = false;
992 protected $childExpansionCache;
995 * Construct a new preprocessor frame.
996 * @param Preprocessor $preprocessor The parent preprocessor
998 public function __construct( $preprocessor ) {
999 $this->preprocessor
= $preprocessor;
1000 $this->parser
= $preprocessor->parser
;
1001 $this->title
= $this->parser
->mTitle
;
1002 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
1003 $this->loopCheckHash
= array();
1005 $this->childExpansionCache
= array();
1009 * Create a new child frame
1010 * $args is optionally a multi-root PPNode or array containing the template arguments
1012 * @param bool|array $args
1013 * @param Title|bool $title
1014 * @param int $indexOffset
1015 * @return PPTemplateFrame_DOM
1017 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1018 $namedArgs = array();
1019 $numberedArgs = array();
1020 if ( $title === false ) {
1021 $title = $this->title
;
1023 if ( $args !== false ) {
1025 if ( $args instanceof PPNode
) {
1026 $args = $args->node
;
1028 foreach ( $args as $arg ) {
1029 if ( $arg instanceof PPNode
) {
1032 if ( !$xpath ||
$xpath->document
!== $arg->ownerDocument
) {
1033 $xpath = new DOMXPath( $arg->ownerDocument
);
1036 $nameNodes = $xpath->query( 'name', $arg );
1037 $value = $xpath->query( 'value', $arg );
1038 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1039 // Numbered parameter
1040 $index = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
1041 $index = $index - $indexOffset;
1042 if ( isset( $namedArgs[$index] ) ||
isset( $numberedArgs[$index] ) ) {
1043 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1045 $numberedArgs[$index] = $value->item( 0 );
1046 unset( $namedArgs[$index] );
1049 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
) );
1050 if ( isset( $namedArgs[$name] ) ||
isset( $numberedArgs[$name] ) ) {
1051 $this->parser
->addTrackingCategory( 'duplicate-args-category' );
1053 $namedArgs[$name] = $value->item( 0 );
1054 unset( $numberedArgs[$name] );
1058 return new PPTemplateFrame_DOM( $this->preprocessor
, $this, $numberedArgs, $namedArgs, $title );
1062 * @throws MWException
1063 * @param string|int $key
1064 * @param string|PPNode_DOM|DOMDocument $root
1068 public function cachedExpand( $key, $root, $flags = 0 ) {
1069 // we don't have a parent, so we don't have a cache
1070 return $this->expand( $root, $flags );
1074 * @throws MWException
1075 * @param string|PPNode_DOM|DOMDocument $root
1079 public function expand( $root, $flags = 0 ) {
1080 static $expansionDepth = 0;
1081 if ( is_string( $root ) ) {
1085 if ( ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->getMaxPPNodeCount() ) {
1086 $this->parser
->limitationWarn( 'node-count-exceeded',
1087 $this->parser
->mPPNodeCount
,
1088 $this->parser
->mOptions
->getMaxPPNodeCount()
1090 return '<span class="error">Node-count limit exceeded</span>';
1093 if ( $expansionDepth > $this->parser
->mOptions
->getMaxPPExpandDepth() ) {
1094 $this->parser
->limitationWarn( 'expansion-depth-exceeded',
1096 $this->parser
->mOptions
->getMaxPPExpandDepth()
1098 return '<span class="error">Expansion depth limit exceeded</span>';
1101 if ( $expansionDepth > $this->parser
->mHighestExpansionDepth
) {
1102 $this->parser
->mHighestExpansionDepth
= $expansionDepth;
1105 if ( $root instanceof PPNode_DOM
) {
1106 $root = $root->node
;
1108 if ( $root instanceof DOMDocument
) {
1109 $root = $root->documentElement
;
1112 $outStack = array( '', '' );
1113 $iteratorStack = array( false, $root );
1114 $indexStack = array( 0, 0 );
1116 while ( count( $iteratorStack ) > 1 ) {
1117 $level = count( $outStack ) - 1;
1118 $iteratorNode =& $iteratorStack[$level];
1119 $out =& $outStack[$level];
1120 $index =& $indexStack[$level];
1122 if ( $iteratorNode instanceof PPNode_DOM
) {
1123 $iteratorNode = $iteratorNode->node
;
1126 if ( is_array( $iteratorNode ) ) {
1127 if ( $index >= count( $iteratorNode ) ) {
1128 // All done with this iterator
1129 $iteratorStack[$level] = false;
1130 $contextNode = false;
1132 $contextNode = $iteratorNode[$index];
1135 } elseif ( $iteratorNode instanceof DOMNodeList
) {
1136 if ( $index >= $iteratorNode->length
) {
1137 // All done with this iterator
1138 $iteratorStack[$level] = false;
1139 $contextNode = false;
1141 $contextNode = $iteratorNode->item( $index );
1145 // Copy to $contextNode and then delete from iterator stack,
1146 // because this is not an iterator but we do have to execute it once
1147 $contextNode = $iteratorStack[$level];
1148 $iteratorStack[$level] = false;
1151 if ( $contextNode instanceof PPNode_DOM
) {
1152 $contextNode = $contextNode->node
;
1155 $newIterator = false;
1157 if ( $contextNode === false ) {
1159 } elseif ( is_string( $contextNode ) ) {
1160 $out .= $contextNode;
1161 } elseif ( is_array( $contextNode ) ||
$contextNode instanceof DOMNodeList
) {
1162 $newIterator = $contextNode;
1163 } elseif ( $contextNode instanceof DOMNode
) {
1164 if ( $contextNode->nodeType
== XML_TEXT_NODE
) {
1165 $out .= $contextNode->nodeValue
;
1166 } elseif ( $contextNode->nodeName
== 'template' ) {
1167 # Double-brace expansion
1168 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1169 $titles = $xpath->query( 'title', $contextNode );
1170 $title = $titles->item( 0 );
1171 $parts = $xpath->query( 'part', $contextNode );
1172 if ( $flags & PPFrame
::NO_TEMPLATES
) {
1173 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1175 $lineStart = $contextNode->getAttribute( 'lineStart' );
1177 'title' => new PPNode_DOM( $title ),
1178 'parts' => new PPNode_DOM( $parts ),
1179 'lineStart' => $lineStart );
1180 $ret = $this->parser
->braceSubstitution( $params, $this );
1181 if ( isset( $ret['object'] ) ) {
1182 $newIterator = $ret['object'];
1184 $out .= $ret['text'];
1187 } elseif ( $contextNode->nodeName
== 'tplarg' ) {
1188 # Triple-brace expansion
1189 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1190 $titles = $xpath->query( 'title', $contextNode );
1191 $title = $titles->item( 0 );
1192 $parts = $xpath->query( 'part', $contextNode );
1193 if ( $flags & PPFrame
::NO_ARGS
) {
1194 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1197 'title' => new PPNode_DOM( $title ),
1198 'parts' => new PPNode_DOM( $parts ) );
1199 $ret = $this->parser
->argSubstitution( $params, $this );
1200 if ( isset( $ret['object'] ) ) {
1201 $newIterator = $ret['object'];
1203 $out .= $ret['text'];
1206 } elseif ( $contextNode->nodeName
== 'comment' ) {
1207 # HTML-style comment
1208 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1209 if ( $this->parser
->ot
['html']
1210 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
1211 ||
( $flags & PPFrame
::STRIP_COMMENTS
)
1214 } elseif ( $this->parser
->ot
['wiki'] && !( $flags & PPFrame
::RECOVER_COMMENTS
) ) {
1215 # Add a strip marker in PST mode so that pstPass2() can
1216 # run some old-fashioned regexes on the result.
1217 # Not in RECOVER_COMMENTS mode (extractSections) though.
1218 $out .= $this->parser
->insertStripItem( $contextNode->textContent
);
1220 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1221 $out .= $contextNode->textContent
;
1223 } elseif ( $contextNode->nodeName
== 'ignore' ) {
1224 # Output suppression used by <includeonly> etc.
1225 # OT_WIKI will only respect <ignore> in substed templates.
1226 # The other output types respect it unless NO_IGNORE is set.
1227 # extractSections() sets NO_IGNORE and so never respects it.
1228 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] )
1229 ||
( $flags & PPFrame
::NO_IGNORE
)
1231 $out .= $contextNode->textContent
;
1235 } elseif ( $contextNode->nodeName
== 'ext' ) {
1237 $xpath = new DOMXPath( $contextNode->ownerDocument
);
1238 $names = $xpath->query( 'name', $contextNode );
1239 $attrs = $xpath->query( 'attr', $contextNode );
1240 $inners = $xpath->query( 'inner', $contextNode );
1241 $closes = $xpath->query( 'close', $contextNode );
1242 if ( $flags & PPFrame
::NO_TAGS
) {
1243 $s = '<' . $this->expand( $names->item( 0 ), $flags );
1244 if ( $attrs->length
> 0 ) {
1245 $s .= $this->expand( $attrs->item( 0 ), $flags );
1247 if ( $inners->length
> 0 ) {
1248 $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
1249 if ( $closes->length
> 0 ) {
1250 $s .= $this->expand( $closes->item( 0 ), $flags );
1258 'name' => new PPNode_DOM( $names->item( 0 ) ),
1259 'attr' => $attrs->length
> 0 ?
new PPNode_DOM( $attrs->item( 0 ) ) : null,
1260 'inner' => $inners->length
> 0 ?
new PPNode_DOM( $inners->item( 0 ) ) : null,
1261 'close' => $closes->length
> 0 ?
new PPNode_DOM( $closes->item( 0 ) ) : null,
1263 $out .= $this->parser
->extensionSubstitution( $params, $this );
1265 } elseif ( $contextNode->nodeName
== 'h' ) {
1267 $s = $this->expand( $contextNode->childNodes
, $flags );
1269 # Insert a heading marker only for <h> children of <root>
1270 # This is to stop extractSections from going over multiple tree levels
1271 if ( $contextNode->parentNode
->nodeName
== 'root' && $this->parser
->ot
['html'] ) {
1272 # Insert heading index marker
1273 $headingIndex = $contextNode->getAttribute( 'i' );
1274 $titleText = $this->title
->getPrefixedDBkey();
1275 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
1276 $serial = count( $this->parser
->mHeadings
) - 1;
1277 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser
::MARKER_SUFFIX
;
1278 $count = $contextNode->getAttribute( 'level' );
1279 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1280 $this->parser
->mStripState
->addGeneral( $marker, '' );
1284 # Generic recursive expansion
1285 $newIterator = $contextNode->childNodes
;
1288 throw new MWException( __METHOD__
. ': Invalid parameter type' );
1291 if ( $newIterator !== false ) {
1292 if ( $newIterator instanceof PPNode_DOM
) {
1293 $newIterator = $newIterator->node
;
1296 $iteratorStack[] = $newIterator;
1298 } elseif ( $iteratorStack[$level] === false ) {
1299 // Return accumulated value to parent
1300 // With tail recursion
1301 while ( $iteratorStack[$level] === false && $level > 0 ) {
1302 $outStack[$level - 1] .= $out;
1303 array_pop( $outStack );
1304 array_pop( $iteratorStack );
1305 array_pop( $indexStack );
1311 return $outStack[0];
1315 * @param string $sep
1317 * @param string|PPNode_DOM|DOMDocument $args,...
1320 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1321 $args = array_slice( func_get_args(), 2 );
1325 foreach ( $args as $root ) {
1326 if ( $root instanceof PPNode_DOM
) {
1327 $root = $root->node
;
1329 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1330 $root = array( $root );
1332 foreach ( $root as $node ) {
1338 $s .= $this->expand( $node, $flags );
1345 * Implode with no flags specified
1346 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1348 * @param string $sep
1349 * @param string|PPNode_DOM|DOMDocument $args,...
1352 public function implode( $sep /*, ... */ ) {
1353 $args = array_slice( func_get_args(), 1 );
1357 foreach ( $args as $root ) {
1358 if ( $root instanceof PPNode_DOM
) {
1359 $root = $root->node
;
1361 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1362 $root = array( $root );
1364 foreach ( $root as $node ) {
1370 $s .= $this->expand( $node );
1377 * Makes an object that, when expand()ed, will be the same as one obtained
1380 * @param string $sep
1381 * @param string|PPNode_DOM|DOMDocument $args,...
1384 public function virtualImplode( $sep /*, ... */ ) {
1385 $args = array_slice( func_get_args(), 1 );
1389 foreach ( $args as $root ) {
1390 if ( $root instanceof PPNode_DOM
) {
1391 $root = $root->node
;
1393 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1394 $root = array( $root );
1396 foreach ( $root as $node ) {
1409 * Virtual implode with brackets
1410 * @param string $start
1411 * @param string $sep
1412 * @param string $end
1413 * @param string|PPNode_DOM|DOMDocument $args,...
1416 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1417 $args = array_slice( func_get_args(), 3 );
1418 $out = array( $start );
1421 foreach ( $args as $root ) {
1422 if ( $root instanceof PPNode_DOM
) {
1423 $root = $root->node
;
1425 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
1426 $root = array( $root );
1428 foreach ( $root as $node ) {
1441 public function __toString() {
1445 public function getPDBK( $level = false ) {
1446 if ( $level === false ) {
1447 return $this->title
->getPrefixedDBkey();
1449 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
1456 public function getArguments() {
1463 public function getNumberedArguments() {
1470 public function getNamedArguments() {
1475 * Returns true if there are no arguments in this frame
1479 public function isEmpty() {
1483 public function getArgument( $name ) {
1488 * Returns true if the infinite loop check is OK, false if a loop is detected
1490 * @param Title $title
1493 public function loopCheck( $title ) {
1494 return !isset( $this->loopCheckHash
[$title->getPrefixedDBkey()] );
1498 * Return true if the frame is a template frame
1502 public function isTemplate() {
1507 * Get a title of frame
1511 public function getTitle() {
1512 return $this->title
;
1516 * Set the volatile flag
1520 public function setVolatile( $flag = true ) {
1521 $this->volatile
= $flag;
1525 * Get the volatile flag
1529 public function isVolatile() {
1530 return $this->volatile
;
1538 public function setTTL( $ttl ) {
1539 if ( $ttl !== null && ( $this->ttl
=== null ||
$ttl < $this->ttl
) ) {
1549 public function getTTL() {
1555 * Expansion frame with template arguments
1557 * @codingStandardsIgnoreStart
1559 class PPTemplateFrame_DOM
extends PPFrame_DOM
{
1560 // @codingStandardsIgnoreEnd
1562 public $numberedArgs, $namedArgs;
1568 public $numberedExpansionCache, $namedExpansionCache;
1571 * @param Preprocessor $preprocessor
1572 * @param bool|PPFrame_DOM $parent
1573 * @param array $numberedArgs
1574 * @param array $namedArgs
1575 * @param bool|Title $title
1577 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1578 $namedArgs = array(), $title = false
1580 parent
::__construct( $preprocessor );
1582 $this->parent
= $parent;
1583 $this->numberedArgs
= $numberedArgs;
1584 $this->namedArgs
= $namedArgs;
1585 $this->title
= $title;
1586 $pdbk = $title ?
$title->getPrefixedDBkey() : false;
1587 $this->titleCache
= $parent->titleCache
;
1588 $this->titleCache
[] = $pdbk;
1589 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
1590 if ( $pdbk !== false ) {
1591 $this->loopCheckHash
[$pdbk] = true;
1593 $this->depth
= $parent->depth +
1;
1594 $this->numberedExpansionCache
= $this->namedExpansionCache
= array();
1597 public function __toString() {
1600 $args = $this->numberedArgs +
$this->namedArgs
;
1601 foreach ( $args as $name => $value ) {
1607 $s .= "\"$name\":\"" .
1608 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';
1615 * @throws MWException
1616 * @param string|int $key
1617 * @param string|PPNode_DOM|DOMDocument $root
1621 public function cachedExpand( $key, $root, $flags = 0 ) {
1622 if ( isset( $this->parent
->childExpansionCache
[$key] ) ) {
1623 return $this->parent
->childExpansionCache
[$key];
1625 $retval = $this->expand( $root, $flags );
1626 if ( !$this->isVolatile() ) {
1627 $this->parent
->childExpansionCache
[$key] = $retval;
1633 * Returns true if there are no arguments in this frame
1637 public function isEmpty() {
1638 return !count( $this->numberedArgs
) && !count( $this->namedArgs
);
1641 public function getArguments() {
1642 $arguments = array();
1643 foreach ( array_merge(
1644 array_keys( $this->numberedArgs
),
1645 array_keys( $this->namedArgs
) ) as $key ) {
1646 $arguments[$key] = $this->getArgument( $key );
1651 public function getNumberedArguments() {
1652 $arguments = array();
1653 foreach ( array_keys( $this->numberedArgs
) as $key ) {
1654 $arguments[$key] = $this->getArgument( $key );
1659 public function getNamedArguments() {
1660 $arguments = array();
1661 foreach ( array_keys( $this->namedArgs
) as $key ) {
1662 $arguments[$key] = $this->getArgument( $key );
1667 public function getNumberedArgument( $index ) {
1668 if ( !isset( $this->numberedArgs
[$index] ) ) {
1671 if ( !isset( $this->numberedExpansionCache
[$index] ) ) {
1672 # No trimming for unnamed arguments
1673 $this->numberedExpansionCache
[$index] = $this->parent
->expand(
1674 $this->numberedArgs
[$index],
1675 PPFrame
::STRIP_COMMENTS
1678 return $this->numberedExpansionCache
[$index];
1681 public function getNamedArgument( $name ) {
1682 if ( !isset( $this->namedArgs
[$name] ) ) {
1685 if ( !isset( $this->namedExpansionCache
[$name] ) ) {
1686 # Trim named arguments post-expand, for backwards compatibility
1687 $this->namedExpansionCache
[$name] = trim(
1688 $this->parent
->expand( $this->namedArgs
[$name], PPFrame
::STRIP_COMMENTS
) );
1690 return $this->namedExpansionCache
[$name];
1693 public function getArgument( $name ) {
1694 $text = $this->getNumberedArgument( $name );
1695 if ( $text === false ) {
1696 $text = $this->getNamedArgument( $name );
1702 * Return true if the frame is a template frame
1706 public function isTemplate() {
1710 public function setVolatile( $flag = true ) {
1711 parent
::setVolatile( $flag );
1712 $this->parent
->setVolatile( $flag );
1715 public function setTTL( $ttl ) {
1716 parent
::setTTL( $ttl );
1717 $this->parent
->setTTL( $ttl );
1722 * Expansion frame with custom arguments
1724 * @codingStandardsIgnoreStart
1726 class PPCustomFrame_DOM
extends PPFrame_DOM
{
1727 // @codingStandardsIgnoreEnd
1731 public function __construct( $preprocessor, $args ) {
1732 parent
::__construct( $preprocessor );
1733 $this->args
= $args;
1736 public function __toString() {
1739 foreach ( $this->args
as $name => $value ) {
1745 $s .= "\"$name\":\"" .
1746 str_replace( '"', '\\"', $value->__toString() ) . '"';
1755 public function isEmpty() {
1756 return !count( $this->args
);
1759 public function getArgument( $index ) {
1760 if ( !isset( $this->args
[$index] ) ) {
1763 return $this->args
[$index];
1766 public function getArguments() {
1773 * @codingStandardsIgnoreStart
1775 class PPNode_DOM
implements PPNode
{
1776 // @codingStandardsIgnoreEnd
1784 public function __construct( $node, $xpath = false ) {
1785 $this->node
= $node;
1791 public function getXPath() {
1792 if ( $this->xpath
=== null ) {
1793 $this->xpath
= new DOMXPath( $this->node
->ownerDocument
);
1795 return $this->xpath
;
1798 public function __toString() {
1799 if ( $this->node
instanceof DOMNodeList
) {
1801 foreach ( $this->node
as $node ) {
1802 $s .= $node->ownerDocument
->saveXML( $node );
1805 $s = $this->node
->ownerDocument
->saveXML( $this->node
);
1811 * @return bool|PPNode_DOM
1813 public function getChildren() {
1814 return $this->node
->childNodes ?
new self( $this->node
->childNodes
) : false;
1818 * @return bool|PPNode_DOM
1820 public function getFirstChild() {
1821 return $this->node
->firstChild ?
new self( $this->node
->firstChild
) : false;
1825 * @return bool|PPNode_DOM
1827 public function getNextSibling() {
1828 return $this->node
->nextSibling ?
new self( $this->node
->nextSibling
) : false;
1832 * @param string $type
1834 * @return bool|PPNode_DOM
1836 public function getChildrenOfType( $type ) {
1837 return new self( $this->getXPath()->query( $type, $this->node
) );
1843 public function getLength() {
1844 if ( $this->node
instanceof DOMNodeList
) {
1845 return $this->node
->length
;
1853 * @return bool|PPNode_DOM
1855 public function item( $i ) {
1856 $item = $this->node
->item( $i );
1857 return $item ?
new self( $item ) : false;
1863 public function getName() {
1864 if ( $this->node
instanceof DOMNodeList
) {
1867 return $this->node
->nodeName
;
1872 * Split a "<part>" node into an associative array containing:
1873 * - name PPNode name
1874 * - index String index
1875 * - value PPNode value
1877 * @throws MWException
1880 public function splitArg() {
1881 $xpath = $this->getXPath();
1882 $names = $xpath->query( 'name', $this->node
);
1883 $values = $xpath->query( 'value', $this->node
);
1884 if ( !$names->length ||
!$values->length
) {
1885 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
1887 $name = $names->item( 0 );
1888 $index = $name->getAttribute( 'index' );
1890 'name' => new self( $name ),
1892 'value' => new self( $values->item( 0 ) ) );
1896 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1897 * All values in the resulting array are PPNodes. Inner and close are optional.
1899 * @throws MWException
1902 public function splitExt() {
1903 $xpath = $this->getXPath();
1904 $names = $xpath->query( 'name', $this->node
);
1905 $attrs = $xpath->query( 'attr', $this->node
);
1906 $inners = $xpath->query( 'inner', $this->node
);
1907 $closes = $xpath->query( 'close', $this->node
);
1908 if ( !$names->length ||
!$attrs->length
) {
1909 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
1912 'name' => new self( $names->item( 0 ) ),
1913 'attr' => new self( $attrs->item( 0 ) ) );
1914 if ( $inners->length
) {
1915 $parts['inner'] = new self( $inners->item( 0 ) );
1917 if ( $closes->length
) {
1918 $parts['close'] = new self( $closes->item( 0 ) );
1924 * Split a "<h>" node
1925 * @throws MWException
1928 public function splitHeading() {
1929 if ( $this->getName() !== 'h' ) {
1930 throw new MWException( 'Invalid h node passed to ' . __METHOD__
);
1933 'i' => $this->node
->getAttribute( 'i' ),
1934 'level' => $this->node
->getAttribute( 'level' ),
1935 'contents' => $this->getChildren()