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