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