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