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