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