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