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