Provisional revert of r89648: "Another try at fixing bug 93 "tilde signatures inside...
[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 ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1093 $out .= $contextNode->textContent;
1094 } else {
1095 $out .= '';
1096 }
1097 } elseif ( $contextNode->nodeName == 'ext' ) {
1098 # Extension tag
1099 $xpath = new DOMXPath( $contextNode->ownerDocument );
1100 $names = $xpath->query( 'name', $contextNode );
1101 $attrs = $xpath->query( 'attr', $contextNode );
1102 $inners = $xpath->query( 'inner', $contextNode );
1103 $closes = $xpath->query( 'close', $contextNode );
1104 $params = array(
1105 'name' => new PPNode_DOM( $names->item( 0 ) ),
1106 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1107 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1108 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1109 );
1110 $out .= $this->parser->extensionSubstitution( $params, $this );
1111 } elseif ( $contextNode->nodeName == 'h' ) {
1112 # Heading
1113 $s = $this->expand( $contextNode->childNodes, $flags );
1114
1115 # Insert a heading marker only for <h> children of <root>
1116 # This is to stop extractSections from going over multiple tree levels
1117 if ( $contextNode->parentNode->nodeName == 'root'
1118 && $this->parser->ot['html'] )
1119 {
1120 # Insert heading index marker
1121 $headingIndex = $contextNode->getAttribute( 'i' );
1122 $titleText = $this->title->getPrefixedDBkey();
1123 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1124 $serial = count( $this->parser->mHeadings ) - 1;
1125 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1126 $count = $contextNode->getAttribute( 'level' );
1127 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1128 $this->parser->mStripState->addGeneral( $marker, '' );
1129 }
1130 $out .= $s;
1131 } else {
1132 # Generic recursive expansion
1133 $newIterator = $contextNode->childNodes;
1134 }
1135 } else {
1136 wfProfileOut( __METHOD__ );
1137 throw new MWException( __METHOD__.': Invalid parameter type' );
1138 }
1139
1140 if ( $newIterator !== false ) {
1141 if ( $newIterator instanceof PPNode_DOM ) {
1142 $newIterator = $newIterator->node;
1143 }
1144 $outStack[] = '';
1145 $iteratorStack[] = $newIterator;
1146 $indexStack[] = 0;
1147 } elseif ( $iteratorStack[$level] === false ) {
1148 // Return accumulated value to parent
1149 // With tail recursion
1150 while ( $iteratorStack[$level] === false && $level > 0 ) {
1151 $outStack[$level - 1] .= $out;
1152 array_pop( $outStack );
1153 array_pop( $iteratorStack );
1154 array_pop( $indexStack );
1155 $level--;
1156 }
1157 }
1158 }
1159 --$expansionDepth;
1160 wfProfileOut( __METHOD__ );
1161 return $outStack[0];
1162 }
1163
1164 /**
1165 * @param $sep
1166 * @param $flags
1167 * @return string
1168 */
1169 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1170 $args = array_slice( func_get_args(), 2 );
1171
1172 $first = true;
1173 $s = '';
1174 foreach ( $args as $root ) {
1175 if ( $root instanceof PPNode_DOM ) $root = $root->node;
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 $s .= $sep;
1184 }
1185 $s .= $this->expand( $node, $flags );
1186 }
1187 }
1188 return $s;
1189 }
1190
1191 /**
1192 * Implode with no flags specified
1193 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1194 *
1195 * @return string
1196 */
1197 function implode( $sep /*, ... */ ) {
1198 $args = array_slice( func_get_args(), 1 );
1199
1200 $first = true;
1201 $s = '';
1202 foreach ( $args as $root ) {
1203 if ( $root instanceof PPNode_DOM ) {
1204 $root = $root->node;
1205 }
1206 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1207 $root = array( $root );
1208 }
1209 foreach ( $root as $node ) {
1210 if ( $first ) {
1211 $first = false;
1212 } else {
1213 $s .= $sep;
1214 }
1215 $s .= $this->expand( $node );
1216 }
1217 }
1218 return $s;
1219 }
1220
1221 /**
1222 * Makes an object that, when expand()ed, will be the same as one obtained
1223 * with implode()
1224 *
1225 * @return array
1226 */
1227 function virtualImplode( $sep /*, ... */ ) {
1228 $args = array_slice( func_get_args(), 1 );
1229 $out = array();
1230 $first = true;
1231
1232 foreach ( $args as $root ) {
1233 if ( $root instanceof PPNode_DOM ) {
1234 $root = $root->node;
1235 }
1236 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1237 $root = array( $root );
1238 }
1239 foreach ( $root as $node ) {
1240 if ( $first ) {
1241 $first = false;
1242 } else {
1243 $out[] = $sep;
1244 }
1245 $out[] = $node;
1246 }
1247 }
1248 return $out;
1249 }
1250
1251 /**
1252 * Virtual implode with brackets
1253 */
1254 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1255 $args = array_slice( func_get_args(), 3 );
1256 $out = array( $start );
1257 $first = true;
1258
1259 foreach ( $args as $root ) {
1260 if ( $root instanceof PPNode_DOM ) {
1261 $root = $root->node;
1262 }
1263 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1264 $root = array( $root );
1265 }
1266 foreach ( $root as $node ) {
1267 if ( $first ) {
1268 $first = false;
1269 } else {
1270 $out[] = $sep;
1271 }
1272 $out[] = $node;
1273 }
1274 }
1275 $out[] = $end;
1276 return $out;
1277 }
1278
1279 function __toString() {
1280 return 'frame{}';
1281 }
1282
1283 function getPDBK( $level = false ) {
1284 if ( $level === false ) {
1285 return $this->title->getPrefixedDBkey();
1286 } else {
1287 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1288 }
1289 }
1290
1291 /**
1292 * @return array
1293 */
1294 function getArguments() {
1295 return array();
1296 }
1297
1298 /**
1299 * @return array
1300 */
1301 function getNumberedArguments() {
1302 return array();
1303 }
1304
1305 /**
1306 * @return array
1307 */
1308 function getNamedArguments() {
1309 return array();
1310 }
1311
1312 /**
1313 * Returns true if there are no arguments in this frame
1314 *
1315 * @return bool
1316 */
1317 function isEmpty() {
1318 return true;
1319 }
1320
1321 function getArgument( $name ) {
1322 return false;
1323 }
1324
1325 /**
1326 * Returns true if the infinite loop check is OK, false if a loop is detected
1327 *
1328 * @return bool
1329 */
1330 function loopCheck( $title ) {
1331 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1332 }
1333
1334 /**
1335 * Return true if the frame is a template frame
1336 *
1337 * @return bool
1338 */
1339 function isTemplate() {
1340 return false;
1341 }
1342 }
1343
1344 /**
1345 * Expansion frame with template arguments
1346 * @ingroup Parser
1347 */
1348 class PPTemplateFrame_DOM extends PPFrame_DOM {
1349 var $numberedArgs, $namedArgs;
1350
1351 /**
1352 * @var PPFrame_DOM
1353 */
1354 var $parent;
1355 var $numberedExpansionCache, $namedExpansionCache;
1356
1357 /**
1358 * @param $preprocessor
1359 * @param $parent PPFrame_DOM
1360 * @param $numberedArgs array
1361 * @param $namedArgs array
1362 * @param $title Title
1363 */
1364 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1365 parent::__construct( $preprocessor );
1366
1367 $this->parent = $parent;
1368 $this->numberedArgs = $numberedArgs;
1369 $this->namedArgs = $namedArgs;
1370 $this->title = $title;
1371 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1372 $this->titleCache = $parent->titleCache;
1373 $this->titleCache[] = $pdbk;
1374 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1375 if ( $pdbk !== false ) {
1376 $this->loopCheckHash[$pdbk] = true;
1377 }
1378 $this->depth = $parent->depth + 1;
1379 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1380 }
1381
1382 function __toString() {
1383 $s = 'tplframe{';
1384 $first = true;
1385 $args = $this->numberedArgs + $this->namedArgs;
1386 foreach ( $args as $name => $value ) {
1387 if ( $first ) {
1388 $first = false;
1389 } else {
1390 $s .= ', ';
1391 }
1392 $s .= "\"$name\":\"" .
1393 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1394 }
1395 $s .= '}';
1396 return $s;
1397 }
1398
1399 /**
1400 * Returns true if there are no arguments in this frame
1401 *
1402 * @return bool
1403 */
1404 function isEmpty() {
1405 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1406 }
1407
1408 function getArguments() {
1409 $arguments = array();
1410 foreach ( array_merge(
1411 array_keys($this->numberedArgs),
1412 array_keys($this->namedArgs)) as $key ) {
1413 $arguments[$key] = $this->getArgument($key);
1414 }
1415 return $arguments;
1416 }
1417
1418 function getNumberedArguments() {
1419 $arguments = array();
1420 foreach ( array_keys($this->numberedArgs) as $key ) {
1421 $arguments[$key] = $this->getArgument($key);
1422 }
1423 return $arguments;
1424 }
1425
1426 function getNamedArguments() {
1427 $arguments = array();
1428 foreach ( array_keys($this->namedArgs) as $key ) {
1429 $arguments[$key] = $this->getArgument($key);
1430 }
1431 return $arguments;
1432 }
1433
1434 function getNumberedArgument( $index ) {
1435 if ( !isset( $this->numberedArgs[$index] ) ) {
1436 return false;
1437 }
1438 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1439 # No trimming for unnamed arguments
1440 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1441 }
1442 return $this->numberedExpansionCache[$index];
1443 }
1444
1445 function getNamedArgument( $name ) {
1446 if ( !isset( $this->namedArgs[$name] ) ) {
1447 return false;
1448 }
1449 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1450 # Trim named arguments post-expand, for backwards compatibility
1451 $this->namedExpansionCache[$name] = trim(
1452 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1453 }
1454 return $this->namedExpansionCache[$name];
1455 }
1456
1457 function getArgument( $name ) {
1458 $text = $this->getNumberedArgument( $name );
1459 if ( $text === false ) {
1460 $text = $this->getNamedArgument( $name );
1461 }
1462 return $text;
1463 }
1464
1465 /**
1466 * Return true if the frame is a template frame
1467 *
1468 * @return bool
1469 */
1470 function isTemplate() {
1471 return true;
1472 }
1473 }
1474
1475 /**
1476 * Expansion frame with custom arguments
1477 * @ingroup Parser
1478 */
1479 class PPCustomFrame_DOM extends PPFrame_DOM {
1480 var $args;
1481
1482 function __construct( $preprocessor, $args ) {
1483 parent::__construct( $preprocessor );
1484 $this->args = $args;
1485 }
1486
1487 function __toString() {
1488 $s = 'cstmframe{';
1489 $first = true;
1490 foreach ( $this->args as $name => $value ) {
1491 if ( $first ) {
1492 $first = false;
1493 } else {
1494 $s .= ', ';
1495 }
1496 $s .= "\"$name\":\"" .
1497 str_replace( '"', '\\"', $value->__toString() ) . '"';
1498 }
1499 $s .= '}';
1500 return $s;
1501 }
1502
1503 /**
1504 * @return bool
1505 */
1506 function isEmpty() {
1507 return !count( $this->args );
1508 }
1509
1510 function getArgument( $index ) {
1511 if ( !isset( $this->args[$index] ) ) {
1512 return false;
1513 }
1514 return $this->args[$index];
1515 }
1516 }
1517
1518 /**
1519 * @ingroup Parser
1520 */
1521 class PPNode_DOM implements PPNode {
1522
1523 /**
1524 * @var DOMElement
1525 */
1526 var $node;
1527 var $xpath;
1528
1529 function __construct( $node, $xpath = false ) {
1530 $this->node = $node;
1531 }
1532
1533 /**
1534 * @return DOMXPath
1535 */
1536 function getXPath() {
1537 if ( $this->xpath === null ) {
1538 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1539 }
1540 return $this->xpath;
1541 }
1542
1543 function __toString() {
1544 if ( $this->node instanceof DOMNodeList ) {
1545 $s = '';
1546 foreach ( $this->node as $node ) {
1547 $s .= $node->ownerDocument->saveXML( $node );
1548 }
1549 } else {
1550 $s = $this->node->ownerDocument->saveXML( $this->node );
1551 }
1552 return $s;
1553 }
1554
1555 /**
1556 * @return bool|PPNode_DOM
1557 */
1558 function getChildren() {
1559 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1560 }
1561
1562 /**
1563 * @return bool|PPNode_DOM
1564 */
1565 function getFirstChild() {
1566 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1567 }
1568
1569 /**
1570 * @return bool|PPNode_DOM
1571 */
1572 function getNextSibling() {
1573 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1574 }
1575
1576 /**
1577 * @param $type
1578 *
1579 * @return bool|PPNode_DOM
1580 */
1581 function getChildrenOfType( $type ) {
1582 return new self( $this->getXPath()->query( $type, $this->node ) );
1583 }
1584
1585 /**
1586 * @return int
1587 */
1588 function getLength() {
1589 if ( $this->node instanceof DOMNodeList ) {
1590 return $this->node->length;
1591 } else {
1592 return false;
1593 }
1594 }
1595
1596 /**
1597 * @param $i
1598 * @return bool|PPNode_DOM
1599 */
1600 function item( $i ) {
1601 $item = $this->node->item( $i );
1602 return $item ? new self( $item ) : false;
1603 }
1604
1605 /**
1606 * @return string
1607 */
1608 function getName() {
1609 if ( $this->node instanceof DOMNodeList ) {
1610 return '#nodelist';
1611 } else {
1612 return $this->node->nodeName;
1613 }
1614 }
1615
1616 /**
1617 * Split a <part> node into an associative array containing:
1618 * name PPNode name
1619 * index String index
1620 * value PPNode value
1621 *
1622 * @return array
1623 */
1624 function splitArg() {
1625 $xpath = $this->getXPath();
1626 $names = $xpath->query( 'name', $this->node );
1627 $values = $xpath->query( 'value', $this->node );
1628 if ( !$names->length || !$values->length ) {
1629 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1630 }
1631 $name = $names->item( 0 );
1632 $index = $name->getAttribute( 'index' );
1633 return array(
1634 'name' => new self( $name ),
1635 'index' => $index,
1636 'value' => new self( $values->item( 0 ) ) );
1637 }
1638
1639 /**
1640 * Split an <ext> node into an associative array containing name, attr, inner and close
1641 * All values in the resulting array are PPNodes. Inner and close are optional.
1642 *
1643 * @return array
1644 */
1645 function splitExt() {
1646 $xpath = $this->getXPath();
1647 $names = $xpath->query( 'name', $this->node );
1648 $attrs = $xpath->query( 'attr', $this->node );
1649 $inners = $xpath->query( 'inner', $this->node );
1650 $closes = $xpath->query( 'close', $this->node );
1651 if ( !$names->length || !$attrs->length ) {
1652 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1653 }
1654 $parts = array(
1655 'name' => new self( $names->item( 0 ) ),
1656 'attr' => new self( $attrs->item( 0 ) ) );
1657 if ( $inners->length ) {
1658 $parts['inner'] = new self( $inners->item( 0 ) );
1659 }
1660 if ( $closes->length ) {
1661 $parts['close'] = new self( $closes->item( 0 ) );
1662 }
1663 return $parts;
1664 }
1665
1666 /**
1667 * Split a <h> node
1668 */
1669 function splitHeading() {
1670 if ( $this->getName() !== 'h' ) {
1671 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1672 }
1673 return array(
1674 'i' => $this->node->getAttribute( 'i' ),
1675 'level' => $this->node->getAttribute( 'level' ),
1676 'contents' => $this->getChildren()
1677 );
1678 }
1679 }