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