Fix function level comments that start with /* not /**
[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 = $wgPreprocessorCacheThreshold !== false && 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 (or the '>' if there's none)
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 $part->visualEnd = $wsStart;
348 }
349 // Else comments abutting, no change in visual end
350 $part->commentEnd = $endPos;
351 }
352 $i = $endPos + 1;
353 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
354 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
355 }
356 continue;
357 }
358 $name = $matches[1];
359 $lowerName = strtolower( $name );
360 $attrStart = $i + strlen( $name ) + 1;
361
362 // Find end of tag
363 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
364 if ( $tagEndPos === false ) {
365 // Infinite backtrack
366 // Disable tag search to prevent worst-case O(N^2) performance
367 $noMoreGT = true;
368 $accum .= '&lt;';
369 ++$i;
370 continue;
371 }
372
373 // Handle ignored tags
374 if ( in_array( $lowerName, $ignoredTags ) ) {
375 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
376 $i = $tagEndPos + 1;
377 continue;
378 }
379
380 $tagStartPos = $i;
381 if ( $text[$tagEndPos-1] == '/' ) {
382 $attrEnd = $tagEndPos - 1;
383 $inner = null;
384 $i = $tagEndPos + 1;
385 $close = '';
386 } else {
387 $attrEnd = $tagEndPos;
388 // Find closing tag
389 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
390 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
391 {
392 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
393 $i = $matches[0][1] + strlen( $matches[0][0] );
394 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
395 } else {
396 // No end tag -- let it run out to the end of the text.
397 $inner = substr( $text, $tagEndPos + 1 );
398 $i = strlen( $text );
399 $close = '';
400 }
401 }
402 // <includeonly> and <noinclude> just become <ignore> tags
403 if ( in_array( $lowerName, $ignoredElements ) ) {
404 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
405 . '</ignore>';
406 continue;
407 }
408
409 $accum .= '<ext>';
410 if ( $attrEnd <= $attrStart ) {
411 $attr = '';
412 } else {
413 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
414 }
415 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
416 // Note that the attr element contains the whitespace between name and attribute,
417 // this is necessary for precise reconstruction during pre-save transform.
418 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
419 if ( $inner !== null ) {
420 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
421 }
422 $accum .= $close . '</ext>';
423 }
424
425 elseif ( $found == 'line-start' ) {
426 // Is this the start of a heading?
427 // Line break belongs before the heading element in any case
428 if ( $fakeLineStart ) {
429 $fakeLineStart = false;
430 } else {
431 $accum .= $curChar;
432 $i++;
433 }
434
435 $count = strspn( $text, '=', $i, 6 );
436 if ( $count == 1 && $findEquals ) {
437 // DWIM: This looks kind of like a name/value separator
438 // Let's let the equals handler have it and break the potential heading
439 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
440 } elseif ( $count > 0 ) {
441 $piece = array(
442 'open' => "\n",
443 'close' => "\n",
444 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
445 'startPos' => $i,
446 'count' => $count );
447 $stack->push( $piece );
448 $accum =& $stack->getAccum();
449 $flags = $stack->getFlags();
450 extract( $flags );
451 $i += $count;
452 }
453 }
454
455 elseif ( $found == 'line-end' ) {
456 $piece = $stack->top;
457 // A heading must be open, otherwise \n wouldn't have been in the search list
458 assert( $piece->open == "\n" );
459 $part = $piece->getCurrentPart();
460 // Search back through the input to see if it has a proper close
461 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
462 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
463 $searchStart = $i - $wsLength;
464 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
465 // Comment found at line end
466 // Search for equals signs before the comment
467 $searchStart = $part->visualEnd;
468 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
469 }
470 $count = $piece->count;
471 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
472 if ( $equalsLength > 0 ) {
473 if ( $searchStart - $equalsLength == $piece->startPos ) {
474 // This is just a single string of equals signs on its own line
475 // Replicate the doHeadings behaviour /={count}(.+)={count}/
476 // First find out how many equals signs there really are (don't stop at 6)
477 $count = $equalsLength;
478 if ( $count < 3 ) {
479 $count = 0;
480 } else {
481 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
482 }
483 } else {
484 $count = min( $equalsLength, $count );
485 }
486 if ( $count > 0 ) {
487 // Normal match, output <h>
488 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
489 $headingIndex++;
490 } else {
491 // Single equals sign on its own line, count=0
492 $element = $accum;
493 }
494 } else {
495 // No match, no <h>, just pass down the inner text
496 $element = $accum;
497 }
498 // Unwind the stack
499 $stack->pop();
500 $accum =& $stack->getAccum();
501 $flags = $stack->getFlags();
502 extract( $flags );
503
504 // Append the result to the enclosing accumulator
505 $accum .= $element;
506 // Note that we do NOT increment the input pointer.
507 // This is because the closing linebreak could be the opening linebreak of
508 // another heading. Infinite loops are avoided because the next iteration MUST
509 // hit the heading open case above, which unconditionally increments the
510 // input pointer.
511 } elseif ( $found == 'open' ) {
512 # count opening brace characters
513 $count = strspn( $text, $curChar, $i );
514
515 # we need to add to stack only if opening brace count is enough for one of the rules
516 if ( $count >= $rule['min'] ) {
517 # Add it to the stack
518 $piece = array(
519 'open' => $curChar,
520 'close' => $rule['end'],
521 'count' => $count,
522 'lineStart' => ($i == 0 || $text[$i-1] == "\n"),
523 );
524
525 $stack->push( $piece );
526 $accum =& $stack->getAccum();
527 $flags = $stack->getFlags();
528 extract( $flags );
529 } else {
530 # Add literal brace(s)
531 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
532 }
533 $i += $count;
534 } elseif ( $found == 'close' ) {
535 $piece = $stack->top;
536 # lets check if there are enough characters for closing brace
537 $maxCount = $piece->count;
538 $count = strspn( $text, $curChar, $i, $maxCount );
539
540 # check for maximum matching characters (if there are 5 closing
541 # characters, we will probably need only 3 - depending on the rules)
542 $rule = $rules[$piece->open];
543 if ( $count > $rule['max'] ) {
544 # The specified maximum exists in the callback array, unless the caller
545 # has made an error
546 $matchingCount = $rule['max'];
547 } else {
548 # Count is less than the maximum
549 # Skip any gaps in the callback array to find the true largest match
550 # Need to use array_key_exists not isset because the callback can be null
551 $matchingCount = $count;
552 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
553 --$matchingCount;
554 }
555 }
556
557 if ($matchingCount <= 0) {
558 # No matching element found in callback array
559 # Output a literal closing brace and continue
560 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
561 $i += $count;
562 continue;
563 }
564 $name = $rule['names'][$matchingCount];
565 if ( $name === null ) {
566 // No element, just literal text
567 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
568 } else {
569 # Create XML element
570 # Note: $parts is already XML, does not need to be encoded further
571 $parts = $piece->parts;
572 $title = $parts[0]->out;
573 unset( $parts[0] );
574
575 # The invocation is at the start of the line if lineStart is set in
576 # the stack, and all opening brackets are used up.
577 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
578 $attr = ' lineStart="1"';
579 } else {
580 $attr = '';
581 }
582
583 $element = "<$name$attr>";
584 $element .= "<title>$title</title>";
585 $argIndex = 1;
586 foreach ( $parts as $part ) {
587 if ( isset( $part->eqpos ) ) {
588 $argName = substr( $part->out, 0, $part->eqpos );
589 $argValue = substr( $part->out, $part->eqpos + 1 );
590 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
591 } else {
592 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
593 $argIndex++;
594 }
595 }
596 $element .= "</$name>";
597 }
598
599 # Advance input pointer
600 $i += $matchingCount;
601
602 # Unwind the stack
603 $stack->pop();
604 $accum =& $stack->getAccum();
605
606 # Re-add the old stack element if it still has unmatched opening characters remaining
607 if ($matchingCount < $piece->count) {
608 $piece->parts = array( new PPDPart );
609 $piece->count -= $matchingCount;
610 # do we still qualify for any callback with remaining count?
611 $names = $rules[$piece->open]['names'];
612 $skippedBraces = 0;
613 $enclosingAccum =& $accum;
614 while ( $piece->count ) {
615 if ( array_key_exists( $piece->count, $names ) ) {
616 $stack->push( $piece );
617 $accum =& $stack->getAccum();
618 break;
619 }
620 --$piece->count;
621 $skippedBraces ++;
622 }
623 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
624 }
625 $flags = $stack->getFlags();
626 extract( $flags );
627
628 # Add XML element to the enclosing accumulator
629 $accum .= $element;
630 }
631
632 elseif ( $found == 'pipe' ) {
633 $findEquals = true; // shortcut for getFlags()
634 $stack->addPart();
635 $accum =& $stack->getAccum();
636 ++$i;
637 }
638
639 elseif ( $found == 'equals' ) {
640 $findEquals = false; // shortcut for getFlags()
641 $stack->getCurrentPart()->eqpos = strlen( $accum );
642 $accum .= '=';
643 ++$i;
644 }
645 }
646
647 # Output any remaining unclosed brackets
648 foreach ( $stack->stack as $piece ) {
649 $stack->rootAccum .= $piece->breakSyntax();
650 }
651 $stack->rootAccum .= '</root>';
652 $xml = $stack->rootAccum;
653
654 wfProfileOut( __METHOD__ );
655
656 return $xml;
657 }
658 }
659
660 /**
661 * Stack class to help Preprocessor::preprocessToObj()
662 * @ingroup Parser
663 */
664 class PPDStack {
665 var $stack, $rootAccum, $top;
666 var $out;
667 var $elementClass = 'PPDStackElement';
668
669 static $false = false;
670
671 function __construct() {
672 $this->stack = array();
673 $this->top = false;
674 $this->rootAccum = '';
675 $this->accum =& $this->rootAccum;
676 }
677
678 function count() {
679 return count( $this->stack );
680 }
681
682 function &getAccum() {
683 return $this->accum;
684 }
685
686 function getCurrentPart() {
687 if ( $this->top === false ) {
688 return false;
689 } else {
690 return $this->top->getCurrentPart();
691 }
692 }
693
694 function push( $data ) {
695 if ( $data instanceof $this->elementClass ) {
696 $this->stack[] = $data;
697 } else {
698 $class = $this->elementClass;
699 $this->stack[] = new $class( $data );
700 }
701 $this->top = $this->stack[ count( $this->stack ) - 1 ];
702 $this->accum =& $this->top->getAccum();
703 }
704
705 function pop() {
706 if ( !count( $this->stack ) ) {
707 throw new MWException( __METHOD__.': no elements remaining' );
708 }
709 $temp = array_pop( $this->stack );
710
711 if ( count( $this->stack ) ) {
712 $this->top = $this->stack[ count( $this->stack ) - 1 ];
713 $this->accum =& $this->top->getAccum();
714 } else {
715 $this->top = self::$false;
716 $this->accum =& $this->rootAccum;
717 }
718 return $temp;
719 }
720
721 function addPart( $s = '' ) {
722 $this->top->addPart( $s );
723 $this->accum =& $this->top->getAccum();
724 }
725
726 function getFlags() {
727 if ( !count( $this->stack ) ) {
728 return array(
729 'findEquals' => false,
730 'findPipe' => false,
731 'inHeading' => false,
732 );
733 } else {
734 return $this->top->getFlags();
735 }
736 }
737 }
738
739 /**
740 * @ingroup Parser
741 */
742 class PPDStackElement {
743 var $open, // Opening character (\n for heading)
744 $close, // Matching closing character
745 $count, // Number of opening characters found (number of "=" for heading)
746 $parts, // Array of PPDPart objects describing pipe-separated parts.
747 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
748
749 var $partClass = 'PPDPart';
750
751 function __construct( $data = array() ) {
752 $class = $this->partClass;
753 $this->parts = array( new $class );
754
755 foreach ( $data as $name => $value ) {
756 $this->$name = $value;
757 }
758 }
759
760 function &getAccum() {
761 return $this->parts[count($this->parts) - 1]->out;
762 }
763
764 function addPart( $s = '' ) {
765 $class = $this->partClass;
766 $this->parts[] = new $class( $s );
767 }
768
769 function getCurrentPart() {
770 return $this->parts[count($this->parts) - 1];
771 }
772
773 function getFlags() {
774 $partCount = count( $this->parts );
775 $findPipe = $this->open != "\n" && $this->open != '[';
776 return array(
777 'findPipe' => $findPipe,
778 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
779 'inHeading' => $this->open == "\n",
780 );
781 }
782
783 /**
784 * Get the output string that would result if the close is not found.
785 */
786 function breakSyntax( $openingCount = false ) {
787 if ( $this->open == "\n" ) {
788 $s = $this->parts[0]->out;
789 } else {
790 if ( $openingCount === false ) {
791 $openingCount = $this->count;
792 }
793 $s = str_repeat( $this->open, $openingCount );
794 $first = true;
795 foreach ( $this->parts as $part ) {
796 if ( $first ) {
797 $first = false;
798 } else {
799 $s .= '|';
800 }
801 $s .= $part->out;
802 }
803 }
804 return $s;
805 }
806 }
807
808 /**
809 * @ingroup Parser
810 */
811 class PPDPart {
812 var $out; // Output accumulator string
813
814 // Optional member variables:
815 // eqpos Position of equals sign in output accumulator
816 // commentEnd Past-the-end input pointer for the last comment encountered
817 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
818
819 function __construct( $out = '' ) {
820 $this->out = $out;
821 }
822 }
823
824 /**
825 * An expansion frame, used as a context to expand the result of preprocessToObj()
826 * @ingroup Parser
827 */
828 class PPFrame_DOM implements PPFrame {
829 var $preprocessor, $parser, $title;
830 var $titleCache;
831
832 /**
833 * Hashtable listing templates which are disallowed for expansion in this frame,
834 * having been encountered previously in parent frames.
835 */
836 var $loopCheckHash;
837
838 /**
839 * Recursion depth of this frame, top = 0
840 * Note that this is NOT the same as expansion depth in expand()
841 */
842 var $depth;
843
844
845 /**
846 * Construct a new preprocessor frame.
847 * @param $preprocessor Preprocessor: The parent preprocessor
848 */
849 function __construct( $preprocessor ) {
850 $this->preprocessor = $preprocessor;
851 $this->parser = $preprocessor->parser;
852 $this->title = $this->parser->mTitle;
853 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
854 $this->loopCheckHash = array();
855 $this->depth = 0;
856 }
857
858 /**
859 * Create a new child frame
860 * $args is optionally a multi-root PPNode or array containing the template arguments
861 */
862 function newChild( $args = false, $title = false ) {
863 $namedArgs = array();
864 $numberedArgs = array();
865 if ( $title === false ) {
866 $title = $this->title;
867 }
868 if ( $args !== false ) {
869 $xpath = false;
870 if ( $args instanceof PPNode ) {
871 $args = $args->node;
872 }
873 foreach ( $args as $arg ) {
874 if ( !$xpath ) {
875 $xpath = new DOMXPath( $arg->ownerDocument );
876 }
877
878 $nameNodes = $xpath->query( 'name', $arg );
879 $value = $xpath->query( 'value', $arg );
880 if ( $nameNodes->item( 0 )->hasAttributes() ) {
881 // Numbered parameter
882 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
883 $numberedArgs[$index] = $value->item( 0 );
884 unset( $namedArgs[$index] );
885 } else {
886 // Named parameter
887 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
888 $namedArgs[$name] = $value->item( 0 );
889 unset( $numberedArgs[$name] );
890 }
891 }
892 }
893 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
894 }
895
896 function expand( $root, $flags = 0 ) {
897 static $expansionDepth = 0;
898 if ( is_string( $root ) ) {
899 return $root;
900 }
901
902 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() )
903 {
904 return '<span class="error">Node-count limit exceeded</span>';
905 }
906
907 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
908 return '<span class="error">Expansion depth limit exceeded</span>';
909 }
910 wfProfileIn( __METHOD__ );
911 ++$expansionDepth;
912
913 if ( $root instanceof PPNode_DOM ) {
914 $root = $root->node;
915 }
916 if ( $root instanceof DOMDocument ) {
917 $root = $root->documentElement;
918 }
919
920 $outStack = array( '', '' );
921 $iteratorStack = array( false, $root );
922 $indexStack = array( 0, 0 );
923
924 while ( count( $iteratorStack ) > 1 ) {
925 $level = count( $outStack ) - 1;
926 $iteratorNode =& $iteratorStack[ $level ];
927 $out =& $outStack[$level];
928 $index =& $indexStack[$level];
929
930 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
931
932 if ( is_array( $iteratorNode ) ) {
933 if ( $index >= count( $iteratorNode ) ) {
934 // All done with this iterator
935 $iteratorStack[$level] = false;
936 $contextNode = false;
937 } else {
938 $contextNode = $iteratorNode[$index];
939 $index++;
940 }
941 } elseif ( $iteratorNode instanceof DOMNodeList ) {
942 if ( $index >= $iteratorNode->length ) {
943 // All done with this iterator
944 $iteratorStack[$level] = false;
945 $contextNode = false;
946 } else {
947 $contextNode = $iteratorNode->item( $index );
948 $index++;
949 }
950 } else {
951 // Copy to $contextNode and then delete from iterator stack,
952 // because this is not an iterator but we do have to execute it once
953 $contextNode = $iteratorStack[$level];
954 $iteratorStack[$level] = false;
955 }
956
957 if ( $contextNode instanceof PPNode_DOM ) {
958 $contextNode = $contextNode->node;
959 }
960
961 $newIterator = false;
962
963 if ( $contextNode === false ) {
964 // nothing to do
965 } elseif ( is_string( $contextNode ) ) {
966 $out .= $contextNode;
967 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
968 $newIterator = $contextNode;
969 } elseif ( $contextNode instanceof DOMNode ) {
970 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
971 $out .= $contextNode->nodeValue;
972 } elseif ( $contextNode->nodeName == 'template' ) {
973 # Double-brace expansion
974 $xpath = new DOMXPath( $contextNode->ownerDocument );
975 $titles = $xpath->query( 'title', $contextNode );
976 $title = $titles->item( 0 );
977 $parts = $xpath->query( 'part', $contextNode );
978 if ( $flags & PPFrame::NO_TEMPLATES ) {
979 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
980 } else {
981 $lineStart = $contextNode->getAttribute( 'lineStart' );
982 $params = array(
983 'title' => new PPNode_DOM( $title ),
984 'parts' => new PPNode_DOM( $parts ),
985 'lineStart' => $lineStart );
986 $ret = $this->parser->braceSubstitution( $params, $this );
987 if ( isset( $ret['object'] ) ) {
988 $newIterator = $ret['object'];
989 } else {
990 $out .= $ret['text'];
991 }
992 }
993 } elseif ( $contextNode->nodeName == 'tplarg' ) {
994 # Triple-brace expansion
995 $xpath = new DOMXPath( $contextNode->ownerDocument );
996 $titles = $xpath->query( 'title', $contextNode );
997 $title = $titles->item( 0 );
998 $parts = $xpath->query( 'part', $contextNode );
999 if ( $flags & PPFrame::NO_ARGS ) {
1000 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1001 } else {
1002 $params = array(
1003 'title' => new PPNode_DOM( $title ),
1004 'parts' => new PPNode_DOM( $parts ) );
1005 $ret = $this->parser->argSubstitution( $params, $this );
1006 if ( isset( $ret['object'] ) ) {
1007 $newIterator = $ret['object'];
1008 } else {
1009 $out .= $ret['text'];
1010 }
1011 }
1012 } elseif ( $contextNode->nodeName == 'comment' ) {
1013 # HTML-style comment
1014 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1015 if ( $this->parser->ot['html']
1016 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1017 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1018 {
1019 $out .= '';
1020 }
1021 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1022 # Not in RECOVER_COMMENTS mode (extractSections) though
1023 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1024 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1025 }
1026 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1027 else {
1028 $out .= $contextNode->textContent;
1029 }
1030 } elseif ( $contextNode->nodeName == 'ignore' ) {
1031 # Output suppression used by <includeonly> etc.
1032 # OT_WIKI will only respect <ignore> in substed templates.
1033 # The other output types respect it unless NO_IGNORE is set.
1034 # extractSections() sets NO_IGNORE and so never respects it.
1035 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1036 $out .= $contextNode->textContent;
1037 } else {
1038 $out .= '';
1039 }
1040 } elseif ( $contextNode->nodeName == 'ext' ) {
1041 # Extension tag
1042 $xpath = new DOMXPath( $contextNode->ownerDocument );
1043 $names = $xpath->query( 'name', $contextNode );
1044 $attrs = $xpath->query( 'attr', $contextNode );
1045 $inners = $xpath->query( 'inner', $contextNode );
1046 $closes = $xpath->query( 'close', $contextNode );
1047 $params = array(
1048 'name' => new PPNode_DOM( $names->item( 0 ) ),
1049 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1050 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1051 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1052 );
1053 $out .= $this->parser->extensionSubstitution( $params, $this );
1054 } elseif ( $contextNode->nodeName == 'h' ) {
1055 # Heading
1056 $s = $this->expand( $contextNode->childNodes, $flags );
1057
1058 # Insert a heading marker only for <h> children of <root>
1059 # This is to stop extractSections from going over multiple tree levels
1060 if ( $contextNode->parentNode->nodeName == 'root'
1061 && $this->parser->ot['html'] )
1062 {
1063 # Insert heading index marker
1064 $headingIndex = $contextNode->getAttribute( 'i' );
1065 $titleText = $this->title->getPrefixedDBkey();
1066 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1067 $serial = count( $this->parser->mHeadings ) - 1;
1068 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1069 $count = $contextNode->getAttribute( 'level' );
1070 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1071 $this->parser->mStripState->addGeneral( $marker, '' );
1072 }
1073 $out .= $s;
1074 } else {
1075 # Generic recursive expansion
1076 $newIterator = $contextNode->childNodes;
1077 }
1078 } else {
1079 wfProfileOut( __METHOD__ );
1080 throw new MWException( __METHOD__.': Invalid parameter type' );
1081 }
1082
1083 if ( $newIterator !== false ) {
1084 if ( $newIterator instanceof PPNode_DOM ) {
1085 $newIterator = $newIterator->node;
1086 }
1087 $outStack[] = '';
1088 $iteratorStack[] = $newIterator;
1089 $indexStack[] = 0;
1090 } elseif ( $iteratorStack[$level] === false ) {
1091 // Return accumulated value to parent
1092 // With tail recursion
1093 while ( $iteratorStack[$level] === false && $level > 0 ) {
1094 $outStack[$level - 1] .= $out;
1095 array_pop( $outStack );
1096 array_pop( $iteratorStack );
1097 array_pop( $indexStack );
1098 $level--;
1099 }
1100 }
1101 }
1102 --$expansionDepth;
1103 wfProfileOut( __METHOD__ );
1104 return $outStack[0];
1105 }
1106
1107 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1108 $args = array_slice( func_get_args(), 2 );
1109
1110 $first = true;
1111 $s = '';
1112 foreach ( $args as $root ) {
1113 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1114 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1115 $root = array( $root );
1116 }
1117 foreach ( $root as $node ) {
1118 if ( $first ) {
1119 $first = false;
1120 } else {
1121 $s .= $sep;
1122 }
1123 $s .= $this->expand( $node, $flags );
1124 }
1125 }
1126 return $s;
1127 }
1128
1129 /**
1130 * Implode with no flags specified
1131 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1132 */
1133 function implode( $sep /*, ... */ ) {
1134 $args = array_slice( func_get_args(), 1 );
1135
1136 $first = true;
1137 $s = '';
1138 foreach ( $args as $root ) {
1139 if ( $root instanceof PPNode_DOM ) {
1140 $root = $root->node;
1141 }
1142 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1143 $root = array( $root );
1144 }
1145 foreach ( $root as $node ) {
1146 if ( $first ) {
1147 $first = false;
1148 } else {
1149 $s .= $sep;
1150 }
1151 $s .= $this->expand( $node );
1152 }
1153 }
1154 return $s;
1155 }
1156
1157 /**
1158 * Makes an object that, when expand()ed, will be the same as one obtained
1159 * with implode()
1160 */
1161 function virtualImplode( $sep /*, ... */ ) {
1162 $args = array_slice( func_get_args(), 1 );
1163 $out = array();
1164 $first = true;
1165
1166 foreach ( $args as $root ) {
1167 if ( $root instanceof PPNode_DOM ) {
1168 $root = $root->node;
1169 }
1170 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1171 $root = array( $root );
1172 }
1173 foreach ( $root as $node ) {
1174 if ( $first ) {
1175 $first = false;
1176 } else {
1177 $out[] = $sep;
1178 }
1179 $out[] = $node;
1180 }
1181 }
1182 return $out;
1183 }
1184
1185 /**
1186 * Virtual implode with brackets
1187 */
1188 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1189 $args = array_slice( func_get_args(), 3 );
1190 $out = array( $start );
1191 $first = true;
1192
1193 foreach ( $args as $root ) {
1194 if ( $root instanceof PPNode_DOM ) {
1195 $root = $root->node;
1196 }
1197 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1198 $root = array( $root );
1199 }
1200 foreach ( $root as $node ) {
1201 if ( $first ) {
1202 $first = false;
1203 } else {
1204 $out[] = $sep;
1205 }
1206 $out[] = $node;
1207 }
1208 }
1209 $out[] = $end;
1210 return $out;
1211 }
1212
1213 function __toString() {
1214 return 'frame{}';
1215 }
1216
1217 function getPDBK( $level = false ) {
1218 if ( $level === false ) {
1219 return $this->title->getPrefixedDBkey();
1220 } else {
1221 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1222 }
1223 }
1224
1225 function getArguments() {
1226 return array();
1227 }
1228
1229 function getNumberedArguments() {
1230 return array();
1231 }
1232
1233 function getNamedArguments() {
1234 return array();
1235 }
1236
1237 /**
1238 * Returns true if there are no arguments in this frame
1239 */
1240 function isEmpty() {
1241 return true;
1242 }
1243
1244 function getArgument( $name ) {
1245 return false;
1246 }
1247
1248 /**
1249 * Returns true if the infinite loop check is OK, false if a loop is detected
1250 */
1251 function loopCheck( $title ) {
1252 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1253 }
1254
1255 /**
1256 * Return true if the frame is a template frame
1257 */
1258 function isTemplate() {
1259 return false;
1260 }
1261 }
1262
1263 /**
1264 * Expansion frame with template arguments
1265 * @ingroup Parser
1266 */
1267 class PPTemplateFrame_DOM extends PPFrame_DOM {
1268 var $numberedArgs, $namedArgs, $parent;
1269 var $numberedExpansionCache, $namedExpansionCache;
1270
1271 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1272 parent::__construct( $preprocessor );
1273
1274 $this->parent = $parent;
1275 $this->numberedArgs = $numberedArgs;
1276 $this->namedArgs = $namedArgs;
1277 $this->title = $title;
1278 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1279 $this->titleCache = $parent->titleCache;
1280 $this->titleCache[] = $pdbk;
1281 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1282 if ( $pdbk !== false ) {
1283 $this->loopCheckHash[$pdbk] = true;
1284 }
1285 $this->depth = $parent->depth + 1;
1286 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1287 }
1288
1289 function __toString() {
1290 $s = 'tplframe{';
1291 $first = true;
1292 $args = $this->numberedArgs + $this->namedArgs;
1293 foreach ( $args as $name => $value ) {
1294 if ( $first ) {
1295 $first = false;
1296 } else {
1297 $s .= ', ';
1298 }
1299 $s .= "\"$name\":\"" .
1300 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1301 }
1302 $s .= '}';
1303 return $s;
1304 }
1305 /**
1306 * Returns true if there are no arguments in this frame
1307 */
1308 function isEmpty() {
1309 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1310 }
1311
1312 function getArguments() {
1313 $arguments = array();
1314 foreach ( array_merge(
1315 array_keys($this->numberedArgs),
1316 array_keys($this->namedArgs)) as $key ) {
1317 $arguments[$key] = $this->getArgument($key);
1318 }
1319 return $arguments;
1320 }
1321
1322 function getNumberedArguments() {
1323 $arguments = array();
1324 foreach ( array_keys($this->numberedArgs) as $key ) {
1325 $arguments[$key] = $this->getArgument($key);
1326 }
1327 return $arguments;
1328 }
1329
1330 function getNamedArguments() {
1331 $arguments = array();
1332 foreach ( array_keys($this->namedArgs) as $key ) {
1333 $arguments[$key] = $this->getArgument($key);
1334 }
1335 return $arguments;
1336 }
1337
1338 function getNumberedArgument( $index ) {
1339 if ( !isset( $this->numberedArgs[$index] ) ) {
1340 return false;
1341 }
1342 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1343 # No trimming for unnamed arguments
1344 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1345 }
1346 return $this->numberedExpansionCache[$index];
1347 }
1348
1349 function getNamedArgument( $name ) {
1350 if ( !isset( $this->namedArgs[$name] ) ) {
1351 return false;
1352 }
1353 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1354 # Trim named arguments post-expand, for backwards compatibility
1355 $this->namedExpansionCache[$name] = trim(
1356 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1357 }
1358 return $this->namedExpansionCache[$name];
1359 }
1360
1361 function getArgument( $name ) {
1362 $text = $this->getNumberedArgument( $name );
1363 if ( $text === false ) {
1364 $text = $this->getNamedArgument( $name );
1365 }
1366 return $text;
1367 }
1368
1369 /**
1370 * Return true if the frame is a template frame
1371 */
1372 function isTemplate() {
1373 return true;
1374 }
1375 }
1376
1377 /**
1378 * Expansion frame with custom arguments
1379 * @ingroup Parser
1380 */
1381 class PPCustomFrame_DOM extends PPFrame_DOM {
1382 var $args;
1383
1384 function __construct( $preprocessor, $args ) {
1385 parent::__construct( $preprocessor );
1386 $this->args = $args;
1387 }
1388
1389 function __toString() {
1390 $s = 'cstmframe{';
1391 $first = true;
1392 foreach ( $this->args as $name => $value ) {
1393 if ( $first ) {
1394 $first = false;
1395 } else {
1396 $s .= ', ';
1397 }
1398 $s .= "\"$name\":\"" .
1399 str_replace( '"', '\\"', $value->__toString() ) . '"';
1400 }
1401 $s .= '}';
1402 return $s;
1403 }
1404
1405 function isEmpty() {
1406 return !count( $this->args );
1407 }
1408
1409 function getArgument( $index ) {
1410 if ( !isset( $this->args[$index] ) ) {
1411 return false;
1412 }
1413 return $this->args[$index];
1414 }
1415 }
1416
1417 /**
1418 * @ingroup Parser
1419 */
1420 class PPNode_DOM implements PPNode {
1421 var $node, $xpath;
1422
1423 function __construct( $node, $xpath = false ) {
1424 $this->node = $node;
1425 }
1426
1427 function getXPath() {
1428 if ( $this->xpath === null ) {
1429 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1430 }
1431 return $this->xpath;
1432 }
1433
1434 function __toString() {
1435 if ( $this->node instanceof DOMNodeList ) {
1436 $s = '';
1437 foreach ( $this->node as $node ) {
1438 $s .= $node->ownerDocument->saveXML( $node );
1439 }
1440 } else {
1441 $s = $this->node->ownerDocument->saveXML( $this->node );
1442 }
1443 return $s;
1444 }
1445
1446 function getChildren() {
1447 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1448 }
1449
1450 function getFirstChild() {
1451 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1452 }
1453
1454 function getNextSibling() {
1455 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1456 }
1457
1458 function getChildrenOfType( $type ) {
1459 return new self( $this->getXPath()->query( $type, $this->node ) );
1460 }
1461
1462 function getLength() {
1463 if ( $this->node instanceof DOMNodeList ) {
1464 return $this->node->length;
1465 } else {
1466 return false;
1467 }
1468 }
1469
1470 function item( $i ) {
1471 $item = $this->node->item( $i );
1472 return $item ? new self( $item ) : false;
1473 }
1474
1475 function getName() {
1476 if ( $this->node instanceof DOMNodeList ) {
1477 return '#nodelist';
1478 } else {
1479 return $this->node->nodeName;
1480 }
1481 }
1482
1483 /**
1484 * Split a <part> node into an associative array containing:
1485 * name PPNode name
1486 * index String index
1487 * value PPNode value
1488 */
1489 function splitArg() {
1490 $xpath = $this->getXPath();
1491 $names = $xpath->query( 'name', $this->node );
1492 $values = $xpath->query( 'value', $this->node );
1493 if ( !$names->length || !$values->length ) {
1494 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1495 }
1496 $name = $names->item( 0 );
1497 $index = $name->getAttribute( 'index' );
1498 return array(
1499 'name' => new self( $name ),
1500 'index' => $index,
1501 'value' => new self( $values->item( 0 ) ) );
1502 }
1503
1504 /**
1505 * Split an <ext> node into an associative array containing name, attr, inner and close
1506 * All values in the resulting array are PPNodes. Inner and close are optional.
1507 */
1508 function splitExt() {
1509 $xpath = $this->getXPath();
1510 $names = $xpath->query( 'name', $this->node );
1511 $attrs = $xpath->query( 'attr', $this->node );
1512 $inners = $xpath->query( 'inner', $this->node );
1513 $closes = $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->getName() !== '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 }