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