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