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