Remove some more unused variables
[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
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 }
626 $flags = $stack->getFlags();
627 extract( $flags );
628
629 # Add XML element to the enclosing accumulator
630 $accum .= $element;
631 }
632
633 elseif ( $found == 'pipe' ) {
634 $findEquals = true; // shortcut for getFlags()
635 $stack->addPart();
636 $accum =& $stack->getAccum();
637 ++$i;
638 }
639
640 elseif ( $found == 'equals' ) {
641 $findEquals = false; // shortcut for getFlags()
642 $stack->getCurrentPart()->eqpos = strlen( $accum );
643 $accum .= '=';
644 ++$i;
645 }
646 }
647
648 # Output any remaining unclosed brackets
649 foreach ( $stack->stack as $piece ) {
650 $stack->rootAccum .= $piece->breakSyntax();
651 }
652 $stack->rootAccum .= '</root>';
653 $xml = $stack->rootAccum;
654
655 wfProfileOut( __METHOD__ );
656
657 return $xml;
658 }
659 }
660
661 /**
662 * Stack class to help Preprocessor::preprocessToObj()
663 * @ingroup Parser
664 */
665 class PPDStack {
666 var $stack, $rootAccum, $top;
667 var $out;
668 var $elementClass = 'PPDStackElement';
669
670 static $false = false;
671
672 function __construct() {
673 $this->stack = array();
674 $this->top = false;
675 $this->rootAccum = '';
676 $this->accum =& $this->rootAccum;
677 }
678
679 function count() {
680 return count( $this->stack );
681 }
682
683 function &getAccum() {
684 return $this->accum;
685 }
686
687 function getCurrentPart() {
688 if ( $this->top === false ) {
689 return false;
690 } else {
691 return $this->top->getCurrentPart();
692 }
693 }
694
695 function push( $data ) {
696 if ( $data instanceof $this->elementClass ) {
697 $this->stack[] = $data;
698 } else {
699 $class = $this->elementClass;
700 $this->stack[] = new $class( $data );
701 }
702 $this->top = $this->stack[ count( $this->stack ) - 1 ];
703 $this->accum =& $this->top->getAccum();
704 }
705
706 function pop() {
707 if ( !count( $this->stack ) ) {
708 throw new MWException( __METHOD__.': no elements remaining' );
709 }
710 $temp = array_pop( $this->stack );
711
712 if ( count( $this->stack ) ) {
713 $this->top = $this->stack[ count( $this->stack ) - 1 ];
714 $this->accum =& $this->top->getAccum();
715 } else {
716 $this->top = self::$false;
717 $this->accum =& $this->rootAccum;
718 }
719 return $temp;
720 }
721
722 function addPart( $s = '' ) {
723 $this->top->addPart( $s );
724 $this->accum =& $this->top->getAccum();
725 }
726
727 function getFlags() {
728 if ( !count( $this->stack ) ) {
729 return array(
730 'findEquals' => false,
731 'findPipe' => false,
732 'inHeading' => false,
733 );
734 } else {
735 return $this->top->getFlags();
736 }
737 }
738 }
739
740 /**
741 * @ingroup Parser
742 */
743 class PPDStackElement {
744 var $open, // Opening character (\n for heading)
745 $close, // Matching closing character
746 $count, // Number of opening characters found (number of "=" for heading)
747 $parts, // Array of PPDPart objects describing pipe-separated parts.
748 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
749
750 var $partClass = 'PPDPart';
751
752 function __construct( $data = array() ) {
753 $class = $this->partClass;
754 $this->parts = array( new $class );
755
756 foreach ( $data as $name => $value ) {
757 $this->$name = $value;
758 }
759 }
760
761 function &getAccum() {
762 return $this->parts[count($this->parts) - 1]->out;
763 }
764
765 function addPart( $s = '' ) {
766 $class = $this->partClass;
767 $this->parts[] = new $class( $s );
768 }
769
770 function getCurrentPart() {
771 return $this->parts[count($this->parts) - 1];
772 }
773
774 function getFlags() {
775 $partCount = count( $this->parts );
776 $findPipe = $this->open != "\n" && $this->open != '[';
777 return array(
778 'findPipe' => $findPipe,
779 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
780 'inHeading' => $this->open == "\n",
781 );
782 }
783
784 /**
785 * Get the output string that would result if the close is not found.
786 */
787 function breakSyntax( $openingCount = false ) {
788 if ( $this->open == "\n" ) {
789 $s = $this->parts[0]->out;
790 } else {
791 if ( $openingCount === false ) {
792 $openingCount = $this->count;
793 }
794 $s = str_repeat( $this->open, $openingCount );
795 $first = true;
796 foreach ( $this->parts as $part ) {
797 if ( $first ) {
798 $first = false;
799 } else {
800 $s .= '|';
801 }
802 $s .= $part->out;
803 }
804 }
805 return $s;
806 }
807 }
808
809 /**
810 * @ingroup Parser
811 */
812 class PPDPart {
813 var $out; // Output accumulator string
814
815 // Optional member variables:
816 // eqpos Position of equals sign in output accumulator
817 // commentEnd Past-the-end input pointer for the last comment encountered
818 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
819
820 function __construct( $out = '' ) {
821 $this->out = $out;
822 }
823 }
824
825 /**
826 * An expansion frame, used as a context to expand the result of preprocessToObj()
827 * @ingroup Parser
828 */
829 class PPFrame_DOM implements PPFrame {
830 var $preprocessor, $parser, $title;
831 var $titleCache;
832
833 /**
834 * Hashtable listing templates which are disallowed for expansion in this frame,
835 * having been encountered previously in parent frames.
836 */
837 var $loopCheckHash;
838
839 /**
840 * Recursion depth of this frame, top = 0
841 * Note that this is NOT the same as expansion depth in expand()
842 */
843 var $depth;
844
845
846 /**
847 * Construct a new preprocessor frame.
848 * @param $preprocessor Preprocessor: The parent preprocessor
849 */
850 function __construct( $preprocessor ) {
851 $this->preprocessor = $preprocessor;
852 $this->parser = $preprocessor->parser;
853 $this->title = $this->parser->mTitle;
854 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
855 $this->loopCheckHash = array();
856 $this->depth = 0;
857 }
858
859 /**
860 * Create a new child frame
861 * $args is optionally a multi-root PPNode or array containing the template arguments
862 */
863 function newChild( $args = false, $title = false ) {
864 $namedArgs = array();
865 $numberedArgs = array();
866 if ( $title === false ) {
867 $title = $this->title;
868 }
869 if ( $args !== false ) {
870 $xpath = false;
871 if ( $args instanceof PPNode ) {
872 $args = $args->node;
873 }
874 foreach ( $args as $arg ) {
875 if ( !$xpath ) {
876 $xpath = new DOMXPath( $arg->ownerDocument );
877 }
878
879 $nameNodes = $xpath->query( 'name', $arg );
880 $value = $xpath->query( 'value', $arg );
881 if ( $nameNodes->item( 0 )->hasAttributes() ) {
882 // Numbered parameter
883 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
884 $numberedArgs[$index] = $value->item( 0 );
885 unset( $namedArgs[$index] );
886 } else {
887 // Named parameter
888 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
889 $namedArgs[$name] = $value->item( 0 );
890 unset( $numberedArgs[$name] );
891 }
892 }
893 }
894 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
895 }
896
897 function expand( $root, $flags = 0 ) {
898 static $expansionDepth = 0;
899 if ( is_string( $root ) ) {
900 return $root;
901 }
902
903 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() )
904 {
905 return '<span class="error">Node-count limit exceeded</span>';
906 }
907
908 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
909 return '<span class="error">Expansion depth limit exceeded</span>';
910 }
911 wfProfileIn( __METHOD__ );
912 ++$expansionDepth;
913
914 if ( $root instanceof PPNode_DOM ) {
915 $root = $root->node;
916 }
917 if ( $root instanceof DOMDocument ) {
918 $root = $root->documentElement;
919 }
920
921 $outStack = array( '', '' );
922 $iteratorStack = array( false, $root );
923 $indexStack = array( 0, 0 );
924
925 while ( count( $iteratorStack ) > 1 ) {
926 $level = count( $outStack ) - 1;
927 $iteratorNode =& $iteratorStack[ $level ];
928 $out =& $outStack[$level];
929 $index =& $indexStack[$level];
930
931 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
932
933 if ( is_array( $iteratorNode ) ) {
934 if ( $index >= count( $iteratorNode ) ) {
935 // All done with this iterator
936 $iteratorStack[$level] = false;
937 $contextNode = false;
938 } else {
939 $contextNode = $iteratorNode[$index];
940 $index++;
941 }
942 } elseif ( $iteratorNode instanceof DOMNodeList ) {
943 if ( $index >= $iteratorNode->length ) {
944 // All done with this iterator
945 $iteratorStack[$level] = false;
946 $contextNode = false;
947 } else {
948 $contextNode = $iteratorNode->item( $index );
949 $index++;
950 }
951 } else {
952 // Copy to $contextNode and then delete from iterator stack,
953 // because this is not an iterator but we do have to execute it once
954 $contextNode = $iteratorStack[$level];
955 $iteratorStack[$level] = false;
956 }
957
958 if ( $contextNode instanceof PPNode_DOM ) $contextNode = $contextNode->node;
959
960 $newIterator = false;
961
962 if ( $contextNode === false ) {
963 // nothing to do
964 } elseif ( is_string( $contextNode ) ) {
965 $out .= $contextNode;
966 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
967 $newIterator = $contextNode;
968 } elseif ( $contextNode instanceof DOMNode ) {
969 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
970 $out .= $contextNode->nodeValue;
971 } elseif ( $contextNode->nodeName == 'template' ) {
972 # Double-brace expansion
973 $xpath = new DOMXPath( $contextNode->ownerDocument );
974 $titles = $xpath->query( 'title', $contextNode );
975 $title = $titles->item( 0 );
976 $parts = $xpath->query( 'part', $contextNode );
977 if ( $flags & PPFrame::NO_TEMPLATES ) {
978 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
979 } else {
980 $lineStart = $contextNode->getAttribute( 'lineStart' );
981 $params = array(
982 'title' => new PPNode_DOM( $title ),
983 'parts' => new PPNode_DOM( $parts ),
984 'lineStart' => $lineStart );
985 $ret = $this->parser->braceSubstitution( $params, $this );
986 if ( isset( $ret['object'] ) ) {
987 $newIterator = $ret['object'];
988 } else {
989 $out .= $ret['text'];
990 }
991 }
992 } elseif ( $contextNode->nodeName == 'tplarg' ) {
993 # Triple-brace expansion
994 $xpath = new DOMXPath( $contextNode->ownerDocument );
995 $titles = $xpath->query( 'title', $contextNode );
996 $title = $titles->item( 0 );
997 $parts = $xpath->query( 'part', $contextNode );
998 if ( $flags & PPFrame::NO_ARGS ) {
999 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1000 } else {
1001 $params = array(
1002 'title' => new PPNode_DOM( $title ),
1003 'parts' => new PPNode_DOM( $parts ) );
1004 $ret = $this->parser->argSubstitution( $params, $this );
1005 if ( isset( $ret['object'] ) ) {
1006 $newIterator = $ret['object'];
1007 } else {
1008 $out .= $ret['text'];
1009 }
1010 }
1011 } elseif ( $contextNode->nodeName == 'comment' ) {
1012 # HTML-style comment
1013 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1014 if ( $this->parser->ot['html']
1015 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1016 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1017 {
1018 $out .= '';
1019 }
1020 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1021 # Not in RECOVER_COMMENTS mode (extractSections) though
1022 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1023 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1024 }
1025 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1026 else {
1027 $out .= $contextNode->textContent;
1028 }
1029 } elseif ( $contextNode->nodeName == 'ignore' ) {
1030 # Output suppression used by <includeonly> etc.
1031 # OT_WIKI will only respect <ignore> in substed templates.
1032 # The other output types respect it unless NO_IGNORE is set.
1033 # extractSections() sets NO_IGNORE and so never respects it.
1034 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1035 $out .= $contextNode->textContent;
1036 } else {
1037 $out .= '';
1038 }
1039 } elseif ( $contextNode->nodeName == 'ext' ) {
1040 # Extension tag
1041 $xpath = new DOMXPath( $contextNode->ownerDocument );
1042 $names = $xpath->query( 'name', $contextNode );
1043 $attrs = $xpath->query( 'attr', $contextNode );
1044 $inners = $xpath->query( 'inner', $contextNode );
1045 $closes = $xpath->query( 'close', $contextNode );
1046 $params = array(
1047 'name' => new PPNode_DOM( $names->item( 0 ) ),
1048 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1049 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1050 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1051 );
1052 $out .= $this->parser->extensionSubstitution( $params, $this );
1053 } elseif ( $contextNode->nodeName == 'h' ) {
1054 # Heading
1055 $s = $this->expand( $contextNode->childNodes, $flags );
1056
1057 # Insert a heading marker only for <h> children of <root>
1058 # This is to stop extractSections from going over multiple tree levels
1059 if ( $contextNode->parentNode->nodeName == 'root'
1060 && $this->parser->ot['html'] )
1061 {
1062 # Insert heading index marker
1063 $headingIndex = $contextNode->getAttribute( 'i' );
1064 $titleText = $this->title->getPrefixedDBkey();
1065 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1066 $serial = count( $this->parser->mHeadings ) - 1;
1067 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1068 $count = $contextNode->getAttribute( 'level' );
1069 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1070 $this->parser->mStripState->general->setPair( $marker, '' );
1071 }
1072 $out .= $s;
1073 } else {
1074 # Generic recursive expansion
1075 $newIterator = $contextNode->childNodes;
1076 }
1077 } else {
1078 wfProfileOut( __METHOD__ );
1079 throw new MWException( __METHOD__.': Invalid parameter type' );
1080 }
1081
1082 if ( $newIterator !== false ) {
1083 if ( $newIterator instanceof PPNode_DOM ) {
1084 $newIterator = $newIterator->node;
1085 }
1086 $outStack[] = '';
1087 $iteratorStack[] = $newIterator;
1088 $indexStack[] = 0;
1089 } elseif ( $iteratorStack[$level] === false ) {
1090 // Return accumulated value to parent
1091 // With tail recursion
1092 while ( $iteratorStack[$level] === false && $level > 0 ) {
1093 $outStack[$level - 1] .= $out;
1094 array_pop( $outStack );
1095 array_pop( $iteratorStack );
1096 array_pop( $indexStack );
1097 $level--;
1098 }
1099 }
1100 }
1101 --$expansionDepth;
1102 wfProfileOut( __METHOD__ );
1103 return $outStack[0];
1104 }
1105
1106 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1107 $args = array_slice( func_get_args(), 2 );
1108
1109 $first = true;
1110 $s = '';
1111 foreach ( $args as $root ) {
1112 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1113 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1114 $root = array( $root );
1115 }
1116 foreach ( $root as $node ) {
1117 if ( $first ) {
1118 $first = false;
1119 } else {
1120 $s .= $sep;
1121 }
1122 $s .= $this->expand( $node, $flags );
1123 }
1124 }
1125 return $s;
1126 }
1127
1128 /**
1129 * Implode with no flags specified
1130 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1131 */
1132 function implode( $sep /*, ... */ ) {
1133 $args = array_slice( func_get_args(), 1 );
1134
1135 $first = true;
1136 $s = '';
1137 foreach ( $args as $root ) {
1138 if ( $root instanceof PPNode_DOM ) {
1139 $root = $root->node;
1140 }
1141 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1142 $root = array( $root );
1143 }
1144 foreach ( $root as $node ) {
1145 if ( $first ) {
1146 $first = false;
1147 } else {
1148 $s .= $sep;
1149 }
1150 $s .= $this->expand( $node );
1151 }
1152 }
1153 return $s;
1154 }
1155
1156 /**
1157 * Makes an object that, when expand()ed, will be the same as one obtained
1158 * with implode()
1159 */
1160 function virtualImplode( $sep /*, ... */ ) {
1161 $args = array_slice( func_get_args(), 1 );
1162 $out = array();
1163 $first = true;
1164
1165 foreach ( $args as $root ) {
1166 if ( $root instanceof PPNode_DOM ) {
1167 $root = $root->node;
1168 }
1169 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1170 $root = array( $root );
1171 }
1172 foreach ( $root as $node ) {
1173 if ( $first ) {
1174 $first = false;
1175 } else {
1176 $out[] = $sep;
1177 }
1178 $out[] = $node;
1179 }
1180 }
1181 return $out;
1182 }
1183
1184 /**
1185 * Virtual implode with brackets
1186 */
1187 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1188 $args = array_slice( func_get_args(), 3 );
1189 $out = array( $start );
1190 $first = true;
1191
1192 foreach ( $args as $root ) {
1193 if ( $root instanceof PPNode_DOM ) {
1194 $root = $root->node;
1195 }
1196 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1197 $root = array( $root );
1198 }
1199 foreach ( $root as $node ) {
1200 if ( $first ) {
1201 $first = false;
1202 } else {
1203 $out[] = $sep;
1204 }
1205 $out[] = $node;
1206 }
1207 }
1208 $out[] = $end;
1209 return $out;
1210 }
1211
1212 function __toString() {
1213 return 'frame{}';
1214 }
1215
1216 function getPDBK( $level = false ) {
1217 if ( $level === false ) {
1218 return $this->title->getPrefixedDBkey();
1219 } else {
1220 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1221 }
1222 }
1223
1224 function getArguments() {
1225 return array();
1226 }
1227
1228 function getNumberedArguments() {
1229 return array();
1230 }
1231
1232 function getNamedArguments() {
1233 return array();
1234 }
1235
1236 /**
1237 * Returns true if there are no arguments in this frame
1238 */
1239 function isEmpty() {
1240 return true;
1241 }
1242
1243 function getArgument( $name ) {
1244 return false;
1245 }
1246
1247 /**
1248 * Returns true if the infinite loop check is OK, false if a loop is detected
1249 */
1250 function loopCheck( $title ) {
1251 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1252 }
1253
1254 /**
1255 * Return true if the frame is a template frame
1256 */
1257 function isTemplate() {
1258 return false;
1259 }
1260 }
1261
1262 /**
1263 * Expansion frame with template arguments
1264 * @ingroup Parser
1265 */
1266 class PPTemplateFrame_DOM extends PPFrame_DOM {
1267 var $numberedArgs, $namedArgs, $parent;
1268 var $numberedExpansionCache, $namedExpansionCache;
1269
1270 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1271 parent::__construct( $preprocessor );
1272
1273 $this->parent = $parent;
1274 $this->numberedArgs = $numberedArgs;
1275 $this->namedArgs = $namedArgs;
1276 $this->title = $title;
1277 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1278 $this->titleCache = $parent->titleCache;
1279 $this->titleCache[] = $pdbk;
1280 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1281 if ( $pdbk !== false ) {
1282 $this->loopCheckHash[$pdbk] = true;
1283 }
1284 $this->depth = $parent->depth + 1;
1285 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1286 }
1287
1288 function __toString() {
1289 $s = 'tplframe{';
1290 $first = true;
1291 $args = $this->numberedArgs + $this->namedArgs;
1292 foreach ( $args as $name => $value ) {
1293 if ( $first ) {
1294 $first = false;
1295 } else {
1296 $s .= ', ';
1297 }
1298 $s .= "\"$name\":\"" .
1299 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1300 }
1301 $s .= '}';
1302 return $s;
1303 }
1304 /**
1305 * Returns true if there are no arguments in this frame
1306 */
1307 function isEmpty() {
1308 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1309 }
1310
1311 function getArguments() {
1312 $arguments = array();
1313 foreach ( array_merge(
1314 array_keys($this->numberedArgs),
1315 array_keys($this->namedArgs)) as $key ) {
1316 $arguments[$key] = $this->getArgument($key);
1317 }
1318 return $arguments;
1319 }
1320
1321 function getNumberedArguments() {
1322 $arguments = array();
1323 foreach ( array_keys($this->numberedArgs) as $key ) {
1324 $arguments[$key] = $this->getArgument($key);
1325 }
1326 return $arguments;
1327 }
1328
1329 function getNamedArguments() {
1330 $arguments = array();
1331 foreach ( array_keys($this->namedArgs) as $key ) {
1332 $arguments[$key] = $this->getArgument($key);
1333 }
1334 return $arguments;
1335 }
1336
1337 function getNumberedArgument( $index ) {
1338 if ( !isset( $this->numberedArgs[$index] ) ) {
1339 return false;
1340 }
1341 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1342 # No trimming for unnamed arguments
1343 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1344 }
1345 return $this->numberedExpansionCache[$index];
1346 }
1347
1348 function getNamedArgument( $name ) {
1349 if ( !isset( $this->namedArgs[$name] ) ) {
1350 return false;
1351 }
1352 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1353 # Trim named arguments post-expand, for backwards compatibility
1354 $this->namedExpansionCache[$name] = trim(
1355 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1356 }
1357 return $this->namedExpansionCache[$name];
1358 }
1359
1360 function getArgument( $name ) {
1361 $text = $this->getNumberedArgument( $name );
1362 if ( $text === false ) {
1363 $text = $this->getNamedArgument( $name );
1364 }
1365 return $text;
1366 }
1367
1368 /**
1369 * Return true if the frame is a template frame
1370 */
1371 function isTemplate() {
1372 return true;
1373 }
1374 }
1375
1376 /**
1377 * Expansion frame with custom arguments
1378 * @ingroup Parser
1379 */
1380 class PPCustomFrame_DOM extends PPFrame_DOM {
1381 var $args;
1382
1383 function __construct( $preprocessor, $args ) {
1384 parent::__construct( $preprocessor );
1385 $this->args = $args;
1386 }
1387
1388 function __toString() {
1389 $s = 'cstmframe{';
1390 $first = true;
1391 foreach ( $this->args as $name => $value ) {
1392 if ( $first ) {
1393 $first = false;
1394 } else {
1395 $s .= ', ';
1396 }
1397 $s .= "\"$name\":\"" .
1398 str_replace( '"', '\\"', $value->__toString() ) . '"';
1399 }
1400 $s .= '}';
1401 return $s;
1402 }
1403
1404 function isEmpty() {
1405 return !count( $this->args );
1406 }
1407
1408 function getArgument( $index ) {
1409 if ( !isset( $this->args[$index] ) ) {
1410 return false;
1411 }
1412 return $this->args[$index];
1413 }
1414 }
1415
1416 /**
1417 * @ingroup Parser
1418 */
1419 class PPNode_DOM implements PPNode {
1420 var $node;
1421
1422 function __construct( $node, $xpath = false ) {
1423 $this->node = $node;
1424 }
1425
1426 function __get( $name ) {
1427 if ( $name == 'xpath' ) {
1428 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1429 }
1430 return $this->xpath;
1431 }
1432
1433 function __toString() {
1434 if ( $this->node instanceof DOMNodeList ) {
1435 $s = '';
1436 foreach ( $this->node as $node ) {
1437 $s .= $node->ownerDocument->saveXML( $node );
1438 }
1439 } else {
1440 $s = $this->node->ownerDocument->saveXML( $this->node );
1441 }
1442 return $s;
1443 }
1444
1445 function getChildren() {
1446 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1447 }
1448
1449 function getFirstChild() {
1450 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1451 }
1452
1453 function getNextSibling() {
1454 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1455 }
1456
1457 function getChildrenOfType( $type ) {
1458 return new self( $this->xpath->query( $type, $this->node ) );
1459 }
1460
1461 function getLength() {
1462 if ( $this->node instanceof DOMNodeList ) {
1463 return $this->node->length;
1464 } else {
1465 return false;
1466 }
1467 }
1468
1469 function item( $i ) {
1470 $item = $this->node->item( $i );
1471 return $item ? new self( $item ) : false;
1472 }
1473
1474 function getName() {
1475 if ( $this->node instanceof DOMNodeList ) {
1476 return '#nodelist';
1477 } else {
1478 return $this->node->nodeName;
1479 }
1480 }
1481
1482 /**
1483 * Split a <part> node into an associative array containing:
1484 * name PPNode name
1485 * index String index
1486 * value PPNode value
1487 */
1488 function splitArg() {
1489 $names = $this->xpath->query( 'name', $this->node );
1490 $values = $this->xpath->query( 'value', $this->node );
1491 if ( !$names->length || !$values->length ) {
1492 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1493 }
1494 $name = $names->item( 0 );
1495 $index = $name->getAttribute( 'index' );
1496 return array(
1497 'name' => new self( $name ),
1498 'index' => $index,
1499 'value' => new self( $values->item( 0 ) ) );
1500 }
1501
1502 /**
1503 * Split an <ext> node into an associative array containing name, attr, inner and close
1504 * All values in the resulting array are PPNodes. Inner and close are optional.
1505 */
1506 function splitExt() {
1507 $names = $this->xpath->query( 'name', $this->node );
1508 $attrs = $this->xpath->query( 'attr', $this->node );
1509 $inners = $this->xpath->query( 'inner', $this->node );
1510 $closes = $this->xpath->query( 'close', $this->node );
1511 if ( !$names->length || !$attrs->length ) {
1512 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1513 }
1514 $parts = array(
1515 'name' => new self( $names->item( 0 ) ),
1516 'attr' => new self( $attrs->item( 0 ) ) );
1517 if ( $inners->length ) {
1518 $parts['inner'] = new self( $inners->item( 0 ) );
1519 }
1520 if ( $closes->length ) {
1521 $parts['close'] = new self( $closes->item( 0 ) );
1522 }
1523 return $parts;
1524 }
1525
1526 /**
1527 * Split a <h> node
1528 */
1529 function splitHeading() {
1530 if ( !$this->nodeName == 'h' ) {
1531 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1532 }
1533 return array(
1534 'i' => $this->node->getAttribute( 'i' ),
1535 'level' => $this->node->getAttribute( 'level' ),
1536 'contents' => $this->getChildren()
1537 );
1538 }
1539 }