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