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