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