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