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