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