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