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