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