Fixup fixme on r67819
[lhc/web/wiklou.git] / includes / parser / Preprocessor_DOM.php
1 <?php
2 /**
3 * Preprocessor using PHP's dom extension
4 *
5 * @file
6 * @ingroup Parser
7 */
8
9 /**
10 * @ingroup Parser
11 */
12 class Preprocessor_DOM implements Preprocessor {
13 var $parser, $memoryLimit;
14
15 const CACHE_VERSION = 1;
16
17 function __construct( $parser ) {
18 $this->parser = $parser;
19 $mem = ini_get( 'memory_limit' );
20 $this->memoryLimit = false;
21 if ( strval( $mem ) !== '' && $mem != -1 ) {
22 if ( preg_match( '/^\d+$/', $mem ) ) {
23 $this->memoryLimit = $mem;
24 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
25 $this->memoryLimit = $m[1] * 1048576;
26 }
27 }
28 }
29
30 function newFrame() {
31 return new PPFrame_DOM( $this );
32 }
33
34 function newCustomFrame( $args ) {
35 return new PPCustomFrame_DOM( $this, $args );
36 }
37
38 function newPartNodeArray( $values ) {
39 //NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
40 $xml = "<list>";
41
42 foreach ( $values as $k => $val ) {
43
44 if ( is_int( $k ) ) {
45 $xml .= "<part><name index=\"$k\"/><value>" . htmlspecialchars( $val ) ."</value></part>";
46 } else {
47 $xml .= "<part><name>" . htmlspecialchars( $k ) . "</name><value>" . htmlspecialchars( $val ) . "</value></part>";
48 }
49 }
50
51 $xml .= "</list>";
52
53 $dom = new DOMDocument();
54 $dom->loadXML( $xml );
55 $root = $dom->documentElement;
56
57 $node = new PPNode_DOM( $root->childNodes );
58 return $node;
59 }
60
61 function memCheck() {
62 if ( $this->memoryLimit === false ) {
63 return;
64 }
65 $usage = memory_get_usage();
66 if ( $usage > $this->memoryLimit * 0.9 ) {
67 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
68 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
69 }
70 return $usage <= $this->memoryLimit * 0.8;
71 }
72
73 /**
74 * Preprocess some wikitext and return the document tree.
75 * This is the ghost of Parser::replace_variables().
76 *
77 * @param $text String: the text to parse
78 * @param $flags Integer: bitwise combination of:
79 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
80 * included. Default is to assume a direct page view.
81 *
82 * The generated DOM tree must depend only on the input text and the flags.
83 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
84 *
85 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
86 * change in the DOM tree for a given text, must be passed through the section identifier
87 * in the section edit link and thus back to extractSections().
88 *
89 * The output of this function is currently only cached in process memory, but a persistent
90 * cache may be implemented at a later date which takes further advantage of these strict
91 * dependency requirements.
92 *
93 * @private
94 */
95 function preprocessToObj( $text, $flags = 0 ) {
96 wfProfileIn( __METHOD__ );
97 global $wgMemc, $wgPreprocessorCacheThreshold;
98
99 $xml = false;
100 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
101 if ( $cacheable ) {
102 wfProfileIn( __METHOD__.'-cacheable' );
103
104 $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
105 $cacheValue = $wgMemc->get( $cacheKey );
106 if ( $cacheValue ) {
107 $version = substr( $cacheValue, 0, 8 );
108 if ( intval( $version ) == self::CACHE_VERSION ) {
109 $xml = substr( $cacheValue, 8 );
110 // From the cache
111 wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
112 }
113 }
114 }
115 if ( $xml === false ) {
116 if ( $cacheable ) {
117 wfProfileIn( __METHOD__.'-cache-miss' );
118 $xml = $this->preprocessToXml( $text, $flags );
119 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
120 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
121 wfProfileOut( __METHOD__.'-cache-miss' );
122 wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
123 } else {
124 $xml = $this->preprocessToXml( $text, $flags );
125 }
126
127 }
128 wfProfileIn( __METHOD__.'-loadXML' );
129 $dom = new DOMDocument;
130 wfSuppressWarnings();
131 $result = $dom->loadXML( $xml );
132 wfRestoreWarnings();
133 if ( !$result ) {
134 // Try running the XML through UtfNormal to get rid of invalid characters
135 $xml = UtfNormal::cleanUp( $xml );
136 $result = $dom->loadXML( $xml );
137 if ( !$result ) {
138 throw new MWException( __METHOD__.' generated invalid XML' );
139 }
140 }
141 $obj = new PPNode_DOM( $dom->documentElement );
142 wfProfileOut( __METHOD__.'-loadXML' );
143 if ( $cacheable ) {
144 wfProfileOut( __METHOD__.'-cacheable' );
145 }
146 wfProfileOut( __METHOD__ );
147 return $obj;
148 }
149
150 function preprocessToXml( $text, $flags = 0 ) {
151 wfProfileIn( __METHOD__ );
152 $rules = array(
153 '{' => array(
154 'end' => '}',
155 'names' => array(
156 2 => 'template',
157 3 => 'tplarg',
158 ),
159 'min' => 2,
160 'max' => 3,
161 ),
162 '[' => array(
163 'end' => ']',
164 'names' => array( 2 => null ),
165 'min' => 2,
166 'max' => 2,
167 )
168 );
169
170 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
171
172 $xmlishElements = $this->parser->getStripList();
173 $enableOnlyinclude = false;
174 if ( $forInclusion ) {
175 $ignoredTags = array( 'includeonly', '/includeonly' );
176 $ignoredElements = array( 'noinclude' );
177 $xmlishElements[] = 'noinclude';
178 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
179 $enableOnlyinclude = true;
180 }
181 } else {
182 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
183 $ignoredElements = array( 'includeonly' );
184 $xmlishElements[] = 'includeonly';
185 }
186 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
187
188 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
189 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
190
191 $stack = new PPDStack;
192
193 $searchBase = "[{<\n"; #}
194 $revText = strrev( $text ); // For fast reverse searches
195
196 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
197 $accum =& $stack->getAccum(); # Current accumulator
198 $accum = '<root>';
199 $findEquals = false; # True to find equals signs in arguments
200 $findPipe = false; # True to take notice of pipe characters
201 $headingIndex = 1;
202 $inHeading = false; # True if $i is inside a possible heading
203 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
204 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
205 $fakeLineStart = true; # Do a line-start run without outputting an LF character
206
207 while ( true ) {
208 //$this->memCheck();
209
210 if ( $findOnlyinclude ) {
211 // Ignore all input up to the next <onlyinclude>
212 $startPos = strpos( $text, '<onlyinclude>', $i );
213 if ( $startPos === false ) {
214 // Ignored section runs to the end
215 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
216 break;
217 }
218 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
219 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
220 $i = $tagEndPos;
221 $findOnlyinclude = false;
222 }
223
224 if ( $fakeLineStart ) {
225 $found = 'line-start';
226 $curChar = '';
227 } else {
228 # Find next opening brace, closing brace or pipe
229 $search = $searchBase;
230 if ( $stack->top === false ) {
231 $currentClosing = '';
232 } else {
233 $currentClosing = $stack->top->close;
234 $search .= $currentClosing;
235 }
236 if ( $findPipe ) {
237 $search .= '|';
238 }
239 if ( $findEquals ) {
240 // First equals will be for the template
241 $search .= '=';
242 }
243 $rule = null;
244 # Output literal section, advance input counter
245 $literalLength = strcspn( $text, $search, $i );
246 if ( $literalLength > 0 ) {
247 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
248 $i += $literalLength;
249 }
250 if ( $i >= strlen( $text ) ) {
251 if ( $currentClosing == "\n" ) {
252 // Do a past-the-end run to finish off the heading
253 $curChar = '';
254 $found = 'line-end';
255 } else {
256 # All done
257 break;
258 }
259 } else {
260 $curChar = $text[$i];
261 if ( $curChar == '|' ) {
262 $found = 'pipe';
263 } elseif ( $curChar == '=' ) {
264 $found = 'equals';
265 } elseif ( $curChar == '<' ) {
266 $found = 'angle';
267 } elseif ( $curChar == "\n" ) {
268 if ( $inHeading ) {
269 $found = 'line-end';
270 } else {
271 $found = 'line-start';
272 }
273 } elseif ( $curChar == $currentClosing ) {
274 $found = 'close';
275 } elseif ( isset( $rules[$curChar] ) ) {
276 $found = 'open';
277 $rule = $rules[$curChar];
278 } else {
279 # Some versions of PHP have a strcspn which stops on null characters
280 # Ignore and continue
281 ++$i;
282 continue;
283 }
284 }
285 }
286
287 if ( $found == 'angle' ) {
288 $matches = false;
289 // Handle </onlyinclude>
290 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
291 $findOnlyinclude = true;
292 continue;
293 }
294
295 // Determine element name
296 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
297 // Element name missing or not listed
298 $accum .= '&lt;';
299 ++$i;
300 continue;
301 }
302 // Handle comments
303 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
304 // To avoid leaving blank lines, when a comment is both preceded
305 // and followed by a newline (ignoring spaces), trim leading and
306 // trailing spaces and one of the newlines.
307
308 // Find the end
309 $endPos = strpos( $text, '-->', $i + 4 );
310 if ( $endPos === false ) {
311 // Unclosed comment in input, runs to end
312 $inner = substr( $text, $i );
313 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
314 $i = strlen( $text );
315 } else {
316 // Search backwards for leading whitespace
317 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
318 // Search forwards for trailing whitespace
319 // $wsEnd will be the position of the last space
320 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
321 // Eat the line if possible
322 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
323 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
324 // it's a possible beneficial b/c break.
325 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
326 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
327 {
328 $startPos = $wsStart;
329 $endPos = $wsEnd + 1;
330 // Remove leading whitespace from the end of the accumulator
331 // Sanity check first though
332 $wsLength = $i - $wsStart;
333 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
334 $accum = substr( $accum, 0, -$wsLength );
335 }
336 // Do a line-start run next time to look for headings after the comment
337 $fakeLineStart = true;
338 } else {
339 // No line to eat, just take the comment itself
340 $startPos = $i;
341 $endPos += 2;
342 }
343
344 if ( $stack->top ) {
345 $part = $stack->top->getCurrentPart();
346 if ( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) {
347 // Comments abutting, no change in visual end
348 $part->commentEnd = $wsEnd;
349 } else {
350 $part->visualEnd = $wsStart;
351 $part->commentEnd = $endPos;
352 }
353 }
354 $i = $endPos + 1;
355 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
356 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
357 }
358 continue;
359 }
360 $name = $matches[1];
361 $lowerName = strtolower( $name );
362 $attrStart = $i + strlen( $name ) + 1;
363
364 // Find end of tag
365 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
366 if ( $tagEndPos === false ) {
367 // Infinite backtrack
368 // Disable tag search to prevent worst-case O(N^2) performance
369 $noMoreGT = true;
370 $accum .= '&lt;';
371 ++$i;
372 continue;
373 }
374
375 // Handle ignored tags
376 if ( in_array( $lowerName, $ignoredTags ) ) {
377 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
378 $i = $tagEndPos + 1;
379 continue;
380 }
381
382 $tagStartPos = $i;
383 if ( $text[$tagEndPos-1] == '/' ) {
384 $attrEnd = $tagEndPos - 1;
385 $inner = null;
386 $i = $tagEndPos + 1;
387 $close = '';
388 } else {
389 $attrEnd = $tagEndPos;
390 // Find closing tag
391 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
392 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
393 {
394 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
395 $i = $matches[0][1] + strlen( $matches[0][0] );
396 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
397 } else {
398 // No end tag -- let it run out to the end of the text.
399 $inner = substr( $text, $tagEndPos + 1 );
400 $i = strlen( $text );
401 $close = '';
402 }
403 }
404 // <includeonly> and <noinclude> just become <ignore> tags
405 if ( in_array( $lowerName, $ignoredElements ) ) {
406 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
407 . '</ignore>';
408 continue;
409 }
410
411 $accum .= '<ext>';
412 if ( $attrEnd <= $attrStart ) {
413 $attr = '';
414 } else {
415 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
416 }
417 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
418 // Note that the attr element contains the whitespace between name and attribute,
419 // this is necessary for precise reconstruction during pre-save transform.
420 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
421 if ( $inner !== null ) {
422 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
423 }
424 $accum .= $close . '</ext>';
425 }
426
427 elseif ( $found == 'line-start' ) {
428 // Is this the start of a heading?
429 // Line break belongs before the heading element in any case
430 if ( $fakeLineStart ) {
431 $fakeLineStart = false;
432 } else {
433 $accum .= $curChar;
434 $i++;
435 }
436
437 $count = strspn( $text, '=', $i, 6 );
438 if ( $count == 1 && $findEquals ) {
439 // DWIM: This looks kind of like a name/value separator
440 // Let's let the equals handler have it and break the potential heading
441 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
442 } elseif ( $count > 0 ) {
443 $piece = array(
444 'open' => "\n",
445 'close' => "\n",
446 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
447 'startPos' => $i,
448 'count' => $count );
449 $stack->push( $piece );
450 $accum =& $stack->getAccum();
451 $flags = $stack->getFlags();
452 extract( $flags );
453 $i += $count;
454 }
455 }
456
457 elseif ( $found == 'line-end' ) {
458 $piece = $stack->top;
459 // A heading must be open, otherwise \n wouldn't have been in the search list
460 assert( $piece->open == "\n" );
461 $part = $piece->getCurrentPart();
462 // Search back through the input to see if it has a proper close
463 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
464 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
465 $searchStart = $i - $wsLength;
466 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
467 // Comment found at line end
468 // Search for equals signs before the comment
469 $searchStart = $part->visualEnd;
470 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
471 }
472 $count = $piece->count;
473 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
474 if ( $equalsLength > 0 ) {
475 if ( $searchStart - $equalsLength == $piece->startPos ) {
476 // This is just a single string of equals signs on its own line
477 // Replicate the doHeadings behaviour /={count}(.+)={count}/
478 // First find out how many equals signs there really are (don't stop at 6)
479 $count = $equalsLength;
480 if ( $count < 3 ) {
481 $count = 0;
482 } else {
483 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
484 }
485 } else {
486 $count = min( $equalsLength, $count );
487 }
488 if ( $count > 0 ) {
489 // Normal match, output <h>
490 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
491 $headingIndex++;
492 } else {
493 // Single equals sign on its own line, count=0
494 $element = $accum;
495 }
496 } else {
497 // No match, no <h>, just pass down the inner text
498 $element = $accum;
499 }
500 // Unwind the stack
501 $stack->pop();
502 $accum =& $stack->getAccum();
503 $flags = $stack->getFlags();
504 extract( $flags );
505
506 // Append the result to the enclosing accumulator
507 $accum .= $element;
508 // Note that we do NOT increment the input pointer.
509 // This is because the closing linebreak could be the opening linebreak of
510 // another heading. Infinite loops are avoided because the next iteration MUST
511 // hit the heading open case above, which unconditionally increments the
512 // input pointer.
513 } elseif ( $found == 'open' ) {
514 # count opening brace characters
515 $count = strspn( $text, $curChar, $i );
516
517 # we need to add to stack only if opening brace count is enough for one of the rules
518 if ( $count >= $rule['min'] ) {
519 # Add it to the stack
520 $piece = array(
521 'open' => $curChar,
522 'close' => $rule['end'],
523 'count' => $count,
524 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
525 );
526
527 $stack->push( $piece );
528 $accum =& $stack->getAccum();
529 $flags = $stack->getFlags();
530 extract( $flags );
531 } else {
532 # Add literal brace(s)
533 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
534 }
535 $i += $count;
536 } elseif ( $found == 'close' ) {
537 $piece = $stack->top;
538 # lets check if there are enough characters for closing brace
539 $maxCount = $piece->count;
540 $count = strspn( $text, $curChar, $i, $maxCount );
541
542 # check for maximum matching characters (if there are 5 closing
543 # characters, we will probably need only 3 - depending on the rules)
544 $rule = $rules[$piece->open];
545 if ( $count > $rule['max'] ) {
546 # The specified maximum exists in the callback array, unless the caller
547 # has made an error
548 $matchingCount = $rule['max'];
549 } else {
550 # Count is less than the maximum
551 # Skip any gaps in the callback array to find the true largest match
552 # Need to use array_key_exists not isset because the callback can be null
553 $matchingCount = $count;
554 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
555 --$matchingCount;
556 }
557 }
558
559 if ($matchingCount <= 0) {
560 # No matching element found in callback array
561 # Output a literal closing brace and continue
562 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
563 $i += $count;
564 continue;
565 }
566 $name = $rule['names'][$matchingCount];
567 if ( $name === null ) {
568 // No element, just literal text
569 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
570 } else {
571 # Create XML element
572 # Note: $parts is already XML, does not need to be encoded further
573 $parts = $piece->parts;
574 $title = $parts[0]->out;
575 unset( $parts[0] );
576
577 # The invocation is at the start of the line if lineStart is set in
578 # the stack, and all opening brackets are used up.
579 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
580 $attr = ' lineStart="1"';
581 } else {
582 $attr = '';
583 }
584
585 $element = "<$name$attr>";
586 $element .= "<title>$title</title>";
587 $argIndex = 1;
588 foreach ( $parts as $part ) {
589 if ( isset( $part->eqpos ) ) {
590 $argName = substr( $part->out, 0, $part->eqpos );
591 $argValue = substr( $part->out, $part->eqpos + 1 );
592 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
593 } else {
594 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
595 $argIndex++;
596 }
597 }
598 $element .= "</$name>";
599 }
600
601 # Advance input pointer
602 $i += $matchingCount;
603
604 # Unwind the stack
605 $stack->pop();
606 $accum =& $stack->getAccum();
607
608 # Re-add the old stack element if it still has unmatched opening characters remaining
609 if ($matchingCount < $piece->count) {
610 $piece->parts = array( new PPDPart );
611 $piece->count -= $matchingCount;
612 # do we still qualify for any callback with remaining count?
613 $names = $rules[$piece->open]['names'];
614 $skippedBraces = 0;
615 $enclosingAccum =& $accum;
616 while ( $piece->count ) {
617 if ( array_key_exists( $piece->count, $names ) ) {
618 $stack->push( $piece );
619 $accum =& $stack->getAccum();
620 break;
621 }
622 --$piece->count;
623 $skippedBraces ++;
624 }
625 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
626 }
627 $flags = $stack->getFlags();
628 extract( $flags );
629
630 # Add XML element to the enclosing accumulator
631 $accum .= $element;
632 }
633
634 elseif ( $found == 'pipe' ) {
635 $findEquals = true; // shortcut for getFlags()
636 $stack->addPart();
637 $accum =& $stack->getAccum();
638 ++$i;
639 }
640
641 elseif ( $found == 'equals' ) {
642 $findEquals = false; // shortcut for getFlags()
643 $stack->getCurrentPart()->eqpos = strlen( $accum );
644 $accum .= '=';
645 ++$i;
646 }
647 }
648
649 # Output any remaining unclosed brackets
650 foreach ( $stack->stack as $piece ) {
651 $stack->rootAccum .= $piece->breakSyntax();
652 }
653 $stack->rootAccum .= '</root>';
654 $xml = $stack->rootAccum;
655
656 wfProfileOut( __METHOD__ );
657
658 return $xml;
659 }
660 }
661
662 /**
663 * Stack class to help Preprocessor::preprocessToObj()
664 * @ingroup Parser
665 */
666 class PPDStack {
667 var $stack, $rootAccum, $top;
668 var $out;
669 var $elementClass = 'PPDStackElement';
670
671 static $false = false;
672
673 function __construct() {
674 $this->stack = array();
675 $this->top = false;
676 $this->rootAccum = '';
677 $this->accum =& $this->rootAccum;
678 }
679
680 function count() {
681 return count( $this->stack );
682 }
683
684 function &getAccum() {
685 return $this->accum;
686 }
687
688 function getCurrentPart() {
689 if ( $this->top === false ) {
690 return false;
691 } else {
692 return $this->top->getCurrentPart();
693 }
694 }
695
696 function push( $data ) {
697 if ( $data instanceof $this->elementClass ) {
698 $this->stack[] = $data;
699 } else {
700 $class = $this->elementClass;
701 $this->stack[] = new $class( $data );
702 }
703 $this->top = $this->stack[ count( $this->stack ) - 1 ];
704 $this->accum =& $this->top->getAccum();
705 }
706
707 function pop() {
708 if ( !count( $this->stack ) ) {
709 throw new MWException( __METHOD__.': no elements remaining' );
710 }
711 $temp = array_pop( $this->stack );
712
713 if ( count( $this->stack ) ) {
714 $this->top = $this->stack[ count( $this->stack ) - 1 ];
715 $this->accum =& $this->top->getAccum();
716 } else {
717 $this->top = self::$false;
718 $this->accum =& $this->rootAccum;
719 }
720 return $temp;
721 }
722
723 function addPart( $s = '' ) {
724 $this->top->addPart( $s );
725 $this->accum =& $this->top->getAccum();
726 }
727
728 function getFlags() {
729 if ( !count( $this->stack ) ) {
730 return array(
731 'findEquals' => false,
732 'findPipe' => false,
733 'inHeading' => false,
734 );
735 } else {
736 return $this->top->getFlags();
737 }
738 }
739 }
740
741 /**
742 * @ingroup Parser
743 */
744 class PPDStackElement {
745 var $open, // Opening character (\n for heading)
746 $close, // Matching closing character
747 $count, // Number of opening characters found (number of "=" for heading)
748 $parts, // Array of PPDPart objects describing pipe-separated parts.
749 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
750
751 var $partClass = 'PPDPart';
752
753 function __construct( $data = array() ) {
754 $class = $this->partClass;
755 $this->parts = array( new $class );
756
757 foreach ( $data as $name => $value ) {
758 $this->$name = $value;
759 }
760 }
761
762 function &getAccum() {
763 return $this->parts[count($this->parts) - 1]->out;
764 }
765
766 function addPart( $s = '' ) {
767 $class = $this->partClass;
768 $this->parts[] = new $class( $s );
769 }
770
771 function getCurrentPart() {
772 return $this->parts[count($this->parts) - 1];
773 }
774
775 function getFlags() {
776 $partCount = count( $this->parts );
777 $findPipe = $this->open != "\n" && $this->open != '[';
778 return array(
779 'findPipe' => $findPipe,
780 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
781 'inHeading' => $this->open == "\n",
782 );
783 }
784
785 /**
786 * Get the output string that would result if the close is not found.
787 */
788 function breakSyntax( $openingCount = false ) {
789 if ( $this->open == "\n" ) {
790 $s = $this->parts[0]->out;
791 } else {
792 if ( $openingCount === false ) {
793 $openingCount = $this->count;
794 }
795 $s = str_repeat( $this->open, $openingCount );
796 $first = true;
797 foreach ( $this->parts as $part ) {
798 if ( $first ) {
799 $first = false;
800 } else {
801 $s .= '|';
802 }
803 $s .= $part->out;
804 }
805 }
806 return $s;
807 }
808 }
809
810 /**
811 * @ingroup Parser
812 */
813 class PPDPart {
814 var $out; // Output accumulator string
815
816 // Optional member variables:
817 // eqpos Position of equals sign in output accumulator
818 // commentEnd Past-the-end input pointer for the last comment encountered
819 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
820
821 function __construct( $out = '' ) {
822 $this->out = $out;
823 }
824 }
825
826 /**
827 * An expansion frame, used as a context to expand the result of preprocessToObj()
828 * @ingroup Parser
829 */
830 class PPFrame_DOM implements PPFrame {
831 var $preprocessor, $parser, $title;
832 var $titleCache;
833
834 /**
835 * Hashtable listing templates which are disallowed for expansion in this frame,
836 * having been encountered previously in parent frames.
837 */
838 var $loopCheckHash;
839
840 /**
841 * Recursion depth of this frame, top = 0
842 * Note that this is NOT the same as expansion depth in expand()
843 */
844 var $depth;
845
846
847 /**
848 * Construct a new preprocessor frame.
849 * @param $preprocessor Preprocessor: The parent preprocessor
850 */
851 function __construct( $preprocessor ) {
852 $this->preprocessor = $preprocessor;
853 $this->parser = $preprocessor->parser;
854 $this->title = $this->parser->mTitle;
855 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
856 $this->loopCheckHash = array();
857 $this->depth = 0;
858 }
859
860 /**
861 * Create a new child frame
862 * $args is optionally a multi-root PPNode or array containing the template arguments
863 */
864 function newChild( $args = false, $title = false ) {
865 $namedArgs = array();
866 $numberedArgs = array();
867 if ( $title === false ) {
868 $title = $this->title;
869 }
870 if ( $args !== false ) {
871 $xpath = false;
872 if ( $args instanceof PPNode ) {
873 $args = $args->node;
874 }
875 foreach ( $args as $arg ) {
876 if ( !$xpath ) {
877 $xpath = new DOMXPath( $arg->ownerDocument );
878 }
879
880 $nameNodes = $xpath->query( 'name', $arg );
881 $value = $xpath->query( 'value', $arg );
882 if ( $nameNodes->item( 0 )->hasAttributes() ) {
883 // Numbered parameter
884 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
885 $numberedArgs[$index] = $value->item( 0 );
886 unset( $namedArgs[$index] );
887 } else {
888 // Named parameter
889 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
890 $namedArgs[$name] = $value->item( 0 );
891 unset( $numberedArgs[$name] );
892 }
893 }
894 }
895 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
896 }
897
898 function expand( $root, $flags = 0 ) {
899 static $expansionDepth = 0;
900 if ( is_string( $root ) ) {
901 return $root;
902 }
903
904 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() )
905 {
906 return '<span class="error">Node-count limit exceeded</span>';
907 }
908
909 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
910 return '<span class="error">Expansion depth limit exceeded</span>';
911 }
912 wfProfileIn( __METHOD__ );
913 ++$expansionDepth;
914
915 if ( $root instanceof PPNode_DOM ) {
916 $root = $root->node;
917 }
918 if ( $root instanceof DOMDocument ) {
919 $root = $root->documentElement;
920 }
921
922 $outStack = array( '', '' );
923 $iteratorStack = array( false, $root );
924 $indexStack = array( 0, 0 );
925
926 while ( count( $iteratorStack ) > 1 ) {
927 $level = count( $outStack ) - 1;
928 $iteratorNode =& $iteratorStack[ $level ];
929 $out =& $outStack[$level];
930 $index =& $indexStack[$level];
931
932 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
933
934 if ( is_array( $iteratorNode ) ) {
935 if ( $index >= count( $iteratorNode ) ) {
936 // All done with this iterator
937 $iteratorStack[$level] = false;
938 $contextNode = false;
939 } else {
940 $contextNode = $iteratorNode[$index];
941 $index++;
942 }
943 } elseif ( $iteratorNode instanceof DOMNodeList ) {
944 if ( $index >= $iteratorNode->length ) {
945 // All done with this iterator
946 $iteratorStack[$level] = false;
947 $contextNode = false;
948 } else {
949 $contextNode = $iteratorNode->item( $index );
950 $index++;
951 }
952 } else {
953 // Copy to $contextNode and then delete from iterator stack,
954 // because this is not an iterator but we do have to execute it once
955 $contextNode = $iteratorStack[$level];
956 $iteratorStack[$level] = false;
957 }
958
959 if ( $contextNode instanceof PPNode_DOM ) {
960 $contextNode = $contextNode->node;
961 }
962
963 $newIterator = false;
964
965 if ( $contextNode === false ) {
966 // nothing to do
967 } elseif ( is_string( $contextNode ) ) {
968 $out .= $contextNode;
969 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
970 $newIterator = $contextNode;
971 } elseif ( $contextNode instanceof DOMNode ) {
972 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
973 $out .= $contextNode->nodeValue;
974 } elseif ( $contextNode->nodeName == 'template' ) {
975 # Double-brace expansion
976 $xpath = new DOMXPath( $contextNode->ownerDocument );
977 $titles = $xpath->query( 'title', $contextNode );
978 $title = $titles->item( 0 );
979 $parts = $xpath->query( 'part', $contextNode );
980 if ( $flags & PPFrame::NO_TEMPLATES ) {
981 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
982 } else {
983 $lineStart = $contextNode->getAttribute( 'lineStart' );
984 $params = array(
985 'title' => new PPNode_DOM( $title ),
986 'parts' => new PPNode_DOM( $parts ),
987 'lineStart' => $lineStart );
988 $ret = $this->parser->braceSubstitution( $params, $this );
989 if ( isset( $ret['object'] ) ) {
990 $newIterator = $ret['object'];
991 } else {
992 $out .= $ret['text'];
993 }
994 }
995 } elseif ( $contextNode->nodeName == 'tplarg' ) {
996 # Triple-brace expansion
997 $xpath = new DOMXPath( $contextNode->ownerDocument );
998 $titles = $xpath->query( 'title', $contextNode );
999 $title = $titles->item( 0 );
1000 $parts = $xpath->query( 'part', $contextNode );
1001 if ( $flags & PPFrame::NO_ARGS ) {
1002 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1003 } else {
1004 $params = array(
1005 'title' => new PPNode_DOM( $title ),
1006 'parts' => new PPNode_DOM( $parts ) );
1007 $ret = $this->parser->argSubstitution( $params, $this );
1008 if ( isset( $ret['object'] ) ) {
1009 $newIterator = $ret['object'];
1010 } else {
1011 $out .= $ret['text'];
1012 }
1013 }
1014 } elseif ( $contextNode->nodeName == 'comment' ) {
1015 # HTML-style comment
1016 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1017 if ( $this->parser->ot['html']
1018 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1019 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1020 {
1021 $out .= '';
1022 }
1023 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1024 # Not in RECOVER_COMMENTS mode (extractSections) though
1025 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1026 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1027 }
1028 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1029 else {
1030 $out .= $contextNode->textContent;
1031 }
1032 } elseif ( $contextNode->nodeName == 'ignore' ) {
1033 # Output suppression used by <includeonly> etc.
1034 # OT_WIKI will only respect <ignore> in substed templates.
1035 # The other output types respect it unless NO_IGNORE is set.
1036 # extractSections() sets NO_IGNORE and so never respects it.
1037 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1038 $out .= $contextNode->textContent;
1039 } else {
1040 $out .= '';
1041 }
1042 } elseif ( $contextNode->nodeName == 'ext' ) {
1043 # Extension tag
1044 $xpath = new DOMXPath( $contextNode->ownerDocument );
1045 $names = $xpath->query( 'name', $contextNode );
1046 $attrs = $xpath->query( 'attr', $contextNode );
1047 $inners = $xpath->query( 'inner', $contextNode );
1048 $closes = $xpath->query( 'close', $contextNode );
1049 $params = array(
1050 'name' => new PPNode_DOM( $names->item( 0 ) ),
1051 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1052 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1053 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1054 );
1055 $out .= $this->parser->extensionSubstitution( $params, $this );
1056 } elseif ( $contextNode->nodeName == 'h' ) {
1057 # Heading
1058 $s = $this->expand( $contextNode->childNodes, $flags );
1059
1060 # Insert a heading marker only for <h> children of <root>
1061 # This is to stop extractSections from going over multiple tree levels
1062 if ( $contextNode->parentNode->nodeName == 'root'
1063 && $this->parser->ot['html'] )
1064 {
1065 # Insert heading index marker
1066 $headingIndex = $contextNode->getAttribute( 'i' );
1067 $titleText = $this->title->getPrefixedDBkey();
1068 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1069 $serial = count( $this->parser->mHeadings ) - 1;
1070 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1071 $count = $contextNode->getAttribute( 'level' );
1072 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1073 $this->parser->mStripState->general->setPair( $marker, '' );
1074 }
1075 $out .= $s;
1076 } else {
1077 # Generic recursive expansion
1078 $newIterator = $contextNode->childNodes;
1079 }
1080 } else {
1081 wfProfileOut( __METHOD__ );
1082 throw new MWException( __METHOD__.': Invalid parameter type' );
1083 }
1084
1085 if ( $newIterator !== false ) {
1086 if ( $newIterator instanceof PPNode_DOM ) {
1087 $newIterator = $newIterator->node;
1088 }
1089 $outStack[] = '';
1090 $iteratorStack[] = $newIterator;
1091 $indexStack[] = 0;
1092 } elseif ( $iteratorStack[$level] === false ) {
1093 // Return accumulated value to parent
1094 // With tail recursion
1095 while ( $iteratorStack[$level] === false && $level > 0 ) {
1096 $outStack[$level - 1] .= $out;
1097 array_pop( $outStack );
1098 array_pop( $iteratorStack );
1099 array_pop( $indexStack );
1100 $level--;
1101 }
1102 }
1103 }
1104 --$expansionDepth;
1105 wfProfileOut( __METHOD__ );
1106 return $outStack[0];
1107 }
1108
1109 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1110 $args = array_slice( func_get_args(), 2 );
1111
1112 $first = true;
1113 $s = '';
1114 foreach ( $args as $root ) {
1115 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1116 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1117 $root = array( $root );
1118 }
1119 foreach ( $root as $node ) {
1120 if ( $first ) {
1121 $first = false;
1122 } else {
1123 $s .= $sep;
1124 }
1125 $s .= $this->expand( $node, $flags );
1126 }
1127 }
1128 return $s;
1129 }
1130
1131 /**
1132 * Implode with no flags specified
1133 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1134 */
1135 function implode( $sep /*, ... */ ) {
1136 $args = array_slice( func_get_args(), 1 );
1137
1138 $first = true;
1139 $s = '';
1140 foreach ( $args as $root ) {
1141 if ( $root instanceof PPNode_DOM ) {
1142 $root = $root->node;
1143 }
1144 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1145 $root = array( $root );
1146 }
1147 foreach ( $root as $node ) {
1148 if ( $first ) {
1149 $first = false;
1150 } else {
1151 $s .= $sep;
1152 }
1153 $s .= $this->expand( $node );
1154 }
1155 }
1156 return $s;
1157 }
1158
1159 /**
1160 * Makes an object that, when expand()ed, will be the same as one obtained
1161 * with implode()
1162 */
1163 function virtualImplode( $sep /*, ... */ ) {
1164 $args = array_slice( func_get_args(), 1 );
1165 $out = array();
1166 $first = true;
1167
1168 foreach ( $args as $root ) {
1169 if ( $root instanceof PPNode_DOM ) {
1170 $root = $root->node;
1171 }
1172 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1173 $root = array( $root );
1174 }
1175 foreach ( $root as $node ) {
1176 if ( $first ) {
1177 $first = false;
1178 } else {
1179 $out[] = $sep;
1180 }
1181 $out[] = $node;
1182 }
1183 }
1184 return $out;
1185 }
1186
1187 /**
1188 * Virtual implode with brackets
1189 */
1190 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1191 $args = array_slice( func_get_args(), 3 );
1192 $out = array( $start );
1193 $first = true;
1194
1195 foreach ( $args as $root ) {
1196 if ( $root instanceof PPNode_DOM ) {
1197 $root = $root->node;
1198 }
1199 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1200 $root = array( $root );
1201 }
1202 foreach ( $root as $node ) {
1203 if ( $first ) {
1204 $first = false;
1205 } else {
1206 $out[] = $sep;
1207 }
1208 $out[] = $node;
1209 }
1210 }
1211 $out[] = $end;
1212 return $out;
1213 }
1214
1215 function __toString() {
1216 return 'frame{}';
1217 }
1218
1219 function getPDBK( $level = false ) {
1220 if ( $level === false ) {
1221 return $this->title->getPrefixedDBkey();
1222 } else {
1223 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1224 }
1225 }
1226
1227 function getArguments() {
1228 return array();
1229 }
1230
1231 function getNumberedArguments() {
1232 return array();
1233 }
1234
1235 function getNamedArguments() {
1236 return array();
1237 }
1238
1239 /**
1240 * Returns true if there are no arguments in this frame
1241 */
1242 function isEmpty() {
1243 return true;
1244 }
1245
1246 function getArgument( $name ) {
1247 return false;
1248 }
1249
1250 /**
1251 * Returns true if the infinite loop check is OK, false if a loop is detected
1252 */
1253 function loopCheck( $title ) {
1254 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1255 }
1256
1257 /**
1258 * Return true if the frame is a template frame
1259 */
1260 function isTemplate() {
1261 return false;
1262 }
1263 }
1264
1265 /**
1266 * Expansion frame with template arguments
1267 * @ingroup Parser
1268 */
1269 class PPTemplateFrame_DOM extends PPFrame_DOM {
1270 var $numberedArgs, $namedArgs, $parent;
1271 var $numberedExpansionCache, $namedExpansionCache;
1272
1273 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1274 parent::__construct( $preprocessor );
1275
1276 $this->parent = $parent;
1277 $this->numberedArgs = $numberedArgs;
1278 $this->namedArgs = $namedArgs;
1279 $this->title = $title;
1280 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1281 $this->titleCache = $parent->titleCache;
1282 $this->titleCache[] = $pdbk;
1283 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1284 if ( $pdbk !== false ) {
1285 $this->loopCheckHash[$pdbk] = true;
1286 }
1287 $this->depth = $parent->depth + 1;
1288 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1289 }
1290
1291 function __toString() {
1292 $s = 'tplframe{';
1293 $first = true;
1294 $args = $this->numberedArgs + $this->namedArgs;
1295 foreach ( $args as $name => $value ) {
1296 if ( $first ) {
1297 $first = false;
1298 } else {
1299 $s .= ', ';
1300 }
1301 $s .= "\"$name\":\"" .
1302 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1303 }
1304 $s .= '}';
1305 return $s;
1306 }
1307 /**
1308 * Returns true if there are no arguments in this frame
1309 */
1310 function isEmpty() {
1311 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1312 }
1313
1314 function getArguments() {
1315 $arguments = array();
1316 foreach ( array_merge(
1317 array_keys($this->numberedArgs),
1318 array_keys($this->namedArgs)) as $key ) {
1319 $arguments[$key] = $this->getArgument($key);
1320 }
1321 return $arguments;
1322 }
1323
1324 function getNumberedArguments() {
1325 $arguments = array();
1326 foreach ( array_keys($this->numberedArgs) as $key ) {
1327 $arguments[$key] = $this->getArgument($key);
1328 }
1329 return $arguments;
1330 }
1331
1332 function getNamedArguments() {
1333 $arguments = array();
1334 foreach ( array_keys($this->namedArgs) as $key ) {
1335 $arguments[$key] = $this->getArgument($key);
1336 }
1337 return $arguments;
1338 }
1339
1340 function getNumberedArgument( $index ) {
1341 if ( !isset( $this->numberedArgs[$index] ) ) {
1342 return false;
1343 }
1344 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1345 # No trimming for unnamed arguments
1346 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1347 }
1348 return $this->numberedExpansionCache[$index];
1349 }
1350
1351 function getNamedArgument( $name ) {
1352 if ( !isset( $this->namedArgs[$name] ) ) {
1353 return false;
1354 }
1355 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1356 # Trim named arguments post-expand, for backwards compatibility
1357 $this->namedExpansionCache[$name] = trim(
1358 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1359 }
1360 return $this->namedExpansionCache[$name];
1361 }
1362
1363 function getArgument( $name ) {
1364 $text = $this->getNumberedArgument( $name );
1365 if ( $text === false ) {
1366 $text = $this->getNamedArgument( $name );
1367 }
1368 return $text;
1369 }
1370
1371 /**
1372 * Return true if the frame is a template frame
1373 */
1374 function isTemplate() {
1375 return true;
1376 }
1377 }
1378
1379 /**
1380 * Expansion frame with custom arguments
1381 * @ingroup Parser
1382 */
1383 class PPCustomFrame_DOM extends PPFrame_DOM {
1384 var $args;
1385
1386 function __construct( $preprocessor, $args ) {
1387 parent::__construct( $preprocessor );
1388 $this->args = $args;
1389 }
1390
1391 function __toString() {
1392 $s = 'cstmframe{';
1393 $first = true;
1394 foreach ( $this->args as $name => $value ) {
1395 if ( $first ) {
1396 $first = false;
1397 } else {
1398 $s .= ', ';
1399 }
1400 $s .= "\"$name\":\"" .
1401 str_replace( '"', '\\"', $value->__toString() ) . '"';
1402 }
1403 $s .= '}';
1404 return $s;
1405 }
1406
1407 function isEmpty() {
1408 return !count( $this->args );
1409 }
1410
1411 function getArgument( $index ) {
1412 if ( !isset( $this->args[$index] ) ) {
1413 return false;
1414 }
1415 return $this->args[$index];
1416 }
1417 }
1418
1419 /**
1420 * @ingroup Parser
1421 */
1422 class PPNode_DOM implements PPNode {
1423 var $node;
1424
1425 function __construct( $node, $xpath = false ) {
1426 $this->node = $node;
1427 }
1428
1429 function __get( $name ) {
1430 if ( $name == 'xpath' ) {
1431 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1432 }
1433 return $this->xpath;
1434 }
1435
1436 function __toString() {
1437 if ( $this->node instanceof DOMNodeList ) {
1438 $s = '';
1439 foreach ( $this->node as $node ) {
1440 $s .= $node->ownerDocument->saveXML( $node );
1441 }
1442 } else {
1443 $s = $this->node->ownerDocument->saveXML( $this->node );
1444 }
1445 return $s;
1446 }
1447
1448 function getChildren() {
1449 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1450 }
1451
1452 function getFirstChild() {
1453 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1454 }
1455
1456 function getNextSibling() {
1457 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1458 }
1459
1460 function getChildrenOfType( $type ) {
1461 return new self( $this->xpath->query( $type, $this->node ) );
1462 }
1463
1464 function getLength() {
1465 if ( $this->node instanceof DOMNodeList ) {
1466 return $this->node->length;
1467 } else {
1468 return false;
1469 }
1470 }
1471
1472 function item( $i ) {
1473 $item = $this->node->item( $i );
1474 return $item ? new self( $item ) : false;
1475 }
1476
1477 function getName() {
1478 if ( $this->node instanceof DOMNodeList ) {
1479 return '#nodelist';
1480 } else {
1481 return $this->node->nodeName;
1482 }
1483 }
1484
1485 /**
1486 * Split a <part> node into an associative array containing:
1487 * name PPNode name
1488 * index String index
1489 * value PPNode value
1490 */
1491 function splitArg() {
1492 $names = $this->xpath->query( 'name', $this->node );
1493 $values = $this->xpath->query( 'value', $this->node );
1494 if ( !$names->length || !$values->length ) {
1495 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1496 }
1497 $name = $names->item( 0 );
1498 $index = $name->getAttribute( 'index' );
1499 return array(
1500 'name' => new self( $name ),
1501 'index' => $index,
1502 'value' => new self( $values->item( 0 ) ) );
1503 }
1504
1505 /**
1506 * Split an <ext> node into an associative array containing name, attr, inner and close
1507 * All values in the resulting array are PPNodes. Inner and close are optional.
1508 */
1509 function splitExt() {
1510 $names = $this->xpath->query( 'name', $this->node );
1511 $attrs = $this->xpath->query( 'attr', $this->node );
1512 $inners = $this->xpath->query( 'inner', $this->node );
1513 $closes = $this->xpath->query( 'close', $this->node );
1514 if ( !$names->length || !$attrs->length ) {
1515 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1516 }
1517 $parts = array(
1518 'name' => new self( $names->item( 0 ) ),
1519 'attr' => new self( $attrs->item( 0 ) ) );
1520 if ( $inners->length ) {
1521 $parts['inner'] = new self( $inners->item( 0 ) );
1522 }
1523 if ( $closes->length ) {
1524 $parts['close'] = new self( $closes->item( 0 ) );
1525 }
1526 return $parts;
1527 }
1528
1529 /**
1530 * Split a <h> node
1531 */
1532 function splitHeading() {
1533 if ( !$this->nodeName == 'h' ) {
1534 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1535 }
1536 return array(
1537 'i' => $this->node->getAttribute( 'i' ),
1538 'level' => $this->node->getAttribute( 'level' ),
1539 'contents' => $this->getChildren()
1540 );
1541 }
1542 }