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