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