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