Merge "Use local context to get messages and time formatting methods of Language...
[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
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 ) {
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 $numberedArgs[$bits['index']] = $bits['value'];
908 unset( $namedArgs[$bits['index']] );
909 } else {
910 // Named parameter
911 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
912 $namedArgs[$name] = $bits['value'];
913 unset( $numberedArgs[$name] );
914 }
915 }
916 }
917 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
918 }
919
920 /**
921 * @throws MWException
922 * @param $root
923 * @param $flags int
924 * @return string
925 */
926 function expand( $root, $flags = 0 ) {
927 static $expansionDepth = 0;
928 if ( is_string( $root ) ) {
929 return $root;
930 }
931
932 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
933 $this->parser->limitationWarn( 'node-count-exceeded',
934 $this->parser->mPPNodeCount,
935 $this->parser->mOptions->getMaxPPNodeCount()
936 );
937 return '<span class="error">Node-count limit exceeded</span>';
938 }
939 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
940 $this->parser->limitationWarn( 'expansion-depth-exceeded',
941 $expansionDepth,
942 $this->parser->mOptions->getMaxPPExpandDepth()
943 );
944 return '<span class="error">Expansion depth limit exceeded</span>';
945 }
946 ++$expansionDepth;
947
948 $outStack = array( '', '' );
949 $iteratorStack = array( false, $root );
950 $indexStack = array( 0, 0 );
951
952 while ( count( $iteratorStack ) > 1 ) {
953 $level = count( $outStack ) - 1;
954 $iteratorNode =& $iteratorStack[ $level ];
955 $out =& $outStack[$level];
956 $index =& $indexStack[$level];
957
958 if ( is_array( $iteratorNode ) ) {
959 if ( $index >= count( $iteratorNode ) ) {
960 // All done with this iterator
961 $iteratorStack[$level] = false;
962 $contextNode = false;
963 } else {
964 $contextNode = $iteratorNode[$index];
965 $index++;
966 }
967 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
968 if ( $index >= $iteratorNode->getLength() ) {
969 // All done with this iterator
970 $iteratorStack[$level] = false;
971 $contextNode = false;
972 } else {
973 $contextNode = $iteratorNode->item( $index );
974 $index++;
975 }
976 } else {
977 // Copy to $contextNode and then delete from iterator stack,
978 // because this is not an iterator but we do have to execute it once
979 $contextNode = $iteratorStack[$level];
980 $iteratorStack[$level] = false;
981 }
982
983 $newIterator = false;
984
985 if ( $contextNode === false ) {
986 // nothing to do
987 } elseif ( is_string( $contextNode ) ) {
988 $out .= $contextNode;
989 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
990 $newIterator = $contextNode;
991 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
992 // No output
993 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
994 $out .= $contextNode->value;
995 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
996 if ( $contextNode->name == 'template' ) {
997 # Double-brace expansion
998 $bits = $contextNode->splitTemplate();
999 if ( $flags & PPFrame::NO_TEMPLATES ) {
1000 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
1001 } else {
1002 $ret = $this->parser->braceSubstitution( $bits, $this );
1003 if ( isset( $ret['object'] ) ) {
1004 $newIterator = $ret['object'];
1005 } else {
1006 $out .= $ret['text'];
1007 }
1008 }
1009 } elseif ( $contextNode->name == 'tplarg' ) {
1010 # Triple-brace expansion
1011 $bits = $contextNode->splitTemplate();
1012 if ( $flags & PPFrame::NO_ARGS ) {
1013 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1014 } else {
1015 $ret = $this->parser->argSubstitution( $bits, $this );
1016 if ( isset( $ret['object'] ) ) {
1017 $newIterator = $ret['object'];
1018 } else {
1019 $out .= $ret['text'];
1020 }
1021 }
1022 } elseif ( $contextNode->name == 'comment' ) {
1023 # HTML-style comment
1024 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1025 if ( $this->parser->ot['html']
1026 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1027 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1028 {
1029 $out .= '';
1030 }
1031 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1032 # Not in RECOVER_COMMENTS mode (extractSections) though
1033 elseif ( $this->parser->ot['wiki'] && ! ( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1034 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1035 }
1036 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1037 else {
1038 $out .= $contextNode->firstChild->value;
1039 }
1040 } elseif ( $contextNode->name == 'ignore' ) {
1041 # Output suppression used by <includeonly> etc.
1042 # OT_WIKI will only respect <ignore> in substed templates.
1043 # The other output types respect it unless NO_IGNORE is set.
1044 # extractSections() sets NO_IGNORE and so never respects it.
1045 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1046 $out .= $contextNode->firstChild->value;
1047 } else {
1048 //$out .= '';
1049 }
1050 } elseif ( $contextNode->name == 'ext' ) {
1051 # Extension tag
1052 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1053 $out .= $this->parser->extensionSubstitution( $bits, $this );
1054 } elseif ( $contextNode->name == 'h' ) {
1055 # Heading
1056 if ( $this->parser->ot['html'] ) {
1057 # Expand immediately and insert heading index marker
1058 $s = '';
1059 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1060 $s .= $this->expand( $node, $flags );
1061 }
1062
1063 $bits = $contextNode->splitHeading();
1064 $titleText = $this->title->getPrefixedDBkey();
1065 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1066 $serial = count( $this->parser->mHeadings ) - 1;
1067 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1068 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1069 $this->parser->mStripState->addGeneral( $marker, '' );
1070 $out .= $s;
1071 } else {
1072 # Expand in virtual stack
1073 $newIterator = $contextNode->getChildren();
1074 }
1075 } else {
1076 # Generic recursive expansion
1077 $newIterator = $contextNode->getChildren();
1078 }
1079 } else {
1080 throw new MWException( __METHOD__.': Invalid parameter type' );
1081 }
1082
1083 if ( $newIterator !== false ) {
1084 $outStack[] = '';
1085 $iteratorStack[] = $newIterator;
1086 $indexStack[] = 0;
1087 } elseif ( $iteratorStack[$level] === false ) {
1088 // Return accumulated value to parent
1089 // With tail recursion
1090 while ( $iteratorStack[$level] === false && $level > 0 ) {
1091 $outStack[$level - 1] .= $out;
1092 array_pop( $outStack );
1093 array_pop( $iteratorStack );
1094 array_pop( $indexStack );
1095 $level--;
1096 }
1097 }
1098 }
1099 --$expansionDepth;
1100 return $outStack[0];
1101 }
1102
1103 /**
1104 * @param $sep
1105 * @param $flags
1106 * @return string
1107 */
1108 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1109 $args = array_slice( func_get_args(), 2 );
1110
1111 $first = true;
1112 $s = '';
1113 foreach ( $args as $root ) {
1114 if ( $root instanceof PPNode_Hash_Array ) {
1115 $root = $root->value;
1116 }
1117 if ( !is_array( $root ) ) {
1118 $root = array( $root );
1119 }
1120 foreach ( $root as $node ) {
1121 if ( $first ) {
1122 $first = false;
1123 } else {
1124 $s .= $sep;
1125 }
1126 $s .= $this->expand( $node, $flags );
1127 }
1128 }
1129 return $s;
1130 }
1131
1132 /**
1133 * Implode with no flags specified
1134 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1135 * @return string
1136 */
1137 function implode( $sep /*, ... */ ) {
1138 $args = array_slice( func_get_args(), 1 );
1139
1140 $first = true;
1141 $s = '';
1142 foreach ( $args as $root ) {
1143 if ( $root instanceof PPNode_Hash_Array ) {
1144 $root = $root->value;
1145 }
1146 if ( !is_array( $root ) ) {
1147 $root = array( $root );
1148 }
1149 foreach ( $root as $node ) {
1150 if ( $first ) {
1151 $first = false;
1152 } else {
1153 $s .= $sep;
1154 }
1155 $s .= $this->expand( $node );
1156 }
1157 }
1158 return $s;
1159 }
1160
1161 /**
1162 * Makes an object that, when expand()ed, will be the same as one obtained
1163 * with implode()
1164 *
1165 * @return PPNode_Hash_Array
1166 */
1167 function virtualImplode( $sep /*, ... */ ) {
1168 $args = array_slice( func_get_args(), 1 );
1169 $out = array();
1170 $first = true;
1171
1172 foreach ( $args as $root ) {
1173 if ( $root instanceof PPNode_Hash_Array ) {
1174 $root = $root->value;
1175 }
1176 if ( !is_array( $root ) ) {
1177 $root = array( $root );
1178 }
1179 foreach ( $root as $node ) {
1180 if ( $first ) {
1181 $first = false;
1182 } else {
1183 $out[] = $sep;
1184 }
1185 $out[] = $node;
1186 }
1187 }
1188 return new PPNode_Hash_Array( $out );
1189 }
1190
1191 /**
1192 * Virtual implode with brackets
1193 *
1194 * @return PPNode_Hash_Array
1195 */
1196 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1197 $args = array_slice( func_get_args(), 3 );
1198 $out = array( $start );
1199 $first = true;
1200
1201 foreach ( $args as $root ) {
1202 if ( $root instanceof PPNode_Hash_Array ) {
1203 $root = $root->value;
1204 }
1205 if ( !is_array( $root ) ) {
1206 $root = array( $root );
1207 }
1208 foreach ( $root as $node ) {
1209 if ( $first ) {
1210 $first = false;
1211 } else {
1212 $out[] = $sep;
1213 }
1214 $out[] = $node;
1215 }
1216 }
1217 $out[] = $end;
1218 return new PPNode_Hash_Array( $out );
1219 }
1220
1221 function __toString() {
1222 return 'frame{}';
1223 }
1224
1225 /**
1226 * @param $level bool
1227 * @return array|bool|String
1228 */
1229 function getPDBK( $level = false ) {
1230 if ( $level === false ) {
1231 return $this->title->getPrefixedDBkey();
1232 } else {
1233 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1234 }
1235 }
1236
1237 /**
1238 * @return array
1239 */
1240 function getArguments() {
1241 return array();
1242 }
1243
1244 /**
1245 * @return array
1246 */
1247 function getNumberedArguments() {
1248 return array();
1249 }
1250
1251 /**
1252 * @return array
1253 */
1254 function getNamedArguments() {
1255 return array();
1256 }
1257
1258 /**
1259 * Returns true if there are no arguments in this frame
1260 *
1261 * @return bool
1262 */
1263 function isEmpty() {
1264 return true;
1265 }
1266
1267 /**
1268 * @param $name
1269 * @return bool
1270 */
1271 function getArgument( $name ) {
1272 return false;
1273 }
1274
1275 /**
1276 * Returns true if the infinite loop check is OK, false if a loop is detected
1277 *
1278 * @param $title Title
1279 *
1280 * @return bool
1281 */
1282 function loopCheck( $title ) {
1283 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1284 }
1285
1286 /**
1287 * Return true if the frame is a template frame
1288 *
1289 * @return bool
1290 */
1291 function isTemplate() {
1292 return false;
1293 }
1294
1295 /**
1296 * Get a title of frame
1297 *
1298 * @return Title
1299 */
1300 function getTitle() {
1301 return $this->title;
1302 }
1303 }
1304
1305 /**
1306 * Expansion frame with template arguments
1307 * @ingroup Parser
1308 */
1309 class PPTemplateFrame_Hash extends PPFrame_Hash {
1310 var $numberedArgs, $namedArgs, $parent;
1311 var $numberedExpansionCache, $namedExpansionCache;
1312
1313 /**
1314 * @param $preprocessor
1315 * @param $parent
1316 * @param $numberedArgs array
1317 * @param $namedArgs array
1318 * @param $title Title
1319 */
1320 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1321 parent::__construct( $preprocessor );
1322
1323 $this->parent = $parent;
1324 $this->numberedArgs = $numberedArgs;
1325 $this->namedArgs = $namedArgs;
1326 $this->title = $title;
1327 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1328 $this->titleCache = $parent->titleCache;
1329 $this->titleCache[] = $pdbk;
1330 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1331 if ( $pdbk !== false ) {
1332 $this->loopCheckHash[$pdbk] = true;
1333 }
1334 $this->depth = $parent->depth + 1;
1335 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1336 }
1337
1338 function __toString() {
1339 $s = 'tplframe{';
1340 $first = true;
1341 $args = $this->numberedArgs + $this->namedArgs;
1342 foreach ( $args as $name => $value ) {
1343 if ( $first ) {
1344 $first = false;
1345 } else {
1346 $s .= ', ';
1347 }
1348 $s .= "\"$name\":\"" .
1349 str_replace( '"', '\\"', $value->__toString() ) . '"';
1350 }
1351 $s .= '}';
1352 return $s;
1353 }
1354 /**
1355 * Returns true if there are no arguments in this frame
1356 *
1357 * @return bool
1358 */
1359 function isEmpty() {
1360 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1361 }
1362
1363 /**
1364 * @return array
1365 */
1366 function getArguments() {
1367 $arguments = array();
1368 foreach ( array_merge(
1369 array_keys($this->numberedArgs),
1370 array_keys($this->namedArgs)) as $key ) {
1371 $arguments[$key] = $this->getArgument($key);
1372 }
1373 return $arguments;
1374 }
1375
1376 /**
1377 * @return array
1378 */
1379 function getNumberedArguments() {
1380 $arguments = array();
1381 foreach ( array_keys($this->numberedArgs) as $key ) {
1382 $arguments[$key] = $this->getArgument($key);
1383 }
1384 return $arguments;
1385 }
1386
1387 /**
1388 * @return array
1389 */
1390 function getNamedArguments() {
1391 $arguments = array();
1392 foreach ( array_keys($this->namedArgs) as $key ) {
1393 $arguments[$key] = $this->getArgument($key);
1394 }
1395 return $arguments;
1396 }
1397
1398 /**
1399 * @param $index
1400 * @return array|bool
1401 */
1402 function getNumberedArgument( $index ) {
1403 if ( !isset( $this->numberedArgs[$index] ) ) {
1404 return false;
1405 }
1406 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1407 # No trimming for unnamed arguments
1408 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1409 }
1410 return $this->numberedExpansionCache[$index];
1411 }
1412
1413 /**
1414 * @param $name
1415 * @return bool
1416 */
1417 function getNamedArgument( $name ) {
1418 if ( !isset( $this->namedArgs[$name] ) ) {
1419 return false;
1420 }
1421 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1422 # Trim named arguments post-expand, for backwards compatibility
1423 $this->namedExpansionCache[$name] = trim(
1424 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1425 }
1426 return $this->namedExpansionCache[$name];
1427 }
1428
1429 /**
1430 * @param $name
1431 * @return array|bool
1432 */
1433 function getArgument( $name ) {
1434 $text = $this->getNumberedArgument( $name );
1435 if ( $text === false ) {
1436 $text = $this->getNamedArgument( $name );
1437 }
1438 return $text;
1439 }
1440
1441 /**
1442 * Return true if the frame is a template frame
1443 *
1444 * @return bool
1445 */
1446 function isTemplate() {
1447 return true;
1448 }
1449 }
1450
1451 /**
1452 * Expansion frame with custom arguments
1453 * @ingroup Parser
1454 */
1455 class PPCustomFrame_Hash extends PPFrame_Hash {
1456 var $args;
1457
1458 function __construct( $preprocessor, $args ) {
1459 parent::__construct( $preprocessor );
1460 $this->args = $args;
1461 }
1462
1463 function __toString() {
1464 $s = 'cstmframe{';
1465 $first = true;
1466 foreach ( $this->args as $name => $value ) {
1467 if ( $first ) {
1468 $first = false;
1469 } else {
1470 $s .= ', ';
1471 }
1472 $s .= "\"$name\":\"" .
1473 str_replace( '"', '\\"', $value->__toString() ) . '"';
1474 }
1475 $s .= '}';
1476 return $s;
1477 }
1478
1479 /**
1480 * @return bool
1481 */
1482 function isEmpty() {
1483 return !count( $this->args );
1484 }
1485
1486 /**
1487 * @param $index
1488 * @return bool
1489 */
1490 function getArgument( $index ) {
1491 if ( !isset( $this->args[$index] ) ) {
1492 return false;
1493 }
1494 return $this->args[$index];
1495 }
1496 }
1497
1498 /**
1499 * @ingroup Parser
1500 */
1501 class PPNode_Hash_Tree implements PPNode {
1502 var $name, $firstChild, $lastChild, $nextSibling;
1503
1504 function __construct( $name ) {
1505 $this->name = $name;
1506 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1507 }
1508
1509 function __toString() {
1510 $inner = '';
1511 $attribs = '';
1512 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1513 if ( $node instanceof PPNode_Hash_Attr ) {
1514 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1515 } else {
1516 $inner .= $node->__toString();
1517 }
1518 }
1519 if ( $inner === '' ) {
1520 return "<{$this->name}$attribs/>";
1521 } else {
1522 return "<{$this->name}$attribs>$inner</{$this->name}>";
1523 }
1524 }
1525
1526 /**
1527 * @param $name
1528 * @param $text
1529 * @return PPNode_Hash_Tree
1530 */
1531 static function newWithText( $name, $text ) {
1532 $obj = new self( $name );
1533 $obj->addChild( new PPNode_Hash_Text( $text ) );
1534 return $obj;
1535 }
1536
1537 function addChild( $node ) {
1538 if ( $this->lastChild === false ) {
1539 $this->firstChild = $this->lastChild = $node;
1540 } else {
1541 $this->lastChild->nextSibling = $node;
1542 $this->lastChild = $node;
1543 }
1544 }
1545
1546 /**
1547 * @return PPNode_Hash_Array
1548 */
1549 function getChildren() {
1550 $children = array();
1551 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1552 $children[] = $child;
1553 }
1554 return new PPNode_Hash_Array( $children );
1555 }
1556
1557 function getFirstChild() {
1558 return $this->firstChild;
1559 }
1560
1561 function getNextSibling() {
1562 return $this->nextSibling;
1563 }
1564
1565 function getChildrenOfType( $name ) {
1566 $children = array();
1567 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1568 if ( isset( $child->name ) && $child->name === $name ) {
1569 $children[] = $name;
1570 }
1571 }
1572 return $children;
1573 }
1574
1575 /**
1576 * @return bool
1577 */
1578 function getLength() {
1579 return false;
1580 }
1581
1582 /**
1583 * @param $i
1584 * @return bool
1585 */
1586 function item( $i ) {
1587 return false;
1588 }
1589
1590 /**
1591 * @return string
1592 */
1593 function getName() {
1594 return $this->name;
1595 }
1596
1597 /**
1598 * Split a <part> node into an associative array containing:
1599 * name PPNode name
1600 * index String index
1601 * value PPNode value
1602 *
1603 * @return array
1604 */
1605 function splitArg() {
1606 $bits = array();
1607 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1608 if ( !isset( $child->name ) ) {
1609 continue;
1610 }
1611 if ( $child->name === 'name' ) {
1612 $bits['name'] = $child;
1613 if ( $child->firstChild instanceof PPNode_Hash_Attr
1614 && $child->firstChild->name === 'index' )
1615 {
1616 $bits['index'] = $child->firstChild->value;
1617 }
1618 } elseif ( $child->name === 'value' ) {
1619 $bits['value'] = $child;
1620 }
1621 }
1622
1623 if ( !isset( $bits['name'] ) ) {
1624 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1625 }
1626 if ( !isset( $bits['index'] ) ) {
1627 $bits['index'] = '';
1628 }
1629 return $bits;
1630 }
1631
1632 /**
1633 * Split an <ext> node into an associative array containing name, attr, inner and close
1634 * All values in the resulting array are PPNodes. Inner and close are optional.
1635 *
1636 * @return array
1637 */
1638 function splitExt() {
1639 $bits = array();
1640 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1641 if ( !isset( $child->name ) ) {
1642 continue;
1643 }
1644 if ( $child->name == 'name' ) {
1645 $bits['name'] = $child;
1646 } elseif ( $child->name == 'attr' ) {
1647 $bits['attr'] = $child;
1648 } elseif ( $child->name == 'inner' ) {
1649 $bits['inner'] = $child;
1650 } elseif ( $child->name == 'close' ) {
1651 $bits['close'] = $child;
1652 }
1653 }
1654 if ( !isset( $bits['name'] ) ) {
1655 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1656 }
1657 return $bits;
1658 }
1659
1660 /**
1661 * Split an <h> node
1662 *
1663 * @return array
1664 */
1665 function splitHeading() {
1666 if ( $this->name !== 'h' ) {
1667 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1668 }
1669 $bits = array();
1670 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1671 if ( !isset( $child->name ) ) {
1672 continue;
1673 }
1674 if ( $child->name == 'i' ) {
1675 $bits['i'] = $child->value;
1676 } elseif ( $child->name == 'level' ) {
1677 $bits['level'] = $child->value;
1678 }
1679 }
1680 if ( !isset( $bits['i'] ) ) {
1681 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1682 }
1683 return $bits;
1684 }
1685
1686 /**
1687 * Split a <template> or <tplarg> node
1688 *
1689 * @return array
1690 */
1691 function splitTemplate() {
1692 $parts = array();
1693 $bits = array( 'lineStart' => '' );
1694 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1695 if ( !isset( $child->name ) ) {
1696 continue;
1697 }
1698 if ( $child->name == 'title' ) {
1699 $bits['title'] = $child;
1700 }
1701 if ( $child->name == 'part' ) {
1702 $parts[] = $child;
1703 }
1704 if ( $child->name == 'lineStart' ) {
1705 $bits['lineStart'] = '1';
1706 }
1707 }
1708 if ( !isset( $bits['title'] ) ) {
1709 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1710 }
1711 $bits['parts'] = new PPNode_Hash_Array( $parts );
1712 return $bits;
1713 }
1714 }
1715
1716 /**
1717 * @ingroup Parser
1718 */
1719 class PPNode_Hash_Text implements PPNode {
1720 var $value, $nextSibling;
1721
1722 function __construct( $value ) {
1723 if ( is_object( $value ) ) {
1724 throw new MWException( __CLASS__ . ' given object instead of string' );
1725 }
1726 $this->value = $value;
1727 }
1728
1729 function __toString() {
1730 return htmlspecialchars( $this->value );
1731 }
1732
1733 function getNextSibling() {
1734 return $this->nextSibling;
1735 }
1736
1737 function getChildren() { return false; }
1738 function getFirstChild() { return false; }
1739 function getChildrenOfType( $name ) { return false; }
1740 function getLength() { return false; }
1741 function item( $i ) { return false; }
1742 function getName() { return '#text'; }
1743 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1744 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1745 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1746 }
1747
1748 /**
1749 * @ingroup Parser
1750 */
1751 class PPNode_Hash_Array implements PPNode {
1752 var $value, $nextSibling;
1753
1754 function __construct( $value ) {
1755 $this->value = $value;
1756 }
1757
1758 function __toString() {
1759 return var_export( $this, true );
1760 }
1761
1762 function getLength() {
1763 return count( $this->value );
1764 }
1765
1766 function item( $i ) {
1767 return $this->value[$i];
1768 }
1769
1770 function getName() { return '#nodelist'; }
1771
1772 function getNextSibling() {
1773 return $this->nextSibling;
1774 }
1775
1776 function getChildren() { return false; }
1777 function getFirstChild() { return false; }
1778 function getChildrenOfType( $name ) { return false; }
1779 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1780 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1781 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1782 }
1783
1784 /**
1785 * @ingroup Parser
1786 */
1787 class PPNode_Hash_Attr implements PPNode {
1788 var $name, $value, $nextSibling;
1789
1790 function __construct( $name, $value ) {
1791 $this->name = $name;
1792 $this->value = $value;
1793 }
1794
1795 function __toString() {
1796 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1797 }
1798
1799 function getName() {
1800 return $this->name;
1801 }
1802
1803 function getNextSibling() {
1804 return $this->nextSibling;
1805 }
1806
1807 function getChildren() { return false; }
1808 function getFirstChild() { return false; }
1809 function getChildrenOfType( $name ) { return false; }
1810 function getLength() { return false; }
1811 function item( $i ) { return false; }
1812 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1813 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1814 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1815 }