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