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