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