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