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