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