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