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