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