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