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