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