Adding/updating Persian translations
[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 $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 var $elementClass = 'PPDStackElement';
592
593 static $false = false;
594
595 function __construct() {
596 $this->stack = array();
597 $this->top = false;
598 $this->rootAccum = '';
599 $this->accum =& $this->rootAccum;
600 }
601
602 function count() {
603 return count( $this->stack );
604 }
605
606 function &getAccum() {
607 return $this->accum;
608 }
609
610 function getCurrentPart() {
611 if ( $this->top === false ) {
612 return false;
613 } else {
614 return $this->top->getCurrentPart();
615 }
616 }
617
618 function push( $data ) {
619 if ( $data instanceof $this->elementClass ) {
620 $this->stack[] = $data;
621 } else {
622 $class = $this->elementClass;
623 $this->stack[] = new $class( $data );
624 }
625 $this->top = $this->stack[ count( $this->stack ) - 1 ];
626 $this->accum =& $this->top->getAccum();
627 }
628
629 function pop() {
630 if ( !count( $this->stack ) ) {
631 throw new MWException( __METHOD__.': no elements remaining' );
632 }
633 $temp = array_pop( $this->stack );
634
635 if ( count( $this->stack ) ) {
636 $this->top = $this->stack[ count( $this->stack ) - 1 ];
637 $this->accum =& $this->top->getAccum();
638 } else {
639 $this->top = self::$false;
640 $this->accum =& $this->rootAccum;
641 }
642 return $temp;
643 }
644
645 function addPart( $s = '' ) {
646 $this->top->addPart( $s );
647 $this->accum =& $this->top->getAccum();
648 }
649
650 function getFlags() {
651 if ( !count( $this->stack ) ) {
652 return array(
653 'findEquals' => false,
654 'findPipe' => false,
655 'inHeading' => false,
656 );
657 } else {
658 return $this->top->getFlags();
659 }
660 }
661 }
662
663 class PPDStackElement {
664 var $open, // Opening character (\n for heading)
665 $close, // Matching closing character
666 $count, // Number of opening characters found (number of "=" for heading)
667 $parts, // Array of PPDPart objects describing pipe-separated parts.
668 $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
669
670 var $partClass = 'PPDPart';
671
672 function __construct( $data = array() ) {
673 $class = $this->partClass;
674 $this->parts = array( new $class );
675
676 foreach ( $data as $name => $value ) {
677 $this->$name = $value;
678 }
679 }
680
681 function &getAccum() {
682 return $this->parts[count($this->parts) - 1]->out;
683 }
684
685 function addPart( $s = '' ) {
686 $class = $this->partClass;
687 $this->parts[] = new $class( $s );
688 }
689
690 function getCurrentPart() {
691 return $this->parts[count($this->parts) - 1];
692 }
693
694 function getFlags() {
695 $partCount = count( $this->parts );
696 $findPipe = $this->open != "\n" && $this->open != '[';
697 return array(
698 'findPipe' => $findPipe,
699 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
700 'inHeading' => $this->open == "\n",
701 );
702 }
703
704 /**
705 * Get the output string that would result if the close is not found.
706 */
707 function breakSyntax( $openingCount = false ) {
708 if ( $this->open == "\n" ) {
709 $s = $this->parts[0]->out;
710 } else {
711 if ( $openingCount === false ) {
712 $openingCount = $this->count;
713 }
714 $s = str_repeat( $this->open, $openingCount );
715 $first = true;
716 foreach ( $this->parts as $part ) {
717 if ( $first ) {
718 $first = false;
719 } else {
720 $s .= '|';
721 }
722 $s .= $part->out;
723 }
724 }
725 return $s;
726 }
727 }
728
729 class PPDPart {
730 var $out; // Output accumulator string
731
732 // Optional member variables:
733 // eqpos Position of equals sign in output accumulator
734 // commentEnd Past-the-end input pointer for the last comment encountered
735 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
736
737 function __construct( $out = '' ) {
738 $this->out = $out;
739 }
740 }
741
742 /**
743 * An expansion frame, used as a context to expand the result of preprocessToObj()
744 */
745 class PPFrame_DOM implements PPFrame {
746 var $preprocessor, $parser, $title;
747 var $titleCache;
748
749 /**
750 * Hashtable listing templates which are disallowed for expansion in this frame,
751 * having been encountered previously in parent frames.
752 */
753 var $loopCheckHash;
754
755 /**
756 * Recursion depth of this frame, top = 0
757 */
758 var $depth;
759
760
761 /**
762 * Construct a new preprocessor frame.
763 * @param Preprocessor $preprocessor The parent preprocessor
764 */
765 function __construct( $preprocessor ) {
766 $this->preprocessor = $preprocessor;
767 $this->parser = $preprocessor->parser;
768 $this->title = $this->parser->mTitle;
769 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
770 $this->loopCheckHash = array();
771 $this->depth = 0;
772 }
773
774 /**
775 * Create a new child frame
776 * $args is optionally a multi-root PPNode or array containing the template arguments
777 */
778 function newChild( $args = false, $title = false ) {
779 $namedArgs = array();
780 $numberedArgs = array();
781 if ( $title === false ) {
782 $title = $this->title;
783 }
784 if ( $args !== false ) {
785 $xpath = false;
786 if ( $args instanceof PPNode ) {
787 $args = $args->node;
788 }
789 foreach ( $args as $arg ) {
790 if ( !$xpath ) {
791 $xpath = new DOMXPath( $arg->ownerDocument );
792 }
793
794 $nameNodes = $xpath->query( 'name', $arg );
795 $value = $xpath->query( 'value', $arg );
796 if ( $nameNodes->item( 0 )->hasAttributes() ) {
797 // Numbered parameter
798 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
799 $numberedArgs[$index] = $value->item( 0 );
800 unset( $namedArgs[$index] );
801 } else {
802 // Named parameter
803 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
804 $namedArgs[$name] = $value->item( 0 );
805 unset( $numberedArgs[$name] );
806 }
807 }
808 }
809 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
810 }
811
812 function expand( $root, $flags = 0 ) {
813 if ( is_string( $root ) ) {
814 return $root;
815 }
816
817 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
818 {
819 return '<span class="error">Node-count limit exceeded</span>';
820 }
821
822 if ( $root instanceof PPNode_DOM ) {
823 $root = $root->node;
824 }
825 if ( $root instanceof DOMDocument ) {
826 $root = $root->documentElement;
827 }
828
829 $outStack = array( '', '' );
830 $iteratorStack = array( false, $root );
831 $indexStack = array( 0, 0 );
832
833 while ( count( $iteratorStack ) > 1 ) {
834 $level = count( $outStack ) - 1;
835 $iteratorNode =& $iteratorStack[ $level ];
836 $out =& $outStack[$level];
837 $index =& $indexStack[$level];
838
839 if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
840
841 if ( is_array( $iteratorNode ) ) {
842 if ( $index >= count( $iteratorNode ) ) {
843 // All done with this iterator
844 $iteratorStack[$level] = false;
845 $contextNode = false;
846 } else {
847 $contextNode = $iteratorNode[$index];
848 $index++;
849 }
850 } elseif ( $iteratorNode instanceof DOMNodeList ) {
851 if ( $index >= $iteratorNode->length ) {
852 // All done with this iterator
853 $iteratorStack[$level] = false;
854 $contextNode = false;
855 } else {
856 $contextNode = $iteratorNode->item( $index );
857 $index++;
858 }
859 } else {
860 // Copy to $contextNode and then delete from iterator stack,
861 // because this is not an iterator but we do have to execute it once
862 $contextNode = $iteratorStack[$level];
863 $iteratorStack[$level] = false;
864 }
865
866 if ( $contextNode instanceof PPNode_DOM ) $contextNode = $contextNode->node;
867
868 $newIterator = false;
869
870 if ( $contextNode === false ) {
871 // nothing to do
872 } elseif ( is_string( $contextNode ) ) {
873 $out .= $contextNode;
874 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
875 $newIterator = $contextNode;
876 } elseif ( $contextNode instanceof DOMNode ) {
877 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
878 $out .= $contextNode->nodeValue;
879 } elseif ( $contextNode->nodeName == 'template' ) {
880 # Double-brace expansion
881 $xpath = new DOMXPath( $contextNode->ownerDocument );
882 $titles = $xpath->query( 'title', $contextNode );
883 $title = $titles->item( 0 );
884 $parts = $xpath->query( 'part', $contextNode );
885 if ( $flags & self::NO_TEMPLATES ) {
886 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
887 } else {
888 $lineStart = $contextNode->getAttribute( 'lineStart' );
889 $params = array(
890 'title' => new PPNode_DOM( $title ),
891 'parts' => new PPNode_DOM( $parts ),
892 'lineStart' => $lineStart );
893 $ret = $this->parser->braceSubstitution( $params, $this );
894 if ( isset( $ret['object'] ) ) {
895 $newIterator = $ret['object'];
896 } else {
897 $out .= $ret['text'];
898 }
899 }
900 } elseif ( $contextNode->nodeName == 'tplarg' ) {
901 # Triple-brace expansion
902 $xpath = new DOMXPath( $contextNode->ownerDocument );
903 $titles = $xpath->query( 'title', $contextNode );
904 $title = $titles->item( 0 );
905 $parts = $xpath->query( 'part', $contextNode );
906 if ( $flags & self::NO_ARGS ) {
907 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
908 } else {
909 $params = array(
910 'title' => new PPNode_DOM( $title ),
911 'parts' => new PPNode_DOM( $parts ) );
912 $ret = $this->parser->argSubstitution( $params, $this );
913 if ( isset( $ret['object'] ) ) {
914 $newIterator = $ret['object'];
915 } else {
916 $out .= $ret['text'];
917 }
918 }
919 } elseif ( $contextNode->nodeName == 'comment' ) {
920 # HTML-style comment
921 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
922 if ( $this->parser->ot['html']
923 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
924 || ( $flags & self::STRIP_COMMENTS ) )
925 {
926 $out .= '';
927 }
928 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
929 # Not in RECOVER_COMMENTS mode (extractSections) though
930 elseif ( $this->parser->ot['wiki'] && ! ( $flags & self::RECOVER_COMMENTS ) ) {
931 $out .= $this->parser->insertStripItem( $contextNode->textContent );
932 }
933 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
934 else {
935 $out .= $contextNode->textContent;
936 }
937 } elseif ( $contextNode->nodeName == 'ignore' ) {
938 # Output suppression used by <includeonly> etc.
939 # OT_WIKI will only respect <ignore> in substed templates.
940 # The other output types respect it unless NO_IGNORE is set.
941 # extractSections() sets NO_IGNORE and so never respects it.
942 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
943 $out .= $contextNode->textContent;
944 } else {
945 $out .= '';
946 }
947 } elseif ( $contextNode->nodeName == 'ext' ) {
948 # Extension tag
949 $xpath = new DOMXPath( $contextNode->ownerDocument );
950 $names = $xpath->query( 'name', $contextNode );
951 $attrs = $xpath->query( 'attr', $contextNode );
952 $inners = $xpath->query( 'inner', $contextNode );
953 $closes = $xpath->query( 'close', $contextNode );
954 $params = array(
955 'name' => new PPNode_DOM( $names->item( 0 ) ),
956 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
957 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
958 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
959 );
960 $out .= $this->parser->extensionSubstitution( $params, $this );
961 } elseif ( $contextNode->nodeName == 'h' ) {
962 # Heading
963 $s = $this->expand( $contextNode->childNodes, $flags );
964
965 # Insert a heading marker only for <h> children of <root>
966 # This is to stop extractSections from going over multiple tree levels
967 if ( $contextNode->parentNode->nodeName == 'root'
968 && $this->parser->ot['html'] )
969 {
970 # Insert heading index marker
971 $headingIndex = $contextNode->getAttribute( 'i' );
972 $titleText = $this->title->getPrefixedDBkey();
973 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
974 $serial = count( $this->parser->mHeadings ) - 1;
975 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
976 $count = $contextNode->getAttribute( 'level' );
977 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
978 $this->parser->mStripState->general->setPair( $marker, '' );
979 }
980 $out .= $s;
981 } else {
982 # Generic recursive expansion
983 $newIterator = $contextNode->childNodes;
984 }
985 } else {
986 throw new MWException( __METHOD__.': Invalid parameter type' );
987 }
988
989 if ( $newIterator !== false ) {
990 if ( $newIterator instanceof PPNode_DOM ) {
991 $newIterator = $newIterator->node;
992 }
993 $outStack[] = '';
994 $iteratorStack[] = $newIterator;
995 $indexStack[] = 0;
996 } elseif ( $iteratorStack[$level] === false ) {
997 // Return accumulated value to parent
998 // With tail recursion
999 while ( $iteratorStack[$level] === false && $level > 0 ) {
1000 $outStack[$level - 1] .= $out;
1001 array_pop( $outStack );
1002 array_pop( $iteratorStack );
1003 array_pop( $indexStack );
1004 $level--;
1005 }
1006 }
1007 }
1008 return $outStack[0];
1009 }
1010
1011 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1012 $args = array_slice( func_get_args(), 2 );
1013
1014 $first = true;
1015 $s = '';
1016 foreach ( $args as $root ) {
1017 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1018 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1019 $root = array( $root );
1020 }
1021 foreach ( $root as $node ) {
1022 if ( $first ) {
1023 $first = false;
1024 } else {
1025 $s .= $sep;
1026 }
1027 $s .= $this->expand( $node, $flags );
1028 }
1029 }
1030 return $s;
1031 }
1032
1033 /**
1034 * Implode with no flags specified
1035 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1036 */
1037 function implode( $sep /*, ... */ ) {
1038 $args = array_slice( func_get_args(), 1 );
1039
1040 $first = true;
1041 $s = '';
1042 foreach ( $args as $root ) {
1043 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1044 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1045 $root = array( $root );
1046 }
1047 foreach ( $root as $node ) {
1048 if ( $first ) {
1049 $first = false;
1050 } else {
1051 $s .= $sep;
1052 }
1053 $s .= $this->expand( $node );
1054 }
1055 }
1056 return $s;
1057 }
1058
1059 /**
1060 * Makes an object that, when expand()ed, will be the same as one obtained
1061 * with implode()
1062 */
1063 function virtualImplode( $sep /*, ... */ ) {
1064 $args = array_slice( func_get_args(), 1 );
1065 $out = array();
1066 $first = true;
1067 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1068
1069 foreach ( $args as $root ) {
1070 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1071 $root = array( $root );
1072 }
1073 foreach ( $root as $node ) {
1074 if ( $first ) {
1075 $first = false;
1076 } else {
1077 $out[] = $sep;
1078 }
1079 $out[] = $node;
1080 }
1081 }
1082 return $out;
1083 }
1084
1085 /**
1086 * Virtual implode with brackets
1087 */
1088 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1089 $args = array_slice( func_get_args(), 3 );
1090 $out = array( $start );
1091 $first = true;
1092
1093 foreach ( $args as $root ) {
1094 if ( $root instanceof PPNode_DOM ) $root = $root->node;
1095 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1096 $root = array( $root );
1097 }
1098 foreach ( $root as $node ) {
1099 if ( $first ) {
1100 $first = false;
1101 } else {
1102 $out[] = $sep;
1103 }
1104 $out[] = $node;
1105 }
1106 }
1107 $out[] = $end;
1108 return $out;
1109 }
1110
1111 function __toString() {
1112 return 'frame{}';
1113 }
1114
1115 function getPDBK( $level = false ) {
1116 if ( $level === false ) {
1117 return $this->title->getPrefixedDBkey();
1118 } else {
1119 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1120 }
1121 }
1122
1123 /**
1124 * Returns true if there are no arguments in this frame
1125 */
1126 function isEmpty() {
1127 return true;
1128 }
1129
1130 function getArgument( $name ) {
1131 return false;
1132 }
1133
1134 /**
1135 * Returns true if the infinite loop check is OK, false if a loop is detected
1136 */
1137 function loopCheck( $title ) {
1138 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1139 }
1140
1141 /**
1142 * Return true if the frame is a template frame
1143 */
1144 function isTemplate() {
1145 return false;
1146 }
1147 }
1148
1149 /**
1150 * Expansion frame with template arguments
1151 */
1152 class PPTemplateFrame_DOM extends PPFrame_DOM {
1153 var $numberedArgs, $namedArgs, $parent;
1154 var $numberedExpansionCache, $namedExpansionCache;
1155
1156 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1157 $this->preprocessor = $preprocessor;
1158 $this->parser = $preprocessor->parser;
1159 $this->parent = $parent;
1160 $this->numberedArgs = $numberedArgs;
1161 $this->namedArgs = $namedArgs;
1162 $this->title = $title;
1163 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1164 $this->titleCache = $parent->titleCache;
1165 $this->titleCache[] = $pdbk;
1166 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1167 if ( $pdbk !== false ) {
1168 $this->loopCheckHash[$pdbk] = true;
1169 }
1170 $this->depth = $parent->depth + 1;
1171 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1172 }
1173
1174 function __toString() {
1175 $s = 'tplframe{';
1176 $first = true;
1177 $args = $this->numberedArgs + $this->namedArgs;
1178 foreach ( $args as $name => $value ) {
1179 if ( $first ) {
1180 $first = false;
1181 } else {
1182 $s .= ', ';
1183 }
1184 $s .= "\"$name\":\"" .
1185 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1186 }
1187 $s .= '}';
1188 return $s;
1189 }
1190 /**
1191 * Returns true if there are no arguments in this frame
1192 */
1193 function isEmpty() {
1194 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1195 }
1196
1197 function getNumberedArgument( $index ) {
1198 if ( !isset( $this->numberedArgs[$index] ) ) {
1199 return false;
1200 }
1201 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1202 # No trimming for unnamed arguments
1203 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], self::STRIP_COMMENTS );
1204 }
1205 return $this->numberedExpansionCache[$index];
1206 }
1207
1208 function getNamedArgument( $name ) {
1209 if ( !isset( $this->namedArgs[$name] ) ) {
1210 return false;
1211 }
1212 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1213 # Trim named arguments post-expand, for backwards compatibility
1214 $this->namedExpansionCache[$name] = trim(
1215 $this->parent->expand( $this->namedArgs[$name], self::STRIP_COMMENTS ) );
1216 }
1217 return $this->namedExpansionCache[$name];
1218 }
1219
1220 function getArgument( $name ) {
1221 $text = $this->getNumberedArgument( $name );
1222 if ( $text === false ) {
1223 $text = $this->getNamedArgument( $name );
1224 }
1225 return $text;
1226 }
1227
1228 /**
1229 * Return true if the frame is a template frame
1230 */
1231 function isTemplate() {
1232 return true;
1233 }
1234 }
1235
1236 class PPNode_DOM implements PPNode {
1237 var $node;
1238
1239 function __construct( $node, $xpath = false ) {
1240 $this->node = $node;
1241 }
1242
1243 function __get( $name ) {
1244 if ( $name == 'xpath' ) {
1245 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1246 }
1247 return $this->xpath;
1248 }
1249
1250 function __toString() {
1251 if ( $this->node instanceof DOMNodeList ) {
1252 $s = '';
1253 foreach ( $this->node as $node ) {
1254 $s .= $node->ownerDocument->saveXML( $node );
1255 }
1256 } else {
1257 $s = $this->node->ownerDocument->saveXML( $this->node );
1258 }
1259 return $s;
1260 }
1261
1262 function getChildren() {
1263 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1264 }
1265
1266 function getFirstChild() {
1267 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1268 }
1269
1270 function getNextSibling() {
1271 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1272 }
1273
1274 function getChildrenOfType( $type ) {
1275 return new self( $this->xpath->query( $type, $this->node ) );
1276 }
1277
1278 function getLength() {
1279 if ( $this->node instanceof DOMNodeList ) {
1280 return $this->node->length;
1281 } else {
1282 return false;
1283 }
1284 }
1285
1286 function item( $i ) {
1287 $item = $this->node->item( $i );
1288 return $item ? new self( $item ) : false;
1289 }
1290
1291 function getName() {
1292 if ( $this->node instanceof DOMNodeList ) {
1293 return '#nodelist';
1294 } else {
1295 return $this->node->nodeName;
1296 }
1297 }
1298
1299 /**
1300 * Split a <part> node into an associative array containing:
1301 * name PPNode name
1302 * index String index
1303 * value PPNode value
1304 */
1305 function splitArg() {
1306 $names = $this->xpath->query( 'name', $this->node );
1307 $values = $this->xpath->query( 'value', $this->node );
1308 if ( !$names->length || !$values->length ) {
1309 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1310 }
1311 $name = $names->item( 0 );
1312 $index = $name->getAttribute( 'index' );
1313 return array(
1314 'name' => new self( $name ),
1315 'index' => $index,
1316 'value' => new self( $values->item( 0 ) ) );
1317 }
1318
1319 /**
1320 * Split an <ext> node into an associative array containing name, attr, inner and close
1321 * All values in the resulting array are PPNodes. Inner and close are optional.
1322 */
1323 function splitExt() {
1324 $names = $this->xpath->query( 'name', $this->node );
1325 $attrs = $this->xpath->query( 'attr', $this->node );
1326 $inners = $this->xpath->query( 'inner', $this->node );
1327 $closes = $this->xpath->query( 'close', $this->node );
1328 if ( !$names->length || !$attrs->length ) {
1329 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1330 }
1331 $parts = array(
1332 'name' => new self( $names->item( 0 ) ),
1333 'attr' => new self( $attrs->item( 0 ) ) );
1334 if ( $inners->length ) {
1335 $parts['inner'] = new self( $inners->item( 0 ) );
1336 }
1337 if ( $closes->length ) {
1338 $parts['close'] = new self( $closes->item( 0 ) );
1339 }
1340 return $parts;
1341 }
1342
1343 /**
1344 * Split a <h> node
1345 */
1346 function splitHeading() {
1347 if ( !$this->nodeName == 'h' ) {
1348 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1349 }
1350 return array(
1351 'i' => $this->node->getAttribute( 'i' ),
1352 'level' => $this->node->getAttribute( 'level' ),
1353 'contents' => $this->getChildren()
1354 );
1355 }
1356 }