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