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