Split parser related files to have one class in one file
[lhc/web/wiklou.git] / includes / parser / Preprocessor_DOM.php
1 <?php
2 /**
3 * Preprocessor using PHP's dom extension
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 /**
25 * @ingroup Parser
26 */
27 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
28 class Preprocessor_DOM extends Preprocessor {
29
30 /**
31 * @var Parser
32 */
33 public $parser;
34
35 public $memoryLimit;
36
37 const CACHE_PREFIX = 'preprocess-xml';
38
39 public function __construct( $parser ) {
40 $this->parser = $parser;
41 $mem = ini_get( 'memory_limit' );
42 $this->memoryLimit = false;
43 if ( strval( $mem ) !== '' && $mem != -1 ) {
44 if ( preg_match( '/^\d+$/', $mem ) ) {
45 $this->memoryLimit = $mem;
46 } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
47 $this->memoryLimit = $m[1] * 1048576;
48 }
49 }
50 }
51
52 /**
53 * @return PPFrame_DOM
54 */
55 public function newFrame() {
56 return new PPFrame_DOM( $this );
57 }
58
59 /**
60 * @param array $args
61 * @return PPCustomFrame_DOM
62 */
63 public function newCustomFrame( $args ) {
64 return new PPCustomFrame_DOM( $this, $args );
65 }
66
67 /**
68 * @param array $values
69 * @return PPNode_DOM
70 * @throws MWException
71 */
72 public function newPartNodeArray( $values ) {
73 // NOTE: DOM manipulation is slower than building & parsing XML! (or so Tim sais)
74 $xml = "<list>";
75
76 foreach ( $values as $k => $val ) {
77 if ( is_int( $k ) ) {
78 $xml .= "<part><name index=\"$k\"/><value>"
79 . htmlspecialchars( $val ) . "</value></part>";
80 } else {
81 $xml .= "<part><name>" . htmlspecialchars( $k )
82 . "</name>=<value>" . htmlspecialchars( $val ) . "</value></part>";
83 }
84 }
85
86 $xml .= "</list>";
87
88 $dom = new DOMDocument();
89 Wikimedia\suppressWarnings();
90 $result = $dom->loadXML( $xml );
91 Wikimedia\restoreWarnings();
92 if ( !$result ) {
93 // Try running the XML through UtfNormal to get rid of invalid characters
94 $xml = UtfNormal\Validator::cleanUp( $xml );
95 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
96 // don't barf when the XML is >256 levels deep
97 $result = $dom->loadXML( $xml, 1 << 19 );
98 }
99
100 if ( !$result ) {
101 throw new MWException( 'Parameters passed to ' . __METHOD__ . ' result in invalid XML' );
102 }
103
104 $root = $dom->documentElement;
105 $node = new PPNode_DOM( $root->childNodes );
106 return $node;
107 }
108
109 /**
110 * @throws MWException
111 * @return bool
112 */
113 public function memCheck() {
114 if ( $this->memoryLimit === false ) {
115 return true;
116 }
117 $usage = memory_get_usage();
118 if ( $usage > $this->memoryLimit * 0.9 ) {
119 $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
120 throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
121 }
122 return $usage <= $this->memoryLimit * 0.8;
123 }
124
125 /**
126 * Preprocess some wikitext and return the document tree.
127 * This is the ghost of Parser::replace_variables().
128 *
129 * @param string $text The text to parse
130 * @param int $flags Bitwise combination of:
131 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>"
132 * as if the text is being included. Default
133 * is to assume a direct page view.
134 *
135 * The generated DOM tree must depend only on the input text and the flags.
136 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
137 *
138 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
139 * change in the DOM tree for a given text, must be passed through the section identifier
140 * in the section edit link and thus back to extractSections().
141 *
142 * The output of this function is currently only cached in process memory, but a persistent
143 * cache may be implemented at a later date which takes further advantage of these strict
144 * dependency requirements.
145 *
146 * @throws MWException
147 * @return PPNode_DOM
148 */
149 public function preprocessToObj( $text, $flags = 0 ) {
150 $xml = $this->cacheGetTree( $text, $flags );
151 if ( $xml === false ) {
152 $xml = $this->preprocessToXml( $text, $flags );
153 $this->cacheSetTree( $text, $flags, $xml );
154 }
155
156 // Fail if the number of elements exceeds acceptable limits
157 // Do not attempt to generate the DOM
158 $this->parser->mGeneratedPPNodeCount += substr_count( $xml, '<' );
159 $max = $this->parser->mOptions->getMaxGeneratedPPNodeCount();
160 if ( $this->parser->mGeneratedPPNodeCount > $max ) {
161 // if ( $cacheable ) { ... }
162 throw new MWException( __METHOD__ . ': generated node count limit exceeded' );
163 }
164
165 $dom = new DOMDocument;
166 Wikimedia\suppressWarnings();
167 $result = $dom->loadXML( $xml );
168 Wikimedia\restoreWarnings();
169 if ( !$result ) {
170 // Try running the XML through UtfNormal to get rid of invalid characters
171 $xml = UtfNormal\Validator::cleanUp( $xml );
172 // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2
173 // don't barf when the XML is >256 levels deep.
174 $result = $dom->loadXML( $xml, 1 << 19 );
175 }
176 if ( $result ) {
177 $obj = new PPNode_DOM( $dom->documentElement );
178 }
179
180 // if ( $cacheable ) { ... }
181
182 if ( !$result ) {
183 throw new MWException( __METHOD__ . ' generated invalid XML' );
184 }
185 return $obj;
186 }
187
188 /**
189 * @param string $text
190 * @param int $flags
191 * @return string
192 */
193 public function preprocessToXml( $text, $flags = 0 ) {
194 global $wgDisableLangConversion;
195
196 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
197
198 $xmlishElements = $this->parser->getStripList();
199 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
200 $enableOnlyinclude = false;
201 if ( $forInclusion ) {
202 $ignoredTags = [ 'includeonly', '/includeonly' ];
203 $ignoredElements = [ 'noinclude' ];
204 $xmlishElements[] = 'noinclude';
205 if ( strpos( $text, '<onlyinclude>' ) !== false
206 && strpos( $text, '</onlyinclude>' ) !== false
207 ) {
208 $enableOnlyinclude = true;
209 }
210 } else {
211 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
212 $ignoredElements = [ 'includeonly' ];
213 $xmlishElements[] = 'includeonly';
214 }
215 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
216
217 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
218 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
219
220 $stack = new PPDStack;
221
222 $searchBase = "[{<\n"; # }
223 if ( !$wgDisableLangConversion ) {
224 $searchBase .= '-';
225 }
226
227 // For fast reverse searches
228 $revText = strrev( $text );
229 $lengthText = strlen( $text );
230
231 // Input pointer, starts out pointing to a pseudo-newline before the start
232 $i = 0;
233 // Current accumulator
234 $accum =& $stack->getAccum();
235 $accum = '<root>';
236 // True to find equals signs in arguments
237 $findEquals = false;
238 // True to take notice of pipe characters
239 $findPipe = false;
240 $headingIndex = 1;
241 // True if $i is inside a possible heading
242 $inHeading = false;
243 // True if there are no more greater-than (>) signs right of $i
244 $noMoreGT = false;
245 // Map of tag name => true if there are no more closing tags of given type right of $i
246 $noMoreClosingTag = [];
247 // True to ignore all input up to the next <onlyinclude>
248 $findOnlyinclude = $enableOnlyinclude;
249 // Do a line-start run without outputting an LF character
250 $fakeLineStart = true;
251
252 while ( true ) {
253 // $this->memCheck();
254
255 if ( $findOnlyinclude ) {
256 // Ignore all input up to the next <onlyinclude>
257 $startPos = strpos( $text, '<onlyinclude>', $i );
258 if ( $startPos === false ) {
259 // Ignored section runs to the end
260 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
261 break;
262 }
263 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
264 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
265 $i = $tagEndPos;
266 $findOnlyinclude = false;
267 }
268
269 if ( $fakeLineStart ) {
270 $found = 'line-start';
271 $curChar = '';
272 } else {
273 # Find next opening brace, closing brace or pipe
274 $search = $searchBase;
275 if ( $stack->top === false ) {
276 $currentClosing = '';
277 } else {
278 $currentClosing = $stack->top->close;
279 $search .= $currentClosing;
280 }
281 if ( $findPipe ) {
282 $search .= '|';
283 }
284 if ( $findEquals ) {
285 // First equals will be for the template
286 $search .= '=';
287 }
288 $rule = null;
289 # Output literal section, advance input counter
290 $literalLength = strcspn( $text, $search, $i );
291 if ( $literalLength > 0 ) {
292 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
293 $i += $literalLength;
294 }
295 if ( $i >= $lengthText ) {
296 if ( $currentClosing == "\n" ) {
297 // Do a past-the-end run to finish off the heading
298 $curChar = '';
299 $found = 'line-end';
300 } else {
301 # All done
302 break;
303 }
304 } else {
305 $curChar = $curTwoChar = $text[$i];
306 if ( ( $i + 1 ) < $lengthText ) {
307 $curTwoChar .= $text[$i + 1];
308 }
309 if ( $curChar == '|' ) {
310 $found = 'pipe';
311 } elseif ( $curChar == '=' ) {
312 $found = 'equals';
313 } elseif ( $curChar == '<' ) {
314 $found = 'angle';
315 } elseif ( $curChar == "\n" ) {
316 if ( $inHeading ) {
317 $found = 'line-end';
318 } else {
319 $found = 'line-start';
320 }
321 } elseif ( $curTwoChar == $currentClosing ) {
322 $found = 'close';
323 $curChar = $curTwoChar;
324 } elseif ( $curChar == $currentClosing ) {
325 $found = 'close';
326 } elseif ( isset( $this->rules[$curTwoChar] ) ) {
327 $curChar = $curTwoChar;
328 $found = 'open';
329 $rule = $this->rules[$curChar];
330 } elseif ( isset( $this->rules[$curChar] ) ) {
331 $found = 'open';
332 $rule = $this->rules[$curChar];
333 } else {
334 # Some versions of PHP have a strcspn which stops on
335 # null characters; ignore these and continue.
336 # We also may get '-' and '}' characters here which
337 # don't match -{ or $currentClosing. Add these to
338 # output and continue.
339 if ( $curChar == '-' || $curChar == '}' ) {
340 $accum .= $curChar;
341 }
342 ++$i;
343 continue;
344 }
345 }
346 }
347
348 if ( $found == 'angle' ) {
349 $matches = false;
350 // Handle </onlyinclude>
351 if ( $enableOnlyinclude
352 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
353 ) {
354 $findOnlyinclude = true;
355 continue;
356 }
357
358 // Determine element name
359 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
360 // Element name missing or not listed
361 $accum .= '&lt;';
362 ++$i;
363 continue;
364 }
365 // Handle comments
366 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
367 // To avoid leaving blank lines, when a sequence of
368 // space-separated comments is both preceded and followed by
369 // a newline (ignoring spaces), then
370 // trim leading and trailing spaces and the trailing newline.
371
372 // Find the end
373 $endPos = strpos( $text, '-->', $i + 4 );
374 if ( $endPos === false ) {
375 // Unclosed comment in input, runs to end
376 $inner = substr( $text, $i );
377 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
378 $i = $lengthText;
379 } else {
380 // Search backwards for leading whitespace
381 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
382
383 // Search forwards for trailing whitespace
384 // $wsEnd will be the position of the last space (or the '>' if there's none)
385 $wsEnd = $endPos + 2 + strspn( $text, " \t", $endPos + 3 );
386
387 // Keep looking forward as long as we're finding more
388 // comments.
389 $comments = [ [ $wsStart, $wsEnd ] ];
390 while ( substr( $text, $wsEnd + 1, 4 ) == '<!--' ) {
391 $c = strpos( $text, '-->', $wsEnd + 4 );
392 if ( $c === false ) {
393 break;
394 }
395 $c = $c + 2 + strspn( $text, " \t", $c + 3 );
396 $comments[] = [ $wsEnd + 1, $c ];
397 $wsEnd = $c;
398 }
399
400 // Eat the line if possible
401 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
402 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
403 // it's a possible beneficial b/c break.
404 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
405 && substr( $text, $wsEnd + 1, 1 ) == "\n"
406 ) {
407 // Remove leading whitespace from the end of the accumulator
408 // Sanity check first though
409 $wsLength = $i - $wsStart;
410 if ( $wsLength > 0
411 && strspn( $accum, " \t", -$wsLength ) === $wsLength
412 ) {
413 $accum = substr( $accum, 0, -$wsLength );
414 }
415
416 // Dump all but the last comment to the accumulator
417 foreach ( $comments as $j => $com ) {
418 $startPos = $com[0];
419 $endPos = $com[1] + 1;
420 if ( $j == ( count( $comments ) - 1 ) ) {
421 break;
422 }
423 $inner = substr( $text, $startPos, $endPos - $startPos );
424 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
425 }
426
427 // Do a line-start run next time to look for headings after the comment
428 $fakeLineStart = true;
429 } else {
430 // No line to eat, just take the comment itself
431 $startPos = $i;
432 $endPos += 2;
433 }
434
435 if ( $stack->top ) {
436 $part = $stack->top->getCurrentPart();
437 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
438 $part->visualEnd = $wsStart;
439 }
440 // Else comments abutting, no change in visual end
441 $part->commentEnd = $endPos;
442 }
443 $i = $endPos + 1;
444 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
445 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
446 }
447 continue;
448 }
449 $name = $matches[1];
450 $lowerName = strtolower( $name );
451 $attrStart = $i + strlen( $name ) + 1;
452
453 // Find end of tag
454 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
455 if ( $tagEndPos === false ) {
456 // Infinite backtrack
457 // Disable tag search to prevent worst-case O(N^2) performance
458 $noMoreGT = true;
459 $accum .= '&lt;';
460 ++$i;
461 continue;
462 }
463
464 // Handle ignored tags
465 if ( in_array( $lowerName, $ignoredTags ) ) {
466 $accum .= '<ignore>'
467 . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) )
468 . '</ignore>';
469 $i = $tagEndPos + 1;
470 continue;
471 }
472
473 $tagStartPos = $i;
474 if ( $text[$tagEndPos - 1] == '/' ) {
475 $attrEnd = $tagEndPos - 1;
476 $inner = null;
477 $i = $tagEndPos + 1;
478 $close = '';
479 } else {
480 $attrEnd = $tagEndPos;
481 // Find closing tag
482 if (
483 !isset( $noMoreClosingTag[$name] ) &&
484 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
485 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
486 ) {
487 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
488 $i = $matches[0][1] + strlen( $matches[0][0] );
489 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
490 } else {
491 // No end tag
492 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
493 // Let it run out to the end of the text.
494 $inner = substr( $text, $tagEndPos + 1 );
495 $i = $lengthText;
496 $close = '';
497 } else {
498 // Don't match the tag, treat opening tag as literal and resume parsing.
499 $i = $tagEndPos + 1;
500 $accum .= htmlspecialchars( substr( $text, $tagStartPos, $tagEndPos + 1 - $tagStartPos ) );
501 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
502 $noMoreClosingTag[$name] = true;
503 continue;
504 }
505 }
506 }
507 // <includeonly> and <noinclude> just become <ignore> tags
508 if ( in_array( $lowerName, $ignoredElements ) ) {
509 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
510 . '</ignore>';
511 continue;
512 }
513
514 $accum .= '<ext>';
515 if ( $attrEnd <= $attrStart ) {
516 $attr = '';
517 } else {
518 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
519 }
520 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
521 // Note that the attr element contains the whitespace between name and attribute,
522 // this is necessary for precise reconstruction during pre-save transform.
523 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
524 if ( $inner !== null ) {
525 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
526 }
527 $accum .= $close . '</ext>';
528 } elseif ( $found == 'line-start' ) {
529 // Is this the start of a heading?
530 // Line break belongs before the heading element in any case
531 if ( $fakeLineStart ) {
532 $fakeLineStart = false;
533 } else {
534 $accum .= $curChar;
535 $i++;
536 }
537
538 $count = strspn( $text, '=', $i, 6 );
539 if ( $count == 1 && $findEquals ) {
540 // DWIM: This looks kind of like a name/value separator.
541 // Let's let the equals handler have it and break the
542 // potential heading. This is heuristic, but AFAICT the
543 // methods for completely correct disambiguation are very
544 // complex.
545 } elseif ( $count > 0 ) {
546 $piece = [
547 'open' => "\n",
548 'close' => "\n",
549 'parts' => [ new PPDPart( str_repeat( '=', $count ) ) ],
550 'startPos' => $i,
551 'count' => $count ];
552 $stack->push( $piece );
553 $accum =& $stack->getAccum();
554 $stackFlags = $stack->getFlags();
555 if ( isset( $stackFlags['findEquals'] ) ) {
556 $findEquals = $stackFlags['findEquals'];
557 }
558 if ( isset( $stackFlags['findPipe'] ) ) {
559 $findPipe = $stackFlags['findPipe'];
560 }
561 if ( isset( $stackFlags['inHeading'] ) ) {
562 $inHeading = $stackFlags['inHeading'];
563 }
564 $i += $count;
565 }
566 } elseif ( $found == 'line-end' ) {
567 $piece = $stack->top;
568 // A heading must be open, otherwise \n wouldn't have been in the search list
569 // FIXME: Don't use assert()
570 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.assert
571 assert( $piece->open === "\n" );
572 $part = $piece->getCurrentPart();
573 // Search back through the input to see if it has a proper close.
574 // Do this using the reversed string since the other solutions
575 // (end anchor, etc.) are inefficient.
576 $wsLength = strspn( $revText, " \t", $lengthText - $i );
577 $searchStart = $i - $wsLength;
578 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
579 // Comment found at line end
580 // Search for equals signs before the comment
581 $searchStart = $part->visualEnd;
582 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
583 }
584 $count = $piece->count;
585 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
586 if ( $equalsLength > 0 ) {
587 if ( $searchStart - $equalsLength == $piece->startPos ) {
588 // This is just a single string of equals signs on its own line
589 // Replicate the doHeadings behavior /={count}(.+)={count}/
590 // First find out how many equals signs there really are (don't stop at 6)
591 $count = $equalsLength;
592 if ( $count < 3 ) {
593 $count = 0;
594 } else {
595 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
596 }
597 } else {
598 $count = min( $equalsLength, $count );
599 }
600 if ( $count > 0 ) {
601 // Normal match, output <h>
602 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
603 $headingIndex++;
604 } else {
605 // Single equals sign on its own line, count=0
606 $element = $accum;
607 }
608 } else {
609 // No match, no <h>, just pass down the inner text
610 $element = $accum;
611 }
612 // Unwind the stack
613 $stack->pop();
614 $accum =& $stack->getAccum();
615 $stackFlags = $stack->getFlags();
616 if ( isset( $stackFlags['findEquals'] ) ) {
617 $findEquals = $stackFlags['findEquals'];
618 }
619 if ( isset( $stackFlags['findPipe'] ) ) {
620 $findPipe = $stackFlags['findPipe'];
621 }
622 if ( isset( $stackFlags['inHeading'] ) ) {
623 $inHeading = $stackFlags['inHeading'];
624 }
625
626 // Append the result to the enclosing accumulator
627 $accum .= $element;
628 // Note that we do NOT increment the input pointer.
629 // This is because the closing linebreak could be the opening linebreak of
630 // another heading. Infinite loops are avoided because the next iteration MUST
631 // hit the heading open case above, which unconditionally increments the
632 // input pointer.
633 } elseif ( $found == 'open' ) {
634 # count opening brace characters
635 $curLen = strlen( $curChar );
636 $count = ( $curLen > 1 ) ?
637 # allow the final character to repeat
638 strspn( $text, $curChar[$curLen - 1], $i + 1 ) + 1 :
639 strspn( $text, $curChar, $i );
640
641 $savedPrefix = '';
642 $lineStart = ( $i > 0 && $text[$i - 1] == "\n" );
643
644 if ( $curChar === "-{" && $count > $curLen ) {
645 // -{ => {{ transition because rightmost wins
646 $savedPrefix = '-';
647 $i++;
648 $curChar = '{';
649 $count--;
650 $rule = $this->rules[$curChar];
651 }
652
653 # we need to add to stack only if opening brace count is enough for one of the rules
654 if ( $count >= $rule['min'] ) {
655 # Add it to the stack
656 $piece = [
657 'open' => $curChar,
658 'close' => $rule['end'],
659 'savedPrefix' => $savedPrefix,
660 'count' => $count,
661 'lineStart' => $lineStart,
662 ];
663
664 $stack->push( $piece );
665 $accum =& $stack->getAccum();
666 $stackFlags = $stack->getFlags();
667 if ( isset( $stackFlags['findEquals'] ) ) {
668 $findEquals = $stackFlags['findEquals'];
669 }
670 if ( isset( $stackFlags['findPipe'] ) ) {
671 $findPipe = $stackFlags['findPipe'];
672 }
673 if ( isset( $stackFlags['inHeading'] ) ) {
674 $inHeading = $stackFlags['inHeading'];
675 }
676 } else {
677 # Add literal brace(s)
678 $accum .= htmlspecialchars( $savedPrefix . str_repeat( $curChar, $count ) );
679 }
680 $i += $count;
681 } elseif ( $found == 'close' ) {
682 $piece = $stack->top;
683 # lets check if there are enough characters for closing brace
684 $maxCount = $piece->count;
685 if ( $piece->close === '}-' && $curChar === '}' ) {
686 $maxCount--; # don't try to match closing '-' as a '}'
687 }
688 $curLen = strlen( $curChar );
689 $count = ( $curLen > 1 ) ? $curLen :
690 strspn( $text, $curChar, $i, $maxCount );
691
692 # check for maximum matching characters (if there are 5 closing
693 # characters, we will probably need only 3 - depending on the rules)
694 $rule = $this->rules[$piece->open];
695 if ( $count > $rule['max'] ) {
696 # The specified maximum exists in the callback array, unless the caller
697 # has made an error
698 $matchingCount = $rule['max'];
699 } else {
700 # Count is less than the maximum
701 # Skip any gaps in the callback array to find the true largest match
702 # Need to use array_key_exists not isset because the callback can be null
703 $matchingCount = $count;
704 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
705 --$matchingCount;
706 }
707 }
708
709 if ( $matchingCount <= 0 ) {
710 # No matching element found in callback array
711 # Output a literal closing brace and continue
712 $endText = substr( $text, $i, $count );
713 $accum .= htmlspecialchars( $endText );
714 $i += $count;
715 continue;
716 }
717 $name = $rule['names'][$matchingCount];
718 if ( $name === null ) {
719 // No element, just literal text
720 $endText = substr( $text, $i, $matchingCount );
721 $element = $piece->breakSyntax( $matchingCount ) . $endText;
722 } else {
723 # Create XML element
724 # Note: $parts is already XML, does not need to be encoded further
725 $parts = $piece->parts;
726 $title = $parts[0]->out;
727 unset( $parts[0] );
728
729 # The invocation is at the start of the line if lineStart is set in
730 # the stack, and all opening brackets are used up.
731 if ( $maxCount == $matchingCount &&
732 !empty( $piece->lineStart ) &&
733 strlen( $piece->savedPrefix ) == 0 ) {
734 $attr = ' lineStart="1"';
735 } else {
736 $attr = '';
737 }
738
739 $element = "<$name$attr>";
740 $element .= "<title>$title</title>";
741 $argIndex = 1;
742 foreach ( $parts as $part ) {
743 if ( isset( $part->eqpos ) ) {
744 $argName = substr( $part->out, 0, $part->eqpos );
745 $argValue = substr( $part->out, $part->eqpos + 1 );
746 $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
747 } else {
748 $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
749 $argIndex++;
750 }
751 }
752 $element .= "</$name>";
753 }
754
755 # Advance input pointer
756 $i += $matchingCount;
757
758 # Unwind the stack
759 $stack->pop();
760 $accum =& $stack->getAccum();
761
762 # Re-add the old stack element if it still has unmatched opening characters remaining
763 if ( $matchingCount < $piece->count ) {
764 $piece->parts = [ new PPDPart ];
765 $piece->count -= $matchingCount;
766 # do we still qualify for any callback with remaining count?
767 $min = $this->rules[$piece->open]['min'];
768 if ( $piece->count >= $min ) {
769 $stack->push( $piece );
770 $accum =& $stack->getAccum();
771 } elseif ( $piece->count == 1 && $piece->open === '{' && $piece->savedPrefix === '-' ) {
772 $piece->savedPrefix = '';
773 $piece->open = '-{';
774 $piece->count = 2;
775 $piece->close = $this->rules[$piece->open]['end'];
776 $stack->push( $piece );
777 $accum =& $stack->getAccum();
778 } else {
779 $s = substr( $piece->open, 0, -1 );
780 $s .= str_repeat(
781 substr( $piece->open, -1 ),
782 $piece->count - strlen( $s )
783 );
784 $accum .= $piece->savedPrefix . $s;
785 }
786 } elseif ( $piece->savedPrefix !== '' ) {
787 $accum .= $piece->savedPrefix;
788 }
789
790 $stackFlags = $stack->getFlags();
791 if ( isset( $stackFlags['findEquals'] ) ) {
792 $findEquals = $stackFlags['findEquals'];
793 }
794 if ( isset( $stackFlags['findPipe'] ) ) {
795 $findPipe = $stackFlags['findPipe'];
796 }
797 if ( isset( $stackFlags['inHeading'] ) ) {
798 $inHeading = $stackFlags['inHeading'];
799 }
800
801 # Add XML element to the enclosing accumulator
802 $accum .= $element;
803 } elseif ( $found == 'pipe' ) {
804 $findEquals = true; // shortcut for getFlags()
805 $stack->addPart();
806 $accum =& $stack->getAccum();
807 ++$i;
808 } elseif ( $found == 'equals' ) {
809 $findEquals = false; // shortcut for getFlags()
810 $stack->getCurrentPart()->eqpos = strlen( $accum );
811 $accum .= '=';
812 ++$i;
813 }
814 }
815
816 # Output any remaining unclosed brackets
817 foreach ( $stack->stack as $piece ) {
818 $stack->rootAccum .= $piece->breakSyntax();
819 }
820 $stack->rootAccum .= '</root>';
821 $xml = $stack->rootAccum;
822
823 return $xml;
824 }
825 }