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