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