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