Align arrows to top, but move down half a line, so it lines up
[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 //$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 $lowerName = strtolower( $name );
271 $attrStart = $i + strlen( $name ) + 1;
272
273 // Find end of tag
274 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
275 if ( $tagEndPos === false ) {
276 // Infinite backtrack
277 // Disable tag search to prevent worst-case O(N^2) performance
278 $noMoreGT = true;
279 $accum .= '&lt;';
280 ++$i;
281 continue;
282 }
283
284 // Handle ignored tags
285 if ( in_array( $lowerName, $ignoredTags ) ) {
286 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
287 $i = $tagEndPos + 1;
288 continue;
289 }
290
291 $tagStartPos = $i;
292 if ( $text[$tagEndPos-1] == '/' ) {
293 $attrEnd = $tagEndPos - 1;
294 $inner = null;
295 $i = $tagEndPos + 1;
296 $close = '';
297 } else {
298 $attrEnd = $tagEndPos;
299 // Find closing tag
300 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) ) {
301 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
302 $i = $matches[0][1] + strlen( $matches[0][0] );
303 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
304 } else {
305 // No end tag -- let it run out to the end of the text.
306 $inner = substr( $text, $tagEndPos + 1 );
307 $i = strlen( $text );
308 $close = '';
309 }
310 }
311 // <includeonly> and <noinclude> just become <ignore> tags
312 if ( in_array( $lowerName, $ignoredElements ) ) {
313 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
314 . '</ignore>';
315 continue;
316 }
317
318 $accum .= '<ext>';
319 if ( $attrEnd <= $attrStart ) {
320 $attr = '';
321 } else {
322 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
323 }
324 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
325 // Note that the attr element contains the whitespace between name and attribute,
326 // this is necessary for precise reconstruction during pre-save transform.
327 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
328 if ( $inner !== null ) {
329 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
330 }
331 $accum .= $close . '</ext>';
332 }
333
334 elseif ( $found == 'line-start' ) {
335 // Is this the start of a heading?
336 // Line break belongs before the heading element in any case
337 if ( $fakeLineStart ) {
338 $fakeLineStart = false;
339 } else {
340 $accum .= $curChar;
341 $i++;
342 }
343
344 $count = strspn( $text, '=', $i, 6 );
345 if ( $count == 1 && $findEquals ) {
346 // DWIM: This looks kind of like a name/value separator
347 // Let's let the equals handler have it and break the potential heading
348 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
349 } elseif ( $count > 0 ) {
350 $piece = array(
351 'open' => "\n",
352 'close' => "\n",
353 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
354 'startPos' => $i,
355 'count' => $count );
356 $stack->push( $piece );
357 $accum =& $stack->getAccum();
358 extract( $stack->getFlags() );
359 $i += $count;
360 }
361 }
362
363 elseif ( $found == 'line-end' ) {
364 $piece = $stack->top;
365 // A heading must be open, otherwise \n wouldn't have been in the search list
366 assert( $piece->open == "\n" );
367 $part = $piece->getCurrentPart();
368 // Search back through the input to see if it has a proper close
369 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
370 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
371 $searchStart = $i - $wsLength;
372 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
373 // Comment found at line end
374 // Search for equals signs before the comment
375 $searchStart = $part->visualEnd;
376 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
377 }
378 $count = $piece->count;
379 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
380 if ( $equalsLength > 0 ) {
381 if ( $i - $equalsLength == $piece->startPos ) {
382 // This is just a single string of equals signs on its own line
383 // Replicate the doHeadings behaviour /={count}(.+)={count}/
384 // First find out how many equals signs there really are (don't stop at 6)
385 $count = $equalsLength;
386 if ( $count < 3 ) {
387 $count = 0;
388 } else {
389 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
390 }
391 } else {
392 $count = min( $equalsLength, $count );
393 }
394 if ( $count > 0 ) {
395 // Normal match, output <h>
396 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
397 $headingIndex++;
398 } else {
399 // Single equals sign on its own line, count=0
400 $element = $accum;
401 }
402 } else {
403 // No match, no <h>, just pass down the inner text
404 $element = $accum;
405 }
406 // Unwind the stack
407 $stack->pop();
408 $accum =& $stack->getAccum();
409 extract( $stack->getFlags() );
410
411 // Append the result to the enclosing accumulator
412 $accum .= $element;
413 // Note that we do NOT increment the input pointer.
414 // This is because the closing linebreak could be the opening linebreak of
415 // another heading. Infinite loops are avoided because the next iteration MUST
416 // hit the heading open case above, which unconditionally increments the
417 // input pointer.
418 }
419
420 elseif ( $found == 'open' ) {
421 # count opening brace characters
422 $count = strspn( $text, $curChar, $i );
423
424 # we need to add to stack only if opening brace count is enough for one of the rules
425 if ( $count >= $rule['min'] ) {
426 # Add it to the stack
427 $piece = array(
428 'open' => $curChar,
429 'close' => $rule['end'],
430 'count' => $count,
431 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
432 );
433
434 $stack->push( $piece );
435 $accum =& $stack->getAccum();
436 extract( $stack->getFlags() );
437 } else {
438 # Add literal brace(s)
439 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
440 }
441 $i += $count;
442 }
443
444 elseif ( $found == 'close' ) {
445 $piece = $stack->top;
446 # lets check if there are enough characters for closing brace
447 $maxCount = $piece->count;
448 $count = strspn( $text, $curChar, $i, $maxCount );
449
450 # check for maximum matching characters (if there are 5 closing
451 # characters, we will probably need only 3 - depending on the rules)
452 $matchingCount = 0;
453 $rule = $rules[$piece->open];
454 if ( $count > $rule['max'] ) {
455 # The specified maximum exists in the callback array, unless the caller
456 # has made an error
457 $matchingCount = $rule['max'];
458 } else {
459 # Count is less than the maximum
460 # Skip any gaps in the callback array to find the true largest match
461 # Need to use array_key_exists not isset because the callback can be null
462 $matchingCount = $count;
463 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
464 --$matchingCount;
465 }
466 }
467
468 if ($matchingCount <= 0) {
469 # No matching element found in callback array
470 # Output a literal closing brace and continue
471 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
472 $i += $count;
473 continue;
474 }
475 $name = $rule['names'][$matchingCount];
476 if ( $name === null ) {
477 // No element, just literal text
478 $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
479 } else {
480 # Create XML element
481 # Note: $parts is already XML, does not need to be encoded further
482 $parts = $piece->parts;
483 $title = $parts[0]->out;
484 unset( $parts[0] );
485
486 # The invocation is at the start of the line if lineStart is set in
487 # the stack, and all opening brackets are used up.
488 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
489 $attr = ' lineStart="1"';
490 } else {
491 $attr = '';
492 }
493
494 $element = "<$name$attr>";
495 $element .= "<title>$title</title>";
496 $argIndex = 1;
497 foreach ( $parts as $partIndex => $part ) {
498 if ( isset( $part->eqpos ) ) {
499 $argName = substr( $part->out, 0, $part->eqpos );
500 $argValue = substr( $part->out, $part->eqpos + 1 );
501 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
502 } else {
503 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
504 $argIndex++;
505 }
506 }
507 $element .= "</$name>";
508 }
509
510 # Advance input pointer
511 $i += $matchingCount;
512
513 # Unwind the stack
514 $stack->pop();
515 $accum =& $stack->getAccum();
516
517 # Re-add the old stack element if it still has unmatched opening characters remaining
518 if ($matchingCount < $piece->count) {
519 $piece->parts = array( new PPDPart );
520 $piece->count -= $matchingCount;
521 # do we still qualify for any callback with remaining count?
522 $names = $rules[$piece->open]['names'];
523 $skippedBraces = 0;
524 $enclosingAccum =& $accum;
525 while ( $piece->count ) {
526 if ( array_key_exists( $piece->count, $names ) ) {
527 $stack->push( $piece );
528 $accum =& $stack->getAccum();
529 break;
530 }
531 --$piece->count;
532 $skippedBraces ++;
533 }
534 $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
535 }
536
537 extract( $stack->getFlags() );
538
539 # Add XML element to the enclosing accumulator
540 $accum .= $element;
541 }
542
543 elseif ( $found == 'pipe' ) {
544 $findEquals = true; // shortcut for getFlags()
545 $stack->addPart();
546 $accum =& $stack->getAccum();
547 ++$i;
548 }
549
550 elseif ( $found == 'equals' ) {
551 $findEquals = false; // shortcut for getFlags()
552 $stack->getCurrentPart()->eqpos = strlen( $accum );
553 $accum .= '=';
554 ++$i;
555 }
556 }
557
558 # Output any remaining unclosed brackets
559 foreach ( $stack->stack as $piece ) {
560 $stack->rootAccum .= $piece->breakSyntax();
561 }
562 $stack->rootAccum .= '</root>';
563 $xml = $stack->rootAccum;
564
565 wfProfileOut( __METHOD__.'-makexml' );
566 wfProfileIn( __METHOD__.'-loadXML' );
567 $dom = new DOMDocument;
568 wfSuppressWarnings();
569 $result = $dom->loadXML( $xml );
570 wfRestoreWarnings();
571 if ( !$result ) {
572 // Try running the XML through UtfNormal to get rid of invalid characters
573 $xml = UtfNormal::cleanUp( $xml );
574 $result = $dom->loadXML( $xml );
575 if ( !$result ) {
576 throw new MWException( __METHOD__.' generated invalid XML' );
577 }
578 }
579 $obj = new PPNode_DOM( $dom->documentElement );
580 wfProfileOut( __METHOD__.'-loadXML' );
581 wfProfileOut( __METHOD__ );
582 return $obj;
583 }
584 }
585
586 /**
587 * Stack class to help Preprocessor::preprocessToObj()
588 */
589 class PPDStack {
590 var $stack, $rootAccum, $top;
591 var $out;
592 var $elementClass = 'PPDStackElement';
593
594 static $false = false;
595
596 function __construct() {
597 $this->stack = array();
598 $this->top = false;
599 $this->rootAccum = '';
600 $this->accum =& $this->rootAccum;
601 }
602
603 function count() {
604 return count( $this->stack );
605 }
606
607 function &getAccum() {
608 return $this->accum;
609 }
610
611 function getCurrentPart() {
612 if ( $this->top === false ) {
613 return false;
614 } else {
615 return $this->top->getCurrentPart();
616 }
617 }
618
619 function push( $data ) {
620 if ( $data instanceof $this->elementClass ) {
621 $this->stack[] = $data;
622 } else {
623 $class = $this->elementClass;
624 $this->stack[] = new $class( $data );
625 }
626 $this->top = $this->stack[ count( $this->stack ) - 1 ];
627 $this->accum =& $this->top->getAccum();
628 }
629
630 function pop() {
631 if ( !count( $this->stack ) ) {
632 throw new MWException( __METHOD__.': no elements remaining' );
633 }
634 $temp = array_pop( $this->stack );
635
636 if ( count( $this->stack ) ) {
637 $this->top = $this->stack[ count( $this->stack ) - 1 ];
638 $this->accum =& $this->top->getAccum();
639 } else {
640 $this->top = self::$false;
641 $this->accum =& $this->rootAccum;
642 }
643 return $temp;
644 }
645
646 function addPart( $s = '' ) {
647 $this->top->addPart( $s );
648 $this->accum =& $this->top->getAccum();
649 }
650
651 function getFlags() {
652 if ( !count( $this->stack ) ) {
653 return array(
654 'findEquals' => false,
655 'findPipe' => false,
656 'inHeading' => false,
657 );
658 } else {
659 return $this->top->getFlags();
660 }
661 }
662 }
663
664 class PPDStackElement {
665 var $open, // Opening character (\n for heading)
666 $close, // Matching closing character
667 $count, // Number of opening characters found (number of "=" for heading)
668 $parts, // Array of PPDPart objects describing pipe-separated parts.
669 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
670
671 var $partClass = 'PPDPart';
672
673 function __construct( $data = array() ) {
674 $class = $this->partClass;
675 $this->parts = array( new $class );
676
677 foreach ( $data as $name => $value ) {
678 $this->$name = $value;
679 }
680 }
681
682 function &getAccum() {
683 return $this->parts[count($this->parts) - 1]->out;
684 }
685
686 function addPart( $s = '' ) {
687 $class = $this->partClass;
688 $this->parts[] = new $class( $s );
689 }
690
691 function getCurrentPart() {
692 return $this->parts[count($this->parts) - 1];
693 }
694
695 function getFlags() {
696 $partCount = count( $this->parts );
697 $findPipe = $this->open != "\n" && $this->open != '[';
698 return array(
699 'findPipe' => $findPipe,
700 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
701 'inHeading' => $this->open == "\n",
702 );
703 }
704
705 /**
706 * Get the output string that would result if the close is not found.
707 */
708 function breakSyntax( $openingCount = false ) {
709 if ( $this->open == "\n" ) {
710 $s = $this->parts[0]->out;
711 } else {
712 if ( $openingCount === false ) {
713 $openingCount = $this->count;
714 }
715 $s = str_repeat( $this->open, $openingCount );
716 $first = true;
717 foreach ( $this->parts as $part ) {
718 if ( $first ) {
719 $first = false;
720 } else {
721 $s .= '|';
722 }
723 $s .= $part->out;
724 }
725 }
726 return $s;
727 }
728 }
729
730 class PPDPart {
731 var $out; // Output accumulator string
732
733 // Optional member variables:
734 // eqpos Position of equals sign in output accumulator
735 // commentEnd Past-the-end input pointer for the last comment encountered
736 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
737
738 function __construct( $out = '' ) {
739 $this->out = $out;
740 }
741 }
742
743 /**
744 * An expansion frame, used as a context to expand the result of preprocessToObj()
745 */
746 class PPFrame_DOM implements PPFrame {
747 var $preprocessor, $parser, $title;
748 var $titleCache;
749
750 /**
751 * Hashtable listing templates which are disallowed for expansion in this frame,
752 * having been encountered previously in parent frames.
753 */
754 var $loopCheckHash;
755
756 /**
757 * Recursion depth of this frame, top = 0
758 */
759 var $depth;
760
761
762 /**
763 * Construct a new preprocessor frame.
764 * @param Preprocessor $preprocessor The parent preprocessor
765 */
766 function __construct( $preprocessor ) {
767 $this->preprocessor = $preprocessor;
768 $this->parser = $preprocessor->parser;
769 $this->title = $this->parser->mTitle;
770 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
771 $this->loopCheckHash = array();
772 $this->depth = 0;
773 }
774
775 /**
776 * Create a new child frame
777 * $args is optionally a multi-root PPNode or array containing the template arguments
778 */
779 function newChild( $args = false, $title = false ) {
780 $namedArgs = array();
781 $numberedArgs = array();
782 if ( $title === false ) {
783 $title = $this->title;
784 }
785 if ( $args !== false ) {
786 $xpath = false;
787 if ( $args instanceof PPNode ) {
788 $args = $args->node;
789 }
790 foreach ( $args as $arg ) {
791 if ( !$xpath ) {
792 $xpath = new DOMXPath( $arg->ownerDocument );
793 }
794
795 $nameNodes = $xpath->query( 'name', $arg );
796 $value = $xpath->query( 'value', $arg );
797 if ( $nameNodes->item( 0 )->hasAttributes() ) {
798 // Numbered parameter
799 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
800 $numberedArgs[$index] = $value->item( 0 );
801 unset( $namedArgs[$index] );
802 } else {
803 // Named parameter
804 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
805 $namedArgs[$name] = $value->item( 0 );
806 unset( $numberedArgs[$name] );
807 }
808 }
809 }
810 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
811 }
812
813 function expand( $root, $flags = 0 ) {
814 if ( is_string( $root ) ) {
815 return $root;
816 }
817
818 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
819 {
820 return '<span class="error">Node-count limit exceeded</span>';
821 }
822
823 if ( $root instanceof PPNode_DOM ) {
824 $root = $root->node;
825 }
826 if ( $root instanceof DOMDocument ) {
827 $root = $root->documentElement;
828 }
829
830 $outStack = array( '', '' );
831 $iteratorStack = array( false, $root );
832 $indexStack = array( 0, 0 );
833
834 while ( count( $iteratorStack ) > 1 ) {
835 $level = count( $outStack ) - 1;
836 $iteratorNode =& $iteratorStack[ $level ];
837 $out =& $outStack[$level];
838 $index =& $indexStack[$level];
839
840 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
841
842 if ( is_array( $iteratorNode ) ) {
843 if ( $index >= count( $iteratorNode ) ) {
844 // All done with this iterator
845 $iteratorStack[$level] = false;
846 $contextNode = false;
847 } else {
848 $contextNode = $iteratorNode[$index];
849 $index++;
850 }
851 } elseif ( $iteratorNode instanceof DOMNodeList ) {
852 if ( $index >= $iteratorNode->length ) {
853 // All done with this iterator
854 $iteratorStack[$level] = false;
855 $contextNode = false;
856 } else {
857 $contextNode = $iteratorNode->item( $index );
858 $index++;
859 }
860 } else {
861 // Copy to $contextNode and then delete from iterator stack,
862 // because this is not an iterator but we do have to execute it once
863 $contextNode = $iteratorStack[$level];
864 $iteratorStack[$level] = false;
865 }
866
867 if ( $contextNode instanceof PPNode_DOM ) $contextNode = $contextNode->node;
868
869 $newIterator = false;
870
871 if ( $contextNode === false ) {
872 // nothing to do
873 } elseif ( is_string( $contextNode ) ) {
874 $out .= $contextNode;
875 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
876 $newIterator = $contextNode;
877 } elseif ( $contextNode instanceof DOMNode ) {
878 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
879 $out .= $contextNode->nodeValue;
880 } elseif ( $contextNode->nodeName == 'template' ) {
881 # Double-brace expansion
882 $xpath = new DOMXPath( $contextNode->ownerDocument );
883 $titles = $xpath->query( 'title', $contextNode );
884 $title = $titles->item( 0 );
885 $parts = $xpath->query( 'part', $contextNode );
886 if ( $flags & self::NO_TEMPLATES ) {
887 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
888 } else {
889 $lineStart = $contextNode->getAttribute( 'lineStart' );
890 $params = array(
891 'title' => new PPNode_DOM( $title ),
892 'parts' => new PPNode_DOM( $parts ),
893 'lineStart' => $lineStart );
894 $ret = $this->parser->braceSubstitution( $params, $this );
895 if ( isset( $ret['object'] ) ) {
896 $newIterator = $ret['object'];
897 } else {
898 $out .= $ret['text'];
899 }
900 }
901 } elseif ( $contextNode->nodeName == 'tplarg' ) {
902 # Triple-brace expansion
903 $xpath = new DOMXPath( $contextNode->ownerDocument );
904 $titles = $xpath->query( 'title', $contextNode );
905 $title = $titles->item( 0 );
906 $parts = $xpath->query( 'part', $contextNode );
907 if ( $flags & self::NO_ARGS ) {
908 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
909 } else {
910 $params = array(
911 'title' => new PPNode_DOM( $title ),
912 'parts' => new PPNode_DOM( $parts ) );
913 $ret = $this->parser->argSubstitution( $params, $this );
914 if ( isset( $ret['object'] ) ) {
915 $newIterator = $ret['object'];
916 } else {
917 $out .= $ret['text'];
918 }
919 }
920 } elseif ( $contextNode->nodeName == 'comment' ) {
921 # HTML-style comment
922 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
923 if ( $this->parser->ot['html']
924 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
925 || ( $flags & self::STRIP_COMMENTS ) )
926 {
927 $out .= '';
928 }
929 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
930 # Not in RECOVER_COMMENTS mode (extractSections) though
931 elseif ( $this->parser->ot['wiki'] && ! ( $flags & self::RECOVER_COMMENTS ) ) {
932 $out .= $this->parser->insertStripItem( $contextNode->textContent );
933 }
934 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
935 else {
936 $out .= $contextNode->textContent;
937 }
938 } elseif ( $contextNode->nodeName == 'ignore' ) {
939 # Output suppression used by <includeonly> etc.
940 # OT_WIKI will only respect <ignore> in substed templates.
941 # The other output types respect it unless NO_IGNORE is set.
942 # extractSections() sets NO_IGNORE and so never respects it.
943 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
944 $out .= $contextNode->textContent;
945 } else {
946 $out .= '';
947 }
948 } elseif ( $contextNode->nodeName == 'ext' ) {
949 # Extension tag
950 $xpath = new DOMXPath( $contextNode->ownerDocument );
951 $names = $xpath->query( 'name', $contextNode );
952 $attrs = $xpath->query( 'attr', $contextNode );
953 $inners = $xpath->query( 'inner', $contextNode );
954 $closes = $xpath->query( 'close', $contextNode );
955 $params = array(
956 'name' => new PPNode_DOM( $names->item( 0 ) ),
957 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
958 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
959 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
960 );
961 $out .= $this->parser->extensionSubstitution( $params, $this );
962 } elseif ( $contextNode->nodeName == 'h' ) {
963 # Heading
964 $s = $this->expand( $contextNode->childNodes, $flags );
965
966 # Insert a heading marker only for <h> children of <root>
967 # This is to stop extractSections from going over multiple tree levels
968 if ( $contextNode->parentNode->nodeName == 'root'
969 && $this->parser->ot['html'] )
970 {
971 # Insert heading index marker
972 $headingIndex = $contextNode->getAttribute( 'i' );
973 $titleText = $this->title->getPrefixedDBkey();
974 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
975 $serial = count( $this->parser->mHeadings ) - 1;
976 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
977 $count = $contextNode->getAttribute( 'level' );
978 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
979 $this->parser->mStripState->general->setPair( $marker, '' );
980 }
981 $out .= $s;
982 } else {
983 # Generic recursive expansion
984 $newIterator = $contextNode->childNodes;
985 }
986 } else {
987 throw new MWException( __METHOD__.': Invalid parameter type' );
988 }
989
990 if ( $newIterator !== false ) {
991 if ( $newIterator instanceof PPNode_DOM ) {
992 $newIterator = $newIterator->node;
993 }
994 $outStack[] = '';
995 $iteratorStack[] = $newIterator;
996 $indexStack[] = 0;
997 } elseif ( $iteratorStack[$level] === false ) {
998 // Return accumulated value to parent
999 // With tail recursion
1000 while ( $iteratorStack[$level] === false && $level > 0 ) {
1001 $outStack[$level - 1] .= $out;
1002 array_pop( $outStack );
1003 array_pop( $iteratorStack );
1004 array_pop( $indexStack );
1005 $level--;
1006 }
1007 }
1008 }
1009 return $outStack[0];
1010 }
1011
1012 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1013 $args = array_slice( func_get_args(), 2 );
1014
1015 $first = true;
1016 $s = '';
1017 foreach ( $args as $root ) {
1018 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1019 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1020 $root = array( $root );
1021 }
1022 foreach ( $root as $node ) {
1023 if ( $first ) {
1024 $first = false;
1025 } else {
1026 $s .= $sep;
1027 }
1028 $s .= $this->expand( $node, $flags );
1029 }
1030 }
1031 return $s;
1032 }
1033
1034 /**
1035 * Implode with no flags specified
1036 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1037 */
1038 function implode( $sep /*, ... */ ) {
1039 $args = array_slice( func_get_args(), 1 );
1040
1041 $first = true;
1042 $s = '';
1043 foreach ( $args as $root ) {
1044 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1045 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1046 $root = array( $root );
1047 }
1048 foreach ( $root as $node ) {
1049 if ( $first ) {
1050 $first = false;
1051 } else {
1052 $s .= $sep;
1053 }
1054 $s .= $this->expand( $node );
1055 }
1056 }
1057 return $s;
1058 }
1059
1060 /**
1061 * Makes an object that, when expand()ed, will be the same as one obtained
1062 * with implode()
1063 */
1064 function virtualImplode( $sep /*, ... */ ) {
1065 $args = array_slice( func_get_args(), 1 );
1066 $out = array();
1067 $first = true;
1068 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1069
1070 foreach ( $args as $root ) {
1071 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1072 $root = array( $root );
1073 }
1074 foreach ( $root as $node ) {
1075 if ( $first ) {
1076 $first = false;
1077 } else {
1078 $out[] = $sep;
1079 }
1080 $out[] = $node;
1081 }
1082 }
1083 return $out;
1084 }
1085
1086 /**
1087 * Virtual implode with brackets
1088 */
1089 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1090 $args = array_slice( func_get_args(), 3 );
1091 $out = array( $start );
1092 $first = true;
1093
1094 foreach ( $args as $root ) {
1095 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1096 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1097 $root = array( $root );
1098 }
1099 foreach ( $root as $node ) {
1100 if ( $first ) {
1101 $first = false;
1102 } else {
1103 $out[] = $sep;
1104 }
1105 $out[] = $node;
1106 }
1107 }
1108 $out[] = $end;
1109 return $out;
1110 }
1111
1112 function __toString() {
1113 return 'frame{}';
1114 }
1115
1116 function getPDBK( $level = false ) {
1117 if ( $level === false ) {
1118 return $this->title->getPrefixedDBkey();
1119 } else {
1120 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1121 }
1122 }
1123
1124 /**
1125 * Returns true if there are no arguments in this frame
1126 */
1127 function isEmpty() {
1128 return true;
1129 }
1130
1131 function getArgument( $name ) {
1132 return false;
1133 }
1134
1135 /**
1136 * Returns true if the infinite loop check is OK, false if a loop is detected
1137 */
1138 function loopCheck( $title ) {
1139 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1140 }
1141
1142 /**
1143 * Return true if the frame is a template frame
1144 */
1145 function isTemplate() {
1146 return false;
1147 }
1148 }
1149
1150 /**
1151 * Expansion frame with template arguments
1152 */
1153 class PPTemplateFrame_DOM extends PPFrame_DOM {
1154 var $numberedArgs, $namedArgs, $parent;
1155 var $numberedExpansionCache, $namedExpansionCache;
1156
1157 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1158 $this->preprocessor = $preprocessor;
1159 $this->parser = $preprocessor->parser;
1160 $this->parent = $parent;
1161 $this->numberedArgs = $numberedArgs;
1162 $this->namedArgs = $namedArgs;
1163 $this->title = $title;
1164 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1165 $this->titleCache = $parent->titleCache;
1166 $this->titleCache[] = $pdbk;
1167 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1168 if ( $pdbk !== false ) {
1169 $this->loopCheckHash[$pdbk] = true;
1170 }
1171 $this->depth = $parent->depth + 1;
1172 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1173 }
1174
1175 function __toString() {
1176 $s = 'tplframe{';
1177 $first = true;
1178 $args = $this->numberedArgs + $this->namedArgs;
1179 foreach ( $args as $name => $value ) {
1180 if ( $first ) {
1181 $first = false;
1182 } else {
1183 $s .= ', ';
1184 }
1185 $s .= "\"$name\":\"" .
1186 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1187 }
1188 $s .= '}';
1189 return $s;
1190 }
1191 /**
1192 * Returns true if there are no arguments in this frame
1193 */
1194 function isEmpty() {
1195 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1196 }
1197
1198 function getNumberedArgument( $index ) {
1199 if ( !isset( $this->numberedArgs[$index] ) ) {
1200 return false;
1201 }
1202 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1203 # No trimming for unnamed arguments
1204 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], self::STRIP_COMMENTS );
1205 }
1206 return $this->numberedExpansionCache[$index];
1207 }
1208
1209 function getNamedArgument( $name ) {
1210 if ( !isset( $this->namedArgs[$name] ) ) {
1211 return false;
1212 }
1213 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1214 # Trim named arguments post-expand, for backwards compatibility
1215 $this->namedExpansionCache[$name] = trim(
1216 $this->parent->expand( $this->namedArgs[$name], self::STRIP_COMMENTS ) );
1217 }
1218 return $this->namedExpansionCache[$name];
1219 }
1220
1221 function getArgument( $name ) {
1222 $text = $this->getNumberedArgument( $name );
1223 if ( $text === false ) {
1224 $text = $this->getNamedArgument( $name );
1225 }
1226 return $text;
1227 }
1228
1229 /**
1230 * Return true if the frame is a template frame
1231 */
1232 function isTemplate() {
1233 return true;
1234 }
1235 }
1236
1237 class PPNode_DOM implements PPNode {
1238 var $node;
1239
1240 function __construct( $node, $xpath = false ) {
1241 $this->node = $node;
1242 }
1243
1244 function __get( $name ) {
1245 if ( $name == 'xpath' ) {
1246 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1247 }
1248 return $this->xpath;
1249 }
1250
1251 function __toString() {
1252 if ( $this->node instanceof DOMNodeList ) {
1253 $s = '';
1254 foreach ( $this->node as $node ) {
1255 $s .= $node->ownerDocument->saveXML( $node );
1256 }
1257 } else {
1258 $s = $this->node->ownerDocument->saveXML( $this->node );
1259 }
1260 return $s;
1261 }
1262
1263 function getChildren() {
1264 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1265 }
1266
1267 function getFirstChild() {
1268 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1269 }
1270
1271 function getNextSibling() {
1272 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1273 }
1274
1275 function getChildrenOfType( $type ) {
1276 return new self( $this->xpath->query( $type, $this->node ) );
1277 }
1278
1279 function getLength() {
1280 if ( $this->node instanceof DOMNodeList ) {
1281 return $this->node->length;
1282 } else {
1283 return false;
1284 }
1285 }
1286
1287 function item( $i ) {
1288 $item = $this->node->item( $i );
1289 return $item ? new self( $item ) : false;
1290 }
1291
1292 function getName() {
1293 if ( $this->node instanceof DOMNodeList ) {
1294 return '#nodelist';
1295 } else {
1296 return $this->node->nodeName;
1297 }
1298 }
1299
1300 /**
1301 * Split a <part> node into an associative array containing:
1302 * name PPNode name
1303 * index String index
1304 * value PPNode value
1305 */
1306 function splitArg() {
1307 $names = $this->xpath->query( 'name', $this->node );
1308 $values = $this->xpath->query( 'value', $this->node );
1309 if ( !$names->length || !$values->length ) {
1310 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1311 }
1312 $name = $names->item( 0 );
1313 $index = $name->getAttribute( 'index' );
1314 return array(
1315 'name' => new self( $name ),
1316 'index' => $index,
1317 'value' => new self( $values->item( 0 ) ) );
1318 }
1319
1320 /**
1321 * Split an <ext> node into an associative array containing name, attr, inner and close
1322 * All values in the resulting array are PPNodes. Inner and close are optional.
1323 */
1324 function splitExt() {
1325 $names = $this->xpath->query( 'name', $this->node );
1326 $attrs = $this->xpath->query( 'attr', $this->node );
1327 $inners = $this->xpath->query( 'inner', $this->node );
1328 $closes = $this->xpath->query( 'close', $this->node );
1329 if ( !$names->length || !$attrs->length ) {
1330 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1331 }
1332 $parts = array(
1333 'name' => new self( $names->item( 0 ) ),
1334 'attr' => new self( $attrs->item( 0 ) ) );
1335 if ( $inners->length ) {
1336 $parts['inner'] = new self( $inners->item( 0 ) );
1337 }
1338 if ( $closes->length ) {
1339 $parts['close'] = new self( $closes->item( 0 ) );
1340 }
1341 return $parts;
1342 }
1343
1344 /**
1345 * Split a <h> node
1346 */
1347 function splitHeading() {
1348 if ( !$this->nodeName == 'h' ) {
1349 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1350 }
1351 return array(
1352 'i' => $this->node->getAttribute( 'i' ),
1353 'level' => $this->node->getAttribute( 'level' ),
1354 'contents' => $this->getChildren()
1355 );
1356 }
1357 }