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