More member variable documentation
[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 // Comments abutting, no change in visual end
309 $part->commentEnd = $wsEnd;
310 } else {
311 $part->visualEnd = $wsStart;
312 $part->commentEnd = $endPos;
313 }
314 }
315 $i = $endPos + 1;
316 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
317 $accum->addNodeWithText( 'comment', $inner );
318 }
319 continue;
320 }
321 $name = $matches[1];
322 $lowerName = strtolower( $name );
323 $attrStart = $i + strlen( $name ) + 1;
324
325 // Find end of tag
326 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
327 if ( $tagEndPos === false ) {
328 // Infinite backtrack
329 // Disable tag search to prevent worst-case O(N^2) performance
330 $noMoreGT = true;
331 $accum->addLiteral( '<' );
332 ++$i;
333 continue;
334 }
335
336 // Handle ignored tags
337 if ( in_array( $lowerName, $ignoredTags ) ) {
338 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i + 1 ) );
339 $i = $tagEndPos + 1;
340 continue;
341 }
342
343 $tagStartPos = $i;
344 if ( $text[$tagEndPos-1] == '/' ) {
345 // Short end tag
346 $attrEnd = $tagEndPos - 1;
347 $inner = null;
348 $i = $tagEndPos + 1;
349 $close = null;
350 } else {
351 $attrEnd = $tagEndPos;
352 // Find closing tag
353 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
354 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
355 {
356 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
357 $i = $matches[0][1] + strlen( $matches[0][0] );
358 $close = $matches[0][0];
359 } else {
360 // No end tag -- let it run out to the end of the text.
361 $inner = substr( $text, $tagEndPos + 1 );
362 $i = strlen( $text );
363 $close = null;
364 }
365 }
366 // <includeonly> and <noinclude> just become <ignore> tags
367 if ( in_array( $lowerName, $ignoredElements ) ) {
368 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
369 continue;
370 }
371
372 if ( $attrEnd <= $attrStart ) {
373 $attr = '';
374 } else {
375 // Note that the attr element contains the whitespace between name and attribute,
376 // this is necessary for precise reconstruction during pre-save transform.
377 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
378 }
379
380 $extNode = new PPNode_Hash_Tree( 'ext' );
381 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'name', $name ) );
382 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'attr', $attr ) );
383 if ( $inner !== null ) {
384 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'inner', $inner ) );
385 }
386 if ( $close !== null ) {
387 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'close', $close ) );
388 }
389 $accum->addNode( $extNode );
390 }
391
392 elseif ( $found == 'line-start' ) {
393 // Is this the start of a heading?
394 // Line break belongs before the heading element in any case
395 if ( $fakeLineStart ) {
396 $fakeLineStart = false;
397 } else {
398 $accum->addLiteral( $curChar );
399 $i++;
400 }
401
402 $count = strspn( $text, '=', $i, 6 );
403 if ( $count == 1 && $findEquals ) {
404 // DWIM: This looks kind of like a name/value separator
405 // Let's let the equals handler have it and break the potential heading
406 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
407 } elseif ( $count > 0 ) {
408 $piece = array(
409 'open' => "\n",
410 'close' => "\n",
411 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
412 'startPos' => $i,
413 'count' => $count );
414 $stack->push( $piece );
415 $accum =& $stack->getAccum();
416 extract( $stack->getFlags() );
417 $i += $count;
418 }
419 }
420
421 elseif ( $found == 'line-end' ) {
422 $piece = $stack->top;
423 // A heading must be open, otherwise \n wouldn't have been in the search list
424 assert( $piece->open == "\n" );
425 $part = $piece->getCurrentPart();
426 // Search back through the input to see if it has a proper close
427 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
428 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
429 $searchStart = $i - $wsLength;
430 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
431 // Comment found at line end
432 // Search for equals signs before the comment
433 $searchStart = $part->visualEnd;
434 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
435 }
436 $count = $piece->count;
437 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
438 if ( $equalsLength > 0 ) {
439 if ( $searchStart - $equalsLength == $piece->startPos ) {
440 // This is just a single string of equals signs on its own line
441 // Replicate the doHeadings behaviour /={count}(.+)={count}/
442 // First find out how many equals signs there really are (don't stop at 6)
443 $count = $equalsLength;
444 if ( $count < 3 ) {
445 $count = 0;
446 } else {
447 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
448 }
449 } else {
450 $count = min( $equalsLength, $count );
451 }
452 if ( $count > 0 ) {
453 // Normal match, output <h>
454 $element = new PPNode_Hash_Tree( 'possible-h' );
455 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
456 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++ ) );
457 $element->lastChild->nextSibling = $accum->firstNode;
458 $element->lastChild = $accum->lastNode;
459 } else {
460 // Single equals sign on its own line, count=0
461 $element = $accum;
462 }
463 } else {
464 // No match, no <h>, just pass down the inner text
465 $element = $accum;
466 }
467 // Unwind the stack
468 $stack->pop();
469 $accum =& $stack->getAccum();
470 extract( $stack->getFlags() );
471
472 // Append the result to the enclosing accumulator
473 if ( $element instanceof PPNode ) {
474 $accum->addNode( $element );
475 } else {
476 $accum->addAccum( $element );
477 }
478 // Note that we do NOT increment the input pointer.
479 // This is because the closing linebreak could be the opening linebreak of
480 // another heading. Infinite loops are avoided because the next iteration MUST
481 // hit the heading open case above, which unconditionally increments the
482 // input pointer.
483 }
484
485 elseif ( $found == 'open' ) {
486 # count opening brace characters
487 $count = strspn( $text, $curChar, $i );
488
489 # we need to add to stack only if opening brace count is enough for one of the rules
490 if ( $count >= $rule['min'] ) {
491 # Add it to the stack
492 $piece = array(
493 'open' => $curChar,
494 'close' => $rule['end'],
495 'count' => $count,
496 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
497 );
498
499 $stack->push( $piece );
500 $accum =& $stack->getAccum();
501 extract( $stack->getFlags() );
502 } else {
503 # Add literal brace(s)
504 $accum->addLiteral( str_repeat( $curChar, $count ) );
505 }
506 $i += $count;
507 }
508
509 elseif ( $found == 'close' ) {
510 $piece = $stack->top;
511 # lets check if there are enough characters for closing brace
512 $maxCount = $piece->count;
513 $count = strspn( $text, $curChar, $i, $maxCount );
514
515 # check for maximum matching characters (if there are 5 closing
516 # characters, we will probably need only 3 - depending on the rules)
517 $rule = $rules[$piece->open];
518 if ( $count > $rule['max'] ) {
519 # The specified maximum exists in the callback array, unless the caller
520 # has made an error
521 $matchingCount = $rule['max'];
522 } else {
523 # Count is less than the maximum
524 # Skip any gaps in the callback array to find the true largest match
525 # Need to use array_key_exists not isset because the callback can be null
526 $matchingCount = $count;
527 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
528 --$matchingCount;
529 }
530 }
531
532 if ($matchingCount <= 0) {
533 # No matching element found in callback array
534 # Output a literal closing brace and continue
535 $accum->addLiteral( str_repeat( $curChar, $count ) );
536 $i += $count;
537 continue;
538 }
539 $name = $rule['names'][$matchingCount];
540 if ( $name === null ) {
541 // No element, just literal text
542 $element = $piece->breakSyntax( $matchingCount );
543 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
544 } else {
545 # Create XML element
546 # Note: $parts is already XML, does not need to be encoded further
547 $parts = $piece->parts;
548 $titleAccum = $parts[0]->out;
549 unset( $parts[0] );
550
551 $element = new PPNode_Hash_Tree( $name );
552
553 # The invocation is at the start of the line if lineStart is set in
554 # the stack, and all opening brackets are used up.
555 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
556 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
557 }
558 $titleNode = new PPNode_Hash_Tree( 'title' );
559 $titleNode->firstChild = $titleAccum->firstNode;
560 $titleNode->lastChild = $titleAccum->lastNode;
561 $element->addChild( $titleNode );
562 $argIndex = 1;
563 foreach ( $parts as $part ) {
564 if ( isset( $part->eqpos ) ) {
565 // Find equals
566 $lastNode = false;
567 for ( $node = $part->out->firstNode; $node; $node = $node->nextSibling ) {
568 if ( $node === $part->eqpos ) {
569 break;
570 }
571 $lastNode = $node;
572 }
573 if ( !$node ) {
574 throw new MWException( __METHOD__. ': eqpos not found' );
575 }
576 if ( $node->name !== 'equals' ) {
577 throw new MWException( __METHOD__ .': eqpos is not equals' );
578 }
579 $equalsNode = $node;
580
581 // Construct name node
582 $nameNode = new PPNode_Hash_Tree( 'name' );
583 if ( $lastNode !== false ) {
584 $lastNode->nextSibling = false;
585 $nameNode->firstChild = $part->out->firstNode;
586 $nameNode->lastChild = $lastNode;
587 }
588
589 // Construct value node
590 $valueNode = new PPNode_Hash_Tree( 'value' );
591 if ( $equalsNode->nextSibling !== false ) {
592 $valueNode->firstChild = $equalsNode->nextSibling;
593 $valueNode->lastChild = $part->out->lastNode;
594 }
595 $partNode = new PPNode_Hash_Tree( 'part' );
596 $partNode->addChild( $nameNode );
597 $partNode->addChild( $equalsNode->firstChild );
598 $partNode->addChild( $valueNode );
599 $element->addChild( $partNode );
600 } else {
601 $partNode = new PPNode_Hash_Tree( 'part' );
602 $nameNode = new PPNode_Hash_Tree( 'name' );
603 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++ ) );
604 $valueNode = new PPNode_Hash_Tree( 'value' );
605 $valueNode->firstChild = $part->out->firstNode;
606 $valueNode->lastChild = $part->out->lastNode;
607 $partNode->addChild( $nameNode );
608 $partNode->addChild( $valueNode );
609 $element->addChild( $partNode );
610 }
611 }
612 }
613
614 # Advance input pointer
615 $i += $matchingCount;
616
617 # Unwind the stack
618 $stack->pop();
619 $accum =& $stack->getAccum();
620
621 # Re-add the old stack element if it still has unmatched opening characters remaining
622 if ($matchingCount < $piece->count) {
623 $piece->parts = array( new PPDPart_Hash );
624 $piece->count -= $matchingCount;
625 # do we still qualify for any callback with remaining count?
626 $names = $rules[$piece->open]['names'];
627 $skippedBraces = 0;
628 $enclosingAccum =& $accum;
629 while ( $piece->count ) {
630 if ( array_key_exists( $piece->count, $names ) ) {
631 $stack->push( $piece );
632 $accum =& $stack->getAccum();
633 break;
634 }
635 --$piece->count;
636 $skippedBraces ++;
637 }
638 $enclosingAccum->addLiteral( str_repeat( $piece->open, $skippedBraces ) );
639 }
640
641 extract( $stack->getFlags() );
642
643 # Add XML element to the enclosing accumulator
644 if ( $element instanceof PPNode ) {
645 $accum->addNode( $element );
646 } else {
647 $accum->addAccum( $element );
648 }
649 }
650
651 elseif ( $found == 'pipe' ) {
652 $findEquals = true; // shortcut for getFlags()
653 $stack->addPart();
654 $accum =& $stack->getAccum();
655 ++$i;
656 }
657
658 elseif ( $found == 'equals' ) {
659 $findEquals = false; // shortcut for getFlags()
660 $accum->addNodeWithText( 'equals', '=' );
661 $stack->getCurrentPart()->eqpos = $accum->lastNode;
662 ++$i;
663 }
664 }
665
666 # Output any remaining unclosed brackets
667 foreach ( $stack->stack as $piece ) {
668 $stack->rootAccum->addAccum( $piece->breakSyntax() );
669 }
670
671 # Enable top-level headings
672 for ( $node = $stack->rootAccum->firstNode; $node; $node = $node->nextSibling ) {
673 if ( isset( $node->name ) && $node->name === 'possible-h' ) {
674 $node->name = 'h';
675 }
676 }
677
678 $rootNode = new PPNode_Hash_Tree( 'root' );
679 $rootNode->firstChild = $stack->rootAccum->firstNode;
680 $rootNode->lastChild = $stack->rootAccum->lastNode;
681
682 // Cache
683 if ($cacheable) {
684 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . serialize( $rootNode );
685 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
686 wfProfileOut( __METHOD__.'-cache-miss' );
687 wfProfileOut( __METHOD__.'-cacheable' );
688 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
689 }
690
691 wfProfileOut( __METHOD__ );
692 return $rootNode;
693 }
694 }
695
696 /**
697 * Stack class to help Preprocessor::preprocessToObj()
698 * @ingroup Parser
699 */
700 class PPDStack_Hash extends PPDStack {
701 function __construct() {
702 $this->elementClass = 'PPDStackElement_Hash';
703 parent::__construct();
704 $this->rootAccum = new PPDAccum_Hash;
705 }
706 }
707
708 /**
709 * @ingroup Parser
710 */
711 class PPDStackElement_Hash extends PPDStackElement {
712 function __construct( $data = array() ) {
713 $this->partClass = 'PPDPart_Hash';
714 parent::__construct( $data );
715 }
716
717 /**
718 * Get the accumulator that would result if the close is not found.
719 */
720 function breakSyntax( $openingCount = false ) {
721 if ( $this->open == "\n" ) {
722 $accum = $this->parts[0]->out;
723 } else {
724 if ( $openingCount === false ) {
725 $openingCount = $this->count;
726 }
727 $accum = new PPDAccum_Hash;
728 $accum->addLiteral( str_repeat( $this->open, $openingCount ) );
729 $first = true;
730 foreach ( $this->parts as $part ) {
731 if ( $first ) {
732 $first = false;
733 } else {
734 $accum->addLiteral( '|' );
735 }
736 $accum->addAccum( $part->out );
737 }
738 }
739 return $accum;
740 }
741 }
742
743 /**
744 * @ingroup Parser
745 */
746 class PPDPart_Hash extends PPDPart {
747 function __construct( $out = '' ) {
748 $accum = new PPDAccum_Hash;
749 if ( $out !== '' ) {
750 $accum->addLiteral( $out );
751 }
752 parent::__construct( $accum );
753 }
754 }
755
756 /**
757 * @ingroup Parser
758 */
759 class PPDAccum_Hash {
760 var $firstNode, $lastNode;
761
762 function __construct() {
763 $this->firstNode = $this->lastNode = false;
764 }
765
766 /**
767 * Append a string literal
768 */
769 function addLiteral( $s ) {
770 if ( $this->lastNode === false ) {
771 $this->firstNode = $this->lastNode = new PPNode_Hash_Text( $s );
772 } elseif ( $this->lastNode instanceof PPNode_Hash_Text ) {
773 $this->lastNode->value .= $s;
774 } else {
775 $this->lastNode->nextSibling = new PPNode_Hash_Text( $s );
776 $this->lastNode = $this->lastNode->nextSibling;
777 }
778 }
779
780 /**
781 * Append a PPNode
782 */
783 function addNode( PPNode $node ) {
784 if ( $this->lastNode === false ) {
785 $this->firstNode = $this->lastNode = $node;
786 } else {
787 $this->lastNode->nextSibling = $node;
788 $this->lastNode = $node;
789 }
790 }
791
792 /**
793 * Append a tree node with text contents
794 */
795 function addNodeWithText( $name, $value ) {
796 $node = PPNode_Hash_Tree::newWithText( $name, $value );
797 $this->addNode( $node );
798 }
799
800 /**
801 * Append a PPAccum_Hash
802 * Takes over ownership of the nodes in the source argument. These nodes may
803 * subsequently be modified, especially nextSibling.
804 */
805 function addAccum( $accum ) {
806 if ( $accum->lastNode === false ) {
807 // nothing to add
808 } elseif ( $this->lastNode === false ) {
809 $this->firstNode = $accum->firstNode;
810 $this->lastNode = $accum->lastNode;
811 } else {
812 $this->lastNode->nextSibling = $accum->firstNode;
813 $this->lastNode = $accum->lastNode;
814 }
815 }
816 }
817
818 /**
819 * An expansion frame, used as a context to expand the result of preprocessToObj()
820 * @ingroup Parser
821 */
822 class PPFrame_Hash implements PPFrame {
823
824 /**
825 * @var Parser
826 */
827 var $parser;
828
829 /**
830 * @var Preprocessor
831 */
832 var $preprocessor;
833
834 /**
835 * @var Title
836 */
837 var $title;
838 var $titleCache;
839
840 /**
841 * Hashtable listing templates which are disallowed for expansion in this frame,
842 * having been encountered previously in parent frames.
843 */
844 var $loopCheckHash;
845
846 /**
847 * Recursion depth of this frame, top = 0
848 * Note that this is NOT the same as expansion depth in expand()
849 */
850 var $depth;
851
852
853 /**
854 * Construct a new preprocessor frame.
855 * @param $preprocessor Preprocessor: the parent preprocessor
856 */
857 function __construct( $preprocessor ) {
858 $this->preprocessor = $preprocessor;
859 $this->parser = $preprocessor->parser;
860 $this->title = $this->parser->mTitle;
861 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
862 $this->loopCheckHash = array();
863 $this->depth = 0;
864 }
865
866 /**
867 * Create a new child frame
868 * $args is optionally a multi-root PPNode or array containing the template arguments
869 */
870 function newChild( $args = false, $title = false ) {
871 $namedArgs = array();
872 $numberedArgs = array();
873 if ( $title === false ) {
874 $title = $this->title;
875 }
876 if ( $args !== false ) {
877 if ( $args instanceof PPNode_Hash_Array ) {
878 $args = $args->value;
879 } elseif ( !is_array( $args ) ) {
880 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
881 }
882 foreach ( $args as $arg ) {
883 $bits = $arg->splitArg();
884 if ( $bits['index'] !== '' ) {
885 // Numbered parameter
886 $numberedArgs[$bits['index']] = $bits['value'];
887 unset( $namedArgs[$bits['index']] );
888 } else {
889 // Named parameter
890 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
891 $namedArgs[$name] = $bits['value'];
892 unset( $numberedArgs[$name] );
893 }
894 }
895 }
896 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
897 }
898
899 function expand( $root, $flags = 0 ) {
900 static $expansionDepth = 0;
901 if ( is_string( $root ) ) {
902 return $root;
903 }
904
905 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
906 return '<span class="error">Node-count limit exceeded</span>';
907 }
908 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
909 return '<span class="error">Expansion depth limit exceeded</span>';
910 }
911 ++$expansionDepth;
912
913 $outStack = array( '', '' );
914 $iteratorStack = array( false, $root );
915 $indexStack = array( 0, 0 );
916
917 while ( count( $iteratorStack ) > 1 ) {
918 $level = count( $outStack ) - 1;
919 $iteratorNode =& $iteratorStack[ $level ];
920 $out =& $outStack[$level];
921 $index =& $indexStack[$level];
922
923 if ( is_array( $iteratorNode ) ) {
924 if ( $index >= count( $iteratorNode ) ) {
925 // All done with this iterator
926 $iteratorStack[$level] = false;
927 $contextNode = false;
928 } else {
929 $contextNode = $iteratorNode[$index];
930 $index++;
931 }
932 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
933 if ( $index >= $iteratorNode->getLength() ) {
934 // All done with this iterator
935 $iteratorStack[$level] = false;
936 $contextNode = false;
937 } else {
938 $contextNode = $iteratorNode->item( $index );
939 $index++;
940 }
941 } else {
942 // Copy to $contextNode and then delete from iterator stack,
943 // because this is not an iterator but we do have to execute it once
944 $contextNode = $iteratorStack[$level];
945 $iteratorStack[$level] = false;
946 }
947
948 $newIterator = false;
949
950 if ( $contextNode === false ) {
951 // nothing to do
952 } elseif ( is_string( $contextNode ) ) {
953 $out .= $contextNode;
954 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
955 $newIterator = $contextNode;
956 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
957 // No output
958 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
959 $out .= $contextNode->value;
960 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
961 if ( $contextNode->name == 'template' ) {
962 # Double-brace expansion
963 $bits = $contextNode->splitTemplate();
964 if ( $flags & PPFrame::NO_TEMPLATES ) {
965 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
966 } else {
967 $ret = $this->parser->braceSubstitution( $bits, $this );
968 if ( isset( $ret['object'] ) ) {
969 $newIterator = $ret['object'];
970 } else {
971 $out .= $ret['text'];
972 }
973 }
974 } elseif ( $contextNode->name == 'tplarg' ) {
975 # Triple-brace expansion
976 $bits = $contextNode->splitTemplate();
977 if ( $flags & PPFrame::NO_ARGS ) {
978 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
979 } else {
980 $ret = $this->parser->argSubstitution( $bits, $this );
981 if ( isset( $ret['object'] ) ) {
982 $newIterator = $ret['object'];
983 } else {
984 $out .= $ret['text'];
985 }
986 }
987 } elseif ( $contextNode->name == 'comment' ) {
988 # HTML-style comment
989 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
990 if ( $this->parser->ot['html']
991 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
992 || ( $flags & PPFrame::STRIP_COMMENTS ) )
993 {
994 $out .= '';
995 }
996 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
997 # Not in RECOVER_COMMENTS mode (extractSections) though
998 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
999 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1000 }
1001 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1002 else {
1003 $out .= $contextNode->firstChild->value;
1004 }
1005 } elseif ( $contextNode->name == 'ignore' ) {
1006 # Output suppression used by <includeonly> etc.
1007 # OT_WIKI will only respect <ignore> in substed templates.
1008 # The other output types respect it unless NO_IGNORE is set.
1009 # extractSections() sets NO_IGNORE and so never respects it.
1010 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1011 $out .= $contextNode->firstChild->value;
1012 } else {
1013 //$out .= '';
1014 }
1015 } elseif ( $contextNode->name == 'ext' ) {
1016 # Extension tag
1017 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1018 $out .= $this->parser->extensionSubstitution( $bits, $this );
1019 } elseif ( $contextNode->name == 'h' ) {
1020 # Heading
1021 if ( $this->parser->ot['html'] ) {
1022 # Expand immediately and insert heading index marker
1023 $s = '';
1024 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1025 $s .= $this->expand( $node, $flags );
1026 }
1027
1028 $bits = $contextNode->splitHeading();
1029 $titleText = $this->title->getPrefixedDBkey();
1030 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1031 $serial = count( $this->parser->mHeadings ) - 1;
1032 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1033 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1034 $this->parser->mStripState->setGeneral( $marker, '' );
1035 $out .= $s;
1036 } else {
1037 # Expand in virtual stack
1038 $newIterator = $contextNode->getChildren();
1039 }
1040 } else {
1041 # Generic recursive expansion
1042 $newIterator = $contextNode->getChildren();
1043 }
1044 } else {
1045 throw new MWException( __METHOD__.': Invalid parameter type' );
1046 }
1047
1048 if ( $newIterator !== false ) {
1049 $outStack[] = '';
1050 $iteratorStack[] = $newIterator;
1051 $indexStack[] = 0;
1052 } elseif ( $iteratorStack[$level] === false ) {
1053 // Return accumulated value to parent
1054 // With tail recursion
1055 while ( $iteratorStack[$level] === false && $level > 0 ) {
1056 $outStack[$level - 1] .= $out;
1057 array_pop( $outStack );
1058 array_pop( $iteratorStack );
1059 array_pop( $indexStack );
1060 $level--;
1061 }
1062 }
1063 }
1064 --$expansionDepth;
1065 return $outStack[0];
1066 }
1067
1068 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1069 $args = array_slice( func_get_args(), 2 );
1070
1071 $first = true;
1072 $s = '';
1073 foreach ( $args as $root ) {
1074 if ( $root instanceof PPNode_Hash_Array ) {
1075 $root = $root->value;
1076 }
1077 if ( !is_array( $root ) ) {
1078 $root = array( $root );
1079 }
1080 foreach ( $root as $node ) {
1081 if ( $first ) {
1082 $first = false;
1083 } else {
1084 $s .= $sep;
1085 }
1086 $s .= $this->expand( $node, $flags );
1087 }
1088 }
1089 return $s;
1090 }
1091
1092 /**
1093 * Implode with no flags specified
1094 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1095 */
1096 function implode( $sep /*, ... */ ) {
1097 $args = array_slice( func_get_args(), 1 );
1098
1099 $first = true;
1100 $s = '';
1101 foreach ( $args as $root ) {
1102 if ( $root instanceof PPNode_Hash_Array ) {
1103 $root = $root->value;
1104 }
1105 if ( !is_array( $root ) ) {
1106 $root = array( $root );
1107 }
1108 foreach ( $root as $node ) {
1109 if ( $first ) {
1110 $first = false;
1111 } else {
1112 $s .= $sep;
1113 }
1114 $s .= $this->expand( $node );
1115 }
1116 }
1117 return $s;
1118 }
1119
1120 /**
1121 * Makes an object that, when expand()ed, will be the same as one obtained
1122 * with implode()
1123 */
1124 function virtualImplode( $sep /*, ... */ ) {
1125 $args = array_slice( func_get_args(), 1 );
1126 $out = array();
1127 $first = true;
1128
1129 foreach ( $args as $root ) {
1130 if ( $root instanceof PPNode_Hash_Array ) {
1131 $root = $root->value;
1132 }
1133 if ( !is_array( $root ) ) {
1134 $root = array( $root );
1135 }
1136 foreach ( $root as $node ) {
1137 if ( $first ) {
1138 $first = false;
1139 } else {
1140 $out[] = $sep;
1141 }
1142 $out[] = $node;
1143 }
1144 }
1145 return new PPNode_Hash_Array( $out );
1146 }
1147
1148 /**
1149 * Virtual implode with brackets
1150 */
1151 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1152 $args = array_slice( func_get_args(), 3 );
1153 $out = array( $start );
1154 $first = true;
1155
1156 foreach ( $args as $root ) {
1157 if ( $root instanceof PPNode_Hash_Array ) {
1158 $root = $root->value;
1159 }
1160 if ( !is_array( $root ) ) {
1161 $root = array( $root );
1162 }
1163 foreach ( $root as $node ) {
1164 if ( $first ) {
1165 $first = false;
1166 } else {
1167 $out[] = $sep;
1168 }
1169 $out[] = $node;
1170 }
1171 }
1172 $out[] = $end;
1173 return new PPNode_Hash_Array( $out );
1174 }
1175
1176 function __toString() {
1177 return 'frame{}';
1178 }
1179
1180 function getPDBK( $level = false ) {
1181 if ( $level === false ) {
1182 return $this->title->getPrefixedDBkey();
1183 } else {
1184 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1185 }
1186 }
1187
1188 function getArguments() {
1189 return array();
1190 }
1191
1192 function getNumberedArguments() {
1193 return array();
1194 }
1195
1196 function getNamedArguments() {
1197 return array();
1198 }
1199
1200 /**
1201 * Returns true if there are no arguments in this frame
1202 */
1203 function isEmpty() {
1204 return true;
1205 }
1206
1207 function getArgument( $name ) {
1208 return false;
1209 }
1210
1211 /**
1212 * Returns true if the infinite loop check is OK, false if a loop is detected
1213 *
1214 * @param $title Title
1215 */
1216 function loopCheck( $title ) {
1217 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1218 }
1219
1220 /**
1221 * Return true if the frame is a template frame
1222 */
1223 function isTemplate() {
1224 return false;
1225 }
1226 }
1227
1228 /**
1229 * Expansion frame with template arguments
1230 * @ingroup Parser
1231 */
1232 class PPTemplateFrame_Hash extends PPFrame_Hash {
1233 var $numberedArgs, $namedArgs, $parent;
1234 var $numberedExpansionCache, $namedExpansionCache;
1235
1236 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1237 parent::__construct( $preprocessor );
1238
1239 $this->parent = $parent;
1240 $this->numberedArgs = $numberedArgs;
1241 $this->namedArgs = $namedArgs;
1242 $this->title = $title;
1243 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1244 $this->titleCache = $parent->titleCache;
1245 $this->titleCache[] = $pdbk;
1246 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1247 if ( $pdbk !== false ) {
1248 $this->loopCheckHash[$pdbk] = true;
1249 }
1250 $this->depth = $parent->depth + 1;
1251 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1252 }
1253
1254 function __toString() {
1255 $s = 'tplframe{';
1256 $first = true;
1257 $args = $this->numberedArgs + $this->namedArgs;
1258 foreach ( $args as $name => $value ) {
1259 if ( $first ) {
1260 $first = false;
1261 } else {
1262 $s .= ', ';
1263 }
1264 $s .= "\"$name\":\"" .
1265 str_replace( '"', '\\"', $value->__toString() ) . '"';
1266 }
1267 $s .= '}';
1268 return $s;
1269 }
1270 /**
1271 * Returns true if there are no arguments in this frame
1272 */
1273 function isEmpty() {
1274 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1275 }
1276
1277 function getArguments() {
1278 $arguments = array();
1279 foreach ( array_merge(
1280 array_keys($this->numberedArgs),
1281 array_keys($this->namedArgs)) as $key ) {
1282 $arguments[$key] = $this->getArgument($key);
1283 }
1284 return $arguments;
1285 }
1286
1287 function getNumberedArguments() {
1288 $arguments = array();
1289 foreach ( array_keys($this->numberedArgs) as $key ) {
1290 $arguments[$key] = $this->getArgument($key);
1291 }
1292 return $arguments;
1293 }
1294
1295 function getNamedArguments() {
1296 $arguments = array();
1297 foreach ( array_keys($this->namedArgs) as $key ) {
1298 $arguments[$key] = $this->getArgument($key);
1299 }
1300 return $arguments;
1301 }
1302
1303 function getNumberedArgument( $index ) {
1304 if ( !isset( $this->numberedArgs[$index] ) ) {
1305 return false;
1306 }
1307 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1308 # No trimming for unnamed arguments
1309 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1310 }
1311 return $this->numberedExpansionCache[$index];
1312 }
1313
1314 function getNamedArgument( $name ) {
1315 if ( !isset( $this->namedArgs[$name] ) ) {
1316 return false;
1317 }
1318 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1319 # Trim named arguments post-expand, for backwards compatibility
1320 $this->namedExpansionCache[$name] = trim(
1321 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1322 }
1323 return $this->namedExpansionCache[$name];
1324 }
1325
1326 function getArgument( $name ) {
1327 $text = $this->getNumberedArgument( $name );
1328 if ( $text === false ) {
1329 $text = $this->getNamedArgument( $name );
1330 }
1331 return $text;
1332 }
1333
1334 /**
1335 * Return true if the frame is a template frame
1336 */
1337 function isTemplate() {
1338 return true;
1339 }
1340 }
1341
1342 /**
1343 * Expansion frame with custom arguments
1344 * @ingroup Parser
1345 */
1346 class PPCustomFrame_Hash extends PPFrame_Hash {
1347 var $args;
1348
1349 function __construct( $preprocessor, $args ) {
1350 parent::__construct( $preprocessor );
1351 $this->args = $args;
1352 }
1353
1354 function __toString() {
1355 $s = 'cstmframe{';
1356 $first = true;
1357 foreach ( $this->args as $name => $value ) {
1358 if ( $first ) {
1359 $first = false;
1360 } else {
1361 $s .= ', ';
1362 }
1363 $s .= "\"$name\":\"" .
1364 str_replace( '"', '\\"', $value->__toString() ) . '"';
1365 }
1366 $s .= '}';
1367 return $s;
1368 }
1369
1370 function isEmpty() {
1371 return !count( $this->args );
1372 }
1373
1374 function getArgument( $index ) {
1375 if ( !isset( $this->args[$index] ) ) {
1376 return false;
1377 }
1378 return $this->args[$index];
1379 }
1380 }
1381
1382 /**
1383 * @ingroup Parser
1384 */
1385 class PPNode_Hash_Tree implements PPNode {
1386 var $name, $firstChild, $lastChild, $nextSibling;
1387
1388 function __construct( $name ) {
1389 $this->name = $name;
1390 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1391 }
1392
1393 function __toString() {
1394 $inner = '';
1395 $attribs = '';
1396 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1397 if ( $node instanceof PPNode_Hash_Attr ) {
1398 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1399 } else {
1400 $inner .= $node->__toString();
1401 }
1402 }
1403 if ( $inner === '' ) {
1404 return "<{$this->name}$attribs/>";
1405 } else {
1406 return "<{$this->name}$attribs>$inner</{$this->name}>";
1407 }
1408 }
1409
1410 static function newWithText( $name, $text ) {
1411 $obj = new self( $name );
1412 $obj->addChild( new PPNode_Hash_Text( $text ) );
1413 return $obj;
1414 }
1415
1416 function addChild( $node ) {
1417 if ( $this->lastChild === false ) {
1418 $this->firstChild = $this->lastChild = $node;
1419 } else {
1420 $this->lastChild->nextSibling = $node;
1421 $this->lastChild = $node;
1422 }
1423 }
1424
1425 function getChildren() {
1426 $children = array();
1427 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1428 $children[] = $child;
1429 }
1430 return new PPNode_Hash_Array( $children );
1431 }
1432
1433 function getFirstChild() {
1434 return $this->firstChild;
1435 }
1436
1437 function getNextSibling() {
1438 return $this->nextSibling;
1439 }
1440
1441 function getChildrenOfType( $name ) {
1442 $children = array();
1443 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1444 if ( isset( $child->name ) && $child->name === $name ) {
1445 $children[] = $name;
1446 }
1447 }
1448 return $children;
1449 }
1450
1451 function getLength() { return false; }
1452 function item( $i ) { return false; }
1453
1454 function getName() {
1455 return $this->name;
1456 }
1457
1458 /**
1459 * Split a <part> node into an associative array containing:
1460 * name PPNode name
1461 * index String index
1462 * value PPNode value
1463 */
1464 function splitArg() {
1465 $bits = array();
1466 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1467 if ( !isset( $child->name ) ) {
1468 continue;
1469 }
1470 if ( $child->name === 'name' ) {
1471 $bits['name'] = $child;
1472 if ( $child->firstChild instanceof PPNode_Hash_Attr
1473 && $child->firstChild->name === 'index' )
1474 {
1475 $bits['index'] = $child->firstChild->value;
1476 }
1477 } elseif ( $child->name === 'value' ) {
1478 $bits['value'] = $child;
1479 }
1480 }
1481
1482 if ( !isset( $bits['name'] ) ) {
1483 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1484 }
1485 if ( !isset( $bits['index'] ) ) {
1486 $bits['index'] = '';
1487 }
1488 return $bits;
1489 }
1490
1491 /**
1492 * Split an <ext> node into an associative array containing name, attr, inner and close
1493 * All values in the resulting array are PPNodes. Inner and close are optional.
1494 */
1495 function splitExt() {
1496 $bits = array();
1497 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1498 if ( !isset( $child->name ) ) {
1499 continue;
1500 }
1501 if ( $child->name == 'name' ) {
1502 $bits['name'] = $child;
1503 } elseif ( $child->name == 'attr' ) {
1504 $bits['attr'] = $child;
1505 } elseif ( $child->name == 'inner' ) {
1506 $bits['inner'] = $child;
1507 } elseif ( $child->name == 'close' ) {
1508 $bits['close'] = $child;
1509 }
1510 }
1511 if ( !isset( $bits['name'] ) ) {
1512 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1513 }
1514 return $bits;
1515 }
1516
1517 /**
1518 * Split an <h> node
1519 */
1520 function splitHeading() {
1521 if ( $this->name !== 'h' ) {
1522 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1523 }
1524 $bits = array();
1525 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1526 if ( !isset( $child->name ) ) {
1527 continue;
1528 }
1529 if ( $child->name == 'i' ) {
1530 $bits['i'] = $child->value;
1531 } elseif ( $child->name == 'level' ) {
1532 $bits['level'] = $child->value;
1533 }
1534 }
1535 if ( !isset( $bits['i'] ) ) {
1536 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1537 }
1538 return $bits;
1539 }
1540
1541 /**
1542 * Split a <template> or <tplarg> node
1543 */
1544 function splitTemplate() {
1545 $parts = array();
1546 $bits = array( 'lineStart' => '' );
1547 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1548 if ( !isset( $child->name ) ) {
1549 continue;
1550 }
1551 if ( $child->name == 'title' ) {
1552 $bits['title'] = $child;
1553 }
1554 if ( $child->name == 'part' ) {
1555 $parts[] = $child;
1556 }
1557 if ( $child->name == 'lineStart' ) {
1558 $bits['lineStart'] = '1';
1559 }
1560 }
1561 if ( !isset( $bits['title'] ) ) {
1562 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1563 }
1564 $bits['parts'] = new PPNode_Hash_Array( $parts );
1565 return $bits;
1566 }
1567 }
1568
1569 /**
1570 * @ingroup Parser
1571 */
1572 class PPNode_Hash_Text implements PPNode {
1573 var $value, $nextSibling;
1574
1575 function __construct( $value ) {
1576 if ( is_object( $value ) ) {
1577 throw new MWException( __CLASS__ . ' given object instead of string' );
1578 }
1579 $this->value = $value;
1580 }
1581
1582 function __toString() {
1583 return htmlspecialchars( $this->value );
1584 }
1585
1586 function getNextSibling() {
1587 return $this->nextSibling;
1588 }
1589
1590 function getChildren() { return false; }
1591 function getFirstChild() { return false; }
1592 function getChildrenOfType( $name ) { return false; }
1593 function getLength() { return false; }
1594 function item( $i ) { return false; }
1595 function getName() { return '#text'; }
1596 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1597 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1598 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1599 }
1600
1601 /**
1602 * @ingroup Parser
1603 */
1604 class PPNode_Hash_Array implements PPNode {
1605 var $value, $nextSibling;
1606
1607 function __construct( $value ) {
1608 $this->value = $value;
1609 }
1610
1611 function __toString() {
1612 return var_export( $this, true );
1613 }
1614
1615 function getLength() {
1616 return count( $this->value );
1617 }
1618
1619 function item( $i ) {
1620 return $this->value[$i];
1621 }
1622
1623 function getName() { return '#nodelist'; }
1624
1625 function getNextSibling() {
1626 return $this->nextSibling;
1627 }
1628
1629 function getChildren() { return false; }
1630 function getFirstChild() { return false; }
1631 function getChildrenOfType( $name ) { return false; }
1632 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1633 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1634 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1635 }
1636
1637 /**
1638 * @ingroup Parser
1639 */
1640 class PPNode_Hash_Attr implements PPNode {
1641 var $name, $value, $nextSibling;
1642
1643 function __construct( $name, $value ) {
1644 $this->name = $name;
1645 $this->value = $value;
1646 }
1647
1648 function __toString() {
1649 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1650 }
1651
1652 function getName() {
1653 return $this->name;
1654 }
1655
1656 function getNextSibling() {
1657 return $this->nextSibling;
1658 }
1659
1660 function getChildren() { return false; }
1661 function getFirstChild() { return false; }
1662 function getChildrenOfType( $name ) { return false; }
1663 function getLength() { return false; }
1664 function item( $i ) { return false; }
1665 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1666 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1667 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1668 }