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