Debian Codegraph @

includes/parser/Preprocessor_Hash.php

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