Various documentation updates for includes/parser/
[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 * @param bool|int $openingCount
913 * @return string
914 */
915 function breakSyntax( $openingCount = false ) {
916 if ( $this->open == "\n" ) {
917 $s = $this->parts[0]->out;
918 } else {
919 if ( $openingCount === false ) {
920 $openingCount = $this->count;
921 }
922 $s = str_repeat( $this->open, $openingCount );
923 $first = true;
924 foreach ( $this->parts as $part ) {
925 if ( $first ) {
926 $first = false;
927 } else {
928 $s .= '|';
929 }
930 $s .= $part->out;
931 }
932 }
933 return $s;
934 }
935 }
936
937 /**
938 * @ingroup Parser
939 */
940 class PPDPart {
941 /** @var string */
942 public $out;
943
944 // Optional member variables:
945 // eqpos Position of equals sign in output accumulator
946 // commentEnd Past-the-end input pointer for the last comment encountered
947 // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
948
949 function __construct( $out = '' ) {
950 $this->out = $out;
951 }
952 }
953
954 /**
955 * An expansion frame, used as a context to expand the result of preprocessToObj()
956 * @ingroup Parser
957 */
958 class PPFrame_DOM implements PPFrame {
959 /** @var array */
960 public $titleCache;
961
962 /**
963 * @var array Hashtable listing templates which are disallowed for expansion
964 * in this frame, having been encountered previously in parent frames.
965 */
966 public $loopCheckHash;
967
968 /**
969 * @var int Recursion depth of this frame, top = 0.
970 * Note that this is NOT the same as expansion depth in expand()
971 */
972 public $depth;
973
974 /** @var Preprocessor */
975 protected $preprocessor;
976
977 /** @var Parser */
978 protected $parser;
979
980 /** @var Title */
981 protected $title;
982
983 /**
984 * Construct a new preprocessor frame.
985 * @param Preprocessor $preprocessor The parent preprocessor
986 */
987 function __construct( $preprocessor ) {
988 $this->preprocessor = $preprocessor;
989 $this->parser = $preprocessor->parser;
990 $this->title = $this->parser->mTitle;
991 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
992 $this->loopCheckHash = array();
993 $this->depth = 0;
994 }
995
996 /**
997 * Create a new child frame
998 * $args is optionally a multi-root PPNode or array containing the template arguments
999 *
1000 * @param bool|array $args
1001 * @param Title|bool $title
1002 * @param int $indexOffset
1003 * @return PPTemplateFrame_DOM
1004 */
1005 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1006 $namedArgs = array();
1007 $numberedArgs = array();
1008 if ( $title === false ) {
1009 $title = $this->title;
1010 }
1011 if ( $args !== false ) {
1012 $xpath = false;
1013 if ( $args instanceof PPNode ) {
1014 $args = $args->node;
1015 }
1016 foreach ( $args as $arg ) {
1017 if ( $arg instanceof PPNode ) {
1018 $arg = $arg->node;
1019 }
1020 if ( !$xpath ) {
1021 $xpath = new DOMXPath( $arg->ownerDocument );
1022 }
1023
1024 $nameNodes = $xpath->query( 'name', $arg );
1025 $value = $xpath->query( 'value', $arg );
1026 if ( $nameNodes->item( 0 )->hasAttributes() ) {
1027 // Numbered parameter
1028 $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
1029 $index = $index - $indexOffset;
1030 $numberedArgs[$index] = $value->item( 0 );
1031 unset( $namedArgs[$index] );
1032 } else {
1033 // Named parameter
1034 $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
1035 $namedArgs[$name] = $value->item( 0 );
1036 unset( $numberedArgs[$name] );
1037 }
1038 }
1039 }
1040 return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1041 }
1042
1043 /**
1044 * @throws MWException
1045 * @param string|PPNode_DOM|DOMDocument $root
1046 * @param int $flags
1047 * @return string
1048 */
1049 function expand( $root, $flags = 0 ) {
1050 static $expansionDepth = 0;
1051 if ( is_string( $root ) ) {
1052 return $root;
1053 }
1054
1055 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1056 $this->parser->limitationWarn( 'node-count-exceeded',
1057 $this->parser->mPPNodeCount,
1058 $this->parser->mOptions->getMaxPPNodeCount()
1059 );
1060 return '<span class="error">Node-count limit exceeded</span>';
1061 }
1062
1063 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1064 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1065 $expansionDepth,
1066 $this->parser->mOptions->getMaxPPExpandDepth()
1067 );
1068 return '<span class="error">Expansion depth limit exceeded</span>';
1069 }
1070 wfProfileIn( __METHOD__ );
1071 ++$expansionDepth;
1072 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1073 $this->parser->mHighestExpansionDepth = $expansionDepth;
1074 }
1075
1076 if ( $root instanceof PPNode_DOM ) {
1077 $root = $root->node;
1078 }
1079 if ( $root instanceof DOMDocument ) {
1080 $root = $root->documentElement;
1081 }
1082
1083 $outStack = array( '', '' );
1084 $iteratorStack = array( false, $root );
1085 $indexStack = array( 0, 0 );
1086
1087 while ( count( $iteratorStack ) > 1 ) {
1088 $level = count( $outStack ) - 1;
1089 $iteratorNode =& $iteratorStack[$level];
1090 $out =& $outStack[$level];
1091 $index =& $indexStack[$level];
1092
1093 if ( $iteratorNode instanceof PPNode_DOM ) {
1094 $iteratorNode = $iteratorNode->node;
1095 }
1096
1097 if ( is_array( $iteratorNode ) ) {
1098 if ( $index >= count( $iteratorNode ) ) {
1099 // All done with this iterator
1100 $iteratorStack[$level] = false;
1101 $contextNode = false;
1102 } else {
1103 $contextNode = $iteratorNode[$index];
1104 $index++;
1105 }
1106 } elseif ( $iteratorNode instanceof DOMNodeList ) {
1107 if ( $index >= $iteratorNode->length ) {
1108 // All done with this iterator
1109 $iteratorStack[$level] = false;
1110 $contextNode = false;
1111 } else {
1112 $contextNode = $iteratorNode->item( $index );
1113 $index++;
1114 }
1115 } else {
1116 // Copy to $contextNode and then delete from iterator stack,
1117 // because this is not an iterator but we do have to execute it once
1118 $contextNode = $iteratorStack[$level];
1119 $iteratorStack[$level] = false;
1120 }
1121
1122 if ( $contextNode instanceof PPNode_DOM ) {
1123 $contextNode = $contextNode->node;
1124 }
1125
1126 $newIterator = false;
1127
1128 if ( $contextNode === false ) {
1129 // nothing to do
1130 } elseif ( is_string( $contextNode ) ) {
1131 $out .= $contextNode;
1132 } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
1133 $newIterator = $contextNode;
1134 } elseif ( $contextNode instanceof DOMNode ) {
1135 if ( $contextNode->nodeType == XML_TEXT_NODE ) {
1136 $out .= $contextNode->nodeValue;
1137 } elseif ( $contextNode->nodeName == 'template' ) {
1138 # Double-brace expansion
1139 $xpath = new DOMXPath( $contextNode->ownerDocument );
1140 $titles = $xpath->query( 'title', $contextNode );
1141 $title = $titles->item( 0 );
1142 $parts = $xpath->query( 'part', $contextNode );
1143 if ( $flags & PPFrame::NO_TEMPLATES ) {
1144 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
1145 } else {
1146 $lineStart = $contextNode->getAttribute( 'lineStart' );
1147 $params = array(
1148 'title' => new PPNode_DOM( $title ),
1149 'parts' => new PPNode_DOM( $parts ),
1150 'lineStart' => $lineStart );
1151 $ret = $this->parser->braceSubstitution( $params, $this );
1152 if ( isset( $ret['object'] ) ) {
1153 $newIterator = $ret['object'];
1154 } else {
1155 $out .= $ret['text'];
1156 }
1157 }
1158 } elseif ( $contextNode->nodeName == 'tplarg' ) {
1159 # Triple-brace expansion
1160 $xpath = new DOMXPath( $contextNode->ownerDocument );
1161 $titles = $xpath->query( 'title', $contextNode );
1162 $title = $titles->item( 0 );
1163 $parts = $xpath->query( 'part', $contextNode );
1164 if ( $flags & PPFrame::NO_ARGS ) {
1165 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
1166 } else {
1167 $params = array(
1168 'title' => new PPNode_DOM( $title ),
1169 'parts' => new PPNode_DOM( $parts ) );
1170 $ret = $this->parser->argSubstitution( $params, $this );
1171 if ( isset( $ret['object'] ) ) {
1172 $newIterator = $ret['object'];
1173 } else {
1174 $out .= $ret['text'];
1175 }
1176 }
1177 } elseif ( $contextNode->nodeName == 'comment' ) {
1178 # HTML-style comment
1179 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1180 if ( $this->parser->ot['html']
1181 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1182 || ( $flags & PPFrame::STRIP_COMMENTS )
1183 ) {
1184 $out .= '';
1185 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1186 # Add a strip marker in PST mode so that pstPass2() can
1187 # run some old-fashioned regexes on the result.
1188 # Not in RECOVER_COMMENTS mode (extractSections) though.
1189 $out .= $this->parser->insertStripItem( $contextNode->textContent );
1190 } else {
1191 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1192 $out .= $contextNode->textContent;
1193 }
1194 } elseif ( $contextNode->nodeName == 'ignore' ) {
1195 # Output suppression used by <includeonly> etc.
1196 # OT_WIKI will only respect <ignore> in substed templates.
1197 # The other output types respect it unless NO_IGNORE is set.
1198 # extractSections() sets NO_IGNORE and so never respects it.
1199 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1200 || ( $flags & PPFrame::NO_IGNORE )
1201 ) {
1202 $out .= $contextNode->textContent;
1203 } else {
1204 $out .= '';
1205 }
1206 } elseif ( $contextNode->nodeName == 'ext' ) {
1207 # Extension tag
1208 $xpath = new DOMXPath( $contextNode->ownerDocument );
1209 $names = $xpath->query( 'name', $contextNode );
1210 $attrs = $xpath->query( 'attr', $contextNode );
1211 $inners = $xpath->query( 'inner', $contextNode );
1212 $closes = $xpath->query( 'close', $contextNode );
1213 $params = array(
1214 'name' => new PPNode_DOM( $names->item( 0 ) ),
1215 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
1216 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
1217 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
1218 );
1219 $out .= $this->parser->extensionSubstitution( $params, $this );
1220 } elseif ( $contextNode->nodeName == 'h' ) {
1221 # Heading
1222 $s = $this->expand( $contextNode->childNodes, $flags );
1223
1224 # Insert a heading marker only for <h> children of <root>
1225 # This is to stop extractSections from going over multiple tree levels
1226 if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html'] ) {
1227 # Insert heading index marker
1228 $headingIndex = $contextNode->getAttribute( 'i' );
1229 $titleText = $this->title->getPrefixedDBkey();
1230 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
1231 $serial = count( $this->parser->mHeadings ) - 1;
1232 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1233 $count = $contextNode->getAttribute( 'level' );
1234 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
1235 $this->parser->mStripState->addGeneral( $marker, '' );
1236 }
1237 $out .= $s;
1238 } else {
1239 # Generic recursive expansion
1240 $newIterator = $contextNode->childNodes;
1241 }
1242 } else {
1243 wfProfileOut( __METHOD__ );
1244 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1245 }
1246
1247 if ( $newIterator !== false ) {
1248 if ( $newIterator instanceof PPNode_DOM ) {
1249 $newIterator = $newIterator->node;
1250 }
1251 $outStack[] = '';
1252 $iteratorStack[] = $newIterator;
1253 $indexStack[] = 0;
1254 } elseif ( $iteratorStack[$level] === false ) {
1255 // Return accumulated value to parent
1256 // With tail recursion
1257 while ( $iteratorStack[$level] === false && $level > 0 ) {
1258 $outStack[$level - 1] .= $out;
1259 array_pop( $outStack );
1260 array_pop( $iteratorStack );
1261 array_pop( $indexStack );
1262 $level--;
1263 }
1264 }
1265 }
1266 --$expansionDepth;
1267 wfProfileOut( __METHOD__ );
1268 return $outStack[0];
1269 }
1270
1271 /**
1272 * @param string $sep
1273 * @param int $flags
1274 * @return string
1275 */
1276 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1277 $args = array_slice( func_get_args(), 2 );
1278
1279 $first = true;
1280 $s = '';
1281 foreach ( $args as $root ) {
1282 if ( $root instanceof PPNode_DOM ) {
1283 $root = $root->node;
1284 }
1285 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1286 $root = array( $root );
1287 }
1288 foreach ( $root as $node ) {
1289 if ( $first ) {
1290 $first = false;
1291 } else {
1292 $s .= $sep;
1293 }
1294 $s .= $this->expand( $node, $flags );
1295 }
1296 }
1297 return $s;
1298 }
1299
1300 /**
1301 * Implode with no flags specified
1302 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1303 *
1304 * @param string $sep
1305 * @return string
1306 */
1307 function implode( $sep /*, ... */ ) {
1308 $args = array_slice( func_get_args(), 1 );
1309
1310 $first = true;
1311 $s = '';
1312 foreach ( $args as $root ) {
1313 if ( $root instanceof PPNode_DOM ) {
1314 $root = $root->node;
1315 }
1316 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1317 $root = array( $root );
1318 }
1319 foreach ( $root as $node ) {
1320 if ( $first ) {
1321 $first = false;
1322 } else {
1323 $s .= $sep;
1324 }
1325 $s .= $this->expand( $node );
1326 }
1327 }
1328 return $s;
1329 }
1330
1331 /**
1332 * Makes an object that, when expand()ed, will be the same as one obtained
1333 * with implode()
1334 *
1335 * @param string $sep
1336 * @return array
1337 */
1338 function virtualImplode( $sep /*, ... */ ) {
1339 $args = array_slice( func_get_args(), 1 );
1340 $out = array();
1341 $first = true;
1342
1343 foreach ( $args as $root ) {
1344 if ( $root instanceof PPNode_DOM ) {
1345 $root = $root->node;
1346 }
1347 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1348 $root = array( $root );
1349 }
1350 foreach ( $root as $node ) {
1351 if ( $first ) {
1352 $first = false;
1353 } else {
1354 $out[] = $sep;
1355 }
1356 $out[] = $node;
1357 }
1358 }
1359 return $out;
1360 }
1361
1362 /**
1363 * Virtual implode with brackets
1364 * @param string $start
1365 * @param string $sep
1366 * @param string $end
1367 * @return array
1368 */
1369 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1370 $args = array_slice( func_get_args(), 3 );
1371 $out = array( $start );
1372 $first = true;
1373
1374 foreach ( $args as $root ) {
1375 if ( $root instanceof PPNode_DOM ) {
1376 $root = $root->node;
1377 }
1378 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
1379 $root = array( $root );
1380 }
1381 foreach ( $root as $node ) {
1382 if ( $first ) {
1383 $first = false;
1384 } else {
1385 $out[] = $sep;
1386 }
1387 $out[] = $node;
1388 }
1389 }
1390 $out[] = $end;
1391 return $out;
1392 }
1393
1394 function __toString() {
1395 return 'frame{}';
1396 }
1397
1398 function getPDBK( $level = false ) {
1399 if ( $level === false ) {
1400 return $this->title->getPrefixedDBkey();
1401 } else {
1402 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1403 }
1404 }
1405
1406 /**
1407 * @return array
1408 */
1409 function getArguments() {
1410 return array();
1411 }
1412
1413 /**
1414 * @return array
1415 */
1416 function getNumberedArguments() {
1417 return array();
1418 }
1419
1420 /**
1421 * @return array
1422 */
1423 function getNamedArguments() {
1424 return array();
1425 }
1426
1427 /**
1428 * Returns true if there are no arguments in this frame
1429 *
1430 * @return bool
1431 */
1432 function isEmpty() {
1433 return true;
1434 }
1435
1436 function getArgument( $name ) {
1437 return false;
1438 }
1439
1440 /**
1441 * Returns true if the infinite loop check is OK, false if a loop is detected
1442 *
1443 * @param Title $title
1444 * @return bool
1445 */
1446 function loopCheck( $title ) {
1447 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1448 }
1449
1450 /**
1451 * Return true if the frame is a template frame
1452 *
1453 * @return bool
1454 */
1455 function isTemplate() {
1456 return false;
1457 }
1458
1459 /**
1460 * Get a title of frame
1461 *
1462 * @return Title
1463 */
1464 function getTitle() {
1465 return $this->title;
1466 }
1467 }
1468
1469 /**
1470 * Expansion frame with template arguments
1471 * @ingroup Parser
1472 */
1473 class PPTemplateFrame_DOM extends PPFrame_DOM {
1474 /** @var PPFrame_DOM */
1475 public $parent;
1476
1477 /** @var array */
1478 protected $numberedArgs;
1479
1480 /** @var array */
1481 protected $namedArgs;
1482
1483 /** @var array */
1484 protected $numberedExpansionCache;
1485
1486 /** @var string[] */
1487 protected $namedExpansionCache;
1488
1489 /**
1490 * @param Preprocessor $preprocessor
1491 * @param bool|PPFrame_DOM $parent
1492 * @param array $numberedArgs
1493 * @param array $namedArgs
1494 * @param bool|Title $title
1495 */
1496 function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1497 $namedArgs = array(), $title = false
1498 ) {
1499 parent::__construct( $preprocessor );
1500
1501 $this->parent = $parent;
1502 $this->numberedArgs = $numberedArgs;
1503 $this->namedArgs = $namedArgs;
1504 $this->title = $title;
1505 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1506 $this->titleCache = $parent->titleCache;
1507 $this->titleCache[] = $pdbk;
1508 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1509 if ( $pdbk !== false ) {
1510 $this->loopCheckHash[$pdbk] = true;
1511 }
1512 $this->depth = $parent->depth + 1;
1513 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1514 }
1515
1516 function __toString() {
1517 $s = 'tplframe{';
1518 $first = true;
1519 $args = $this->numberedArgs + $this->namedArgs;
1520 foreach ( $args as $name => $value ) {
1521 if ( $first ) {
1522 $first = false;
1523 } else {
1524 $s .= ', ';
1525 }
1526 $s .= "\"$name\":\"" .
1527 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
1528 }
1529 $s .= '}';
1530 return $s;
1531 }
1532
1533 /**
1534 * Returns true if there are no arguments in this frame
1535 *
1536 * @return bool
1537 */
1538 function isEmpty() {
1539 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1540 }
1541
1542 function getArguments() {
1543 $arguments = array();
1544 foreach ( array_merge(
1545 array_keys( $this->numberedArgs ),
1546 array_keys( $this->namedArgs ) ) as $key ) {
1547 $arguments[$key] = $this->getArgument( $key );
1548 }
1549 return $arguments;
1550 }
1551
1552 function getNumberedArguments() {
1553 $arguments = array();
1554 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1555 $arguments[$key] = $this->getArgument( $key );
1556 }
1557 return $arguments;
1558 }
1559
1560 function getNamedArguments() {
1561 $arguments = array();
1562 foreach ( array_keys( $this->namedArgs ) as $key ) {
1563 $arguments[$key] = $this->getArgument( $key );
1564 }
1565 return $arguments;
1566 }
1567
1568 function getNumberedArgument( $index ) {
1569 if ( !isset( $this->numberedArgs[$index] ) ) {
1570 return false;
1571 }
1572 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1573 # No trimming for unnamed arguments
1574 $this->numberedExpansionCache[$index] = $this->parent->expand(
1575 $this->numberedArgs[$index],
1576 PPFrame::STRIP_COMMENTS
1577 );
1578 }
1579 return $this->numberedExpansionCache[$index];
1580 }
1581
1582 function getNamedArgument( $name ) {
1583 if ( !isset( $this->namedArgs[$name] ) ) {
1584 return false;
1585 }
1586 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1587 # Trim named arguments post-expand, for backwards compatibility
1588 $this->namedExpansionCache[$name] = trim(
1589 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1590 }
1591 return $this->namedExpansionCache[$name];
1592 }
1593
1594 function getArgument( $name ) {
1595 $text = $this->getNumberedArgument( $name );
1596 if ( $text === false ) {
1597 $text = $this->getNamedArgument( $name );
1598 }
1599 return $text;
1600 }
1601
1602 /**
1603 * Return true if the frame is a template frame
1604 *
1605 * @return bool
1606 */
1607 function isTemplate() {
1608 return true;
1609 }
1610 }
1611
1612 /**
1613 * Expansion frame with custom arguments
1614 * @ingroup Parser
1615 */
1616 class PPCustomFrame_DOM extends PPFrame_DOM {
1617 protected $args;
1618
1619 function __construct( $preprocessor, $args ) {
1620 parent::__construct( $preprocessor );
1621 $this->args = $args;
1622 }
1623
1624 function __toString() {
1625 $s = 'cstmframe{';
1626 $first = true;
1627 foreach ( $this->args as $name => $value ) {
1628 if ( $first ) {
1629 $first = false;
1630 } else {
1631 $s .= ', ';
1632 }
1633 $s .= "\"$name\":\"" .
1634 str_replace( '"', '\\"', $value->__toString() ) . '"';
1635 }
1636 $s .= '}';
1637 return $s;
1638 }
1639
1640 /**
1641 * @return bool
1642 */
1643 function isEmpty() {
1644 return !count( $this->args );
1645 }
1646
1647 function getArgument( $index ) {
1648 if ( !isset( $this->args[$index] ) ) {
1649 return false;
1650 }
1651 return $this->args[$index];
1652 }
1653
1654 function getArguments() {
1655 return $this->args;
1656 }
1657 }
1658
1659 /**
1660 * @ingroup Parser
1661 */
1662 class PPNode_DOM implements PPNode {
1663 /** @var DOMElement */
1664 public $node;
1665
1666 /** @var DOMXPath */
1667 protected $xpath;
1668
1669 function __construct( $node, $xpath = false ) {
1670 $this->node = $node;
1671 }
1672
1673 /**
1674 * @return DOMXPath
1675 */
1676 function getXPath() {
1677 if ( $this->xpath === null ) {
1678 $this->xpath = new DOMXPath( $this->node->ownerDocument );
1679 }
1680 return $this->xpath;
1681 }
1682
1683 function __toString() {
1684 if ( $this->node instanceof DOMNodeList ) {
1685 $s = '';
1686 foreach ( $this->node as $node ) {
1687 $s .= $node->ownerDocument->saveXML( $node );
1688 }
1689 } else {
1690 $s = $this->node->ownerDocument->saveXML( $this->node );
1691 }
1692 return $s;
1693 }
1694
1695 /**
1696 * @return bool|PPNode_DOM
1697 */
1698 function getChildren() {
1699 return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
1700 }
1701
1702 /**
1703 * @return bool|PPNode_DOM
1704 */
1705 function getFirstChild() {
1706 return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
1707 }
1708
1709 /**
1710 * @return bool|PPNode_DOM
1711 */
1712 function getNextSibling() {
1713 return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
1714 }
1715
1716 /**
1717 * @param string $type
1718 *
1719 * @return bool|PPNode_DOM
1720 */
1721 function getChildrenOfType( $type ) {
1722 return new self( $this->getXPath()->query( $type, $this->node ) );
1723 }
1724
1725 /**
1726 * @return int
1727 */
1728 function getLength() {
1729 if ( $this->node instanceof DOMNodeList ) {
1730 return $this->node->length;
1731 } else {
1732 return false;
1733 }
1734 }
1735
1736 /**
1737 * @param int $i
1738 * @return bool|PPNode_DOM
1739 */
1740 function item( $i ) {
1741 $item = $this->node->item( $i );
1742 return $item ? new self( $item ) : false;
1743 }
1744
1745 /**
1746 * @return string
1747 */
1748 function getName() {
1749 if ( $this->node instanceof DOMNodeList ) {
1750 return '#nodelist';
1751 } else {
1752 return $this->node->nodeName;
1753 }
1754 }
1755
1756 /**
1757 * Split a "<part>" node into an associative array containing:
1758 * - name PPNode name
1759 * - index String index
1760 * - value PPNode value
1761 *
1762 * @throws MWException
1763 * @return array
1764 */
1765 function splitArg() {
1766 $xpath = $this->getXPath();
1767 $names = $xpath->query( 'name', $this->node );
1768 $values = $xpath->query( 'value', $this->node );
1769 if ( !$names->length || !$values->length ) {
1770 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1771 }
1772 $name = $names->item( 0 );
1773 $index = $name->getAttribute( 'index' );
1774 return array(
1775 'name' => new self( $name ),
1776 'index' => $index,
1777 'value' => new self( $values->item( 0 ) ) );
1778 }
1779
1780 /**
1781 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1782 * All values in the resulting array are PPNodes. Inner and close are optional.
1783 *
1784 * @throws MWException
1785 * @return array
1786 */
1787 function splitExt() {
1788 $xpath = $this->getXPath();
1789 $names = $xpath->query( 'name', $this->node );
1790 $attrs = $xpath->query( 'attr', $this->node );
1791 $inners = $xpath->query( 'inner', $this->node );
1792 $closes = $xpath->query( 'close', $this->node );
1793 if ( !$names->length || !$attrs->length ) {
1794 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1795 }
1796 $parts = array(
1797 'name' => new self( $names->item( 0 ) ),
1798 'attr' => new self( $attrs->item( 0 ) ) );
1799 if ( $inners->length ) {
1800 $parts['inner'] = new self( $inners->item( 0 ) );
1801 }
1802 if ( $closes->length ) {
1803 $parts['close'] = new self( $closes->item( 0 ) );
1804 }
1805 return $parts;
1806 }
1807
1808 /**
1809 * Split a "<h>" node
1810 * @throws MWException
1811 * @return array
1812 */
1813 function splitHeading() {
1814 if ( $this->getName() !== 'h' ) {
1815 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1816 }
1817 return array(
1818 'i' => $this->node->getAttribute( 'i' ),
1819 'level' => $this->node->getAttribute( 'level' ),
1820 'contents' => $this->getChildren()
1821 );
1822 }
1823 }