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