Reverted r86072, r86419 per CR. Lots of conflicts resolved here. Removes lineStart...
[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|false
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 $bits['interwiki'] = $this->title->getInterwiki( );
980 $ret = $this->parser->braceSubstitution( $bits, $this );
981 if ( isset( $ret['object'] ) ) {
982 $newIterator = $ret['object'];
983 } else {
984 $out .= $ret['text'];
985 }
986 }
987 } elseif ( $contextNode->name == 'tplarg' ) {
988 # Triple-brace expansion
989 $bits = $contextNode->splitTemplate();
990 if ( $flags & PPFrame::NO_ARGS ) {
991 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
992 } else {
993 $ret = $this->parser->argSubstitution( $bits, $this );
994 if ( isset( $ret['object'] ) ) {
995 $newIterator = $ret['object'];
996 } else {
997 $out .= $ret['text'];
998 }
999 }
1000 } elseif ( $contextNode->name == 'comment' ) {
1001 # HTML-style comment
1002 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1003 if ( $this->parser->ot['html']
1004 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1005 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1006 {
1007 $out .= '';
1008 }
1009 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1010 # Not in RECOVER_COMMENTS mode (extractSections) though
1011 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1012 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1013 }
1014 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1015 else {
1016 $out .= $contextNode->firstChild->value;
1017 }
1018 } elseif ( $contextNode->name == 'ignore' ) {
1019 # Output suppression used by <includeonly> etc.
1020 # OT_WIKI will only respect <ignore> in substed templates.
1021 # The other output types respect it unless NO_IGNORE is set.
1022 # extractSections() sets NO_IGNORE and so never respects it.
1023 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1024 $out .= $contextNode->firstChild->value;
1025 } else {
1026 //$out .= '';
1027 }
1028 } elseif ( $contextNode->name == 'ext' ) {
1029 # Extension tag
1030 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1031 $out .= $this->parser->extensionSubstitution( $bits, $this );
1032 } elseif ( $contextNode->name == 'h' ) {
1033 # Heading
1034 if ( $this->parser->ot['html'] ) {
1035 # Expand immediately and insert heading index marker
1036 $s = '';
1037 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1038 $s .= $this->expand( $node, $flags );
1039 }
1040
1041 $bits = $contextNode->splitHeading();
1042 $titleText = $this->title->getPrefixedDBkey();
1043 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1044 $serial = count( $this->parser->mHeadings ) - 1;
1045 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1046 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1047 $this->parser->mStripState->addGeneral( $marker, '' );
1048 $out .= $s;
1049 } else {
1050 # Expand in virtual stack
1051 $newIterator = $contextNode->getChildren();
1052 }
1053 } else {
1054 # Generic recursive expansion
1055 $newIterator = $contextNode->getChildren();
1056 }
1057 } else {
1058 throw new MWException( __METHOD__.': Invalid parameter type' );
1059 }
1060
1061 if ( $newIterator !== false ) {
1062 $outStack[] = '';
1063 $iteratorStack[] = $newIterator;
1064 $indexStack[] = 0;
1065 } elseif ( $iteratorStack[$level] === false ) {
1066 // Return accumulated value to parent
1067 // With tail recursion
1068 while ( $iteratorStack[$level] === false && $level > 0 ) {
1069 $outStack[$level - 1] .= $out;
1070 array_pop( $outStack );
1071 array_pop( $iteratorStack );
1072 array_pop( $indexStack );
1073 $level--;
1074 }
1075 }
1076 }
1077 --$expansionDepth;
1078 return $outStack[0];
1079 }
1080
1081 /**
1082 * @param $sep
1083 * @param $flags
1084 * @return string
1085 */
1086 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1087 $args = array_slice( func_get_args(), 2 );
1088
1089 $first = true;
1090 $s = '';
1091 foreach ( $args as $root ) {
1092 if ( $root instanceof PPNode_Hash_Array ) {
1093 $root = $root->value;
1094 }
1095 if ( !is_array( $root ) ) {
1096 $root = array( $root );
1097 }
1098 foreach ( $root as $node ) {
1099 if ( $first ) {
1100 $first = false;
1101 } else {
1102 $s .= $sep;
1103 }
1104 $s .= $this->expand( $node, $flags );
1105 }
1106 }
1107 return $s;
1108 }
1109
1110 /**
1111 * Implode with no flags specified
1112 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1113 * @return string
1114 */
1115 function implode( $sep /*, ... */ ) {
1116 $args = array_slice( func_get_args(), 1 );
1117
1118 $first = true;
1119 $s = '';
1120 foreach ( $args as $root ) {
1121 if ( $root instanceof PPNode_Hash_Array ) {
1122 $root = $root->value;
1123 }
1124 if ( !is_array( $root ) ) {
1125 $root = array( $root );
1126 }
1127 foreach ( $root as $node ) {
1128 if ( $first ) {
1129 $first = false;
1130 } else {
1131 $s .= $sep;
1132 }
1133 $s .= $this->expand( $node );
1134 }
1135 }
1136 return $s;
1137 }
1138
1139 /**
1140 * Makes an object that, when expand()ed, will be the same as one obtained
1141 * with implode()
1142 *
1143 * @return PPNode_Hash_Array
1144 */
1145 function virtualImplode( $sep /*, ... */ ) {
1146 $args = array_slice( func_get_args(), 1 );
1147 $out = array();
1148 $first = true;
1149
1150 foreach ( $args as $root ) {
1151 if ( $root instanceof PPNode_Hash_Array ) {
1152 $root = $root->value;
1153 }
1154 if ( !is_array( $root ) ) {
1155 $root = array( $root );
1156 }
1157 foreach ( $root as $node ) {
1158 if ( $first ) {
1159 $first = false;
1160 } else {
1161 $out[] = $sep;
1162 }
1163 $out[] = $node;
1164 }
1165 }
1166 return new PPNode_Hash_Array( $out );
1167 }
1168
1169 /**
1170 * Virtual implode with brackets
1171 *
1172 * @return PPNode_Hash_Array
1173 */
1174 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1175 $args = array_slice( func_get_args(), 3 );
1176 $out = array( $start );
1177 $first = true;
1178
1179 foreach ( $args as $root ) {
1180 if ( $root instanceof PPNode_Hash_Array ) {
1181 $root = $root->value;
1182 }
1183 if ( !is_array( $root ) ) {
1184 $root = array( $root );
1185 }
1186 foreach ( $root as $node ) {
1187 if ( $first ) {
1188 $first = false;
1189 } else {
1190 $out[] = $sep;
1191 }
1192 $out[] = $node;
1193 }
1194 }
1195 $out[] = $end;
1196 return new PPNode_Hash_Array( $out );
1197 }
1198
1199 function __toString() {
1200 return 'frame{}';
1201 }
1202
1203 /**
1204 * @param $level bool
1205 * @return array|bool|String
1206 */
1207 function getPDBK( $level = false ) {
1208 if ( $level === false ) {
1209 return $this->title->getPrefixedDBkey();
1210 } else {
1211 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1212 }
1213 }
1214
1215 /**
1216 * @return array
1217 */
1218 function getArguments() {
1219 return array();
1220 }
1221
1222 /**
1223 * @return array
1224 */
1225 function getNumberedArguments() {
1226 return array();
1227 }
1228
1229 /**
1230 * @return array
1231 */
1232 function getNamedArguments() {
1233 return array();
1234 }
1235
1236 /**
1237 * Returns true if there are no arguments in this frame
1238 *
1239 * @return bool
1240 */
1241 function isEmpty() {
1242 return true;
1243 }
1244
1245 /**
1246 * @param $name
1247 * @return bool
1248 */
1249 function getArgument( $name ) {
1250 return false;
1251 }
1252
1253 /**
1254 * Returns true if the infinite loop check is OK, false if a loop is detected
1255 *
1256 * @param $title Title
1257 *
1258 * @return bool
1259 */
1260 function loopCheck( $title ) {
1261 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1262 }
1263
1264 /**
1265 * Return true if the frame is a template frame
1266 *
1267 * @return bool
1268 */
1269 function isTemplate() {
1270 return false;
1271 }
1272 }
1273
1274 /**
1275 * Expansion frame with template arguments
1276 * @ingroup Parser
1277 */
1278 class PPTemplateFrame_Hash extends PPFrame_Hash {
1279 var $numberedArgs, $namedArgs, $parent;
1280 var $numberedExpansionCache, $namedExpansionCache;
1281
1282 /**
1283 * @param $preprocessor
1284 * @param $parent
1285 * @param $numberedArgs array
1286 * @param $namedArgs array
1287 * @param $title Title
1288 */
1289 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1290 parent::__construct( $preprocessor );
1291
1292 $this->parent = $parent;
1293 $this->numberedArgs = $numberedArgs;
1294 $this->namedArgs = $namedArgs;
1295 $this->title = $title;
1296 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1297 $this->titleCache = $parent->titleCache;
1298 $this->titleCache[] = $pdbk;
1299 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1300 if ( $pdbk !== false ) {
1301 $this->loopCheckHash[$pdbk] = true;
1302 }
1303 $this->depth = $parent->depth + 1;
1304 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1305 }
1306
1307 function __toString() {
1308 $s = 'tplframe{';
1309 $first = true;
1310 $args = $this->numberedArgs + $this->namedArgs;
1311 foreach ( $args as $name => $value ) {
1312 if ( $first ) {
1313 $first = false;
1314 } else {
1315 $s .= ', ';
1316 }
1317 $s .= "\"$name\":\"" .
1318 str_replace( '"', '\\"', $value->__toString() ) . '"';
1319 }
1320 $s .= '}';
1321 return $s;
1322 }
1323 /**
1324 * Returns true if there are no arguments in this frame
1325 *
1326 * @return bool
1327 */
1328 function isEmpty() {
1329 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1330 }
1331
1332 /**
1333 * @return array
1334 */
1335 function getArguments() {
1336 $arguments = array();
1337 foreach ( array_merge(
1338 array_keys($this->numberedArgs),
1339 array_keys($this->namedArgs)) as $key ) {
1340 $arguments[$key] = $this->getArgument($key);
1341 }
1342 return $arguments;
1343 }
1344
1345 /**
1346 * @return array
1347 */
1348 function getNumberedArguments() {
1349 $arguments = array();
1350 foreach ( array_keys($this->numberedArgs) as $key ) {
1351 $arguments[$key] = $this->getArgument($key);
1352 }
1353 return $arguments;
1354 }
1355
1356 /**
1357 * @return array
1358 */
1359 function getNamedArguments() {
1360 $arguments = array();
1361 foreach ( array_keys($this->namedArgs) as $key ) {
1362 $arguments[$key] = $this->getArgument($key);
1363 }
1364 return $arguments;
1365 }
1366
1367 /**
1368 * @param $index
1369 * @return array|bool
1370 */
1371 function getNumberedArgument( $index ) {
1372 if ( !isset( $this->numberedArgs[$index] ) ) {
1373 return false;
1374 }
1375 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1376 # No trimming for unnamed arguments
1377 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1378 }
1379 return $this->numberedExpansionCache[$index];
1380 }
1381
1382 /**
1383 * @param $name
1384 * @return bool
1385 */
1386 function getNamedArgument( $name ) {
1387 if ( !isset( $this->namedArgs[$name] ) ) {
1388 return false;
1389 }
1390 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1391 # Trim named arguments post-expand, for backwards compatibility
1392 $this->namedExpansionCache[$name] = trim(
1393 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1394 }
1395 return $this->namedExpansionCache[$name];
1396 }
1397
1398 /**
1399 * @param $name
1400 * @return array|bool
1401 */
1402 function getArgument( $name ) {
1403 $text = $this->getNumberedArgument( $name );
1404 if ( $text === false ) {
1405 $text = $this->getNamedArgument( $name );
1406 }
1407 return $text;
1408 }
1409
1410 /**
1411 * Return true if the frame is a template frame
1412 *
1413 * @return bool
1414 */
1415 function isTemplate() {
1416 return true;
1417 }
1418 }
1419
1420 /**
1421 * Expansion frame with custom arguments
1422 * @ingroup Parser
1423 */
1424 class PPCustomFrame_Hash extends PPFrame_Hash {
1425 var $args;
1426
1427 function __construct( $preprocessor, $args ) {
1428 parent::__construct( $preprocessor );
1429 $this->args = $args;
1430 }
1431
1432 function __toString() {
1433 $s = 'cstmframe{';
1434 $first = true;
1435 foreach ( $this->args as $name => $value ) {
1436 if ( $first ) {
1437 $first = false;
1438 } else {
1439 $s .= ', ';
1440 }
1441 $s .= "\"$name\":\"" .
1442 str_replace( '"', '\\"', $value->__toString() ) . '"';
1443 }
1444 $s .= '}';
1445 return $s;
1446 }
1447
1448 /**
1449 * @return bool
1450 */
1451 function isEmpty() {
1452 return !count( $this->args );
1453 }
1454
1455 /**
1456 * @param $index
1457 * @return bool
1458 */
1459 function getArgument( $index ) {
1460 if ( !isset( $this->args[$index] ) ) {
1461 return false;
1462 }
1463 return $this->args[$index];
1464 }
1465 }
1466
1467 /**
1468 * @ingroup Parser
1469 */
1470 class PPNode_Hash_Tree implements PPNode {
1471 var $name, $firstChild, $lastChild, $nextSibling;
1472
1473 function __construct( $name ) {
1474 $this->name = $name;
1475 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1476 }
1477
1478 function __toString() {
1479 $inner = '';
1480 $attribs = '';
1481 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1482 if ( $node instanceof PPNode_Hash_Attr ) {
1483 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1484 } else {
1485 $inner .= $node->__toString();
1486 }
1487 }
1488 if ( $inner === '' ) {
1489 return "<{$this->name}$attribs/>";
1490 } else {
1491 return "<{$this->name}$attribs>$inner</{$this->name}>";
1492 }
1493 }
1494
1495 /**
1496 * @param $name
1497 * @param $text
1498 * @return PPNode_Hash_Tree
1499 */
1500 static function newWithText( $name, $text ) {
1501 $obj = new self( $name );
1502 $obj->addChild( new PPNode_Hash_Text( $text ) );
1503 return $obj;
1504 }
1505
1506 function addChild( $node ) {
1507 if ( $this->lastChild === false ) {
1508 $this->firstChild = $this->lastChild = $node;
1509 } else {
1510 $this->lastChild->nextSibling = $node;
1511 $this->lastChild = $node;
1512 }
1513 }
1514
1515 /**
1516 * @return PPNode_Hash_Array
1517 */
1518 function getChildren() {
1519 $children = array();
1520 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1521 $children[] = $child;
1522 }
1523 return new PPNode_Hash_Array( $children );
1524 }
1525
1526 function getFirstChild() {
1527 return $this->firstChild;
1528 }
1529
1530 function getNextSibling() {
1531 return $this->nextSibling;
1532 }
1533
1534 function getChildrenOfType( $name ) {
1535 $children = array();
1536 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1537 if ( isset( $child->name ) && $child->name === $name ) {
1538 $children[] = $name;
1539 }
1540 }
1541 return $children;
1542 }
1543
1544 /**
1545 * @return bool
1546 */
1547 function getLength() {
1548 return false;
1549 }
1550
1551 /**
1552 * @param $i
1553 * @return bool
1554 */
1555 function item( $i ) {
1556 return false;
1557 }
1558
1559 /**
1560 * @return string
1561 */
1562 function getName() {
1563 return $this->name;
1564 }
1565
1566 /**
1567 * Split a <part> node into an associative array containing:
1568 * name PPNode name
1569 * index String index
1570 * value PPNode value
1571 *
1572 * @return array
1573 */
1574 function splitArg() {
1575 $bits = array();
1576 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1577 if ( !isset( $child->name ) ) {
1578 continue;
1579 }
1580 if ( $child->name === 'name' ) {
1581 $bits['name'] = $child;
1582 if ( $child->firstChild instanceof PPNode_Hash_Attr
1583 && $child->firstChild->name === 'index' )
1584 {
1585 $bits['index'] = $child->firstChild->value;
1586 }
1587 } elseif ( $child->name === 'value' ) {
1588 $bits['value'] = $child;
1589 }
1590 }
1591
1592 if ( !isset( $bits['name'] ) ) {
1593 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1594 }
1595 if ( !isset( $bits['index'] ) ) {
1596 $bits['index'] = '';
1597 }
1598 return $bits;
1599 }
1600
1601 /**
1602 * Split an <ext> node into an associative array containing name, attr, inner and close
1603 * All values in the resulting array are PPNodes. Inner and close are optional.
1604 *
1605 * @return array
1606 */
1607 function splitExt() {
1608 $bits = array();
1609 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1610 if ( !isset( $child->name ) ) {
1611 continue;
1612 }
1613 if ( $child->name == 'name' ) {
1614 $bits['name'] = $child;
1615 } elseif ( $child->name == 'attr' ) {
1616 $bits['attr'] = $child;
1617 } elseif ( $child->name == 'inner' ) {
1618 $bits['inner'] = $child;
1619 } elseif ( $child->name == 'close' ) {
1620 $bits['close'] = $child;
1621 }
1622 }
1623 if ( !isset( $bits['name'] ) ) {
1624 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1625 }
1626 return $bits;
1627 }
1628
1629 /**
1630 * Split an <h> node
1631 *
1632 * @return array
1633 */
1634 function splitHeading() {
1635 if ( $this->name !== 'h' ) {
1636 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1637 }
1638 $bits = array();
1639 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1640 if ( !isset( $child->name ) ) {
1641 continue;
1642 }
1643 if ( $child->name == 'i' ) {
1644 $bits['i'] = $child->value;
1645 } elseif ( $child->name == 'level' ) {
1646 $bits['level'] = $child->value;
1647 }
1648 }
1649 if ( !isset( $bits['i'] ) ) {
1650 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1651 }
1652 return $bits;
1653 }
1654
1655 /**
1656 * Split a <template> or <tplarg> node
1657 *
1658 * @return array
1659 */
1660 function splitTemplate() {
1661 $parts = array();
1662 $bits = array( 'lineStart' => '' );
1663 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1664 if ( !isset( $child->name ) ) {
1665 continue;
1666 }
1667 if ( $child->name == 'title' ) {
1668 $bits['title'] = $child;
1669 }
1670 if ( $child->name == 'part' ) {
1671 $parts[] = $child;
1672 }
1673 if ( $child->name == 'lineStart' ) {
1674 $bits['lineStart'] = '1';
1675 }
1676 }
1677 if ( !isset( $bits['title'] ) ) {
1678 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1679 }
1680 $bits['parts'] = new PPNode_Hash_Array( $parts );
1681 return $bits;
1682 }
1683 }
1684
1685 /**
1686 * @ingroup Parser
1687 */
1688 class PPNode_Hash_Text implements PPNode {
1689 var $value, $nextSibling;
1690
1691 function __construct( $value ) {
1692 if ( is_object( $value ) ) {
1693 throw new MWException( __CLASS__ . ' given object instead of string' );
1694 }
1695 $this->value = $value;
1696 }
1697
1698 function __toString() {
1699 return htmlspecialchars( $this->value );
1700 }
1701
1702 function getNextSibling() {
1703 return $this->nextSibling;
1704 }
1705
1706 function getChildren() { return false; }
1707 function getFirstChild() { return false; }
1708 function getChildrenOfType( $name ) { return false; }
1709 function getLength() { return false; }
1710 function item( $i ) { return false; }
1711 function getName() { return '#text'; }
1712 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1713 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1714 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1715 }
1716
1717 /**
1718 * @ingroup Parser
1719 */
1720 class PPNode_Hash_Array implements PPNode {
1721 var $value, $nextSibling;
1722
1723 function __construct( $value ) {
1724 $this->value = $value;
1725 }
1726
1727 function __toString() {
1728 return var_export( $this, true );
1729 }
1730
1731 function getLength() {
1732 return count( $this->value );
1733 }
1734
1735 function item( $i ) {
1736 return $this->value[$i];
1737 }
1738
1739 function getName() { return '#nodelist'; }
1740
1741 function getNextSibling() {
1742 return $this->nextSibling;
1743 }
1744
1745 function getChildren() { return false; }
1746 function getFirstChild() { return false; }
1747 function getChildrenOfType( $name ) { return false; }
1748 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1749 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1750 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1751 }
1752
1753 /**
1754 * @ingroup Parser
1755 */
1756 class PPNode_Hash_Attr implements PPNode {
1757 var $name, $value, $nextSibling;
1758
1759 function __construct( $name, $value ) {
1760 $this->name = $name;
1761 $this->value = $value;
1762 }
1763
1764 function __toString() {
1765 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1766 }
1767
1768 function getName() {
1769 return $this->name;
1770 }
1771
1772 function getNextSibling() {
1773 return $this->nextSibling;
1774 }
1775
1776 function getChildren() { return false; }
1777 function getFirstChild() { return false; }
1778 function getChildrenOfType( $name ) { return false; }
1779 function getLength() { return false; }
1780 function item( $i ) { return false; }
1781 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1782 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1783 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1784 }