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