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