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