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