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