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