MediaWiki master
Preprocessor_Hash.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Parser;
25
27
46// phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
49 protected const CACHE_VERSION = 4;
50
52 protected $cacheThreshold;
53
61 public function __construct(
64 array $options = []
65 ) {
66 parent::__construct( $parser, $wanCache, $options );
67
68 $this->cacheThreshold = $options['cacheThreshold'] ?? false;
69 }
70
74 public function newFrame() {
75 return new PPFrame_Hash( $this );
76 }
77
82 public function newCustomFrame( $args ) {
83 return new PPCustomFrame_Hash( $this, $args );
84 }
85
90 public function newPartNodeArray( $values ) {
91 $list = [];
92
93 foreach ( $values as $k => $val ) {
94 if ( is_int( $k ) ) {
95 $store = [ [ 'part', [
96 [ 'name', [ [ '@index', [ $k ] ] ] ],
97 [ 'value', [ strval( $val ) ] ],
98 ] ] ];
99 } else {
100 $store = [ [ 'part', [
101 [ 'name', [ strval( $k ) ] ],
102 '=',
103 [ 'value', [ strval( $val ) ] ],
104 ] ] ];
105 }
106
107 $list[] = new PPNode_Hash_Tree( $store, 0 );
108 }
109
110 return new PPNode_Hash_Array( $list );
111 }
112
113 public function preprocessToObj( $text, $flags = 0 ) {
114 if ( $this->disableLangConversion ) {
115 // Language conversions are globally disabled; implicitly set flag
117 }
118
119 $domTreeArray = null;
120 if (
121 $this->cacheThreshold !== false &&
122 strlen( $text ) >= $this->cacheThreshold &&
123 ( $flags & self::DOM_UNCACHED ) != self::DOM_UNCACHED
124 ) {
125 $domTreeJson = $this->wanCache->getWithSetCallback(
126 $this->wanCache->makeKey( 'preprocess-hash', sha1( $text ), $flags ),
127 $this->wanCache::TTL_DAY,
128 function () use ( $text, $flags, &$domTreeArray ) {
129 $domTreeArray = $this->buildDomTreeArrayFromText( $text, $flags );
130
131 return json_encode(
132 $domTreeArray,
133 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
134 );
135 },
136 [ 'version' => self::CACHE_VERSION, 'segmentable' => true ]
137 );
138 $domTreeArray ??= json_decode( $domTreeJson );
139 }
140
141 $domTreeArray ??= $this->buildDomTreeArrayFromText( $text, $flags );
142
143 return new PPNode_Hash_Tree( $domTreeArray, 0 );
144 }
145
151 private function buildDomTreeArrayFromText( $text, $flags ) {
152 $forInclusion = ( $flags & self::DOM_FOR_INCLUSION );
153 $langConversionDisabled = ( $flags & self::DOM_LANG_CONVERSION_DISABLED );
154
155 $xmlishElements = $this->parser->getStripList();
156 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
157 $enableOnlyinclude = false;
158 if ( $forInclusion ) {
159 $ignoredTags = [ 'includeonly', '/includeonly' ];
160 $ignoredElements = [ 'noinclude' ];
161 $xmlishElements[] = 'noinclude';
162 if ( str_contains( $text, '<onlyinclude>' )
163 && str_contains( $text, '</onlyinclude>' )
164 ) {
165 $enableOnlyinclude = true;
166 }
167 } else {
168 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
169 $ignoredElements = [ 'includeonly' ];
170 $xmlishElements[] = 'includeonly';
171 }
172 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
173
174 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
175 $elementsRegex = "~(?:$xmlishRegex)(?=\s|\/>|>)|!--~iA";
176
177 $stack = new PPDStack_Hash;
178
179 $searchBase = "[{<\n";
180 if ( !$langConversionDisabled ) {
181 $searchBase .= '-';
182 }
183
184 // For fast reverse searches
185 $revText = strrev( $text );
186 $lengthText = strlen( $text );
187
188 // Input pointer, starts out pointing to a pseudo-newline before the start
189 $i = 0;
190 // Current accumulator. See the doc comment for Preprocessor_Hash for the format.
191 $accum =& $stack->getAccum();
192 // True to find equals signs in arguments
193 $findEquals = false;
194 // True to take notice of pipe characters
195 $findPipe = false;
196 $headingIndex = 1;
197 // True if $i is inside a possible heading
198 $inHeading = false;
199 // True if there are no more greater-than (>) signs right of $i
200 $noMoreGT = false;
201 // Map of tag name => true if there are no more closing tags of given type right of $i
202 $noMoreClosingTag = [];
203 // True to ignore all input up to the next <onlyinclude>
204 $findOnlyinclude = $enableOnlyinclude;
205 // Do a line-start run without outputting an LF character
206 $fakeLineStart = true;
207
208 while ( true ) {
209 if ( $findOnlyinclude ) {
210 // Ignore all input up to the next <onlyinclude>
211 $startPos = strpos( $text, '<onlyinclude>', $i );
212 if ( $startPos === false ) {
213 // Ignored section runs to the end
214 $accum[] = [ 'ignore', [ substr( $text, $i ) ] ];
215 break;
216 }
217 $tagEndPos = $startPos + 13; // past-the-end of <onlyinclude>
218 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i ) ] ];
219 $i = $tagEndPos;
220 $findOnlyinclude = false;
221 }
222
223 if ( $fakeLineStart ) {
224 $found = 'line-start';
225 $curChar = '';
226 } else {
227 # Find next opening brace, closing brace or pipe
228 $search = $searchBase;
229 if ( $stack->top === false ) {
230 $currentClosing = '';
231 } else {
232 $currentClosing = $stack->top->close;
233 $search .= $currentClosing;
234 }
235 if ( $findPipe ) {
236 $search .= '|';
237 }
238 if ( $findEquals ) {
239 // First equals will be for the template
240 $search .= '=';
241 }
242 $rule = null;
243 # Output literal section, advance input counter
244 $literalLength = strcspn( $text, $search, $i );
245 if ( $literalLength > 0 ) {
246 self::addLiteral( $accum, substr( $text, $i, $literalLength ) );
247 $i += $literalLength;
248 }
249 if ( $i >= $lengthText ) {
250 if ( $currentClosing === "\n" ) {
251 // Do a past-the-end run to finish off the heading
252 $curChar = '';
253 $found = 'line-end';
254 } else {
255 # All done
256 break;
257 }
258 } else {
259 $curChar = $curTwoChar = $text[$i];
260 if ( $i + 1 < $lengthText ) {
261 $curTwoChar .= $text[$i + 1];
262 }
263 if ( $curChar === '|' ) {
264 $found = 'pipe';
265 } elseif ( $curChar === '=' ) {
266 $found = 'equals';
267 } elseif ( $curChar === '<' ) {
268 $found = 'angle';
269 } elseif ( $curChar === "\n" ) {
270 if ( $inHeading ) {
271 $found = 'line-end';
272 } else {
273 $found = 'line-start';
274 }
275 } elseif ( $curTwoChar === $currentClosing ) {
276 $found = 'close';
277 $curChar = $curTwoChar;
278 } elseif ( $curChar === $currentClosing ) {
279 $found = 'close';
280 } elseif ( isset( $this->rules[$curTwoChar] ) ) {
281 $curChar = $curTwoChar;
282 $found = 'open';
283 $rule = $this->rules[$curChar];
284 } elseif ( isset( $this->rules[$curChar] ) ) {
285 $found = 'open';
286 $rule = $this->rules[$curChar];
287 } else {
288 # Some versions of PHP have a strcspn which stops on
289 # null characters; ignore these and continue.
290 # We also may get '-' and '}' characters here which
291 # don't match -{ or $currentClosing. Add these to
292 # output and continue.
293 if ( $curChar === '-' || $curChar === '}' ) {
294 self::addLiteral( $accum, $curChar );
295 }
296 ++$i;
297 continue;
298 }
299 }
300 }
301
302 if ( $found === 'angle' ) {
303 // Handle </onlyinclude>
304 if ( $enableOnlyinclude
305 && substr_compare( $text, '</onlyinclude>', $i, 14 ) === 0
306 ) {
307 $findOnlyinclude = true;
308 continue;
309 }
310
311 // Determine element name
312 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
313 // Element name missing or not listed
314 self::addLiteral( $accum, '<' );
315 ++$i;
316 continue;
317 }
318 $name = $matches[0];
319 // Handle comments
320 if ( $name === '!--' ) {
321 // To avoid leaving blank lines, when a sequence of
322 // space-separated comments is both preceded and followed by
323 // a newline (ignoring spaces), then
324 // trim leading and trailing spaces and the trailing newline.
325
326 // Find the end
327 $endPos = strpos( $text, '-->', $i + 4 );
328 if ( $endPos === false ) {
329 // Unclosed comment in input, runs to end
330 $inner = substr( $text, $i );
331 $accum[] = [ 'comment', [ $inner ] ];
332 $i = $lengthText;
333 } else {
334 // Search backwards for leading whitespace
335 // $wsStart is the first char of the comment (first of the leading space or '<')
336 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
337
338 // $wsEnd will be the char *after* the comment (after last space or the '>' if there's no space)
339 $wsEnd = $endPos + 3; // add length of -->
340 // Search forwards for trailing whitespace
341 $wsEnd += strspn( $text, " \t", $wsEnd );
342
343 // Keep looking forward as long as we're finding more comments on the line
344 $comments = [ [ $wsStart, $wsEnd ] ];
345 while ( substr_compare( $text, '<!--', $wsEnd, 4 ) === 0 ) {
346 $c = strpos( $text, '-->', $wsEnd + 4 );
347 if ( $c === false ) {
348 break;
349 }
350 $c += 3; // add length of -->
351 // Search forwards for trailing whitespace
352 $c += strspn( $text, " \t", $c );
353 $comments[] = [ $wsEnd, $c ];
354 $wsEnd = $c;
355 }
356
357 // Eat the line if possible
358 // TODO: This could theoretically be done if $wsStart === 0, i.e. for comments at
359 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
360 // it's a possible beneficial b/c break.
361 if ( $wsStart > 0 && substr_compare( $text, "\n", $wsStart - 1, 1 ) === 0
362 && substr_compare( $text, "\n", $wsEnd, 1 ) === 0
363 ) {
364 // Remove leading whitespace from the end of the accumulator
365 $wsLength = $i - $wsStart;
366 $endIndex = count( $accum ) - 1;
367
368 if ( $wsLength > 0
369 && $endIndex >= 0
370 && is_string( $accum[$endIndex] )
371 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
372 ) {
373 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
374 }
375
376 // Dump all but the last comment to the accumulator
377 // $endPos includes the newline from the if above, want also eat that
378 [ $startPos, $endPos ] = array_pop( $comments );
379 foreach ( $comments as [ $cStartPos, $cEndPos ] ) {
380 // $cEndPos is the next char, no +1 needed to get correct length between start/end
381 $inner = substr( $text, $cStartPos, $cEndPos - $cStartPos );
382 $accum[] = [ 'comment', [ $inner ] ];
383 }
384
385 // Do a line-start run next time to look for headings after the comment
386 $fakeLineStart = true;
387 } else {
388 // No line to eat, just take the comment itself
389 $startPos = $i;
390 $endPos += 2;
391 }
392
393 if ( $stack->top ) {
394 $part = $stack->top->getCurrentPart();
395 if ( $part->commentEnd !== $wsStart - 1 ) {
396 $part->visualEnd = $wsStart;
397 }
398 // Else comments abutting, no change in visual end
399 $part->commentEnd = $endPos;
400 }
401 $i = $endPos + 1;
402 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
403 $accum[] = [ 'comment', [ $inner ] ];
404 }
405 continue;
406 }
407 $attrStart = $i + strlen( $name ) + 1;
408
409 // Find end of tag
410 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
411 if ( $tagEndPos === false ) {
412 // Infinite backtrack
413 // Disable tag search to prevent worst-case O(N^2) performance
414 $noMoreGT = true;
415 self::addLiteral( $accum, '<' );
416 ++$i;
417 continue;
418 }
419
420 $lowerName = strtolower( $name );
421 // Handle ignored tags
422 if ( in_array( $lowerName, $ignoredTags ) ) {
423 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i + 1 ) ] ];
424 $i = $tagEndPos + 1;
425 continue;
426 }
427
428 $tagStartPos = $i;
429 if ( $text[$tagEndPos - 1] === '/' ) {
430 // Short end tag
431 $attrEnd = $tagEndPos - 1;
432 $inner = null;
433 $i = $tagEndPos + 1;
434 $close = null;
435 } else {
436 $attrEnd = $tagEndPos;
437 // Find closing tag
438 if (
439 !isset( $noMoreClosingTag[$lowerName] ) &&
440 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
441 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
442 ) {
443 [ $close, $closeTagStartPos ] = $matches[0];
444 $inner = substr( $text, $tagEndPos + 1, $closeTagStartPos - $tagEndPos - 1 );
445 $i = $closeTagStartPos + strlen( $close );
446 } else {
447 // No end tag
448 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
449 // Let it run out to the end of the text.
450 $inner = substr( $text, $tagEndPos + 1 );
451 $i = $lengthText;
452 $close = null;
453 } else {
454 // Don't match the tag, treat opening tag as literal and resume parsing.
455 $i = $tagEndPos + 1;
456 self::addLiteral( $accum, substr( $text, $tagStartPos, $tagEndPos + 1 - $tagStartPos ) );
457 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
458 $noMoreClosingTag[$lowerName] = true;
459 continue;
460 }
461 }
462 }
463 // <includeonly> and <noinclude> just become <ignore> tags
464 if ( in_array( $lowerName, $ignoredElements ) ) {
465 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
466 continue;
467 }
468
469 if ( $attrEnd <= $attrStart ) {
470 $attr = '';
471 } else {
472 // Note that the attr element contains the whitespace between name and attribute,
473 // this is necessary for precise reconstruction during pre-save transform.
474 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
475 }
476
477 $children = [
478 [ 'name', [ $name ] ],
479 [ 'attr', [ $attr ] ],
480 ];
481 if ( $inner !== null ) {
482 $children[] = [ 'inner', [ $inner ] ];
483 }
484 if ( $close !== null ) {
485 $children[] = [ 'close', [ $close ] ];
486 }
487 $accum[] = [ 'ext', $children ];
488 } elseif ( $found === 'line-start' ) {
489 // Is this the start of a heading?
490 // Line break belongs before the heading element in any case
491 if ( $fakeLineStart ) {
492 $fakeLineStart = false;
493 } else {
494 self::addLiteral( $accum, $curChar );
495 $i++;
496 }
497
498 // Examine upto 6 characters
499 $count = strspn( $text, '=', $i, min( $lengthText, 6 ) );
500 if ( $count === 1 && $findEquals ) {
501 // DWIM: This looks kind of like a name/value separator.
502 // Let's let the equals handler have it and break the potential
503 // heading. This is heuristic, but AFAICT the methods for
504 // completely correct disambiguation are very complex.
505 } elseif ( $count > 0 ) {
506 $piece = [
507 'open' => "\n",
508 'close' => "\n",
509 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
510 'startPos' => $i,
511 'count' => $count,
512 ];
513 $stack->push( $piece );
514 $accum =& $stack->getAccum();
515 $stackFlags = $stack->getFlags();
516 if ( isset( $stackFlags['findEquals'] ) ) {
517 $findEquals = $stackFlags['findEquals'];
518 }
519 if ( isset( $stackFlags['findPipe'] ) ) {
520 $findPipe = $stackFlags['findPipe'];
521 }
522 if ( isset( $stackFlags['inHeading'] ) ) {
523 $inHeading = $stackFlags['inHeading'];
524 }
525 $i += $count;
526 }
527 } elseif ( $found === 'line-end' ) {
528 $piece = $stack->top;
529 // A heading must be open, otherwise \n wouldn't have been in the search list
530 // FIXME: Don't use assert()
531 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.assert
532 assert( $piece->open === "\n" );
533 $part = $piece->getCurrentPart();
534 // Search back through the input to see if it has a proper close.
535 // Do this using the reversed string since the other solutions
536 // (end anchor, etc.) are inefficient.
537 $wsLength = strspn( $revText, " \t", $lengthText - $i );
538 $searchStart = $i - $wsLength;
539 if ( $part->commentEnd === $searchStart - 1 ) {
540 // Comment found at line end
541 // Search for equals signs before the comment
542 $searchStart = $part->visualEnd;
543 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
544 }
545 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
546 if ( $equalsLength > 0 ) {
547 if ( $searchStart - $equalsLength === $piece->startPos ) {
548 // This is just a single string of equals signs on its own line
549 // Replicate the doHeadings behavior /={count}(.+)={count}/
550 // First find out how many equals signs there really are (don't stop at 6)
551 if ( $equalsLength < 3 ) {
552 $count = 0;
553 } else {
554 $count = min( 6, intval( ( $equalsLength - 1 ) / 2 ) );
555 }
556 } else {
557 $count = min( $equalsLength, $piece->count );
558 }
559 if ( $count > 0 ) {
560 // Normal match, output <h>
561 $element = [ [ 'possible-h',
562 array_merge(
563 [
564 [ '@level', [ $count ] ],
565 [ '@i', [ $headingIndex++ ] ]
566 ],
567 $accum
568 )
569 ] ];
570 } else {
571 // Single equals sign on its own line, count=0
572 $element = $accum;
573 }
574 } else {
575 // No match, no <h>, just pass down the inner text
576 $element = $accum;
577 }
578 // Unwind the stack
579 $stack->pop();
580 $accum =& $stack->getAccum();
581 $stackFlags = $stack->getFlags();
582 if ( isset( $stackFlags['findEquals'] ) ) {
583 $findEquals = $stackFlags['findEquals'];
584 }
585 if ( isset( $stackFlags['findPipe'] ) ) {
586 $findPipe = $stackFlags['findPipe'];
587 }
588 if ( isset( $stackFlags['inHeading'] ) ) {
589 $inHeading = $stackFlags['inHeading'];
590 }
591
592 // Append the result to the enclosing accumulator
593 array_splice( $accum, count( $accum ), 0, $element );
594
595 // Note that we do NOT increment the input pointer.
596 // This is because the closing linebreak could be the opening linebreak of
597 // another heading. Infinite loops are avoided because the next iteration MUST
598 // hit the heading open case above, which unconditionally increments the
599 // input pointer.
600 } elseif ( $found === 'open' ) {
601 # count opening brace characters
602 $curLen = strlen( $curChar );
603 $count = $curLen > 1
604 # allow the final character to repeat
605 ? strspn( $text, $curChar[$curLen - 1], $i + 1 ) + 1
606 : strspn( $text, $curChar, $i );
607
608 $savedPrefix = '';
609 $lineStart = $i > 0 && $text[$i - 1] === "\n";
610
611 if ( $curChar === "-{" && $count > $curLen ) {
612 // -{ => {{ transition because rightmost wins
613 $savedPrefix = '-';
614 $i++;
615 $curChar = '{';
616 $count--;
617 $rule = $this->rules[$curChar];
618 }
619
620 # we need to add to stack only if opening brace count is enough for one of the rules
621 if ( $count >= $rule['min'] ) {
622 # Add it to the stack
623 $piece = [
624 'open' => $curChar,
625 'close' => $rule['end'],
626 'savedPrefix' => $savedPrefix,
627 'count' => $count,
628 'lineStart' => $lineStart,
629 ];
630
631 $stack->push( $piece );
632 $accum =& $stack->getAccum();
633 $stackFlags = $stack->getFlags();
634 if ( isset( $stackFlags['findEquals'] ) ) {
635 $findEquals = $stackFlags['findEquals'];
636 }
637 if ( isset( $stackFlags['findPipe'] ) ) {
638 $findPipe = $stackFlags['findPipe'];
639 }
640 if ( isset( $stackFlags['inHeading'] ) ) {
641 $inHeading = $stackFlags['inHeading'];
642 }
643 } else {
644 # Add literal brace(s)
645 self::addLiteral( $accum, $savedPrefix . str_repeat( $curChar, $count ) );
646 }
647 $i += $count;
648 } elseif ( $found === 'close' ) {
650 $piece = $stack->top;
651 '@phan-var PPDStackElement_Hash $piece';
652 # lets check if there are enough characters for closing brace
653 $maxCount = $piece->count;
654 if ( $piece->close === '}-' && $curChar === '}' ) {
655 $maxCount--; # don't try to match closing '-' as a '}'
656 }
657 $curLen = strlen( $curChar );
658 $count = $curLen > 1
659 ? $curLen
660 : strspn( $text, $curChar, $i, $maxCount );
661
662 # check for maximum matching characters (if there are 5 closing
663 # characters, we will probably need only 3 - depending on the rules)
664 $rule = $this->rules[$piece->open];
665 if ( $count > $rule['max'] ) {
666 # The specified maximum exists in the callback array, unless the caller
667 # has made an error
668 $matchingCount = $rule['max'];
669 } else {
670 # Count is less than the maximum
671 # Skip any gaps in the callback array to find the true largest match
672 # Need to use array_key_exists not isset because the callback can be null
673 $matchingCount = $count;
674 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
675 --$matchingCount;
676 }
677 }
678
679 if ( $matchingCount <= 0 ) {
680 # No matching element found in callback array
681 # Output a literal closing brace and continue
682 $endText = substr( $text, $i, $count );
683 self::addLiteral( $accum, $endText );
684 $i += $count;
685 continue;
686 }
687 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
688 $name = $rule['names'][$matchingCount];
689 if ( $name === null ) {
690 // No element, just literal text
691 $endText = substr( $text, $i, $matchingCount );
692 $element = $piece->breakSyntax( $matchingCount );
693 self::addLiteral( $element, $endText );
694 } else {
695 # Create XML element
696 $parts = $piece->parts;
697 $titleAccum = $parts[0]->out;
698 unset( $parts[0] );
699
700 $children = [];
701
702 # The invocation is at the start of the line if lineStart is set in
703 # the stack, and all opening brackets are used up.
704 if ( $maxCount === $matchingCount &&
705 $piece->lineStart &&
706 $piece->savedPrefix === ''
707 ) {
708 $children[] = [ '@lineStart', [ 1 ] ];
709 }
710 $titleNode = [ 'title', $titleAccum ];
711 $children[] = $titleNode;
712 $argIndex = 1;
713 foreach ( $parts as $part ) {
714 if ( isset( $part->eqpos ) ) {
715 $equalsNode = $part->out[$part->eqpos];
716 $nameNode = [ 'name', array_slice( $part->out, 0, $part->eqpos ) ];
717 $valueNode = [ 'value', array_slice( $part->out, $part->eqpos + 1 ) ];
718 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
719 $children[] = $partNode;
720 } else {
721 $nameNode = [ 'name', [ [ '@index', [ $argIndex++ ] ] ] ];
722 $valueNode = [ 'value', $part->out ];
723 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
724 $children[] = $partNode;
725 }
726 }
727 $element = [ [ $name, $children ] ];
728 }
729
730 # Advance input pointer
731 $i += $matchingCount;
732
733 # Unwind the stack
734 $stack->pop();
735 $accum =& $stack->getAccum();
736
737 # Re-add the old stack element if it still has unmatched opening characters remaining
738 if ( $matchingCount < $piece->count ) {
739 $piece->parts = [ new PPDPart_Hash ];
740 $piece->count -= $matchingCount;
741 # do we still qualify for any callback with remaining count?
742 $min = $this->rules[$piece->open]['min'];
743 if ( $piece->count >= $min ) {
744 $stack->push( $piece );
745 $accum =& $stack->getAccum();
746 } elseif ( $piece->count === 1 && $piece->open === '{' && $piece->savedPrefix === '-' ) {
747 $piece->savedPrefix = '';
748 $piece->open = '-{';
749 $piece->count = 2;
750 $piece->close = $this->rules[$piece->open]['end'];
751 $stack->push( $piece );
752 $accum =& $stack->getAccum();
753 } else {
754 $s = substr( $piece->open, 0, -1 );
755 $s .= str_repeat(
756 substr( $piece->open, -1 ),
757 $piece->count - strlen( $s )
758 );
759 self::addLiteral( $accum, $piece->savedPrefix . $s );
760 }
761 } elseif ( $piece->savedPrefix !== '' ) {
762 self::addLiteral( $accum, $piece->savedPrefix );
763 }
764
765 $stackFlags = $stack->getFlags();
766 if ( isset( $stackFlags['findEquals'] ) ) {
767 $findEquals = $stackFlags['findEquals'];
768 }
769 if ( isset( $stackFlags['findPipe'] ) ) {
770 $findPipe = $stackFlags['findPipe'];
771 }
772 if ( isset( $stackFlags['inHeading'] ) ) {
773 $inHeading = $stackFlags['inHeading'];
774 }
775
776 # Add XML element to the enclosing accumulator
777 array_splice( $accum, count( $accum ), 0, $element );
778 } elseif ( $found === 'pipe' ) {
779 $findEquals = true; // shortcut for getFlags()
780 $stack->addPart();
781 $accum =& $stack->getAccum();
782 ++$i;
783 } elseif ( $found === 'equals' ) {
784 $findEquals = false; // shortcut for getFlags()
785 $accum[] = [ 'equals', [ '=' ] ];
786 $stack->getCurrentPart()->eqpos = count( $accum ) - 1;
787 ++$i;
788 }
789 }
790
791 # Output any remaining unclosed brackets
792 foreach ( $stack->stack as $piece ) {
793 array_splice( $stack->rootAccum, count( $stack->rootAccum ), 0, $piece->breakSyntax() );
794 }
795
796 # Enable top-level headings
797 foreach ( $stack->rootAccum as &$node ) {
798 if ( is_array( $node ) && $node[PPNode_Hash_Tree::NAME] === 'possible-h' ) {
799 $node[PPNode_Hash_Tree::NAME] = 'h';
800 }
801 }
802
803 return [ [ 'root', $stack->rootAccum ] ];
804 }
805
806 private static function addLiteral( array &$accum, $text ) {
807 $n = count( $accum );
808 if ( $n && is_string( $accum[$n - 1] ) ) {
809 $accum[$n - 1] .= $text;
810 } else {
811 $accum[] = $text;
812 }
813 }
814}
815
817class_alias( Preprocessor_Hash::class, 'Preprocessor_Hash' );
Expansion frame with custom arguments.
An expansion frame, used as a context to expand the result of preprocessToObj()
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:145
Differences from DOM schema:
__construct(Parser $parser, ?WANObjectCache $wanCache=null, array $options=[])
const CACHE_VERSION
Cache format version.
int false $cacheThreshold
Min wikitext size for which to cache DOM tree.
preprocessToObj( $text, $flags=0)
Get the document object model for the given wikitext.
const DOM_LANG_CONVERSION_DISABLED
Language conversion construct omission flag for Preprocessor::preprocessToObj()
const DOM_FOR_INCLUSION
Transclusion mode flag for Preprocessor::preprocessToObj()
Multi-datacenter aware caching interface.