Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / includes / parser / Preprocessor_DOM.php
blob4ea7dd4029e6b05c07cd4881a73c2927d05c0df3
1 <?php
2 /**
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
20 * @file
21 * @ingroup Parser
24 /**
25 * @ingroup Parser
27 class Preprocessor_DOM implements Preprocessor {
29 /**
30 * @var Parser
32 var $parser;
34 var $memoryLimit;
36 const CACHE_VERSION = 1;
38 function __construct( $parser ) {
39 $this->parser = $parser;
40 $mem = ini_get( 'memory_limit' );
41 $this->memoryLimit = false;
42 if ( strval( $mem ) !== '' && $mem != -1 ) {
43 if ( preg_match( '/^\d+$/', $mem ) ) {
44 $this->memoryLimit = $mem;
45 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
46 $this->memoryLimit = $m[1] * 1048576;
51 /**
52 * @return PPFrame_DOM
54 function newFrame() {
55 return new PPFrame_DOM( $this );
58 /**
59 * @param $args array
60 * @return PPCustomFrame_DOM
62 function newCustomFrame( $args ) {
63 return new PPCustomFrame_DOM( $this, $args );
66 /**
67 * @param $values
68 * @return PPNode_DOM
70 function newPartNodeArray( $values ) {
71 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
72 $xml = "<list>";
74 foreach ( $values as $k => $val ) {
75 if ( is_int( $k ) ) {
76 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) . "</value></part>";
77 } else {
78 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
82 $xml .= "</list>";
84 $dom = new DOMDocument();
85 $dom->loadXML( $xml );
86 $root = $dom->documentElement;
88 $node = new PPNode_DOM( $root->childNodes );
89 return $node;
92 /**
93 * @throws MWException
94 * @return bool
96 function memCheck() {
97 if ( $this->memoryLimit === false ) {
98 return true;
100 $usage = memory_get_usage();
101 if ( $usage > $this->memoryLimit * 0.9 ) {
102 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
103 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
105 return $usage <= $this->memoryLimit * 0.8;
109 * Preprocess some wikitext and return the document tree.
110 * This is the ghost of Parser::replace_variables().
112 * @param string $text the text to parse
113 * @param $flags Integer: bitwise combination of:
114 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
115 * included. Default is to assume a direct page view.
117 * The generated DOM tree must depend only on the input text and the flags.
118 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
120 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
121 * change in the DOM tree for a given text, must be passed through the section identifier
122 * in the section edit link and thus back to extractSections().
124 * The output of this function is currently only cached in process memory, but a persistent
125 * cache may be implemented at a later date which takes further advantage of these strict
126 * dependency requirements.
128 * @throws MWException
129 * @return PPNode_DOM
131 function preprocessToObj( $text, $flags = 0 ) {
132 wfProfileIn( __METHOD__ );
133 global $wgMemc, $wgPreprocessorCacheThreshold;
135 $xml = false;
136 $cacheable = ( $wgPreprocessorCacheThreshold !== false
137 && strlen( $text ) > $wgPreprocessorCacheThreshold );
138 if ( $cacheable ) {
139 wfProfileIn( __METHOD__ . '-cacheable' );
141 $cacheKey = wfMemcKey( 'preprocess-xml', md5( $text ), $flags );
142 $cacheValue = $wgMemc->get( $cacheKey );
143 if ( $cacheValue ) {
144 $version = substr( $cacheValue, 0, 8 );
145 if ( intval( $version ) == self::CACHE_VERSION ) {
146 $xml = substr( $cacheValue, 8 );
147 // From the cache
148 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
152 if ( $xml === false ) {
153 if ( $cacheable ) {
154 wfProfileIn( __METHOD__ . '-cache-miss' );
155 $xml = $this->preprocessToXml( $text, $flags );
156 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
157 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
158 wfProfileOut( __METHOD__ . '-cache-miss' );
159 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
160 } else {
161 $xml = $this->preprocessToXml( $text, $flags );
166 // Fail if the number of elements exceeds acceptable limits
167 // Do not attempt to generate the DOM
168 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
169 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
170 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
171 if ( $cacheable ) {
172 wfProfileOut( __METHOD__ . '-cacheable' );
174 wfProfileOut( __METHOD__ );
175 throw new MWException( __METHOD__ . ': generated node count limit exceeded' );
178 wfProfileIn( __METHOD__ . '-loadXML' );
179 $dom = new DOMDocument;
180 wfSuppressWarnings();
181 $result = $dom->loadXML( $xml );
182 wfRestoreWarnings();
183 if ( !$result ) {
184 // Try running the XML through UtfNormal to get rid of invalid characters
185 $xml = UtfNormal::cleanUp( $xml );
186 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
187 $result = $dom->loadXML( $xml, 1 << 19 );
188 if ( !$result ) {
189 wfProfileOut( __METHOD__ . '-loadXML' );
190 if ( $cacheable ) {
191 wfProfileOut( __METHOD__ . '-cacheable' );
193 wfProfileOut( __METHOD__ );
194 throw new MWException( __METHOD__ . ' generated invalid XML' );
197 $obj = new PPNode_DOM( $dom->documentElement );
198 wfProfileOut( __METHOD__ . '-loadXML' );
199 if ( $cacheable ) {
200 wfProfileOut( __METHOD__ . '-cacheable' );
202 wfProfileOut( __METHOD__ );
203 return $obj;
207 * @param $text string
208 * @param $flags int
209 * @return string
211 function preprocessToXml( $text, $flags = 0 ) {
212 wfProfileIn( __METHOD__ );
213 $rules = array(
214 '{' => array(
215 'end' => '}',
216 'names' => array(
217 2 => 'template',
218 3 => 'tplarg',
220 'min' => 2,
221 'max' => 3,
223 '[' => array(
224 'end' => ']',
225 'names' => array( 2 => null ),
226 'min' => 2,
227 'max' => 2,
231 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
233 $xmlishElements = $this->parser->getStripList();
234 $enableOnlyinclude = false;
235 if ( $forInclusion ) {
236 $ignoredTags = array( 'includeonly', '/includeonly' );
237 $ignoredElements = array( 'noinclude' );
238 $xmlishElements[] = 'noinclude';
239 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
240 $enableOnlyinclude = true;
242 } else {
243 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
244 $ignoredElements = array( 'includeonly' );
245 $xmlishElements[] = 'includeonly';
247 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
249 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
250 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
252 $stack = new PPDStack;
254 $searchBase = "[{<\n"; #}
255 $revText = strrev( $text ); // For fast reverse searches
256 $lengthText = strlen( $text );
258 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
259 $accum =& $stack->getAccum(); # Current accumulator
260 $accum = '<root>';
261 $findEquals = false; # True to find equals signs in arguments
262 $findPipe = false; # True to take notice of pipe characters
263 $headingIndex = 1;
264 $inHeading = false; # True if $i is inside a possible heading
265 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
266 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
267 $fakeLineStart = true; # Do a line-start run without outputting an LF character
269 while ( true ) {
270 //$this->memCheck();
272 if ( $findOnlyinclude ) {
273 // Ignore all input up to the next <onlyinclude>
274 $startPos = strpos( $text, '<onlyinclude>', $i );
275 if ( $startPos === false ) {
276 // Ignored section runs to the end
277 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
278 break;
280 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
281 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
282 $i = $tagEndPos;
283 $findOnlyinclude = false;
286 if ( $fakeLineStart ) {
287 $found = 'line-start';
288 $curChar = '';
289 } else {
290 # Find next opening brace, closing brace or pipe
291 $search = $searchBase;
292 if ( $stack->top === false ) {
293 $currentClosing = '';
294 } else {
295 $currentClosing = $stack->top->close;
296 $search .= $currentClosing;
298 if ( $findPipe ) {
299 $search .= '|';
301 if ( $findEquals ) {
302 // First equals will be for the template
303 $search .= '=';
305 $rule = null;
306 # Output literal section, advance input counter
307 $literalLength = strcspn( $text, $search, $i );
308 if ( $literalLength > 0 ) {
309 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
310 $i += $literalLength;
312 if ( $i >= $lengthText ) {
313 if ( $currentClosing == "\n" ) {
314 // Do a past-the-end run to finish off the heading
315 $curChar = '';
316 $found = 'line-end';
317 } else {
318 # All done
319 break;
321 } else {
322 $curChar = $text[$i];
323 if ( $curChar == '|' ) {
324 $found = 'pipe';
325 } elseif ( $curChar == '=' ) {
326 $found = 'equals';
327 } elseif ( $curChar == '<' ) {
328 $found = 'angle';
329 } elseif ( $curChar == "\n" ) {
330 if ( $inHeading ) {
331 $found = 'line-end';
332 } else {
333 $found = 'line-start';
335 } elseif ( $curChar == $currentClosing ) {
336 $found = 'close';
337 } elseif ( isset( $rules[$curChar] ) ) {
338 $found = 'open';
339 $rule = $rules[$curChar];
340 } else {
341 # Some versions of PHP have a strcspn which stops on null characters
342 # Ignore and continue
343 ++$i;
344 continue;
349 if ( $found == 'angle' ) {
350 $matches = false;
351 // Handle </onlyinclude>
352 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
353 $findOnlyinclude = true;
354 continue;
357 // Determine element name
358 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
359 // Element name missing or not listed
360 $accum .= '&lt;';
361 ++$i;
362 continue;
364 // Handle comments
365 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
366 // To avoid leaving blank lines, when a comment is both preceded
367 // and followed by a newline (ignoring spaces), trim leading and
368 // trailing spaces and one of the newlines.
370 // Find the end
371 $endPos = strpos( $text, '-->', $i + 4 );
372 if ( $endPos === false ) {
373 // Unclosed comment in input, runs to end
374 $inner = substr( $text, $i );
375 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
376 $i = $lengthText;
377 } else {
378 // Search backwards for leading whitespace
379 $wsStart = $i ? ( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
380 // Search forwards for trailing whitespace
381 // $wsEnd will be the position of the last space (or the '>' if there's none)
382 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
383 // Eat the line if possible
384 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
385 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
386 // it's a possible beneficial b/c break.
387 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
388 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
390 $startPos = $wsStart;
391 $endPos = $wsEnd + 1;
392 // Remove leading whitespace from the end of the accumulator
393 // Sanity check first though
394 $wsLength = $i - $wsStart;
395 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
396 $accum = substr( $accum, 0, -$wsLength );
398 // Do a line-start run next time to look for headings after the comment
399 $fakeLineStart = true;
400 } else {
401 // No line to eat, just take the comment itself
402 $startPos = $i;
403 $endPos += 2;
406 if ( $stack->top ) {
407 $part = $stack->top->getCurrentPart();
408 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
409 $part->visualEnd = $wsStart;
411 // Else comments abutting, no change in visual end
412 $part->commentEnd = $endPos;
414 $i = $endPos + 1;
415 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
416 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
418 continue;
420 $name = $matches[1];
421 $lowerName = strtolower( $name );
422 $attrStart = $i + strlen( $name ) + 1;
424 // Find end of tag
425 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
426 if ( $tagEndPos === false ) {
427 // Infinite backtrack
428 // Disable tag search to prevent worst-case O(N^2) performance
429 $noMoreGT = true;
430 $accum .= '&lt;';
431 ++$i;
432 continue;
435 // Handle ignored tags
436 if ( in_array( $lowerName, $ignoredTags ) ) {
437 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
438 $i = $tagEndPos + 1;
439 continue;
442 $tagStartPos = $i;
443 if ( $text[$tagEndPos - 1] == '/' ) {
444 $attrEnd = $tagEndPos - 1;
445 $inner = null;
446 $i = $tagEndPos + 1;
447 $close = '';
448 } else {
449 $attrEnd = $tagEndPos;
450 // Find closing tag
451 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
452 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
454 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
455 $i = $matches[0][1] + strlen( $matches[0][0] );
456 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
457 } else {
458 // No end tag -- let it run out to the end of the text.
459 $inner = substr( $text, $tagEndPos + 1 );
460 $i = $lengthText;
461 $close = '';
464 // <includeonly> and <noinclude> just become <ignore> tags
465 if ( in_array( $lowerName, $ignoredElements ) ) {
466 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
467 . '</ignore>';
468 continue;
471 $accum .= '<ext>';
472 if ( $attrEnd <= $attrStart ) {
473 $attr = '';
474 } else {
475 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
477 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
478 // Note that the attr element contains the whitespace between name and attribute,
479 // this is necessary for precise reconstruction during pre-save transform.
480 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
481 if ( $inner !== null ) {
482 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
484 $accum .= $close . '</ext>';
485 } elseif ( $found == 'line-start' ) {
486 // Is this the start of a heading?
487 // Line break belongs before the heading element in any case
488 if ( $fakeLineStart ) {
489 $fakeLineStart = false;
490 } else {
491 $accum .= $curChar;
492 $i++;
495 $count = strspn( $text, '=', $i, 6 );
496 if ( $count == 1 && $findEquals ) {
497 // DWIM: This looks kind of like a name/value separator
498 // Let's let the equals handler have it and break the potential heading
499 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
500 } elseif ( $count > 0 ) {
501 $piece = array(
502 'open' => "\n",
503 'close' => "\n",
504 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
505 'startPos' => $i,
506 'count' => $count );
507 $stack->push( $piece );
508 $accum =& $stack->getAccum();
509 $flags = $stack->getFlags();
510 extract( $flags );
511 $i += $count;
513 } elseif ( $found == 'line-end' ) {
514 $piece = $stack->top;
515 // A heading must be open, otherwise \n wouldn't have been in the search list
516 assert( '$piece->open == "\n"' );
517 $part = $piece->getCurrentPart();
518 // Search back through the input to see if it has a proper close
519 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
520 $wsLength = strspn( $revText, " \t", $lengthText - $i );
521 $searchStart = $i - $wsLength;
522 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
523 // Comment found at line end
524 // Search for equals signs before the comment
525 $searchStart = $part->visualEnd;
526 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
528 $count = $piece->count;
529 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
530 if ( $equalsLength > 0 ) {
531 if ( $searchStart - $equalsLength == $piece->startPos ) {
532 // This is just a single string of equals signs on its own line
533 // Replicate the doHeadings behavior /={count}(.+)={count}/
534 // First find out how many equals signs there really are (don't stop at 6)
535 $count = $equalsLength;
536 if ( $count < 3 ) {
537 $count = 0;
538 } else {
539 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
541 } else {
542 $count = min( $equalsLength, $count );
544 if ( $count > 0 ) {
545 // Normal match, output <h>
546 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
547 $headingIndex++;
548 } else {
549 // Single equals sign on its own line, count=0
550 $element = $accum;
552 } else {
553 // No match, no <h>, just pass down the inner text
554 $element = $accum;
556 // Unwind the stack
557 $stack->pop();
558 $accum =& $stack->getAccum();
559 $flags = $stack->getFlags();
560 extract( $flags );
562 // Append the result to the enclosing accumulator
563 $accum .= $element;
564 // Note that we do NOT increment the input pointer.
565 // This is because the closing linebreak could be the opening linebreak of
566 // another heading. Infinite loops are avoided because the next iteration MUST
567 // hit the heading open case above, which unconditionally increments the
568 // input pointer.
569 } elseif ( $found == 'open' ) {
570 # count opening brace characters
571 $count = strspn( $text, $curChar, $i );
573 # we need to add to stack only if opening brace count is enough for one of the rules
574 if ( $count >= $rule['min'] ) {
575 # Add it to the stack
576 $piece = array(
577 'open' => $curChar,
578 'close' => $rule['end'],
579 'count' => $count,
580 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
583 $stack->push( $piece );
584 $accum =& $stack->getAccum();
585 $flags = $stack->getFlags();
586 extract( $flags );
587 } else {
588 # Add literal brace(s)
589 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
591 $i += $count;
592 } elseif ( $found == 'close' ) {
593 $piece = $stack->top;
594 # lets check if there are enough characters for closing brace
595 $maxCount = $piece->count;
596 $count = strspn( $text, $curChar, $i, $maxCount );
598 # check for maximum matching characters (if there are 5 closing
599 # characters, we will probably need only 3 - depending on the rules)
600 $rule = $rules[$piece->open];
601 if ( $count > $rule['max'] ) {
602 # The specified maximum exists in the callback array, unless the caller
603 # has made an error
604 $matchingCount = $rule['max'];
605 } else {
606 # Count is less than the maximum
607 # Skip any gaps in the callback array to find the true largest match
608 # Need to use array_key_exists not isset because the callback can be null
609 $matchingCount = $count;
610 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
611 --$matchingCount;
615 if ( $matchingCount <= 0 ) {
616 # No matching element found in callback array
617 # Output a literal closing brace and continue
618 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
619 $i += $count;
620 continue;
622 $name = $rule['names'][$matchingCount];
623 if ( $name === null ) {
624 // No element, just literal text
625 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
626 } else {
627 # Create XML element
628 # Note: $parts is already XML, does not need to be encoded further
629 $parts = $piece->parts;
630 $title = $parts[0]->out;
631 unset( $parts[0] );
633 # The invocation is at the start of the line if lineStart is set in
634 # the stack, and all opening brackets are used up.
635 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
636 $attr = ' lineStart="1"';
637 } else {
638 $attr = '';
641 $element = "<$name$attr>";
642 $element .= "<title>$title</title>";
643 $argIndex = 1;
644 foreach ( $parts as $part ) {
645 if ( isset( $part->eqpos ) ) {
646 $argName = substr( $part->out, 0, $part->eqpos );
647 $argValue = substr( $part->out, $part->eqpos + 1 );
648 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
649 } else {
650 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
651 $argIndex++;
654 $element .= "</$name>";
657 # Advance input pointer
658 $i += $matchingCount;
660 # Unwind the stack
661 $stack->pop();
662 $accum =& $stack->getAccum();
664 # Re-add the old stack element if it still has unmatched opening characters remaining
665 if ( $matchingCount < $piece->count ) {
666 $piece->parts = array( new PPDPart );
667 $piece->count -= $matchingCount;
668 # do we still qualify for any callback with remaining count?
669 $min = $rules[$piece->open]['min'];
670 if ( $piece->count >= $min ) {
671 $stack->push( $piece );
672 $accum =& $stack->getAccum();
673 } else {
674 $accum .= str_repeat( $piece->open, $piece->count );
677 $flags = $stack->getFlags();
678 extract( $flags );
680 # Add XML element to the enclosing accumulator
681 $accum .= $element;
682 } elseif ( $found == 'pipe' ) {
683 $findEquals = true; // shortcut for getFlags()
684 $stack->addPart();
685 $accum =& $stack->getAccum();
686 ++$i;
687 } elseif ( $found == 'equals' ) {
688 $findEquals = false; // shortcut for getFlags()
689 $stack->getCurrentPart()->eqpos = strlen( $accum );
690 $accum .= '=';
691 ++$i;
695 # Output any remaining unclosed brackets
696 foreach ( $stack->stack as $piece ) {
697 $stack->rootAccum .= $piece->breakSyntax();
699 $stack->rootAccum .= '</root>';
700 $xml = $stack->rootAccum;
702 wfProfileOut( __METHOD__ );
704 return $xml;
709 * Stack class to help Preprocessor::preprocessToObj()
710 * @ingroup Parser
712 class PPDStack {
713 var $stack, $rootAccum;
716 * @var PPDStack
718 var $top;
719 var $out;
720 var $elementClass = 'PPDStackElement';
722 static $false = false;
724 function __construct() {
725 $this->stack = array();
726 $this->top = false;
727 $this->rootAccum = '';
728 $this->accum =& $this->rootAccum;
732 * @return int
734 function count() {
735 return count( $this->stack );
738 function &getAccum() {
739 return $this->accum;
742 function getCurrentPart() {
743 if ( $this->top === false ) {
744 return false;
745 } else {
746 return $this->top->getCurrentPart();
750 function push( $data ) {
751 if ( $data instanceof $this->elementClass ) {
752 $this->stack[] = $data;
753 } else {
754 $class = $this->elementClass;
755 $this->stack[] = new $class( $data );
757 $this->top = $this->stack[count( $this->stack ) - 1];
758 $this->accum =& $this->top->getAccum();
761 function pop() {
762 if ( !count( $this->stack ) ) {
763 throw new MWException( __METHOD__ . ': no elements remaining' );
765 $temp = array_pop( $this->stack );
767 if ( count( $this->stack ) ) {
768 $this->top = $this->stack[count( $this->stack ) - 1];
769 $this->accum =& $this->top->getAccum();
770 } else {
771 $this->top = self::$false;
772 $this->accum =& $this->rootAccum;
774 return $temp;
777 function addPart( $s = '' ) {
778 $this->top->addPart( $s );
779 $this->accum =& $this->top->getAccum();
783 * @return array
785 function getFlags() {
786 if ( !count( $this->stack ) ) {
787 return array(
788 'findEquals' => false,
789 'findPipe' => false,
790 'inHeading' => false,
792 } else {
793 return $this->top->getFlags();
799 * @ingroup Parser
801 class PPDStackElement {
802 var $open, // Opening character (\n for heading)
803 $close, // Matching closing character
804 $count, // Number of opening characters found (number of "=" for heading)
805 $parts, // Array of PPDPart objects describing pipe-separated parts.
806 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
808 var $partClass = 'PPDPart';
810 function __construct( $data = array() ) {
811 $class = $this->partClass;
812 $this->parts = array( new $class );
814 foreach ( $data as $name => $value ) {
815 $this->$name = $value;
819 function &getAccum() {
820 return $this->parts[count( $this->parts ) - 1]->out;
823 function addPart( $s = '' ) {
824 $class = $this->partClass;
825 $this->parts[] = new $class( $s );
828 function getCurrentPart() {
829 return $this->parts[count( $this->parts ) - 1];
833 * @return array
835 function getFlags() {
836 $partCount = count( $this->parts );
837 $findPipe = $this->open != "\n" && $this->open != '[';
838 return array(
839 'findPipe' => $findPipe,
840 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
841 'inHeading' => $this->open == "\n",
846 * Get the output string that would result if the close is not found.
848 * @return string
850 function breakSyntax( $openingCount = false ) {
851 if ( $this->open == "\n" ) {
852 $s = $this->parts[0]->out;
853 } else {
854 if ( $openingCount === false ) {
855 $openingCount = $this->count;
857 $s = str_repeat( $this->open, $openingCount );
858 $first = true;
859 foreach ( $this->parts as $part ) {
860 if ( $first ) {
861 $first = false;
862 } else {
863 $s .= '|';
865 $s .= $part->out;
868 return $s;
873 * @ingroup Parser
875 class PPDPart {
876 var $out; // Output accumulator string
878 // Optional member variables:
879 // eqpos Position of equals sign in output accumulator
880 // commentEnd Past-the-end input pointer for the last comment encountered
881 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
883 function __construct( $out = '' ) {
884 $this->out = $out;
889 * An expansion frame, used as a context to expand the result of preprocessToObj()
890 * @ingroup Parser
892 class PPFrame_DOM implements PPFrame {
895 * @var Preprocessor
897 var $preprocessor;
900 * @var Parser
902 var $parser;
905 * @var Title
907 var $title;
908 var $titleCache;
911 * Hashtable listing templates which are disallowed for expansion in this frame,
912 * having been encountered previously in parent frames.
914 var $loopCheckHash;
917 * Recursion depth of this frame, top = 0
918 * Note that this is NOT the same as expansion depth in expand()
920 var $depth;
923 * Construct a new preprocessor frame.
924 * @param $preprocessor Preprocessor The parent preprocessor
926 function __construct( $preprocessor ) {
927 $this->preprocessor = $preprocessor;
928 $this->parser = $preprocessor->parser;
929 $this->title = $this->parser->mTitle;
930 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
931 $this->loopCheckHash = array();
932 $this->depth = 0;
936 * Create a new child frame
937 * $args is optionally a multi-root PPNode or array containing the template arguments
939 * @return PPTemplateFrame_DOM
941 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
942 $namedArgs = array();
943 $numberedArgs = array();
944 if ( $title === false ) {
945 $title = $this->title;
947 if ( $args !== false ) {
948 $xpath = false;
949 if ( $args instanceof PPNode ) {
950 $args = $args->node;
952 foreach ( $args as $arg ) {
953 if ( $arg instanceof PPNode ) {
954 $arg = $arg->node;
956 if ( !$xpath ) {
957 $xpath = new DOMXPath( $arg->ownerDocument );
960 $nameNodes = $xpath->query( 'name', $arg );
961 $value = $xpath->query( 'value', $arg );
962 if ( $nameNodes->item( 0 )->hasAttributes() ) {
963 // Numbered parameter
964 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
965 $index = $index - $indexOffset;
966 $numberedArgs[$index] = $value->item( 0 );
967 unset( $namedArgs[$index] );
968 } else {
969 // Named parameter
970 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
971 $namedArgs[$name] = $value->item( 0 );
972 unset( $numberedArgs[$name] );
976 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
980 * @throws MWException
981 * @param $root
982 * @param $flags int
983 * @return string
985 function expand( $root, $flags = 0 ) {
986 static $expansionDepth = 0;
987 if ( is_string( $root ) ) {
988 return $root;
991 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
992 $this->parser->limitationWarn( 'node-count-exceeded',
993 $this->parser->mPPNodeCount,
994 $this->parser->mOptions->getMaxPPNodeCount()
996 return '<span class="error">Node-count limit exceeded</span>';
999 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1000 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1001 $expansionDepth,
1002 $this->parser->mOptions->getMaxPPExpandDepth()
1004 return '<span class="error">Expansion depth limit exceeded</span>';
1006 wfProfileIn( __METHOD__ );
1007 ++$expansionDepth;
1008 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1009 $this->parser->mHighestExpansionDepth = $expansionDepth;
1012 if ( $root instanceof PPNode_DOM ) {
1013 $root = $root->node;
1015 if ( $root instanceof DOMDocument ) {
1016 $root = $root->documentElement;
1019 $outStack = array( '', '' );
1020 $iteratorStack = array( false, $root );
1021 $indexStack = array( 0, 0 );
1023 while ( count( $iteratorStack ) > 1 ) {
1024 $level = count( $outStack ) - 1;
1025 $iteratorNode =& $iteratorStack[$level];
1026 $out =& $outStack[$level];
1027 $index =& $indexStack[$level];
1029 if ( $iteratorNode instanceof PPNode_DOM ) {
1030 $iteratorNode = $iteratorNode->node;
1033 if ( is_array( $iteratorNode ) ) {
1034 if ( $index >= count( $iteratorNode ) ) {
1035 // All done with this iterator
1036 $iteratorStack[$level] = false;
1037 $contextNode = false;
1038 } else {
1039 $contextNode = $iteratorNode[$index];
1040 $index++;
1042 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1043 if ( $index >= $iteratorNode->length ) {
1044 // All done with this iterator
1045 $iteratorStack[$level] = false;
1046 $contextNode = false;
1047 } else {
1048 $contextNode = $iteratorNode->item( $index );
1049 $index++;
1051 } else {
1052 // Copy to $contextNode and then delete from iterator stack,
1053 // because this is not an iterator but we do have to execute it once
1054 $contextNode = $iteratorStack[$level];
1055 $iteratorStack[$level] = false;
1058 if ( $contextNode instanceof PPNode_DOM ) {
1059 $contextNode = $contextNode->node;
1062 $newIterator = false;
1064 if ( $contextNode === false ) {
1065 // nothing to do
1066 } elseif ( is_string( $contextNode ) ) {
1067 $out .= $contextNode;
1068 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1069 $newIterator = $contextNode;
1070 } elseif ( $contextNode instanceof DOMNode ) {
1071 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1072 $out .= $contextNode->nodeValue;
1073 } elseif ( $contextNode->nodeName == 'template' ) {
1074 # Double-brace expansion
1075 $xpath = new DOMXPath( $contextNode->ownerDocument );
1076 $titles = $xpath->query( 'title', $contextNode );
1077 $title = $titles->item( 0 );
1078 $parts = $xpath->query( 'part', $contextNode );
1079 if ( $flags & PPFrame::NO_TEMPLATES ) {
1080 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1081 } else {
1082 $lineStart = $contextNode->getAttribute( 'lineStart' );
1083 $params = array(
1084 'title' => new PPNode_DOM( $title ),
1085 'parts' => new PPNode_DOM( $parts ),
1086 'lineStart' => $lineStart );
1087 $ret = $this->parser->braceSubstitution( $params, $this );
1088 if ( isset( $ret['object'] ) ) {
1089 $newIterator = $ret['object'];
1090 } else {
1091 $out .= $ret['text'];
1094 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1095 # Triple-brace expansion
1096 $xpath = new DOMXPath( $contextNode->ownerDocument );
1097 $titles = $xpath->query( 'title', $contextNode );
1098 $title = $titles->item( 0 );
1099 $parts = $xpath->query( 'part', $contextNode );
1100 if ( $flags & PPFrame::NO_ARGS ) {
1101 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1102 } else {
1103 $params = array(
1104 'title' => new PPNode_DOM( $title ),
1105 'parts' => new PPNode_DOM( $parts ) );
1106 $ret = $this->parser->argSubstitution( $params, $this );
1107 if ( isset( $ret['object'] ) ) {
1108 $newIterator = $ret['object'];
1109 } else {
1110 $out .= $ret['text'];
1113 } elseif ( $contextNode->nodeName == 'comment' ) {
1114 # HTML-style comment
1115 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1116 if ( $this->parser->ot['html']
1117 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1118 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1120 $out .= '';
1122 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1123 # Not in RECOVER_COMMENTS mode (extractSections) though
1124 elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1125 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1127 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1128 else {
1129 $out .= $contextNode->textContent;
1131 } elseif ( $contextNode->nodeName == 'ignore' ) {
1132 # Output suppression used by <includeonly> etc.
1133 # OT_WIKI will only respect <ignore> in substed templates.
1134 # The other output types respect it unless NO_IGNORE is set.
1135 # extractSections() sets NO_IGNORE and so never respects it.
1136 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1137 $out .= $contextNode->textContent;
1138 } else {
1139 $out .= '';
1141 } elseif ( $contextNode->nodeName == 'ext' ) {
1142 # Extension tag
1143 $xpath = new DOMXPath( $contextNode->ownerDocument );
1144 $names = $xpath->query( 'name', $contextNode );
1145 $attrs = $xpath->query( 'attr', $contextNode );
1146 $inners = $xpath->query( 'inner', $contextNode );
1147 $closes = $xpath->query( 'close', $contextNode );
1148 $params = array(
1149 'name' => new PPNode_DOM( $names->item( 0 ) ),
1150 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1151 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1152 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1154 $out .= $this->parser->extensionSubstitution( $params, $this );
1155 } elseif ( $contextNode->nodeName == 'h' ) {
1156 # Heading
1157 $s = $this->expand( $contextNode->childNodes, $flags );
1159 # Insert a heading marker only for <h> children of <root>
1160 # This is to stop extractSections from going over multiple tree levels
1161 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html'] ) {
1162 # Insert heading index marker
1163 $headingIndex = $contextNode->getAttribute( 'i' );
1164 $titleText = $this->title->getPrefixedDBkey();
1165 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1166 $serial = count( $this->parser->mHeadings ) - 1;
1167 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1168 $count = $contextNode->getAttribute( 'level' );
1169 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1170 $this->parser->mStripState->addGeneral( $marker, '' );
1172 $out .= $s;
1173 } else {
1174 # Generic recursive expansion
1175 $newIterator = $contextNode->childNodes;
1177 } else {
1178 wfProfileOut( __METHOD__ );
1179 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1182 if ( $newIterator !== false ) {
1183 if ( $newIterator instanceof PPNode_DOM ) {
1184 $newIterator = $newIterator->node;
1186 $outStack[] = '';
1187 $iteratorStack[] = $newIterator;
1188 $indexStack[] = 0;
1189 } elseif ( $iteratorStack[$level] === false ) {
1190 // Return accumulated value to parent
1191 // With tail recursion
1192 while ( $iteratorStack[$level] === false && $level > 0 ) {
1193 $outStack[$level - 1] .= $out;
1194 array_pop( $outStack );
1195 array_pop( $iteratorStack );
1196 array_pop( $indexStack );
1197 $level--;
1201 --$expansionDepth;
1202 wfProfileOut( __METHOD__ );
1203 return $outStack[0];
1207 * @param $sep
1208 * @param $flags
1209 * @return string
1211 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1212 $args = array_slice( func_get_args(), 2 );
1214 $first = true;
1215 $s = '';
1216 foreach ( $args as $root ) {
1217 if ( $root instanceof PPNode_DOM ) {
1218 $root = $root->node;
1220 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1221 $root = array( $root );
1223 foreach ( $root as $node ) {
1224 if ( $first ) {
1225 $first = false;
1226 } else {
1227 $s .= $sep;
1229 $s .= $this->expand( $node, $flags );
1232 return $s;
1236 * Implode with no flags specified
1237 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1239 * @return string
1241 function implode( $sep /*, ... */ ) {
1242 $args = array_slice( func_get_args(), 1 );
1244 $first = true;
1245 $s = '';
1246 foreach ( $args as $root ) {
1247 if ( $root instanceof PPNode_DOM ) {
1248 $root = $root->node;
1250 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1251 $root = array( $root );
1253 foreach ( $root as $node ) {
1254 if ( $first ) {
1255 $first = false;
1256 } else {
1257 $s .= $sep;
1259 $s .= $this->expand( $node );
1262 return $s;
1266 * Makes an object that, when expand()ed, will be the same as one obtained
1267 * with implode()
1269 * @return array
1271 function virtualImplode( $sep /*, ... */ ) {
1272 $args = array_slice( func_get_args(), 1 );
1273 $out = array();
1274 $first = true;
1276 foreach ( $args as $root ) {
1277 if ( $root instanceof PPNode_DOM ) {
1278 $root = $root->node;
1280 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1281 $root = array( $root );
1283 foreach ( $root as $node ) {
1284 if ( $first ) {
1285 $first = false;
1286 } else {
1287 $out[] = $sep;
1289 $out[] = $node;
1292 return $out;
1296 * Virtual implode with brackets
1297 * @return array
1299 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1300 $args = array_slice( func_get_args(), 3 );
1301 $out = array( $start );
1302 $first = true;
1304 foreach ( $args as $root ) {
1305 if ( $root instanceof PPNode_DOM ) {
1306 $root = $root->node;
1308 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1309 $root = array( $root );
1311 foreach ( $root as $node ) {
1312 if ( $first ) {
1313 $first = false;
1314 } else {
1315 $out[] = $sep;
1317 $out[] = $node;
1320 $out[] = $end;
1321 return $out;
1324 function __toString() {
1325 return 'frame{}';
1328 function getPDBK( $level = false ) {
1329 if ( $level === false ) {
1330 return $this->title->getPrefixedDBkey();
1331 } else {
1332 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1337 * @return array
1339 function getArguments() {
1340 return array();
1344 * @return array
1346 function getNumberedArguments() {
1347 return array();
1351 * @return array
1353 function getNamedArguments() {
1354 return array();
1358 * Returns true if there are no arguments in this frame
1360 * @return bool
1362 function isEmpty() {
1363 return true;
1366 function getArgument( $name ) {
1367 return false;
1371 * Returns true if the infinite loop check is OK, false if a loop is detected
1373 * @return bool
1375 function loopCheck( $title ) {
1376 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1380 * Return true if the frame is a template frame
1382 * @return bool
1384 function isTemplate() {
1385 return false;
1389 * Get a title of frame
1391 * @return Title
1393 function getTitle() {
1394 return $this->title;
1399 * Expansion frame with template arguments
1400 * @ingroup Parser
1402 class PPTemplateFrame_DOM extends PPFrame_DOM {
1403 var $numberedArgs, $namedArgs;
1406 * @var PPFrame_DOM
1408 var $parent;
1409 var $numberedExpansionCache, $namedExpansionCache;
1412 * @param $preprocessor
1413 * @param $parent PPFrame_DOM
1414 * @param $numberedArgs array
1415 * @param $namedArgs array
1416 * @param $title Title
1418 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1419 parent::__construct( $preprocessor );
1421 $this->parent = $parent;
1422 $this->numberedArgs = $numberedArgs;
1423 $this->namedArgs = $namedArgs;
1424 $this->title = $title;
1425 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1426 $this->titleCache = $parent->titleCache;
1427 $this->titleCache[] = $pdbk;
1428 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1429 if ( $pdbk !== false ) {
1430 $this->loopCheckHash[$pdbk] = true;
1432 $this->depth = $parent->depth + 1;
1433 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1436 function __toString() {
1437 $s = 'tplframe{';
1438 $first = true;
1439 $args = $this->numberedArgs + $this->namedArgs;
1440 foreach ( $args as $name => $value ) {
1441 if ( $first ) {
1442 $first = false;
1443 } else {
1444 $s .= ', ';
1446 $s .= "\"$name\":\"" .
1447 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1449 $s .= '}';
1450 return $s;
1454 * Returns true if there are no arguments in this frame
1456 * @return bool
1458 function isEmpty() {
1459 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1462 function getArguments() {
1463 $arguments = array();
1464 foreach ( array_merge(
1465 array_keys( $this->numberedArgs ),
1466 array_keys( $this->namedArgs ) ) as $key ) {
1467 $arguments[$key] = $this->getArgument( $key );
1469 return $arguments;
1472 function getNumberedArguments() {
1473 $arguments = array();
1474 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1475 $arguments[$key] = $this->getArgument( $key );
1477 return $arguments;
1480 function getNamedArguments() {
1481 $arguments = array();
1482 foreach ( array_keys( $this->namedArgs ) as $key ) {
1483 $arguments[$key] = $this->getArgument( $key );
1485 return $arguments;
1488 function getNumberedArgument( $index ) {
1489 if ( !isset( $this->numberedArgs[$index] ) ) {
1490 return false;
1492 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1493 # No trimming for unnamed arguments
1494 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1496 return $this->numberedExpansionCache[$index];
1499 function getNamedArgument( $name ) {
1500 if ( !isset( $this->namedArgs[$name] ) ) {
1501 return false;
1503 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1504 # Trim named arguments post-expand, for backwards compatibility
1505 $this->namedExpansionCache[$name] = trim(
1506 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1508 return $this->namedExpansionCache[$name];
1511 function getArgument( $name ) {
1512 $text = $this->getNumberedArgument( $name );
1513 if ( $text === false ) {
1514 $text = $this->getNamedArgument( $name );
1516 return $text;
1520 * Return true if the frame is a template frame
1522 * @return bool
1524 function isTemplate() {
1525 return true;
1530 * Expansion frame with custom arguments
1531 * @ingroup Parser
1533 class PPCustomFrame_DOM extends PPFrame_DOM {
1534 var $args;
1536 function __construct( $preprocessor, $args ) {
1537 parent::__construct( $preprocessor );
1538 $this->args = $args;
1541 function __toString() {
1542 $s = 'cstmframe{';
1543 $first = true;
1544 foreach ( $this->args as $name => $value ) {
1545 if ( $first ) {
1546 $first = false;
1547 } else {
1548 $s .= ', ';
1550 $s .= "\"$name\":\"" .
1551 str_replace( '"', '\\"', $value->__toString() ) . '"';
1553 $s .= '}';
1554 return $s;
1558 * @return bool
1560 function isEmpty() {
1561 return !count( $this->args );
1564 function getArgument( $index ) {
1565 if ( !isset( $this->args[$index] ) ) {
1566 return false;
1568 return $this->args[$index];
1571 function getArguments() {
1572 return $this->args;
1577 * @ingroup Parser
1579 class PPNode_DOM implements PPNode {
1582 * @var DOMElement
1584 var $node;
1585 var $xpath;
1587 function __construct( $node, $xpath = false ) {
1588 $this->node = $node;
1592 * @return DOMXPath
1594 function getXPath() {
1595 if ( $this->xpath === null ) {
1596 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1598 return $this->xpath;
1601 function __toString() {
1602 if ( $this->node instanceof DOMNodeList ) {
1603 $s = '';
1604 foreach ( $this->node as $node ) {
1605 $s .= $node->ownerDocument->saveXML( $node );
1607 } else {
1608 $s = $this->node->ownerDocument->saveXML( $this->node );
1610 return $s;
1614 * @return bool|PPNode_DOM
1616 function getChildren() {
1617 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1621 * @return bool|PPNode_DOM
1623 function getFirstChild() {
1624 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1628 * @return bool|PPNode_DOM
1630 function getNextSibling() {
1631 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1635 * @param $type
1637 * @return bool|PPNode_DOM
1639 function getChildrenOfType( $type ) {
1640 return new self( $this->getXPath()->query( $type, $this->node ) );
1644 * @return int
1646 function getLength() {
1647 if ( $this->node instanceof DOMNodeList ) {
1648 return $this->node->length;
1649 } else {
1650 return false;
1655 * @param $i
1656 * @return bool|PPNode_DOM
1658 function item( $i ) {
1659 $item = $this->node->item( $i );
1660 return $item ? new self( $item ) : false;
1664 * @return string
1666 function getName() {
1667 if ( $this->node instanceof DOMNodeList ) {
1668 return '#nodelist';
1669 } else {
1670 return $this->node->nodeName;
1675 * Split a "<part>" node into an associative array containing:
1676 * - name PPNode name
1677 * - index String index
1678 * - value PPNode value
1680 * @throws MWException
1681 * @return array
1683 function splitArg() {
1684 $xpath = $this->getXPath();
1685 $names = $xpath->query( 'name', $this->node );
1686 $values = $xpath->query( 'value', $this->node );
1687 if ( !$names->length || !$values->length ) {
1688 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1690 $name = $names->item( 0 );
1691 $index = $name->getAttribute( 'index' );
1692 return array(
1693 'name' => new self( $name ),
1694 'index' => $index,
1695 'value' => new self( $values->item( 0 ) ) );
1699 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1700 * All values in the resulting array are PPNodes. Inner and close are optional.
1702 * @throws MWException
1703 * @return array
1705 function splitExt() {
1706 $xpath = $this->getXPath();
1707 $names = $xpath->query( 'name', $this->node );
1708 $attrs = $xpath->query( 'attr', $this->node );
1709 $inners = $xpath->query( 'inner', $this->node );
1710 $closes = $xpath->query( 'close', $this->node );
1711 if ( !$names->length || !$attrs->length ) {
1712 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1714 $parts = array(
1715 'name' => new self( $names->item( 0 ) ),
1716 'attr' => new self( $attrs->item( 0 ) ) );
1717 if ( $inners->length ) {
1718 $parts['inner'] = new self( $inners->item( 0 ) );
1720 if ( $closes->length ) {
1721 $parts['close'] = new self( $closes->item( 0 ) );
1723 return $parts;
1727 * Split a "<h>" node
1728 * @throws MWException
1729 * @return array
1731 function splitHeading() {
1732 if ( $this->getName() !== 'h' ) {
1733 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1735 return array(
1736 'i' => $this->node->getAttribute( 'i' ),
1737 'level' => $this->node->getAttribute( 'level' ),
1738 'contents' => $this->getChildren()