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