Improve the shell cgroup feature
[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( $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( $text, $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 * @param $indexOffset A number subtracted from the index attributes of the arguments
1070 *
1071 * @throws MWException
1072 * @return PPTemplateFrame_HipHop
1073 */
1074 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
1075 $namedArgs = array();
1076 $numberedArgs = array();
1077 if ( $title === false ) {
1078 $title = $this->title;
1079 }
1080 if ( $args !== false ) {
1081 if ( $args instanceof PPNode_HipHop_Array ) {
1082 $args = $args->value;
1083 } elseif ( !is_array( $args ) ) {
1084 throw new MWException( __METHOD__ . ': $args must be array or PPNode_HipHop_Array' );
1085 }
1086 foreach ( $args as $arg ) {
1087 $bits = $arg->splitArg();
1088 if ( $bits['index'] !== '' ) {
1089 // Numbered parameter
1090 $numberedArgs[$bits['index']] = $bits['value'];
1091 unset( $namedArgs[$bits['index']] );
1092 } else {
1093 // Named parameter
1094 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1095 $namedArgs[$name] = $bits['value'];
1096 unset( $numberedArgs[$name] );
1097 }
1098 }
1099 }
1100 return new PPTemplateFrame_HipHop( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
1101 }
1102
1103 /**
1104 * @throws MWException
1105 * @param $root
1106 * @param $flags int
1107 * @return string
1108 */
1109 function expand( $root, $flags = 0 ) {
1110 static $expansionDepth = 0;
1111 if ( is_string( $root ) ) {
1112 return $root;
1113 }
1114
1115 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1116 $this->parser->limitationWarn( 'node-count-exceeded',
1117 $this->parser->mPPNodeCount,
1118 $this->parser->mOptions->getMaxPPNodeCount()
1119 );
1120 return '<span class="error">Node-count limit exceeded</span>';
1121 }
1122 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1123 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1124 $expansionDepth,
1125 $this->parser->mOptions->getMaxPPExpandDepth()
1126 );
1127 return '<span class="error">Expansion depth limit exceeded</span>';
1128 }
1129 ++$expansionDepth;
1130 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1131 $this->parser->mHighestExpansionDepth = $expansionDepth;
1132 }
1133
1134 $outStack = array( '', '' );
1135 $iteratorStack = array( false, $root );
1136 $indexStack = array( 0, 0 );
1137
1138 while ( count( $iteratorStack ) > 1 ) {
1139 $level = count( $outStack ) - 1;
1140 $iteratorNode =& $iteratorStack[ $level ];
1141 $out =& $outStack[$level];
1142 $index =& $indexStack[$level];
1143
1144 if ( is_array( $iteratorNode ) ) {
1145 if ( $index >= count( $iteratorNode ) ) {
1146 // All done with this iterator
1147 $iteratorStack[$level] = false;
1148 $contextNode = false;
1149 } else {
1150 $contextNode = $iteratorNode[$index];
1151 $index++;
1152 }
1153 } elseif ( $iteratorNode instanceof PPNode_HipHop_Array ) {
1154 if ( $index >= $iteratorNode->getLength() ) {
1155 // All done with this iterator
1156 $iteratorStack[$level] = false;
1157 $contextNode = false;
1158 } else {
1159 $contextNode = $iteratorNode->item( $index );
1160 $index++;
1161 }
1162 } else {
1163 // Copy to $contextNode and then delete from iterator stack,
1164 // because this is not an iterator but we do have to execute it once
1165 $contextNode = $iteratorStack[$level];
1166 $iteratorStack[$level] = false;
1167 }
1168
1169 $newIterator = false;
1170
1171 if ( $contextNode === false ) {
1172 // nothing to do
1173 } elseif ( is_string( $contextNode ) ) {
1174 $out .= $contextNode;
1175 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_HipHop_Array ) {
1176 $newIterator = $contextNode;
1177 } elseif ( $contextNode instanceof PPNode_HipHop_Attr ) {
1178 // No output
1179 } elseif ( $contextNode instanceof PPNode_HipHop_Text ) {
1180 $out .= $contextNode->value;
1181 } elseif ( $contextNode instanceof PPNode_HipHop_Tree ) {
1182 if ( $contextNode->name === 'template' ) {
1183 # Double-brace expansion
1184 $bits = $contextNode->splitTemplate();
1185 if ( $flags & PPFrame::NO_TEMPLATES ) {
1186 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
1187 } else {
1188 $ret = $this->parser->braceSubstitution( $bits, $this );
1189 if ( isset( $ret['object'] ) ) {
1190 $newIterator = $ret['object'];
1191 } else {
1192 $out .= $ret['text'];
1193 }
1194 }
1195 } elseif ( $contextNode->name === 'tplarg' ) {
1196 # Triple-brace expansion
1197 $bits = $contextNode->splitTemplate();
1198 if ( $flags & PPFrame::NO_ARGS ) {
1199 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1200 } else {
1201 $ret = $this->parser->argSubstitution( $bits, $this );
1202 if ( isset( $ret['object'] ) ) {
1203 $newIterator = $ret['object'];
1204 } else {
1205 $out .= $ret['text'];
1206 }
1207 }
1208 } elseif ( $contextNode->name === 'comment' ) {
1209 # HTML-style comment
1210 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1211 if ( $this->parser->ot['html']
1212 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1213 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1214 {
1215 $out .= '';
1216 }
1217 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1218 # Not in RECOVER_COMMENTS mode (extractSections) though
1219 elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1220 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1221 }
1222 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1223 else {
1224 $out .= $contextNode->firstChild->value;
1225 }
1226 } elseif ( $contextNode->name === 'ignore' ) {
1227 # Output suppression used by <includeonly> etc.
1228 # OT_WIKI will only respect <ignore> in substed templates.
1229 # The other output types respect it unless NO_IGNORE is set.
1230 # extractSections() sets NO_IGNORE and so never respects it.
1231 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1232 $out .= $contextNode->firstChild->value;
1233 } else {
1234 //$out .= '';
1235 }
1236 } elseif ( $contextNode->name === 'ext' ) {
1237 # Extension tag
1238 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1239 $out .= $this->parser->extensionSubstitution( $bits, $this );
1240 } elseif ( $contextNode->name === 'h' ) {
1241 # Heading
1242 if ( $this->parser->ot['html'] ) {
1243 # Expand immediately and insert heading index marker
1244 $s = '';
1245 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1246 $s .= $this->expand( $node, $flags );
1247 }
1248
1249 $bits = $contextNode->splitHeading();
1250 $titleText = $this->title->getPrefixedDBkey();
1251 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1252 $serial = count( $this->parser->mHeadings ) - 1;
1253 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1254 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1255 $this->parser->mStripState->addGeneral( $marker, '' );
1256 $out .= $s;
1257 } else {
1258 # Expand in virtual stack
1259 $newIterator = $contextNode->getChildren();
1260 }
1261 } else {
1262 # Generic recursive expansion
1263 $newIterator = $contextNode->getChildren();
1264 }
1265 } else {
1266 throw new MWException( __METHOD__.': Invalid parameter type' );
1267 }
1268
1269 if ( $newIterator !== false ) {
1270 $outStack[] = '';
1271 $iteratorStack[] = $newIterator;
1272 $indexStack[] = 0;
1273 } elseif ( $iteratorStack[$level] === false ) {
1274 // Return accumulated value to parent
1275 // With tail recursion
1276 while ( $iteratorStack[$level] === false && $level > 0 ) {
1277 $outStack[$level - 1] .= $out;
1278 array_pop( $outStack );
1279 array_pop( $iteratorStack );
1280 array_pop( $indexStack );
1281 $level--;
1282 }
1283 }
1284 }
1285 --$expansionDepth;
1286 return $outStack[0];
1287 }
1288
1289 /**
1290 * @param $sep
1291 * @param $flags
1292 * @return string
1293 */
1294 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1295 $args = array_slice( func_get_args(), 2 );
1296
1297 $first = true;
1298 $s = '';
1299 foreach ( $args as $root ) {
1300 if ( $root instanceof PPNode_HipHop_Array ) {
1301 $root = $root->value;
1302 }
1303 if ( !is_array( $root ) ) {
1304 $root = array( $root );
1305 }
1306 foreach ( $root as $node ) {
1307 if ( $first ) {
1308 $first = false;
1309 } else {
1310 $s .= $sep;
1311 }
1312 $s .= $this->expand( $node, $flags );
1313 }
1314 }
1315 return $s;
1316 }
1317
1318 /**
1319 * Implode with no flags specified
1320 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1321 * @param $sep
1322 * @return string
1323 */
1324 function implode( $sep /*, ... */ ) {
1325 $args = array_slice( func_get_args(), 1 );
1326
1327 $first = true;
1328 $s = '';
1329 foreach ( $args as $root ) {
1330 if ( $root instanceof PPNode_HipHop_Array ) {
1331 $root = $root->value;
1332 }
1333 if ( !is_array( $root ) ) {
1334 $root = array( $root );
1335 }
1336 foreach ( $root as $node ) {
1337 if ( $first ) {
1338 $first = false;
1339 } else {
1340 $s .= $sep;
1341 }
1342 $s .= $this->expand( $node );
1343 }
1344 }
1345 return $s;
1346 }
1347
1348 /**
1349 * Makes an object that, when expand()ed, will be the same as one obtained
1350 * with implode()
1351 *
1352 * @param $sep
1353 * @return PPNode_HipHop_Array
1354 */
1355 function virtualImplode( $sep /*, ... */ ) {
1356 $args = array_slice( func_get_args(), 1 );
1357 $out = array();
1358 $first = true;
1359
1360 foreach ( $args as $root ) {
1361 if ( $root instanceof PPNode_HipHop_Array ) {
1362 $root = $root->value;
1363 }
1364 if ( !is_array( $root ) ) {
1365 $root = array( $root );
1366 }
1367 foreach ( $root as $node ) {
1368 if ( $first ) {
1369 $first = false;
1370 } else {
1371 $out[] = $sep;
1372 }
1373 $out[] = $node;
1374 }
1375 }
1376 return new PPNode_HipHop_Array( $out );
1377 }
1378
1379 /**
1380 * Virtual implode with brackets
1381 *
1382 * @param $start
1383 * @param $sep
1384 * @param $end
1385 * @return PPNode_HipHop_Array
1386 */
1387 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1388 $args = array_slice( func_get_args(), 3 );
1389 $out = array( $start );
1390 $first = true;
1391
1392 foreach ( $args as $root ) {
1393 if ( $root instanceof PPNode_HipHop_Array ) {
1394 $root = $root->value;
1395 }
1396 if ( !is_array( $root ) ) {
1397 $root = array( $root );
1398 }
1399 foreach ( $root as $node ) {
1400 if ( $first ) {
1401 $first = false;
1402 } else {
1403 $out[] = $sep;
1404 }
1405 $out[] = $node;
1406 }
1407 }
1408 $out[] = $end;
1409 return new PPNode_HipHop_Array( $out );
1410 }
1411
1412 function __toString() {
1413 return 'frame{}';
1414 }
1415
1416 /**
1417 * @param $level bool
1418 * @return array|bool|String
1419 */
1420 function getPDBK( $level = false ) {
1421 if ( $level === false ) {
1422 return $this->title->getPrefixedDBkey();
1423 } else {
1424 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1425 }
1426 }
1427
1428 /**
1429 * @return array
1430 */
1431 function getArguments() {
1432 return array();
1433 }
1434
1435 /**
1436 * @return array
1437 */
1438 function getNumberedArguments() {
1439 return array();
1440 }
1441
1442 /**
1443 * @return array
1444 */
1445 function getNamedArguments() {
1446 return array();
1447 }
1448
1449 /**
1450 * Returns true if there are no arguments in this frame
1451 *
1452 * @return bool
1453 */
1454 function isEmpty() {
1455 return true;
1456 }
1457
1458 /**
1459 * @param $name
1460 * @return bool
1461 */
1462 function getArgument( $name ) {
1463 return false;
1464 }
1465
1466 /**
1467 * Returns true if the infinite loop check is OK, false if a loop is detected
1468 *
1469 * @param $title Title
1470 *
1471 * @return bool
1472 */
1473 function loopCheck( $title ) {
1474 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1475 }
1476
1477 /**
1478 * Return true if the frame is a template frame
1479 *
1480 * @return bool
1481 */
1482 function isTemplate() {
1483 return false;
1484 }
1485
1486 /**
1487 * Get a title of frame
1488 *
1489 * @return Title
1490 */
1491 function getTitle() {
1492 return $this->title;
1493 }
1494 }
1495
1496 /**
1497 * Expansion frame with template arguments
1498 * @ingroup Parser
1499 */
1500 class PPTemplateFrame_HipHop extends PPFrame_HipHop {
1501 var $numberedArgs, $namedArgs, $parent;
1502 var $numberedExpansionCache, $namedExpansionCache;
1503
1504 /**
1505 * @param $preprocessor Preprocessor_HipHop
1506 * @param $parent bool
1507 * @param $numberedArgs array
1508 * @param $namedArgs array
1509 * @param $title Title|bool
1510 */
1511 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1512 parent::__construct( $preprocessor );
1513
1514 $this->parent = $parent;
1515 $this->numberedArgs = $numberedArgs;
1516 $this->namedArgs = $namedArgs;
1517 $this->title = $title;
1518 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1519 $this->titleCache = $parent->titleCache;
1520 $this->titleCache[] = $pdbk;
1521 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1522 if ( $pdbk !== false ) {
1523 $this->loopCheckHash[$pdbk] = true;
1524 }
1525 $this->depth = $parent->depth + 1;
1526 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1527 }
1528
1529 function __toString() {
1530 $s = 'tplframe{';
1531 $first = true;
1532 $args = $this->numberedArgs + $this->namedArgs;
1533 foreach ( $args as $name => $value ) {
1534 if ( $first ) {
1535 $first = false;
1536 } else {
1537 $s .= ', ';
1538 }
1539 $s .= "\"$name\":\"" .
1540 str_replace( '"', '\\"', $value->__toString() ) . '"';
1541 }
1542 $s .= '}';
1543 return $s;
1544 }
1545 /**
1546 * Returns true if there are no arguments in this frame
1547 *
1548 * @return bool
1549 */
1550 function isEmpty() {
1551 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1552 }
1553
1554 /**
1555 * @return array
1556 */
1557 function getArguments() {
1558 $arguments = array();
1559 foreach ( array_merge(
1560 array_keys($this->numberedArgs),
1561 array_keys($this->namedArgs)) as $key ) {
1562 $arguments[$key] = $this->getArgument($key);
1563 }
1564 return $arguments;
1565 }
1566
1567 /**
1568 * @return array
1569 */
1570 function getNumberedArguments() {
1571 $arguments = array();
1572 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1573 $arguments[$key] = $this->getArgument( $key );
1574 }
1575 return $arguments;
1576 }
1577
1578 /**
1579 * @return array
1580 */
1581 function getNamedArguments() {
1582 $arguments = array();
1583 foreach ( array_keys( $this->namedArgs ) as $key ) {
1584 $arguments[$key] = $this->getArgument( $key );
1585 }
1586 return $arguments;
1587 }
1588
1589 /**
1590 * @param $index
1591 * @return array|bool
1592 */
1593 function getNumberedArgument( $index ) {
1594 if ( !isset( $this->numberedArgs[$index] ) ) {
1595 return false;
1596 }
1597 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1598 # No trimming for unnamed arguments
1599 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1600 }
1601 return $this->numberedExpansionCache[$index];
1602 }
1603
1604 /**
1605 * @param $name
1606 * @return bool
1607 */
1608 function getNamedArgument( $name ) {
1609 if ( !isset( $this->namedArgs[$name] ) ) {
1610 return false;
1611 }
1612 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1613 # Trim named arguments post-expand, for backwards compatibility
1614 $this->namedExpansionCache[$name] = trim(
1615 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1616 }
1617 return $this->namedExpansionCache[$name];
1618 }
1619
1620 /**
1621 * @param $name
1622 * @return array|bool
1623 */
1624 function getArgument( $name ) {
1625 $text = $this->getNumberedArgument( $name );
1626 if ( $text === false ) {
1627 $text = $this->getNamedArgument( $name );
1628 }
1629 return $text;
1630 }
1631
1632 /**
1633 * Return true if the frame is a template frame
1634 *
1635 * @return bool
1636 */
1637 function isTemplate() {
1638 return true;
1639 }
1640 }
1641
1642 /**
1643 * Expansion frame with custom arguments
1644 * @ingroup Parser
1645 */
1646 class PPCustomFrame_HipHop extends PPFrame_HipHop {
1647 var $args;
1648
1649 function __construct( $preprocessor, $args ) {
1650 parent::__construct( $preprocessor );
1651 $this->args = $args;
1652 }
1653
1654 function __toString() {
1655 $s = 'cstmframe{';
1656 $first = true;
1657 foreach ( $this->args as $name => $value ) {
1658 if ( $first ) {
1659 $first = false;
1660 } else {
1661 $s .= ', ';
1662 }
1663 $s .= "\"$name\":\"" .
1664 str_replace( '"', '\\"', $value->__toString() ) . '"';
1665 }
1666 $s .= '}';
1667 return $s;
1668 }
1669
1670 /**
1671 * @return bool
1672 */
1673 function isEmpty() {
1674 return !count( $this->args );
1675 }
1676
1677 /**
1678 * @param $index
1679 * @return bool
1680 */
1681 function getArgument( $index ) {
1682 if ( !isset( $this->args[$index] ) ) {
1683 return false;
1684 }
1685 return $this->args[$index];
1686 }
1687 }
1688
1689 /**
1690 * @ingroup Parser
1691 */
1692 class PPNode_HipHop_Tree implements PPNode {
1693 var $name, $firstChild, $lastChild, $nextSibling;
1694
1695 function __construct( $name ) {
1696 $this->name = $name;
1697 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1698 }
1699
1700 function __toString() {
1701 $inner = '';
1702 $attribs = '';
1703 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1704 if ( $node instanceof PPNode_HipHop_Attr ) {
1705 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1706 } else {
1707 $inner .= $node->__toString();
1708 }
1709 }
1710 if ( $inner === '' ) {
1711 return "<{$this->name}$attribs/>";
1712 } else {
1713 return "<{$this->name}$attribs>$inner</{$this->name}>";
1714 }
1715 }
1716
1717 /**
1718 * @param $name
1719 * @param $text
1720 * @return PPNode_HipHop_Tree
1721 */
1722 static function newWithText( $name, $text ) {
1723 $obj = new self( $name );
1724 $obj->addChild( new PPNode_HipHop_Text( $text ) );
1725 return $obj;
1726 }
1727
1728 function addChild( $node ) {
1729 if ( $this->lastChild === false ) {
1730 $this->firstChild = $this->lastChild = $node;
1731 } else {
1732 $this->lastChild->nextSibling = $node;
1733 $this->lastChild = $node;
1734 }
1735 }
1736
1737 /**
1738 * @return PPNode_HipHop_Array
1739 */
1740 function getChildren() {
1741 $children = array();
1742 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1743 $children[] = $child;
1744 }
1745 return new PPNode_HipHop_Array( $children );
1746 }
1747
1748 function getFirstChild() {
1749 return $this->firstChild;
1750 }
1751
1752 function getNextSibling() {
1753 return $this->nextSibling;
1754 }
1755
1756 /**
1757 * @param $name string
1758 * @return array
1759 */
1760 function getChildrenOfType( $name ) {
1761 $children = array();
1762 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1763 if ( isset( $child->name ) && $child->name === $name ) {
1764 $children[] = $child;
1765 }
1766 }
1767 return $children;
1768 }
1769
1770 /**
1771 * @return bool
1772 */
1773 function getLength() {
1774 return false;
1775 }
1776
1777 /**
1778 * @param $i
1779 * @return bool
1780 */
1781 function item( $i ) {
1782 return false;
1783 }
1784
1785 /**
1786 * @return string
1787 */
1788 function getName() {
1789 return $this->name;
1790 }
1791
1792 /**
1793 * Split a <part> node into an associative array containing:
1794 * name PPNode name
1795 * index String index
1796 * value PPNode value
1797 *
1798 * @throws MWException
1799 * @return array
1800 */
1801 function splitArg() {
1802 $bits = array();
1803 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1804 if ( !isset( $child->name ) ) {
1805 continue;
1806 }
1807 if ( $child->name === 'name' ) {
1808 $bits['name'] = $child;
1809 if ( $child->firstChild instanceof PPNode_HipHop_Attr
1810 && $child->firstChild->name === 'index' )
1811 {
1812 $bits['index'] = $child->firstChild->value;
1813 }
1814 } elseif ( $child->name === 'value' ) {
1815 $bits['value'] = $child;
1816 }
1817 }
1818
1819 if ( !isset( $bits['name'] ) ) {
1820 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1821 }
1822 if ( !isset( $bits['index'] ) ) {
1823 $bits['index'] = '';
1824 }
1825 return $bits;
1826 }
1827
1828 /**
1829 * Split an <ext> node into an associative array containing name, attr, inner and close
1830 * All values in the resulting array are PPNodes. Inner and close are optional.
1831 *
1832 * @throws MWException
1833 * @return array
1834 */
1835 function splitExt() {
1836 $bits = array();
1837 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1838 if ( !isset( $child->name ) ) {
1839 continue;
1840 }
1841 if ( $child->name === 'name' ) {
1842 $bits['name'] = $child;
1843 } elseif ( $child->name === 'attr' ) {
1844 $bits['attr'] = $child;
1845 } elseif ( $child->name === 'inner' ) {
1846 $bits['inner'] = $child;
1847 } elseif ( $child->name === 'close' ) {
1848 $bits['close'] = $child;
1849 }
1850 }
1851 if ( !isset( $bits['name'] ) ) {
1852 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1853 }
1854 return $bits;
1855 }
1856
1857 /**
1858 * Split an <h> node
1859 *
1860 * @throws MWException
1861 * @return array
1862 */
1863 function splitHeading() {
1864 if ( $this->name !== 'h' ) {
1865 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1866 }
1867 $bits = array();
1868 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1869 if ( !isset( $child->name ) ) {
1870 continue;
1871 }
1872 if ( $child->name === 'i' ) {
1873 $bits['i'] = $child->value;
1874 } elseif ( $child->name === 'level' ) {
1875 $bits['level'] = $child->value;
1876 }
1877 }
1878 if ( !isset( $bits['i'] ) ) {
1879 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1880 }
1881 return $bits;
1882 }
1883
1884 /**
1885 * Split a <template> or <tplarg> node
1886 *
1887 * @throws MWException
1888 * @return array
1889 */
1890 function splitTemplate() {
1891 $parts = array();
1892 $bits = array( 'lineStart' => '' );
1893 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1894 if ( !isset( $child->name ) ) {
1895 continue;
1896 }
1897 if ( $child->name === 'title' ) {
1898 $bits['title'] = $child;
1899 }
1900 if ( $child->name === 'part' ) {
1901 $parts[] = $child;
1902 }
1903 if ( $child->name === 'lineStart' ) {
1904 $bits['lineStart'] = '1';
1905 }
1906 }
1907 if ( !isset( $bits['title'] ) ) {
1908 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1909 }
1910 $bits['parts'] = new PPNode_HipHop_Array( $parts );
1911 return $bits;
1912 }
1913 }
1914
1915 /**
1916 * @ingroup Parser
1917 */
1918 class PPNode_HipHop_Text implements PPNode {
1919 var $value, $nextSibling;
1920
1921 function __construct( $value ) {
1922 if ( is_object( $value ) ) {
1923 throw new MWException( __CLASS__ . ' given object instead of string' );
1924 }
1925 $this->value = $value;
1926 }
1927
1928 function __toString() {
1929 return htmlspecialchars( $this->value );
1930 }
1931
1932 function getNextSibling() {
1933 return $this->nextSibling;
1934 }
1935
1936 function getChildren() { return false; }
1937 function getFirstChild() { return false; }
1938 function getChildrenOfType( $name ) { return false; }
1939 function getLength() { return false; }
1940 function item( $i ) { return false; }
1941 function getName() { return '#text'; }
1942 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1943 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1944 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1945 }
1946
1947 /**
1948 * @ingroup Parser
1949 */
1950 class PPNode_HipHop_Array implements PPNode {
1951 var $value, $nextSibling;
1952
1953 function __construct( $value ) {
1954 $this->value = $value;
1955 }
1956
1957 function __toString() {
1958 return var_export( $this, true );
1959 }
1960
1961 function getLength() {
1962 return count( $this->value );
1963 }
1964
1965 function item( $i ) {
1966 return $this->value[$i];
1967 }
1968
1969 function getName() { return '#nodelist'; }
1970
1971 function getNextSibling() {
1972 return $this->nextSibling;
1973 }
1974
1975 function getChildren() { return false; }
1976 function getFirstChild() { return false; }
1977 function getChildrenOfType( $name ) { return false; }
1978 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1979 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1980 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1981 }
1982
1983 /**
1984 * @ingroup Parser
1985 */
1986 class PPNode_HipHop_Attr implements PPNode {
1987 var $name, $value, $nextSibling;
1988
1989 function __construct( $name, $value ) {
1990 $this->name = $name;
1991 $this->value = $value;
1992 }
1993
1994 function __toString() {
1995 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1996 }
1997
1998 function getName() {
1999 return $this->name;
2000 }
2001
2002 function getNextSibling() {
2003 return $this->nextSibling;
2004 }
2005
2006 function getChildren() { return false; }
2007 function getFirstChild() { return false; }
2008 function getChildrenOfType( $name ) { return false; }
2009 function getLength() { return false; }
2010 function item( $i ) { return false; }
2011 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
2012 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
2013 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
2014 }