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