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