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