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