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