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