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