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