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