Fix function level comments that start with /* not /**
[lhc/web/wiklou.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 /**
17 * @var Parser
18 */
19 var $parser;
20
21 const CACHE_VERSION = 1;
22
23 function __construct( $parser ) {
24 $this->parser = $parser;
25 }
26
27 function newFrame() {
28 return new PPFrame_Hash( $this );
29 }
30
31 function newCustomFrame( $args ) {
32 return new PPCustomFrame_Hash( $this, $args );
33 }
34
35 function newPartNodeArray( $values ) {
36 $list = array();
37
38 foreach ( $values as $k => $val ) {
39 $partNode = new PPNode_Hash_Tree( 'part' );
40 $nameNode = new PPNode_Hash_Tree( 'name' );
41
42 if ( is_int( $k ) ) {
43 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
44 $partNode->addChild( $nameNode );
45 } else {
46 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
47 $partNode->addChild( $nameNode );
48 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
49 }
50
51 $valueNode = new PPNode_Hash_Tree( 'value' );
52 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
53 $partNode->addChild( $valueNode );
54
55 $list[] = $partNode;
56 }
57
58 $node = new PPNode_Hash_Array( $list );
59 return $node;
60 }
61
62 /**
63 * Preprocess some wikitext and return the document tree.
64 * This is the ghost of Parser::replace_variables().
65 *
66 * @param $text String: the text to parse
67 * @param $flags Integer: bitwise combination of:
68 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
69 * included. Default is to assume a direct page view.
70 *
71 * The generated DOM tree must depend only on the input text and the flags.
72 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
73 *
74 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
75 * change in the DOM tree for a given text, must be passed through the section identifier
76 * in the section edit link and thus back to extractSections().
77 *
78 * The output of this function is currently only cached in process memory, but a persistent
79 * cache may be implemented at a later date which takes further advantage of these strict
80 * dependency requirements.
81 *
82 * @private
83 */
84 function preprocessToObj( $text, $flags = 0 ) {
85 wfProfileIn( __METHOD__ );
86
87 // Check cache.
88 global $wgMemc, $wgPreprocessorCacheThreshold;
89
90 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
91 if ( $cacheable ) {
92 wfProfileIn( __METHOD__.'-cacheable' );
93
94 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
95 $cacheValue = $wgMemc->get( $cacheKey );
96 if ( $cacheValue ) {
97 $version = substr( $cacheValue, 0, 8 );
98 if ( intval( $version ) == self::CACHE_VERSION ) {
99 $hash = unserialize( substr( $cacheValue, 8 ) );
100 // From the cache
101 wfDebugLog( "Preprocessor",
102 "Loaded preprocessor hash from memcached (key $cacheKey)" );
103 wfProfileOut( __METHOD__.'-cacheable' );
104 wfProfileOut( __METHOD__ );
105 return $hash;
106 }
107 }
108 wfProfileIn( __METHOD__.'-cache-miss' );
109 }
110
111 $rules = array(
112 '{' => array(
113 'end' => '}',
114 'names' => array(
115 2 => 'template',
116 3 => 'tplarg',
117 ),
118 'min' => 2,
119 'max' => 3,
120 ),
121 '[' => array(
122 'end' => ']',
123 'names' => array( 2 => null ),
124 'min' => 2,
125 'max' => 2,
126 )
127 );
128
129 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
130
131 $xmlishElements = $this->parser->getStripList();
132 $enableOnlyinclude = false;
133 if ( $forInclusion ) {
134 $ignoredTags = array( 'includeonly', '/includeonly' );
135 $ignoredElements = array( 'noinclude' );
136 $xmlishElements[] = 'noinclude';
137 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
138 $enableOnlyinclude = true;
139 }
140 } else {
141 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
142 $ignoredElements = array( 'includeonly' );
143 $xmlishElements[] = 'includeonly';
144 }
145 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
146
147 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
148 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
149
150 $stack = new PPDStack_Hash;
151
152 $searchBase = "[{<\n";
153 $revText = strrev( $text ); // For fast reverse searches
154
155 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
156 $accum =& $stack->getAccum(); # Current accumulator
157 $findEquals = false; # True to find equals signs in arguments
158 $findPipe = false; # True to take notice of pipe characters
159 $headingIndex = 1;
160 $inHeading = false; # True if $i is inside a possible heading
161 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
162 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
163 $fakeLineStart = true; # Do a line-start run without outputting an LF character
164
165 while ( true ) {
166 //$this->memCheck();
167
168 if ( $findOnlyinclude ) {
169 // Ignore all input up to the next <onlyinclude>
170 $startPos = strpos( $text, '<onlyinclude>', $i );
171 if ( $startPos === false ) {
172 // Ignored section runs to the end
173 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
174 break;
175 }
176 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
177 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
178 $i = $tagEndPos;
179 $findOnlyinclude = false;
180 }
181
182 if ( $fakeLineStart ) {
183 $found = 'line-start';
184 $curChar = '';
185 } else {
186 # Find next opening brace, closing brace or pipe
187 $search = $searchBase;
188 if ( $stack->top === false ) {
189 $currentClosing = '';
190 } else {
191 $currentClosing = $stack->top->close;
192 $search .= $currentClosing;
193 }
194 if ( $findPipe ) {
195 $search .= '|';
196 }
197 if ( $findEquals ) {
198 // First equals will be for the template
199 $search .= '=';
200 }
201 $rule = null;
202 # Output literal section, advance input counter
203 $literalLength = strcspn( $text, $search, $i );
204 if ( $literalLength > 0 ) {
205 $accum->addLiteral( substr( $text, $i, $literalLength ) );
206 $i += $literalLength;
207 }
208 if ( $i >= strlen( $text ) ) {
209 if ( $currentClosing == "\n" ) {
210 // Do a past-the-end run to finish off the heading
211 $curChar = '';
212 $found = 'line-end';
213 } else {
214 # All done
215 break;
216 }
217 } else {
218 $curChar = $text[$i];
219 if ( $curChar == '|' ) {
220 $found = 'pipe';
221 } elseif ( $curChar == '=' ) {
222 $found = 'equals';
223 } elseif ( $curChar == '<' ) {
224 $found = 'angle';
225 } elseif ( $curChar == "\n" ) {
226 if ( $inHeading ) {
227 $found = 'line-end';
228 } else {
229 $found = 'line-start';
230 }
231 } elseif ( $curChar == $currentClosing ) {
232 $found = 'close';
233 } elseif ( isset( $rules[$curChar] ) ) {
234 $found = 'open';
235 $rule = $rules[$curChar];
236 } else {
237 # Some versions of PHP have a strcspn which stops on null characters
238 # Ignore and continue
239 ++$i;
240 continue;
241 }
242 }
243 }
244
245 if ( $found == 'angle' ) {
246 $matches = false;
247 // Handle </onlyinclude>
248 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
249 $findOnlyinclude = true;
250 continue;
251 }
252
253 // Determine element name
254 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
255 // Element name missing or not listed
256 $accum->addLiteral( '<' );
257 ++$i;
258 continue;
259 }
260 // Handle comments
261 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
262 // To avoid leaving blank lines, when a comment is both preceded
263 // and followed by a newline (ignoring spaces), trim leading and
264 // trailing spaces and one of the newlines.
265
266 // Find the end
267 $endPos = strpos( $text, '-->', $i + 4 );
268 if ( $endPos === false ) {
269 // Unclosed comment in input, runs to end
270 $inner = substr( $text, $i );
271 $accum->addNodeWithText( 'comment', $inner );
272 $i = strlen( $text );
273 } else {
274 // Search backwards for leading whitespace
275 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
276 // Search forwards for trailing whitespace
277 // $wsEnd will be the position of the last space (or the '>' if there's none)
278 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
279 // Eat the line if possible
280 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
281 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
282 // it's a possible beneficial b/c break.
283 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
284 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
285 {
286 $startPos = $wsStart;
287 $endPos = $wsEnd + 1;
288 // Remove leading whitespace from the end of the accumulator
289 // Sanity check first though
290 $wsLength = $i - $wsStart;
291 if ( $wsLength > 0
292 && $accum->lastNode instanceof PPNode_Hash_Text
293 && substr( $accum->lastNode->value, -$wsLength ) === str_repeat( ' ', $wsLength ) )
294 {
295 $accum->lastNode->value = substr( $accum->lastNode->value, 0, -$wsLength );
296 }
297 // Do a line-start run next time to look for headings after the comment
298 $fakeLineStart = true;
299 } else {
300 // No line to eat, just take the comment itself
301 $startPos = $i;
302 $endPos += 2;
303 }
304
305 if ( $stack->top ) {
306 $part = $stack->top->getCurrentPart();
307 if ( ! (isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 )) {
308 $part->visualEnd = $wsStart;
309 }
310 // Else comments abutting, no change in visual end
311 $part->commentEnd = $endPos;
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
822 /**
823 * @var Parser
824 */
825 var $parser;
826
827 /**
828 * @var Preprocessor
829 */
830 var $preprocessor;
831
832 /**
833 * @var Title
834 */
835 var $title;
836 var $titleCache;
837
838 /**
839 * Hashtable listing templates which are disallowed for expansion in this frame,
840 * having been encountered previously in parent frames.
841 */
842 var $loopCheckHash;
843
844 /**
845 * Recursion depth of this frame, top = 0
846 * Note that this is NOT the same as expansion depth in expand()
847 */
848 var $depth;
849
850
851 /**
852 * Construct a new preprocessor frame.
853 * @param $preprocessor Preprocessor: the parent preprocessor
854 */
855 function __construct( $preprocessor ) {
856 $this->preprocessor = $preprocessor;
857 $this->parser = $preprocessor->parser;
858 $this->title = $this->parser->mTitle;
859 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
860 $this->loopCheckHash = array();
861 $this->depth = 0;
862 }
863
864 /**
865 * Create a new child frame
866 * $args is optionally a multi-root PPNode or array containing the template arguments
867 */
868 function newChild( $args = false, $title = false ) {
869 $namedArgs = array();
870 $numberedArgs = array();
871 if ( $title === false ) {
872 $title = $this->title;
873 }
874 if ( $args !== false ) {
875 if ( $args instanceof PPNode_Hash_Array ) {
876 $args = $args->value;
877 } elseif ( !is_array( $args ) ) {
878 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
879 }
880 foreach ( $args as $arg ) {
881 $bits = $arg->splitArg();
882 if ( $bits['index'] !== '' ) {
883 // Numbered parameter
884 $numberedArgs[$bits['index']] = $bits['value'];
885 unset( $namedArgs[$bits['index']] );
886 } else {
887 // Named parameter
888 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
889 $namedArgs[$name] = $bits['value'];
890 unset( $numberedArgs[$name] );
891 }
892 }
893 }
894 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
895 }
896
897 function expand( $root, $flags = 0 ) {
898 static $expansionDepth = 0;
899 if ( is_string( $root ) ) {
900 return $root;
901 }
902
903 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
904 return '<span class="error">Node-count limit exceeded</span>';
905 }
906 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
907 return '<span class="error">Expansion depth limit exceeded</span>';
908 }
909 ++$expansionDepth;
910
911 $outStack = array( '', '' );
912 $iteratorStack = array( false, $root );
913 $indexStack = array( 0, 0 );
914
915 while ( count( $iteratorStack ) > 1 ) {
916 $level = count( $outStack ) - 1;
917 $iteratorNode =& $iteratorStack[ $level ];
918 $out =& $outStack[$level];
919 $index =& $indexStack[$level];
920
921 if ( is_array( $iteratorNode ) ) {
922 if ( $index >= count( $iteratorNode ) ) {
923 // All done with this iterator
924 $iteratorStack[$level] = false;
925 $contextNode = false;
926 } else {
927 $contextNode = $iteratorNode[$index];
928 $index++;
929 }
930 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
931 if ( $index >= $iteratorNode->getLength() ) {
932 // All done with this iterator
933 $iteratorStack[$level] = false;
934 $contextNode = false;
935 } else {
936 $contextNode = $iteratorNode->item( $index );
937 $index++;
938 }
939 } else {
940 // Copy to $contextNode and then delete from iterator stack,
941 // because this is not an iterator but we do have to execute it once
942 $contextNode = $iteratorStack[$level];
943 $iteratorStack[$level] = false;
944 }
945
946 $newIterator = false;
947
948 if ( $contextNode === false ) {
949 // nothing to do
950 } elseif ( is_string( $contextNode ) ) {
951 $out .= $contextNode;
952 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
953 $newIterator = $contextNode;
954 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
955 // No output
956 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
957 $out .= $contextNode->value;
958 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
959 if ( $contextNode->name == 'template' ) {
960 # Double-brace expansion
961 $bits = $contextNode->splitTemplate();
962 if ( $flags & PPFrame::NO_TEMPLATES ) {
963 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
964 } else {
965 $ret = $this->parser->braceSubstitution( $bits, $this );
966 if ( isset( $ret['object'] ) ) {
967 $newIterator = $ret['object'];
968 } else {
969 $out .= $ret['text'];
970 }
971 }
972 } elseif ( $contextNode->name == 'tplarg' ) {
973 # Triple-brace expansion
974 $bits = $contextNode->splitTemplate();
975 if ( $flags & PPFrame::NO_ARGS ) {
976 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
977 } else {
978 $ret = $this->parser->argSubstitution( $bits, $this );
979 if ( isset( $ret['object'] ) ) {
980 $newIterator = $ret['object'];
981 } else {
982 $out .= $ret['text'];
983 }
984 }
985 } elseif ( $contextNode->name == 'comment' ) {
986 # HTML-style comment
987 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
988 if ( $this->parser->ot['html']
989 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
990 || ( $flags & PPFrame::STRIP_COMMENTS ) )
991 {
992 $out .= '';
993 }
994 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
995 # Not in RECOVER_COMMENTS mode (extractSections) though
996 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
997 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
998 }
999 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1000 else {
1001 $out .= $contextNode->firstChild->value;
1002 }
1003 } elseif ( $contextNode->name == 'ignore' ) {
1004 # Output suppression used by <includeonly> etc.
1005 # OT_WIKI will only respect <ignore> in substed templates.
1006 # The other output types respect it unless NO_IGNORE is set.
1007 # extractSections() sets NO_IGNORE and so never respects it.
1008 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1009 $out .= $contextNode->firstChild->value;
1010 } else {
1011 //$out .= '';
1012 }
1013 } elseif ( $contextNode->name == 'ext' ) {
1014 # Extension tag
1015 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1016 $out .= $this->parser->extensionSubstitution( $bits, $this );
1017 } elseif ( $contextNode->name == 'h' ) {
1018 # Heading
1019 if ( $this->parser->ot['html'] ) {
1020 # Expand immediately and insert heading index marker
1021 $s = '';
1022 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1023 $s .= $this->expand( $node, $flags );
1024 }
1025
1026 $bits = $contextNode->splitHeading();
1027 $titleText = $this->title->getPrefixedDBkey();
1028 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1029 $serial = count( $this->parser->mHeadings ) - 1;
1030 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1031 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1032 $this->parser->mStripState->addGeneral( $marker, '' );
1033 $out .= $s;
1034 } else {
1035 # Expand in virtual stack
1036 $newIterator = $contextNode->getChildren();
1037 }
1038 } else {
1039 # Generic recursive expansion
1040 $newIterator = $contextNode->getChildren();
1041 }
1042 } else {
1043 throw new MWException( __METHOD__.': Invalid parameter type' );
1044 }
1045
1046 if ( $newIterator !== false ) {
1047 $outStack[] = '';
1048 $iteratorStack[] = $newIterator;
1049 $indexStack[] = 0;
1050 } elseif ( $iteratorStack[$level] === false ) {
1051 // Return accumulated value to parent
1052 // With tail recursion
1053 while ( $iteratorStack[$level] === false && $level > 0 ) {
1054 $outStack[$level - 1] .= $out;
1055 array_pop( $outStack );
1056 array_pop( $iteratorStack );
1057 array_pop( $indexStack );
1058 $level--;
1059 }
1060 }
1061 }
1062 --$expansionDepth;
1063 return $outStack[0];
1064 }
1065
1066 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1067 $args = array_slice( func_get_args(), 2 );
1068
1069 $first = true;
1070 $s = '';
1071 foreach ( $args as $root ) {
1072 if ( $root instanceof PPNode_Hash_Array ) {
1073 $root = $root->value;
1074 }
1075 if ( !is_array( $root ) ) {
1076 $root = array( $root );
1077 }
1078 foreach ( $root as $node ) {
1079 if ( $first ) {
1080 $first = false;
1081 } else {
1082 $s .= $sep;
1083 }
1084 $s .= $this->expand( $node, $flags );
1085 }
1086 }
1087 return $s;
1088 }
1089
1090 /**
1091 * Implode with no flags specified
1092 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1093 */
1094 function implode( $sep /*, ... */ ) {
1095 $args = array_slice( func_get_args(), 1 );
1096
1097 $first = true;
1098 $s = '';
1099 foreach ( $args as $root ) {
1100 if ( $root instanceof PPNode_Hash_Array ) {
1101 $root = $root->value;
1102 }
1103 if ( !is_array( $root ) ) {
1104 $root = array( $root );
1105 }
1106 foreach ( $root as $node ) {
1107 if ( $first ) {
1108 $first = false;
1109 } else {
1110 $s .= $sep;
1111 }
1112 $s .= $this->expand( $node );
1113 }
1114 }
1115 return $s;
1116 }
1117
1118 /**
1119 * Makes an object that, when expand()ed, will be the same as one obtained
1120 * with implode()
1121 */
1122 function virtualImplode( $sep /*, ... */ ) {
1123 $args = array_slice( func_get_args(), 1 );
1124 $out = array();
1125 $first = true;
1126
1127 foreach ( $args as $root ) {
1128 if ( $root instanceof PPNode_Hash_Array ) {
1129 $root = $root->value;
1130 }
1131 if ( !is_array( $root ) ) {
1132 $root = array( $root );
1133 }
1134 foreach ( $root as $node ) {
1135 if ( $first ) {
1136 $first = false;
1137 } else {
1138 $out[] = $sep;
1139 }
1140 $out[] = $node;
1141 }
1142 }
1143 return new PPNode_Hash_Array( $out );
1144 }
1145
1146 /**
1147 * Virtual implode with brackets
1148 */
1149 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1150 $args = array_slice( func_get_args(), 3 );
1151 $out = array( $start );
1152 $first = true;
1153
1154 foreach ( $args as $root ) {
1155 if ( $root instanceof PPNode_Hash_Array ) {
1156 $root = $root->value;
1157 }
1158 if ( !is_array( $root ) ) {
1159 $root = array( $root );
1160 }
1161 foreach ( $root as $node ) {
1162 if ( $first ) {
1163 $first = false;
1164 } else {
1165 $out[] = $sep;
1166 }
1167 $out[] = $node;
1168 }
1169 }
1170 $out[] = $end;
1171 return new PPNode_Hash_Array( $out );
1172 }
1173
1174 function __toString() {
1175 return 'frame{}';
1176 }
1177
1178 function getPDBK( $level = false ) {
1179 if ( $level === false ) {
1180 return $this->title->getPrefixedDBkey();
1181 } else {
1182 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1183 }
1184 }
1185
1186 function getArguments() {
1187 return array();
1188 }
1189
1190 function getNumberedArguments() {
1191 return array();
1192 }
1193
1194 function getNamedArguments() {
1195 return array();
1196 }
1197
1198 /**
1199 * Returns true if there are no arguments in this frame
1200 */
1201 function isEmpty() {
1202 return true;
1203 }
1204
1205 function getArgument( $name ) {
1206 return false;
1207 }
1208
1209 /**
1210 * Returns true if the infinite loop check is OK, false if a loop is detected
1211 *
1212 * @param $title Title
1213 */
1214 function loopCheck( $title ) {
1215 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1216 }
1217
1218 /**
1219 * Return true if the frame is a template frame
1220 */
1221 function isTemplate() {
1222 return false;
1223 }
1224 }
1225
1226 /**
1227 * Expansion frame with template arguments
1228 * @ingroup Parser
1229 */
1230 class PPTemplateFrame_Hash extends PPFrame_Hash {
1231 var $numberedArgs, $namedArgs, $parent;
1232 var $numberedExpansionCache, $namedExpansionCache;
1233
1234 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1235 parent::__construct( $preprocessor );
1236
1237 $this->parent = $parent;
1238 $this->numberedArgs = $numberedArgs;
1239 $this->namedArgs = $namedArgs;
1240 $this->title = $title;
1241 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1242 $this->titleCache = $parent->titleCache;
1243 $this->titleCache[] = $pdbk;
1244 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1245 if ( $pdbk !== false ) {
1246 $this->loopCheckHash[$pdbk] = true;
1247 }
1248 $this->depth = $parent->depth + 1;
1249 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1250 }
1251
1252 function __toString() {
1253 $s = 'tplframe{';
1254 $first = true;
1255 $args = $this->numberedArgs + $this->namedArgs;
1256 foreach ( $args as $name => $value ) {
1257 if ( $first ) {
1258 $first = false;
1259 } else {
1260 $s .= ', ';
1261 }
1262 $s .= "\"$name\":\"" .
1263 str_replace( '"', '\\"', $value->__toString() ) . '"';
1264 }
1265 $s .= '}';
1266 return $s;
1267 }
1268 /**
1269 * Returns true if there are no arguments in this frame
1270 */
1271 function isEmpty() {
1272 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1273 }
1274
1275 function getArguments() {
1276 $arguments = array();
1277 foreach ( array_merge(
1278 array_keys($this->numberedArgs),
1279 array_keys($this->namedArgs)) as $key ) {
1280 $arguments[$key] = $this->getArgument($key);
1281 }
1282 return $arguments;
1283 }
1284
1285 function getNumberedArguments() {
1286 $arguments = array();
1287 foreach ( array_keys($this->numberedArgs) as $key ) {
1288 $arguments[$key] = $this->getArgument($key);
1289 }
1290 return $arguments;
1291 }
1292
1293 function getNamedArguments() {
1294 $arguments = array();
1295 foreach ( array_keys($this->namedArgs) as $key ) {
1296 $arguments[$key] = $this->getArgument($key);
1297 }
1298 return $arguments;
1299 }
1300
1301 function getNumberedArgument( $index ) {
1302 if ( !isset( $this->numberedArgs[$index] ) ) {
1303 return false;
1304 }
1305 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1306 # No trimming for unnamed arguments
1307 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1308 }
1309 return $this->numberedExpansionCache[$index];
1310 }
1311
1312 function getNamedArgument( $name ) {
1313 if ( !isset( $this->namedArgs[$name] ) ) {
1314 return false;
1315 }
1316 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1317 # Trim named arguments post-expand, for backwards compatibility
1318 $this->namedExpansionCache[$name] = trim(
1319 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1320 }
1321 return $this->namedExpansionCache[$name];
1322 }
1323
1324 function getArgument( $name ) {
1325 $text = $this->getNumberedArgument( $name );
1326 if ( $text === false ) {
1327 $text = $this->getNamedArgument( $name );
1328 }
1329 return $text;
1330 }
1331
1332 /**
1333 * Return true if the frame is a template frame
1334 */
1335 function isTemplate() {
1336 return true;
1337 }
1338 }
1339
1340 /**
1341 * Expansion frame with custom arguments
1342 * @ingroup Parser
1343 */
1344 class PPCustomFrame_Hash extends PPFrame_Hash {
1345 var $args;
1346
1347 function __construct( $preprocessor, $args ) {
1348 parent::__construct( $preprocessor );
1349 $this->args = $args;
1350 }
1351
1352 function __toString() {
1353 $s = 'cstmframe{';
1354 $first = true;
1355 foreach ( $this->args as $name => $value ) {
1356 if ( $first ) {
1357 $first = false;
1358 } else {
1359 $s .= ', ';
1360 }
1361 $s .= "\"$name\":\"" .
1362 str_replace( '"', '\\"', $value->__toString() ) . '"';
1363 }
1364 $s .= '}';
1365 return $s;
1366 }
1367
1368 function isEmpty() {
1369 return !count( $this->args );
1370 }
1371
1372 function getArgument( $index ) {
1373 if ( !isset( $this->args[$index] ) ) {
1374 return false;
1375 }
1376 return $this->args[$index];
1377 }
1378 }
1379
1380 /**
1381 * @ingroup Parser
1382 */
1383 class PPNode_Hash_Tree implements PPNode {
1384 var $name, $firstChild, $lastChild, $nextSibling;
1385
1386 function __construct( $name ) {
1387 $this->name = $name;
1388 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1389 }
1390
1391 function __toString() {
1392 $inner = '';
1393 $attribs = '';
1394 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1395 if ( $node instanceof PPNode_Hash_Attr ) {
1396 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1397 } else {
1398 $inner .= $node->__toString();
1399 }
1400 }
1401 if ( $inner === '' ) {
1402 return "<{$this->name}$attribs/>";
1403 } else {
1404 return "<{$this->name}$attribs>$inner</{$this->name}>";
1405 }
1406 }
1407
1408 static function newWithText( $name, $text ) {
1409 $obj = new self( $name );
1410 $obj->addChild( new PPNode_Hash_Text( $text ) );
1411 return $obj;
1412 }
1413
1414 function addChild( $node ) {
1415 if ( $this->lastChild === false ) {
1416 $this->firstChild = $this->lastChild = $node;
1417 } else {
1418 $this->lastChild->nextSibling = $node;
1419 $this->lastChild = $node;
1420 }
1421 }
1422
1423 function getChildren() {
1424 $children = array();
1425 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1426 $children[] = $child;
1427 }
1428 return new PPNode_Hash_Array( $children );
1429 }
1430
1431 function getFirstChild() {
1432 return $this->firstChild;
1433 }
1434
1435 function getNextSibling() {
1436 return $this->nextSibling;
1437 }
1438
1439 function getChildrenOfType( $name ) {
1440 $children = array();
1441 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1442 if ( isset( $child->name ) && $child->name === $name ) {
1443 $children[] = $name;
1444 }
1445 }
1446 return $children;
1447 }
1448
1449 function getLength() { return false; }
1450 function item( $i ) { return false; }
1451
1452 function getName() {
1453 return $this->name;
1454 }
1455
1456 /**
1457 * Split a <part> node into an associative array containing:
1458 * name PPNode name
1459 * index String index
1460 * value PPNode value
1461 */
1462 function splitArg() {
1463 $bits = array();
1464 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1465 if ( !isset( $child->name ) ) {
1466 continue;
1467 }
1468 if ( $child->name === 'name' ) {
1469 $bits['name'] = $child;
1470 if ( $child->firstChild instanceof PPNode_Hash_Attr
1471 && $child->firstChild->name === 'index' )
1472 {
1473 $bits['index'] = $child->firstChild->value;
1474 }
1475 } elseif ( $child->name === 'value' ) {
1476 $bits['value'] = $child;
1477 }
1478 }
1479
1480 if ( !isset( $bits['name'] ) ) {
1481 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1482 }
1483 if ( !isset( $bits['index'] ) ) {
1484 $bits['index'] = '';
1485 }
1486 return $bits;
1487 }
1488
1489 /**
1490 * Split an <ext> node into an associative array containing name, attr, inner and close
1491 * All values in the resulting array are PPNodes. Inner and close are optional.
1492 */
1493 function splitExt() {
1494 $bits = array();
1495 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1496 if ( !isset( $child->name ) ) {
1497 continue;
1498 }
1499 if ( $child->name == 'name' ) {
1500 $bits['name'] = $child;
1501 } elseif ( $child->name == 'attr' ) {
1502 $bits['attr'] = $child;
1503 } elseif ( $child->name == 'inner' ) {
1504 $bits['inner'] = $child;
1505 } elseif ( $child->name == 'close' ) {
1506 $bits['close'] = $child;
1507 }
1508 }
1509 if ( !isset( $bits['name'] ) ) {
1510 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1511 }
1512 return $bits;
1513 }
1514
1515 /**
1516 * Split an <h> node
1517 */
1518 function splitHeading() {
1519 if ( $this->name !== 'h' ) {
1520 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1521 }
1522 $bits = array();
1523 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1524 if ( !isset( $child->name ) ) {
1525 continue;
1526 }
1527 if ( $child->name == 'i' ) {
1528 $bits['i'] = $child->value;
1529 } elseif ( $child->name == 'level' ) {
1530 $bits['level'] = $child->value;
1531 }
1532 }
1533 if ( !isset( $bits['i'] ) ) {
1534 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1535 }
1536 return $bits;
1537 }
1538
1539 /**
1540 * Split a <template> or <tplarg> node
1541 */
1542 function splitTemplate() {
1543 $parts = array();
1544 $bits = array( 'lineStart' => '' );
1545 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1546 if ( !isset( $child->name ) ) {
1547 continue;
1548 }
1549 if ( $child->name == 'title' ) {
1550 $bits['title'] = $child;
1551 }
1552 if ( $child->name == 'part' ) {
1553 $parts[] = $child;
1554 }
1555 if ( $child->name == 'lineStart' ) {
1556 $bits['lineStart'] = '1';
1557 }
1558 }
1559 if ( !isset( $bits['title'] ) ) {
1560 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1561 }
1562 $bits['parts'] = new PPNode_Hash_Array( $parts );
1563 return $bits;
1564 }
1565 }
1566
1567 /**
1568 * @ingroup Parser
1569 */
1570 class PPNode_Hash_Text implements PPNode {
1571 var $value, $nextSibling;
1572
1573 function __construct( $value ) {
1574 if ( is_object( $value ) ) {
1575 throw new MWException( __CLASS__ . ' given object instead of string' );
1576 }
1577 $this->value = $value;
1578 }
1579
1580 function __toString() {
1581 return htmlspecialchars( $this->value );
1582 }
1583
1584 function getNextSibling() {
1585 return $this->nextSibling;
1586 }
1587
1588 function getChildren() { return false; }
1589 function getFirstChild() { return false; }
1590 function getChildrenOfType( $name ) { return false; }
1591 function getLength() { return false; }
1592 function item( $i ) { return false; }
1593 function getName() { return '#text'; }
1594 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1595 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1596 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1597 }
1598
1599 /**
1600 * @ingroup Parser
1601 */
1602 class PPNode_Hash_Array implements PPNode {
1603 var $value, $nextSibling;
1604
1605 function __construct( $value ) {
1606 $this->value = $value;
1607 }
1608
1609 function __toString() {
1610 return var_export( $this, true );
1611 }
1612
1613 function getLength() {
1614 return count( $this->value );
1615 }
1616
1617 function item( $i ) {
1618 return $this->value[$i];
1619 }
1620
1621 function getName() { return '#nodelist'; }
1622
1623 function getNextSibling() {
1624 return $this->nextSibling;
1625 }
1626
1627 function getChildren() { return false; }
1628 function getFirstChild() { return false; }
1629 function getChildrenOfType( $name ) { return false; }
1630 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1631 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1632 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1633 }
1634
1635 /**
1636 * @ingroup Parser
1637 */
1638 class PPNode_Hash_Attr implements PPNode {
1639 var $name, $value, $nextSibling;
1640
1641 function __construct( $name, $value ) {
1642 $this->name = $name;
1643 $this->value = $value;
1644 }
1645
1646 function __toString() {
1647 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1648 }
1649
1650 function getName() {
1651 return $this->name;
1652 }
1653
1654 function getNextSibling() {
1655 return $this->nextSibling;
1656 }
1657
1658 function getChildren() { return false; }
1659 function getFirstChild() { return false; }
1660 function getChildrenOfType( $name ) { return false; }
1661 function getLength() { return false; }
1662 function item( $i ) { return false; }
1663 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1664 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1665 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1666 }