Update some deprecated code
[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 true;
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 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
159 $result = $dom->loadXML( $xml, 1 << 19 );
160 if ( !$result ) {
161 throw new MWException( __METHOD__.' generated invalid XML' );
162 }
163 }
164 $obj = new PPNode_DOM( $dom->documentElement );
165 wfProfileOut( __METHOD__.'-loadXML' );
166 if ( $cacheable ) {
167 wfProfileOut( __METHOD__.'-cacheable' );
168 }
169 wfProfileOut( __METHOD__ );
170 return $obj;
171 }
172
173 /**
174 * @param $text string
175 * @param $flags int
176 * @return string
177 */
178 function preprocessToXml( $text, $flags = 0 ) {
179 wfProfileIn( __METHOD__ );
180 $rules = array(
181 '{' => array(
182 'end' => '}',
183 'names' => array(
184 2 => 'template',
185 3 => 'tplarg',
186 ),
187 'min' => 2,
188 'max' => 3,
189 ),
190 '[' => array(
191 'end' => ']',
192 'names' => array( 2 => null ),
193 'min' => 2,
194 'max' => 2,
195 )
196 );
197
198 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
199
200 $xmlishElements = $this->parser->getStripList();
201 $enableOnlyinclude = false;
202 if ( $forInclusion ) {
203 $ignoredTags = array( 'includeonly', '/includeonly' );
204 $ignoredElements = array( 'noinclude' );
205 $xmlishElements[] = 'noinclude';
206 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
207 $enableOnlyinclude = true;
208 }
209 } else {
210 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
211 $ignoredElements = array( 'includeonly' );
212 $xmlishElements[] = 'includeonly';
213 }
214 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
215
216 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
217 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
218
219 $stack = new PPDStack;
220
221 $searchBase = "[{<\n"; #}
222 $revText = strrev( $text ); // For fast reverse searches
223
224 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
225 $accum =& $stack->getAccum(); # Current accumulator
226 $accum = '<root>';
227 $findEquals = false; # True to find equals signs in arguments
228 $findPipe = false; # True to take notice of pipe characters
229 $headingIndex = 1;
230 $inHeading = false; # True if $i is inside a possible heading
231 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
232 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
233 $fakeLineStart = true; # Do a line-start run without outputting an LF character
234
235 while ( true ) {
236 //$this->memCheck();
237
238 if ( $findOnlyinclude ) {
239 // Ignore all input up to the next <onlyinclude>
240 $startPos = strpos( $text, '<onlyinclude>', $i );
241 if ( $startPos === false ) {
242 // Ignored section runs to the end
243 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
244 break;
245 }
246 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
247 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
248 $i = $tagEndPos;
249 $findOnlyinclude = false;
250 }
251
252 if ( $fakeLineStart ) {
253 $found = 'line-start';
254 $curChar = '';
255 } else {
256 # Find next opening brace, closing brace or pipe
257 $search = $searchBase;
258 if ( $stack->top === false ) {
259 $currentClosing = '';
260 } else {
261 $currentClosing = $stack->top->close;
262 $search .= $currentClosing;
263 }
264 if ( $findPipe ) {
265 $search .= '|';
266 }
267 if ( $findEquals ) {
268 // First equals will be for the template
269 $search .= '=';
270 }
271 $rule = null;
272 # Output literal section, advance input counter
273 $literalLength = strcspn( $text, $search, $i );
274 if ( $literalLength > 0 ) {
275 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
276 $i += $literalLength;
277 }
278 if ( $i >= strlen( $text ) ) {
279 if ( $currentClosing == "\n" ) {
280 // Do a past-the-end run to finish off the heading
281 $curChar = '';
282 $found = 'line-end';
283 } else {
284 # All done
285 break;
286 }
287 } else {
288 $curChar = $text[$i];
289 if ( $curChar == '|' ) {
290 $found = 'pipe';
291 } elseif ( $curChar == '=' ) {
292 $found = 'equals';
293 } elseif ( $curChar == '<' ) {
294 $found = 'angle';
295 } elseif ( $curChar == "\n" ) {
296 if ( $inHeading ) {
297 $found = 'line-end';
298 } else {
299 $found = 'line-start';
300 }
301 } elseif ( $curChar == $currentClosing ) {
302 $found = 'close';
303 } elseif ( isset( $rules[$curChar] ) ) {
304 $found = 'open';
305 $rule = $rules[$curChar];
306 } else {
307 # Some versions of PHP have a strcspn which stops on null characters
308 # Ignore and continue
309 ++$i;
310 continue;
311 }
312 }
313 }
314
315 if ( $found == 'angle' ) {
316 $matches = false;
317 // Handle </onlyinclude>
318 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
319 $findOnlyinclude = true;
320 continue;
321 }
322
323 // Determine element name
324 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
325 // Element name missing or not listed
326 $accum .= '&lt;';
327 ++$i;
328 continue;
329 }
330 // Handle comments
331 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
332 // To avoid leaving blank lines, when a comment is both preceded
333 // and followed by a newline (ignoring spaces), trim leading and
334 // trailing spaces and one of the newlines.
335
336 // Find the end
337 $endPos = strpos( $text, '-->', $i + 4 );
338 if ( $endPos === false ) {
339 // Unclosed comment in input, runs to end
340 $inner = substr( $text, $i );
341 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
342 $i = strlen( $text );
343 } else {
344 // Search backwards for leading whitespace
345 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
346 // Search forwards for trailing whitespace
347 // $wsEnd will be the position of the last space (or the '>' if there's none)
348 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
349 // Eat the line if possible
350 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
351 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
352 // it's a possible beneficial b/c break.
353 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
354 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
355 {
356 $startPos = $wsStart;
357 $endPos = $wsEnd + 1;
358 // Remove leading whitespace from the end of the accumulator
359 // Sanity check first though
360 $wsLength = $i - $wsStart;
361 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
362 $accum = substr( $accum, 0, -$wsLength );
363 }
364 // Do a line-start run next time to look for headings after the comment
365 $fakeLineStart = true;
366 } else {
367 // No line to eat, just take the comment itself
368 $startPos = $i;
369 $endPos += 2;
370 }
371
372 if ( $stack->top ) {
373 $part = $stack->top->getCurrentPart();
374 if ( ! (isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 )) {
375 $part->visualEnd = $wsStart;
376 }
377 // Else comments abutting, no change in visual end
378 $part->commentEnd = $endPos;
379 }
380 $i = $endPos + 1;
381 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
382 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
383 }
384 continue;
385 }
386 $name = $matches[1];
387 $lowerName = strtolower( $name );
388 $attrStart = $i + strlen( $name ) + 1;
389
390 // Find end of tag
391 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
392 if ( $tagEndPos === false ) {
393 // Infinite backtrack
394 // Disable tag search to prevent worst-case O(N^2) performance
395 $noMoreGT = true;
396 $accum .= '&lt;';
397 ++$i;
398 continue;
399 }
400
401 // Handle ignored tags
402 if ( in_array( $lowerName, $ignoredTags ) ) {
403 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
404 $i = $tagEndPos + 1;
405 continue;
406 }
407
408 $tagStartPos = $i;
409 if ( $text[$tagEndPos-1] == '/' ) {
410 $attrEnd = $tagEndPos - 1;
411 $inner = null;
412 $i = $tagEndPos + 1;
413 $close = '';
414 } else {
415 $attrEnd = $tagEndPos;
416 // Find closing tag
417 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
418 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
419 {
420 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
421 $i = $matches[0][1] + strlen( $matches[0][0] );
422 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
423 } else {
424 // No end tag -- let it run out to the end of the text.
425 $inner = substr( $text, $tagEndPos + 1 );
426 $i = strlen( $text );
427 $close = '';
428 }
429 }
430 // <includeonly> and <noinclude> just become <ignore> tags
431 if ( in_array( $lowerName, $ignoredElements ) ) {
432 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
433 . '</ignore>';
434 continue;
435 }
436
437 $accum .= '<ext>';
438 if ( $attrEnd <= $attrStart ) {
439 $attr = '';
440 } else {
441 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
442 }
443 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
444 // Note that the attr element contains the whitespace between name and attribute,
445 // this is necessary for precise reconstruction during pre-save transform.
446 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
447 if ( $inner !== null ) {
448 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
449 }
450 $accum .= $close . '</ext>';
451 } elseif ( $found == 'line-start' ) {
452 // Is this the start of a heading?
453 // Line break belongs before the heading element in any case
454 if ( $fakeLineStart ) {
455 $fakeLineStart = false;
456 } else {
457 $accum .= $curChar;
458 $i++;
459 }
460
461 $count = strspn( $text, '=', $i, 6 );
462 if ( $count == 1 && $findEquals ) {
463 // DWIM: This looks kind of like a name/value separator
464 // Let's let the equals handler have it and break the potential heading
465 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
466 } elseif ( $count > 0 ) {
467 $piece = array(
468 'open' => "\n",
469 'close' => "\n",
470 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
471 'startPos' => $i,
472 'count' => $count );
473 $stack->push( $piece );
474 $accum =& $stack->getAccum();
475 $flags = $stack->getFlags();
476 extract( $flags );
477 $i += $count;
478 }
479 } elseif ( $found == 'line-end' ) {
480 $piece = $stack->top;
481 // A heading must be open, otherwise \n wouldn't have been in the search list
482 assert( $piece->open == "\n" );
483 $part = $piece->getCurrentPart();
484 // Search back through the input to see if it has a proper close
485 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
486 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
487 $searchStart = $i - $wsLength;
488 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
489 // Comment found at line end
490 // Search for equals signs before the comment
491 $searchStart = $part->visualEnd;
492 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
493 }
494 $count = $piece->count;
495 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
496 if ( $equalsLength > 0 ) {
497 if ( $searchStart - $equalsLength == $piece->startPos ) {
498 // This is just a single string of equals signs on its own line
499 // Replicate the doHeadings behaviour /={count}(.+)={count}/
500 // First find out how many equals signs there really are (don't stop at 6)
501 $count = $equalsLength;
502 if ( $count < 3 ) {
503 $count = 0;
504 } else {
505 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
506 }
507 } else {
508 $count = min( $equalsLength, $count );
509 }
510 if ( $count > 0 ) {
511 // Normal match, output <h>
512 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
513 $headingIndex++;
514 } else {
515 // Single equals sign on its own line, count=0
516 $element = $accum;
517 }
518 } else {
519 // No match, no <h>, just pass down the inner text
520 $element = $accum;
521 }
522 // Unwind the stack
523 $stack->pop();
524 $accum =& $stack->getAccum();
525 $flags = $stack->getFlags();
526 extract( $flags );
527
528 // Append the result to the enclosing accumulator
529 $accum .= $element;
530 // Note that we do NOT increment the input pointer.
531 // This is because the closing linebreak could be the opening linebreak of
532 // another heading. Infinite loops are avoided because the next iteration MUST
533 // hit the heading open case above, which unconditionally increments the
534 // input pointer.
535 } elseif ( $found == 'open' ) {
536 # count opening brace characters
537 $count = strspn( $text, $curChar, $i );
538
539 # we need to add to stack only if opening brace count is enough for one of the rules
540 if ( $count >= $rule['min'] ) {
541 # Add it to the stack
542 $piece = array(
543 'open' => $curChar,
544 'close' => $rule['end'],
545 'count' => $count,
546 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
547 );
548
549 $stack->push( $piece );
550 $accum =& $stack->getAccum();
551 $flags = $stack->getFlags();
552 extract( $flags );
553 } else {
554 # Add literal brace(s)
555 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
556 }
557 $i += $count;
558 } elseif ( $found == 'close' ) {
559 $piece = $stack->top;
560 # lets check if there are enough characters for closing brace
561 $maxCount = $piece->count;
562 $count = strspn( $text, $curChar, $i, $maxCount );
563
564 # check for maximum matching characters (if there are 5 closing
565 # characters, we will probably need only 3 - depending on the rules)
566 $rule = $rules[$piece->open];
567 if ( $count > $rule['max'] ) {
568 # The specified maximum exists in the callback array, unless the caller
569 # has made an error
570 $matchingCount = $rule['max'];
571 } else {
572 # Count is less than the maximum
573 # Skip any gaps in the callback array to find the true largest match
574 # Need to use array_key_exists not isset because the callback can be null
575 $matchingCount = $count;
576 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
577 --$matchingCount;
578 }
579 }
580
581 if ( $matchingCount <= 0 ) {
582 # No matching element found in callback array
583 # Output a literal closing brace and continue
584 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
585 $i += $count;
586 continue;
587 }
588 $name = $rule['names'][$matchingCount];
589 if ( $name === null ) {
590 // No element, just literal text
591 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
592 } else {
593 # Create XML element
594 # Note: $parts is already XML, does not need to be encoded further
595 $parts = $piece->parts;
596 $title = $parts[0]->out;
597 unset( $parts[0] );
598
599 # The invocation is at the start of the line if lineStart is set in
600 # the stack, and all opening brackets are used up.
601 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
602 $attr = ' lineStart="1"';
603 } else {
604 $attr = '';
605 }
606
607 $element = "<$name$attr>";
608 $element .= "<title>$title</title>";
609 $argIndex = 1;
610 foreach ( $parts as $part ) {
611 if ( isset( $part->eqpos ) ) {
612 $argName = substr( $part->out, 0, $part->eqpos );
613 $argValue = substr( $part->out, $part->eqpos + 1 );
614 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
615 } else {
616 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
617 $argIndex++;
618 }
619 }
620 $element .= "</$name>";
621 }
622
623 # Advance input pointer
624 $i += $matchingCount;
625
626 # Unwind the stack
627 $stack->pop();
628 $accum =& $stack->getAccum();
629
630 # Re-add the old stack element if it still has unmatched opening characters remaining
631 if ( $matchingCount < $piece->count ) {
632 $piece->parts = array( new PPDPart );
633 $piece->count -= $matchingCount;
634 # do we still qualify for any callback with remaining count?
635 $names = $rules[$piece->open]['names'];
636 $skippedBraces = 0;
637 $enclosingAccum =& $accum;
638 while ( $piece->count ) {
639 if ( array_key_exists( $piece->count, $names ) ) {
640 $stack->push( $piece );
641 $accum =& $stack->getAccum();
642 break;
643 }
644 --$piece->count;
645 $skippedBraces ++;
646 }
647 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
648 }
649 $flags = $stack->getFlags();
650 extract( $flags );
651
652 # Add XML element to the enclosing accumulator
653 $accum .= $element;
654 } elseif ( $found == 'pipe' ) {
655 $findEquals = true; // shortcut for getFlags()
656 $stack->addPart();
657 $accum =& $stack->getAccum();
658 ++$i;
659 } elseif ( $found == 'equals' ) {
660 $findEquals = false; // shortcut for getFlags()
661 $stack->getCurrentPart()->eqpos = strlen( $accum );
662 $accum .= '=';
663 ++$i;
664 }
665 }
666
667 # Output any remaining unclosed brackets
668 foreach ( $stack->stack as $piece ) {
669 $stack->rootAccum .= $piece->breakSyntax();
670 }
671 $stack->rootAccum .= '</root>';
672 $xml = $stack->rootAccum;
673
674 wfProfileOut( __METHOD__ );
675
676 return $xml;
677 }
678 }
679
680 /**
681 * Stack class to help Preprocessor::preprocessToObj()
682 * @ingroup Parser
683 */
684 class PPDStack {
685 var $stack, $rootAccum;
686
687 /**
688 * @var PPDStack
689 */
690 var $top;
691 var $out;
692 var $elementClass = 'PPDStackElement';
693
694 static $false = false;
695
696 function __construct() {
697 $this->stack = array();
698 $this->top = false;
699 $this->rootAccum = '';
700 $this->accum =& $this->rootAccum;
701 }
702
703 /**
704 * @return int
705 */
706 function count() {
707 return count( $this->stack );
708 }
709
710 function &getAccum() {
711 return $this->accum;
712 }
713
714 function getCurrentPart() {
715 if ( $this->top === false ) {
716 return false;
717 } else {
718 return $this->top->getCurrentPart();
719 }
720 }
721
722 function push( $data ) {
723 if ( $data instanceof $this->elementClass ) {
724 $this->stack[] = $data;
725 } else {
726 $class = $this->elementClass;
727 $this->stack[] = new $class( $data );
728 }
729 $this->top = $this->stack[ count( $this->stack ) - 1 ];
730 $this->accum =& $this->top->getAccum();
731 }
732
733 function pop() {
734 if ( !count( $this->stack ) ) {
735 throw new MWException( __METHOD__.': no elements remaining' );
736 }
737 $temp = array_pop( $this->stack );
738
739 if ( count( $this->stack ) ) {
740 $this->top = $this->stack[ count( $this->stack ) - 1 ];
741 $this->accum =& $this->top->getAccum();
742 } else {
743 $this->top = self::$false;
744 $this->accum =& $this->rootAccum;
745 }
746 return $temp;
747 }
748
749 function addPart( $s = '' ) {
750 $this->top->addPart( $s );
751 $this->accum =& $this->top->getAccum();
752 }
753
754 /**
755 * @return array
756 */
757 function getFlags() {
758 if ( !count( $this->stack ) ) {
759 return array(
760 'findEquals' => false,
761 'findPipe' => false,
762 'inHeading' => false,
763 );
764 } else {
765 return $this->top->getFlags();
766 }
767 }
768 }
769
770 /**
771 * @ingroup Parser
772 */
773 class PPDStackElement {
774 var $open, // Opening character (\n for heading)
775 $close, // Matching closing character
776 $count, // Number of opening characters found (number of "=" for heading)
777 $parts, // Array of PPDPart objects describing pipe-separated parts.
778 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
779
780 var $partClass = 'PPDPart';
781
782 function __construct( $data = array() ) {
783 $class = $this->partClass;
784 $this->parts = array( new $class );
785
786 foreach ( $data as $name => $value ) {
787 $this->$name = $value;
788 }
789 }
790
791 function &getAccum() {
792 return $this->parts[count($this->parts) - 1]->out;
793 }
794
795 function addPart( $s = '' ) {
796 $class = $this->partClass;
797 $this->parts[] = new $class( $s );
798 }
799
800 function getCurrentPart() {
801 return $this->parts[count($this->parts) - 1];
802 }
803
804 /**
805 * @return array
806 */
807 function getFlags() {
808 $partCount = count( $this->parts );
809 $findPipe = $this->open != "\n" && $this->open != '[';
810 return array(
811 'findPipe' => $findPipe,
812 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
813 'inHeading' => $this->open == "\n",
814 );
815 }
816
817 /**
818 * Get the output string that would result if the close is not found.
819 *
820 * @return string
821 */
822 function breakSyntax( $openingCount = false ) {
823 if ( $this->open == "\n" ) {
824 $s = $this->parts[0]->out;
825 } else {
826 if ( $openingCount === false ) {
827 $openingCount = $this->count;
828 }
829 $s = str_repeat( $this->open, $openingCount );
830 $first = true;
831 foreach ( $this->parts as $part ) {
832 if ( $first ) {
833 $first = false;
834 } else {
835 $s .= '|';
836 }
837 $s .= $part->out;
838 }
839 }
840 return $s;
841 }
842 }
843
844 /**
845 * @ingroup Parser
846 */
847 class PPDPart {
848 var $out; // Output accumulator string
849
850 // Optional member variables:
851 // eqpos Position of equals sign in output accumulator
852 // commentEnd Past-the-end input pointer for the last comment encountered
853 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
854
855 function __construct( $out = '' ) {
856 $this->out = $out;
857 }
858 }
859
860 /**
861 * An expansion frame, used as a context to expand the result of preprocessToObj()
862 * @ingroup Parser
863 */
864 class PPFrame_DOM implements PPFrame {
865
866 /**
867 * @var Preprocessor
868 */
869 var $preprocessor;
870
871 /**
872 * @var Parser
873 */
874 var $parser;
875
876 /**
877 * @var Title
878 */
879 var $title;
880 var $titleCache;
881
882 /**
883 * Hashtable listing templates which are disallowed for expansion in this frame,
884 * having been encountered previously in parent frames.
885 */
886 var $loopCheckHash;
887
888 /**
889 * Recursion depth of this frame, top = 0
890 * Note that this is NOT the same as expansion depth in expand()
891 */
892 var $depth;
893
894
895 /**
896 * Construct a new preprocessor frame.
897 * @param $preprocessor Preprocessor The parent preprocessor
898 */
899 function __construct( $preprocessor ) {
900 $this->preprocessor = $preprocessor;
901 $this->parser = $preprocessor->parser;
902 $this->title = $this->parser->mTitle;
903 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
904 $this->loopCheckHash = array();
905 $this->depth = 0;
906 }
907
908 /**
909 * Create a new child frame
910 * $args is optionally a multi-root PPNode or array containing the template arguments
911 *
912 * @return PPTemplateFrame_DOM
913 */
914 function newChild( $args = false, $title = false ) {
915 $namedArgs = array();
916 $numberedArgs = array();
917 if ( $title === false ) {
918 $title = $this->title;
919 }
920 if ( $args !== false ) {
921 $xpath = false;
922 if ( $args instanceof PPNode ) {
923 $args = $args->node;
924 }
925 foreach ( $args as $arg ) {
926 if ( !$xpath ) {
927 $xpath = new DOMXPath( $arg->ownerDocument );
928 }
929
930 $nameNodes = $xpath->query( 'name', $arg );
931 $value = $xpath->query( 'value', $arg );
932 if ( $nameNodes->item( 0 )->hasAttributes() ) {
933 // Numbered parameter
934 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
935 $numberedArgs[$index] = $value->item( 0 );
936 unset( $namedArgs[$index] );
937 } else {
938 // Named parameter
939 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
940 $namedArgs[$name] = $value->item( 0 );
941 unset( $numberedArgs[$name] );
942 }
943 }
944 }
945 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
946 }
947
948 /**
949 * @throws MWException
950 * @param $root
951 * @param $flags int
952 * @return string
953 */
954 function expand( $root, $flags = 0 ) {
955 static $expansionDepth = 0;
956 if ( is_string( $root ) ) {
957 return $root;
958 }
959
960 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
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 }