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