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