Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 590
0.00% covered (danger)
0.00%
0 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
WikitextEscapeHandlers
0.00% covered (danger)
0.00%
0 / 590
0.00% covered (danger)
0.00%
0 / 21
64770
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 startsOnANewLine
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 hasBlocksOnLine
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
110
 hasLeadingEscapableQuoteChar
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 hasTrailingEscapableQuoteChar
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 escapedIBSiblingNodeText
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 isFirstContentNode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 liHandler
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
42
 thHandler
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 mediaOptionHandler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 wikilinkHandler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 aHandler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 tdHandler
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
182
 textCanParseAsLink
0.00% covered (danger)
0.00%
0 / 56
0.00% covered (danger)
0.00%
0 / 1
702
 hasWikitextTokens
0.00% covered (danger)
0.00%
0 / 64
0.00% covered (danger)
0.00%
0 / 1
1722
 nowikiWrap
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 escapedText
0.00% covered (danger)
0.00%
0 / 78
0.00% covered (danger)
0.00%
0 / 1
552
 escapeWikitext
0.00% covered (danger)
0.00%
0 / 111
0.00% covered (danger)
0.00%
0 / 1
2652
 appendStr
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
600
 escapeTplArgWT
0.00% covered (danger)
0.00%
0 / 139
0.00% covered (danger)
0.00%
0 / 1
1056
 escapeLinkContent
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Html2Wt;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Parsoid\Config\Env;
8use Wikimedia\Parsoid\Core\DOMCompat;
9use Wikimedia\Parsoid\Core\Sanitizer;
10use Wikimedia\Parsoid\Core\SourceRange;
11use Wikimedia\Parsoid\DOM\Element;
12use Wikimedia\Parsoid\DOM\Node;
13use Wikimedia\Parsoid\Tokens\CommentTk;
14use Wikimedia\Parsoid\Tokens\EmptyLineTk;
15use Wikimedia\Parsoid\Tokens\EndTagTk;
16use Wikimedia\Parsoid\Tokens\EOFTk;
17use Wikimedia\Parsoid\Tokens\NlTk;
18use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
19use Wikimedia\Parsoid\Tokens\TagTk;
20use Wikimedia\Parsoid\Tokens\Token;
21use Wikimedia\Parsoid\Tokens\XMLTagTk;
22use Wikimedia\Parsoid\Utils\DiffDOMUtils;
23use Wikimedia\Parsoid\Utils\DOMUtils;
24use Wikimedia\Parsoid\Utils\PHPUtils;
25use Wikimedia\Parsoid\Utils\TokenUtils;
26use Wikimedia\Parsoid\Utils\Utils;
27use Wikimedia\Parsoid\Utils\WTUtils;
28use Wikimedia\Parsoid\Wikitext\Consts;
29use Wikimedia\Parsoid\Wt2Html\PegTokenizer;
30
31class WikitextEscapeHandlers {
32
33    private const LINKS_ESCAPE_RE = '/(\[\[)|(\]\])|(-\{)|(^[^\[]*\]$)/D';
34
35    /** @var Env */
36    private $env;
37
38    /** @var ?string */
39    private $extName;
40
41    /**
42     * @var PegTokenizer
43     */
44    private $tokenizer;
45
46    public function __construct( Env $env, ?string $extName ) {
47        $this->env = $env;
48        $this->extName = $extName;
49        $this->tokenizer = new PegTokenizer( $env );
50    }
51
52    /**
53     * Ignore the cases where the serializer adds newlines not present in the dom
54     * @param Node $node
55     * @return bool
56     */
57    private static function startsOnANewLine( Node $node ): bool {
58        $name = DOMUtils::nodeName( $node );
59        return TokenUtils::tagOpensBlockScope( $name ) &&
60            !WTUtils::isLiteralHTMLNode( $node );
61    }
62
63    /**
64     * Look ahead on current line for block content
65     *
66     * @param Node $node
67     * @param bool $first
68     * @return bool
69     */
70    private static function hasBlocksOnLine( Node $node, bool $first ): bool {
71        // special case for firstNode:
72        // we're at sol so ignore possible \n at first char
73        if ( $first ) {
74            $textContent = $node->textContent;
75            $offset = strlen( $textContent ) ? 1 : 0;
76            if ( strpos( $textContent, "\n", $offset ) !== false ) {
77                return false;
78            }
79            $node = $node->nextSibling;
80        }
81
82        while ( $node ) {
83            if ( $node instanceof Element ) {
84                if ( DOMUtils::isWikitextBlockNode( $node ) ) {
85                    return !self::startsOnANewLine( $node );
86                }
87                if ( $node->hasChildNodes() ) {
88                    if ( self::hasBlocksOnLine( $node->firstChild, false ) ) {
89                        return true;
90                    }
91                }
92            } else {
93                if ( str_contains( $node->textContent, "\n" ) ) {
94                    return false;
95                }
96            }
97            $node = $node->nextSibling;
98        }
99        return false;
100    }
101
102    /**
103     * @param string $text
104     * @param array $opts [ 'node' => Node ]
105     * @return bool
106     */
107    private static function hasLeadingEscapableQuoteChar( string $text, array $opts ): bool {
108        /** @var Node $node */
109        $node = $opts['node'];
110        // Use 'node.textContent' to do the tests since it hasn't had newlines
111        // stripped out from it.
112        // Ex: For this DOM: <i>x</i>\n'\n<i>y</i>
113        // node.textContent = \n'\n and text = '
114        // Those newline separators can prevent unnecessary <nowiki/> protection
115        // if the string begins with one or more newlines before a leading quote.
116        $origText = $node->textContent;
117        if ( str_starts_with( $origText, "'" ) ) {
118            $prev = DiffDOMUtils::previousNonDeletedSibling( $node );
119            if ( !$prev ) {
120                $prev = $node->parentNode;
121            }
122            if ( DOMUtils::isQuoteElt( $prev ) ) {
123                return true;
124            }
125        }
126
127        return false;
128    }
129
130    /**
131     * @param string $text
132     * @param array $opts [ 'node' => Node ]
133     * @return bool
134     */
135    private static function hasTrailingEscapableQuoteChar( string $text, array $opts ): bool {
136        $node = $opts['node'];
137        // Use 'node.textContent' to do the tests since it hasn't had newlines
138        // stripped out from it.
139        // Ex: For this DOM: <i>x</i>\n'\n<i>y</i>
140        // node.textContent = \n'\n and text = '
141        // Those newline separators can prevent unnecessary <nowiki/> protection
142        // if the string ends with a trailing quote and then one or more newlines.
143        $origText = $node->textContent;
144        if ( str_ends_with( $origText, "'" ) ) {
145            $next = DiffDOMUtils::nextNonDeletedSibling( $node );
146            if ( !$next ) {
147                $next = $node->parentNode;
148            }
149            if ( DOMUtils::isQuoteElt( $next ) ) {
150                return true;
151            }
152        }
153
154        return false;
155    }
156
157    /**
158     * SSS FIXME: By doing a DOM walkahead to identify what else is on the current line,
159     * these heuristics can be improved. Ex: '<i>foo</i> blah blah does not require a
160     * <nowiki/> after the single quote since we know that there are no other quotes on
161     * the rest of the line that will be emitted. Similarly, '' does not need a <nowiki>
162     * wrapper since there are on other quote chars on the line.
163     *
164     * This is checking text-node siblings of i/b tags.
165     *
166     * @param SerializerState $state
167     * @param string $text
168     * @param array $opts [ 'node' => Node ]
169     * @return string
170     */
171    private static function escapedIBSiblingNodeText(
172        SerializerState $state, string $text, array $opts
173    ): string {
174        // For a sequence of 2+ quote chars, we have to
175        // fully wrap the sequence in <nowiki>...</nowiki>
176        // <nowiki/> at the start and end doesn't work.
177        //
178        // Ex: ''<i>foo</i> should serialize to <nowiki>''</nowiki>''foo''.
179        //
180        // Serializing it to ''<nowiki/>''foo'' breaks html2html semantics
181        // since it will parse back to <i><meta../></i>foo<i></i>
182        if ( preg_match( "/''+/", $text ) ) {
183            // Minimize the length of the string that is wrapped in <nowiki>.
184            $pieces = explode( "'", $text );
185            $first = array_shift( $pieces );
186            $last = array_pop( $pieces );
187            return $first . "<nowiki>'" . implode( "'", $pieces ) . "'</nowiki>" . $last;
188        }
189
190        // Check whether the head and/or tail of the text needs <nowiki/> protection.
191        $out = '';
192        if ( self::hasTrailingEscapableQuoteChar( $text, $opts ) ) {
193            $state->hasQuoteNowikis = true;
194            $out = $text . '<nowiki/>';
195        }
196
197        if ( self::hasLeadingEscapableQuoteChar( $text, $opts ) ) {
198            $state->hasQuoteNowikis = true;
199            $out = '<nowiki/>' . ( $out ?: $text );
200        }
201
202        return $out;
203    }
204
205    public function isFirstContentNode( Node $node ): bool {
206        // Skip deleted-node markers
207        return DiffDOMUtils::previousNonDeletedSibling( $node ) === null;
208    }
209
210    /**
211     * @param Node $liNode
212     * @param SerializerState $state
213     * @param string $text
214     * @param array $opts [ 'node' => Node ]
215     * @return bool
216     */
217    public function liHandler(
218        Node $liNode, SerializerState $state, string $text, array $opts
219    ): bool {
220        /** @var Node $node */
221        $node = $opts['node'];
222        if ( $node->parentNode !== $liNode ) {
223            return false;
224        }
225
226        // For <dt> nodes, ":" trigger nowiki outside of elements
227        // For first nodes of <li>'s, bullets in sol posn trigger escaping
228        if ( DOMUtils::nodeName( $liNode ) === 'dt' && str_contains( $text, ':' ) ) {
229            return true;
230        } elseif ( preg_match( '/^[#*:;]*$/D', $state->currLine->text ) &&
231            $this->isFirstContentNode( $node )
232        ) {
233            // Wikitext styling might require whitespace insertion after list bullets.
234            // In those scenarios, presence of bullet-wiktext in the text node is okay.
235            // Hence the check for /^[#*:;]*$/ above.
236            return (bool)strspn( $text, '#*:;', 0, 1 );
237        } else {
238            return false;
239        }
240    }
241
242    /**
243     * @param Node $thNode
244     * @param SerializerState $state
245     * @param string $text
246     * @param array $opts [ 'node' => Node ]
247     * @return bool
248     */
249    public function thHandler(
250        Node $thNode, SerializerState $state, string $text, array $opts
251    ): bool {
252        // {|
253        // !a<div>!!b</div>
254        // !c<div>||d</div>
255        // |}
256        //
257        // The <div> will get split across two <th> tags because
258        // the !! and | has higher precedence in the tokenizer.
259        //
260        // So, no matter where in the DOM subtree of the <th> node
261        // that text shows up in, we have to unconditionally escape
262        // the !! and | characters.
263        //
264        // That is, so long as it serializes to the same line as the
265        // heading was started.
266        return preg_match( '/^\s*!/', $state->currLine->text ) &&
267            preg_match( '/^[^\n]*!!|\|/', $text );
268    }
269
270    public function mediaOptionHandler( SerializerState $state, string $text ): bool {
271        return str_contains( $text, '|' ) || preg_match( self::LINKS_ESCAPE_RE, $text );
272    }
273
274    public function wikilinkHandler( SerializerState $state, string $text ): bool {
275        return (bool)preg_match( self::LINKS_ESCAPE_RE, $text );
276    }
277
278    public function aHandler( SerializerState $state, string $text ): bool {
279        return str_contains( $text, ']' );
280    }
281
282    /**
283     * @param Node $tdNode
284     * @param bool $inWideTD
285     * @param SerializerState $state
286     * @param string $text
287     * @param array $opts [ 'node' => ?Node ]
288     * @return bool
289     */
290    public function tdHandler(
291        Node $tdNode, bool $inWideTD, SerializerState $state, string $text, array $opts
292    ): bool {
293        $node = $opts['node'] ?? null;
294        /*
295         * "|" anywhere in a text node of the <td> subtree can be trouble!
296         * It is not sufficient to just look at immediate child of <td>
297         * Try parsing the following table:
298         *
299         * {|
300         * |a''b|c''
301         * |}
302         *
303         * Similarly, "-" or "+" when emitted after a "|" in sol position
304         * is trouble, but in addition to showing up as the immediate first
305         * child of tdNode, they can appear on the leftmost path from
306         * tdNode as long as the path only has nodes don't emit any wikitext.
307         * Ex: <td><p>-</p></td>, but not: <td><small>-</small></td>
308         */
309
310        // If 'text' is on the same wikitext line as the "|" corresponding
311        // to the <td>
312        // * | in a td should be escaped
313        // * +-} in SOL position (if they show up on the leftmost path with
314        // only zero-wt-emitting nodes on that path)
315        if ( !$node || $state->currLine->firstNode === $tdNode ) {
316            if ( str_contains( $text, '|' ) ) {
317                return true;
318            }
319            if ( !$inWideTD &&
320                $state->currLine->text === '|' &&
321                strspn( $text, '-+}', 0, 1 ) &&
322                $node
323            ) {
324                $n = $node;
325                while ( $n && $n !== $tdNode ) {
326                    if ( !$this->isFirstContentNode( $n ) ||
327                        !( $n === $node || WTUtils::isZeroWidthWikitextElt( $n ) ) ) {
328                        return false;
329                    }
330                    $n = $n->parentNode;
331                }
332                return true;
333            }
334        }
335        return false;
336    }
337
338    public function textCanParseAsLink( Node $node, SerializerState $state, string $text ): bool {
339        $env = $state->getEnv();
340        $env->trace(
341            'wt-escape', 'link-test-text=',
342            static function () use ( $text ) {
343                return PHPUtils::jsonEncode( $text );
344            }
345        );
346
347        // Strip away extraneous characters after a ]] or a ]
348        // They are inessential to the test of whether the ]]/]
349        // will get parsed into a wikilink and only complicate
350        // the logic (needing to ignore entities, etc.).
351        $text = preg_replace( '/\][^\]]*$/D', ']', $text, 1 );
352
353        // text only contains ']' chars.
354        // Since we stripped everything after ']' above, if a newline is
355        // present, a link would have to straddle newlines which is not valid.
356        if ( str_contains( $text, "\n" ) ) {
357            return false;
358        }
359
360        $str = $state->currLine->text . $text;
361        $tokens = $this->tokenizer->tokenizeAs(
362            $str, 'start', sol: false, // sol state is irrelevant here
363        );
364        $n = count( $tokens );
365        $lastToken = $tokens[$n - 1];
366
367        $env->trace( 'wt-escape', 'str=', $str, ';tokens=', $tokens );
368
369        // If 'text' remained outside of any non-string tokens,
370        // it does not need nowiking.
371        if ( $lastToken === $text ||
372            ( is_string( $lastToken ) &&
373                $text === substr( $lastToken, -strlen( $text ) )
374            )
375        ) {
376            return false;
377        }
378
379        // Verify that the tokenized links are valid links
380        $buf = '';
381        for ( $i = $n - 1;  $i >= 0;  $i-- ) {
382            $t = $tokens[$i];
383            if ( is_string( $t ) ) {
384                $buf = $t . $buf;
385            } elseif ( $t instanceof CommentTk ) {
386                $buf = WTSUtils::commentWT( $t->value ) . $buf;
387            } elseif ( $t instanceof XMLTagTk && $t->getName() === 'wikilink' ) {
388                $target = $t->getAttributeV( 'href' );
389                if ( is_array( $target ) ) {
390                    // FIXME: Can lead to false negatives.
391                    // In theory, template expansion *could* make this a link.
392                    return false;
393                }
394                if ( $env->isValidLinkTarget( $target ) &&
395                    !$env->getSiteConfig()->hasValidProtocol( $target )
396                ) {
397                    return true;
398                }
399
400                // Assumes 'src' will always be present which it seems to be.
401                // Tests will fail if anything changes in the tokenizer.
402                $buf = $t->dataParsoid->src . $buf;
403            } elseif ( $t instanceof XMLTagTk && $t->getName() === 'extlink' ) {
404                // Check if the extlink came from a template which in the end
405                // would not really parse as an extlink.
406
407                $href = $t->getAttributeV( 'href' );
408                if ( is_array( $href ) ) {
409                    $href = $href[0];
410                }
411
412                if ( !TokenUtils::isTemplateToken( $href ) ) {
413                    // Not a template and a real href => needs nowiking
414                    if ( is_string( $href ) && preg_match( '#https?://#', $href ) ) {
415                        return true;
416                    }
417                } else {
418                    while ( $node ) {
419                        $node = DiffDOMUtils::previousNonSepSibling( $node );
420                        if ( $node && WTUtils::isFirstEncapsulationWrapperNode( $node ) ) {
421                            // FIXME: This is not entirely correct.
422                            // Assumes that extlink content doesn't have templates.
423                            // Solution: Count # of non-nested templates encountered
424                            // and skip over intermediate templates.
425                            // var content = t.getAttribute('mw:content');
426                            // var n = intermediateNonNestedTemplates(content);
427                            break;
428                        }
429                    }
430
431                    if ( $node instanceof Element && DOMUtils::nodeName( $node ) === 'a' &&
432                        $node->textContent === DOMCompat::getAttribute( $node, 'href' )
433                    ) {
434                        // The template expands to an url link => needs nowiking
435                        return true;
436                    }
437                }
438
439                // Since this will not parse to a real extlink,
440                // update buf with the wikitext src for this token.
441                $tsr = $t->dataParsoid->tsr;
442                $buf = $tsr->substr( $str ) . $buf;
443            } else {
444                // We have no other smarts => be conservative.
445                return true;
446            }
447
448            if ( $text === substr( $buf, -strlen( $text ) ) ) {
449                // 'text' emerged unscathed
450                return false;
451            }
452        }
453
454        // We couldn't prove safety of skipping nowiki-ing.
455        return true;
456    }
457
458    private function hasWikitextTokens(
459        SerializerState $state, bool $onNewline, string $text
460    ): bool {
461        $env = $state->getEnv();
462        $env->trace(
463            'wt-escape', 'nl:', $onNewline, ':text=',
464            static function () use ( $text ) {
465                return PHPUtils::jsonEncode( $text );
466            }
467        );
468
469        // tokenize the text
470        $sol = $onNewline && !( $state->inIndentPre || $state->inPHPBlock );
471
472        // If we're inside a <pre>, we need to add an extra space after every
473        // newline so that the tokenizer correctly parses all tokens in a pre
474        // instead of just the first one. See T95794.
475        if ( $state->inIndentPre ) {
476            $text = str_replace( "\n", "\n ", $text );
477        }
478
479        $tokens = $this->tokenizer->tokenizeAs( $text, 'start', sol: $sol );
480
481        // If the token stream has a XmlTagTk or CommentTk
482        // then this text needs escaping!
483        $numEntities = 0;
484        foreach ( $tokens as $t ) {
485            $env->trace( 'wt-escape', 'T:', $t );
486
487            // Ignore html tags that aren't allowed as literals in wikitext
488            if ( TokenUtils::isHTMLTag( $t ) ) {
489                if (
490                    TokenUtils::matchTypeOf( $t, '#^mw:Extension(/|$)#' ) &&
491                    ( $this->extName !== $t->getAttributeV( 'name' ) )
492                ) {
493                    return true;
494                }
495
496                // Always escape isolated extension tags (T59469). Consider this:
497                // echo "&lt;ref&gt;foo<p>&lt;/ref&gt;</p>" | node parse --html2wt
498                // The <ref> and </ref> tag-like text is spread across the DOM, and in
499                // the worst case can be anywhere. So, we conservatively escape these
500                // elements always (which can lead to excessive nowiki-escapes in some
501                // cases, but is always safe).
502                if ( ( $t instanceof TagTk || $t instanceof EndTagTk ) &&
503                    $env->getSiteConfig()->isExtensionTag( mb_strtolower( $t->getName() ) )
504                ) {
505                    return true;
506                }
507
508                // If the tag is one that's allowed in wikitext, we need to escape
509                // it inside <nowiki>s, because a text node nodeValue always returns
510                // non-escaped entities (that is, converts "&lt;h2&gt;" to "<h2>").
511                // TODO: We should also do this for <a> tags because even if they
512                // aren't allowed in wikitext and thus don't need to be escaped, the
513                // result can be confusing for editors. However, doing it here in a
514                // simple way interacts badly with normal link escaping, so it's
515                // left for later.
516                if ( isset( Consts::$Sanitizer['AllowedLiteralTags'][mb_strtolower( $t->getName() )] ) ) {
517                    // Don't wrap with nowiki if tag will be escaped by the sanitizer
518                    if ( Sanitizer::escapeLiteralHTMLTag( $t ) ) {
519                        continue;
520                    }
521                    return true;
522                } else {
523                    continue;
524                }
525            }
526
527            if ( $t instanceof SelfclosingTagTk ) {
528                // * Ignore RFC/ISBN/PMID tokens when those are encountered in the
529                // context of another link's content -- those are not parsed to
530                // ext-links in that context. (T109371)
531                if ( ( $t->getName() === 'extlink' || $t->getName() === 'wikilink' ) &&
532                    ( $t->dataParsoid->stx ?? null ) === 'magiclink' &&
533                    ( $state->inAttribute || $state->inLink ) ) {
534                    continue;
535                }
536
537                // Ignore url links in attributes (href, mostly)
538                // since they are not in danger of being autolink-ified there.
539                if ( $t->getName() === 'urllink' && ( $state->inAttribute || $state->inLink ) ) {
540                    continue;
541                }
542
543                if ( $t->getName() === 'wikilink' ) {
544                    if ( $env->isValidLinkTarget( $t->getAttributeV( 'href' ) ?? '' ) ) {
545                        return true;
546                    } else {
547                        continue;
548                    }
549                }
550
551                return true;
552            }
553
554            if ( $state->inCaption && $t instanceof TagTk && $t->getName() === 'listItem' ) {
555                continue;
556            }
557
558            if ( $t instanceof TagTk ) {
559                // Ignore mw:Entity tokens
560                if ( $t->getName() === 'span' && TokenUtils::hasTypeOf( $t, 'mw:Entity' ) ) {
561                    $numEntities++;
562                    continue;
563                }
564
565                // Ignore table tokens outside of tables
566                if ( in_array( $t->getName(), [ 'caption', 'td', 'tr', 'th' ], true ) &&
567                    !TokenUtils::isHTMLTag( $t ) &&
568                    $state->wikiTableNesting === 0
569                ) {
570                    continue;
571                }
572
573                // Headings have both SOL and EOL requirements. This tokenization
574                // here only verifies SOL requirements, not EOL requirements.
575                // So, record this information so that we can strip unnecessary
576                // nowikis after the fact.
577                if ( preg_match( '/^h\d$/D', $t->getName() ) ) {
578                    $state->hasHeadingEscapes = true;
579                }
580
581                return true;
582            }
583
584            if ( $t instanceof EndTagTk ) {
585                // Ignore mw:Entity tokens
586                if ( $numEntities > 0 && $t->getName() === 'span' ) {
587                    $numEntities--;
588                    continue;
589                }
590                // Ignore heading tokens
591                if ( preg_match( '/^h\d$/D', $t->getName() ) ) {
592                    continue;
593                }
594
595                // Ignore table tokens outside of tables
596                if ( isset( ( [ 'caption' => 1, 'table' => 1 ] )[$t->getName()] ) &&
597                    $state->wikiTableNesting === 0
598                ) {
599                    continue;
600                }
601
602                // </br>!
603                if ( mb_strtolower( $t->getName() ) === 'br' ) {
604                    continue;
605                }
606
607                return true;
608            }
609        }
610
611        return false;
612    }
613
614    private static function nowikiWrap(
615        string $str, bool $close, bool &$inNowiki, bool &$nowikisAdded, string &$buf
616    ): void {
617        if ( !$inNowiki ) {
618            $buf .= '<nowiki>';
619            $inNowiki = true;
620            $nowikisAdded = true;
621        }
622        $buf .= $str;
623        if ( $close ) {
624            $buf .= '</nowiki>';
625            $inNowiki = false;
626        }
627    }
628
629    /**
630     * This function attempts to wrap smallest escapable units into
631     * nowikis (which can potentially add multiple nowiki pairs in a
632     * single string).  The idea here is that since this should all be
633     * text, anything that tokenizes to another construct needs to be
634     * wrapped.
635     *
636     * Full-wrapping is enabled if the string is being escaped within
637     * context-specific handlers where the tokenization context might
638     * be different from what we use in this code.
639     *
640     * @param SerializerState $state
641     * @param bool $sol
642     * @param string $origText
643     * @param bool $fullWrap
644     * @param bool $dontWrapIfUnnecessary
645     * @return string
646     */
647    public function escapedText(
648        SerializerState $state, bool $sol, string $origText,
649        bool $fullWrap = false, bool $dontWrapIfUnnecessary = false
650    ): string {
651        Assert::invariant(
652            preg_match( '/^(.*?)((?:\r?\n)*)$/sD', $origText, $match ),
653            "Escaped text matching failed: {$origText}"
654        );
655
656        $text = $match[1];
657        $nls = $match[2];
658
659        if ( $fullWrap ) {
660            return '<nowiki>' . $text . '</nowiki>' . $nls;
661        }
662
663        $buf = '';
664        $inNowiki = false;
665        $nowikisAdded = false;
666        // These token types don't come with a closing tag
667        $tokensWithoutClosingTag = PHPUtils::makeSet( [ 'listItem', 'td', 'tr' ] );
668
669        // reverse escaping nowiki tags
670        // we do this so that they tokenize as nowikis
671        // instead of entity enclosed text
672        $text = preg_replace( '#&lt;(/?nowiki\s*/?\s*)&gt;#i', '<$1>', $text );
673
674        $tokens = $this->tokenizer->tokenizeAs( $text, 'start', sol: $sol );
675
676        foreach ( $tokens as $t ) {
677            if ( is_string( $t ) ) {
678                if ( strlen( $t ) > 0 ) {
679                    $t = WTSUtils::escapeNowikiTags( $t );
680                    if ( !$inNowiki && ( ( $sol && $t[0] === ' ' ) || str_contains( $t, "\n " ) ) ) {
681                        $x = preg_split( '/(^|\n) /', $t, -1, PREG_SPLIT_DELIM_CAPTURE );
682                        $buf .= $x[0];
683                        $lastIndexX = count( $x ) - 1;
684                        for ( $k = 1;  $k < $lastIndexX;  $k += 2 ) {
685                            $buf .= $x[$k];
686                            if ( $k !== 1 || $x[$k] === "\n" || $sol ) {
687                                self::nowikiWrap( ' ', true, $inNowiki, $nowikisAdded, $buf );
688                            } else {
689                                $buf .= ' ';
690                            }
691                            $buf .= $x[$k + 1];
692                        }
693                    } else {
694                        $buf .= $t;
695                    }
696                    $sol = false;
697                }
698                continue;
699            }
700
701            $tsr = $t->dataParsoid->tsr ?? null;
702            if ( !( $tsr instanceof SourceRange ) ) {
703                $env = $state->getEnv();
704                $env->log(
705                    'error/html2wt/escapeNowiki',
706                    'Missing tsr for token ',
707                    PHPUtils::jsonEncode( $t ),
708                    'while processing text ',
709                    $text
710                );
711
712                // Bail and wrap the whole thing in a nowiki
713                // if we have missing information.
714                // Use match[1] since text has been clobbered above.
715                return '<nowiki>' . $match[1] . '</nowiki>' . $nls;
716            }
717
718            // Now put back the escaping we removed above
719            $tSrc = WTSUtils::escapeNowikiTags( $tsr->substr( $text ) );
720            switch ( true ) {
721                case $t instanceof CommentTk:
722                    // Comments are sol-transparent
723                    $buf .= $tSrc;
724                    break;
725                case $t instanceof EmptyLineTk:
726                    $sol = true;
727                    break;
728                case $t instanceof NlTk:
729                    $buf .= $tSrc;
730                    $sol = true;
731                    break;
732                case $t instanceof TagTk:
733                    // Treat tokens with missing tags as self-closing tokens
734                    // for the purpose of minimal nowiki escaping
735                    self::nowikiWrap(
736                        $tSrc,
737                        isset( $tokensWithoutClosingTag[$t->getName()] ),
738                        $inNowiki,
739                        $nowikisAdded,
740                        $buf
741                    );
742                    $sol = false;
743                    break;
744                case $t instanceof EndTagTk:
745                    self::nowikiWrap( $tSrc, true, $inNowiki, $nowikisAdded, $buf );
746                    $sol = false;
747                    break;
748                case $t instanceof SelfclosingTagTk:
749                    // Don't bother with marker metas
750                    self::nowikiWrap( $tSrc, true, $inNowiki, $nowikisAdded, $buf );
751                    $sol = false;
752                    break;
753            }
754        }
755
756        // close any unclosed nowikis
757        if ( $inNowiki ) {
758            $buf .= '</nowiki>';
759        }
760
761        // Make sure nowiki is always added
762        // Ex: "foo]]" won't tokenize into tags at all
763        if ( !$nowikisAdded && !$dontWrapIfUnnecessary ) {
764            $buf = '';
765            self::nowikiWrap( $text, true, $inNowiki, $nowikisAdded, $buf );
766        }
767
768        $buf .= $nls;
769        return $buf;
770    }
771
772    /**
773     * @param SerializerState $state
774     * @param string $text
775     * @param array $opts [ 'node' => Node, 'inMultilineMode' => ?bool, 'isLastChild' => ?bool ]
776     * @return string
777     */
778    public function escapeWikitext( SerializerState $state, string $text, array $opts ): string {
779        $env = $state->getEnv();
780        $env->trace(
781            'wt-escape', 'EWT:',
782            static function () use ( $text ) {
783                return PHPUtils::jsonEncode( $text );
784            }
785        );
786
787        /* -----------------------------------------------------------------
788         * General strategy: If a substring requires escaping, we can escape
789         * the entire string without further analysis of the rest of the string.
790         * ----------------------------------------------------------------- */
791
792        $hasMagicWord = preg_match( '/(^|\W)(RFC|ISBN|PMID)\s/', $text );
793        $hasAutolink = $env->getSiteConfig()->findValidProtocol( $text );
794        $fullCheckNeeded = !$state->inLink && ( $hasMagicWord || $hasAutolink );
795        $hasQuoteChar = false;
796        $indentPreUnsafe = false;
797        $hasNonQuoteEscapableChars = false;
798        $indentPreSafeMode = $state->inIndentPre || $state->inPHPBlock;
799        $sol = $state->onSOL && !$indentPreSafeMode;
800
801        // Fast path for special protected characters.
802        if ( $state->protect && preg_match( $state->protect, $text ) ) {
803            return $this->escapedText( $state, $sol, $text );
804        }
805
806        if ( !$fullCheckNeeded ) {
807            $hasQuoteChar = str_contains( $text, "'" );
808            $indentPreUnsafe = !$indentPreSafeMode && (
809                preg_match( '/\n +[^\r\n]*?\S+/', $text ) ||
810                ( $sol && preg_match( '/^ +[^\r\n]*?\S+/', $text ) )
811            );
812            $hasNonQuoteEscapableChars = preg_match( '/[<>\[\]\-\+\|!=#\*:;~{}]|__[^_]*__/', $text );
813            $hasLanguageConverter = preg_match( '/-\{|\}-/', $text );
814            if ( $hasLanguageConverter ) {
815                $fullCheckNeeded = true;
816            }
817        }
818
819        // Quick check for the common case (useful to kill a majority of requests)
820        //
821        // Pure white-space or text without wt-special chars need not be analyzed
822        if ( !$fullCheckNeeded && !$hasQuoteChar && !$indentPreUnsafe && !$hasNonQuoteEscapableChars ) {
823            $env->trace( 'wt-escape', '---No-checks needed---' );
824            return $text;
825        }
826
827        // Context-specific escape handler
828        $wteHandler = PHPUtils::lastItem( $state->wteHandlerStack );
829        if ( $wteHandler && $wteHandler( $state, $text, $opts ) ) {
830            $env->trace( 'wt-escape', '---Context-specific escape handler---' );
831            return $this->escapedText( $state, false, $text, true );
832        }
833
834        // Quote-escape test
835        if ( str_contains( $text, "''" ) ||
836            self::hasLeadingEscapableQuoteChar( $text, $opts ) ||
837            self::hasTrailingEscapableQuoteChar( $text, $opts )
838        ) {
839            // Check if we need full-wrapping <nowiki>..</nowiki>
840            // or selective <nowiki/> escaping for quotes.
841            if ( $fullCheckNeeded ||
842                $indentPreUnsafe ||
843                ( $hasNonQuoteEscapableChars &&
844                    $this->hasWikitextTokens( $state, $sol, $text )
845                )
846            ) {
847                $env->trace( 'wt-escape', '---quotes: escaping text---' );
848                // If the reason for full wrap is that the text contains non-quote
849                // escapable chars, it's still possible to minimize the contents
850                // of the <nowiki> (T71950).
851                return $this->escapedText( $state, $sol, $text );
852            } else {
853                $quoteEscapedText = self::escapedIBSiblingNodeText( $state, $text, $opts );
854                if ( $quoteEscapedText ) {
855                    $env->trace( 'wt-escape', '---sibling of i/b tag---' );
856                    return $quoteEscapedText;
857                }
858            }
859        }
860
861        // Template and template-arg markers are escaped unconditionally!
862        // Conditional escaping requires matching brace pairs and knowledge
863        // of whether we are in template arg context or not.
864        if ( preg_match( '/\{\{\{|\{\{|\}\}\}|\}\}/', $text ) ) {
865            $env->trace( 'wt-escape', '---Unconditional: transclusion chars---' );
866            return $this->escapedText( $state, false, $text );
867        }
868
869        // Once we eliminate the possibility of multi-line tokens, split the text
870        // around newlines and escape each line separately.
871        if ( preg_match( '/\n./', $text ) ) {
872            $env->trace( 'wt-escape', '-- <multi-line-escaping-mode> --' );
873            // We've already processed the full string in a context-specific handler.
874            // No more additional processing required. So, push/pop a null handler.
875            $state->wteHandlerStack[] = null;
876
877            $tmp = [];
878            foreach ( explode( "\n", $text ) as $i => $line ) {
879                if ( $i > 0 ) {
880                    // Update state
881                    $state->onSOL = true;
882                    $state->currLine->text = '';
883                    $opts['inMultilineMode'] = true;
884                }
885                $tmp[] = $this->escapeWikitext( $state, $line, $opts );
886            }
887            $ret = implode( "\n", $tmp );
888
889            array_pop( $state->wteHandlerStack );
890
891            // If nothing changed, check if the original multiline string has
892            // any wikitext tokens (ex: multi-line html tags <div\n>foo</div\n>).
893            if ( $ret === $text && $this->hasWikitextTokens( $state, $sol, $text ) ) {
894                $env->trace( 'wt-escape', '---Found multi-line wt tokens---' );
895                $ret = $this->escapedText( $state, $sol, $text );
896            }
897
898            $env->trace( 'wt-escape', '-- </multi-line-escaping-mode> --' );
899            return $ret;
900        }
901
902        $env->trace(
903            'wt-escape', 'SOL:', $sol,
904            static function () use ( $text ) {
905                return PHPUtils::jsonEncode( $text );
906            }
907        );
908
909        $hasTildes = preg_match( '/~{3,5}/', $text );
910        if ( !$fullCheckNeeded && !$hasTildes ) {
911            // {{, {{{, }}}, }} are handled above.
912            // Test 1: '', [], <>, __FOO__ need escaping wherever they occur
913            // = needs escaping in end-of-line context
914            // Test 2: {|, |}, ||, |-, |+,  , *#:;, ----, =*= need escaping only in SOL context.
915            if ( !$sol && !preg_match( "/''|[<>]|\\[.*\\]|\\]|(=[ ]*(\\n|$))|__[^_]*__/", $text ) ) {
916                // It is not necessary to test for an unmatched opening bracket ([)
917                // as long as we always escape an unmatched closing bracket (]).
918                $env->trace( 'wt-escape', '---Not-SOL and safe---' );
919                return $text;
920            }
921
922            // Quick checks when on a newline
923            // + can only occur as "|+" and - can only occur as "|-" or ----
924            if ( $sol && !preg_match( '/(^|\n)[ #*:;=]|[<\[\]>\|\'!]|\-\-\-\-|__[^_]*__/', $text ) ) {
925                $env->trace( 'wt-escape', '---SOL and safe---' );
926                return $text;
927            }
928        }
929
930        // The front-end parser eliminated pre-tokens in the tokenizer
931        // and moved them to a stream handler. So, we always conservatively
932        // escape text with ' ' in sol posn with one caveat:
933        // * and when the current line has block tokens
934        if ( $indentPreUnsafe &&
935            ( !self::hasBlocksOnLine( $state->currLine->firstNode, true ) ||
936                !empty( $opts['inMultilineMode'] )
937            )
938        ) {
939            $env->trace( 'wt-escape', '---SOL and pre---' );
940            $state->hasIndentPreNowikis = true;
941            return $this->escapedText( $state, $sol, $text );
942        }
943
944        // escape nowiki tags
945        $text = WTSUtils::escapeNowikiTags( $text );
946
947        // Use the tokenizer to see if we have any wikitext tokens
948        //
949        // Ignores entities
950        if ( $hasTildes ) {
951            $env->trace( 'wt-escape', '---Found tildes---' );
952            return $this->escapedText( $state, $sol, $text );
953        } elseif ( $this->hasWikitextTokens( $state, $sol, $text ) ) {
954            $env->trace( 'wt-escape', '---Found WT tokens---' );
955            return $this->escapedText( $state, $sol, $text );
956        } elseif ( preg_match( '/[^\[]*\]/', $text ) &&
957            $this->textCanParseAsLink( $opts['node'], $state, $text )
958        ) {
959            // we have an closing bracket, and
960            // - the text will get parsed as a link in
961            $env->trace( 'wt-escape', '---Links: complex single-line test---' );
962            return $this->escapedText( $state, $sol, $text );
963        } elseif ( !empty( $opts['isLastChild'] ) && str_ends_with( $text, '=' ) ) {
964            // 1. we have an open heading char, and
965            // - text ends in a '='
966            // - text comes from the last child
967            preg_match( '/^h(\d)/', DOMUtils::nodeName( $state->currLine->firstNode ), $headingMatch );
968            if ( $headingMatch ) {
969                $n = intval( $headingMatch[1] );
970                if ( ( $state->currLine->text . $text )[$n] === '=' ) {
971                    // The first character after the heading wikitext is/will be a '='.
972                    // So, the trailing '=' can change semantics if it is not nowikied.
973                    $env->trace( 'wt-escape', '---Heading: complex single-line test---' );
974                    return $this->escapedText( $state, $sol, $text );
975                } else {
976                    return $text;
977                }
978            } elseif ( strlen( $state->currLine->text ) > 0 && $state->currLine->text[0] === '=' ) {
979                $env->trace( 'wt-escape', '---Text-as-heading: complex single-line test---' );
980                return $this->escapedText( $state, $sol, $text );
981            } else {
982                return $text;
983            }
984        } else {
985            $env->trace( 'wt-escape', '---All good!---' );
986            return $text;
987        }
988    }
989
990    /**
991     * @param string $str
992     * @param bool $isLast
993     * @param bool $checkNowiki
994     * @param string &$buf
995     * @param bool &$openNowiki
996     * @param bool $isTemplate
997     * @param bool &$serializeAsNamed
998     * @param array $opts [ 'numPositionalArgs' => int, 'argPositionalIndex' => int, 'type' => string,
999     * 'numArgs' => int, 'argIndex' => int ]
1000     * @param bool $isHTMLTag
1001     */
1002    private static function appendStr(
1003        string $str, bool $isLast, bool $checkNowiki, string &$buf, bool &$openNowiki,
1004        bool $isTemplate, bool &$serializeAsNamed, array $opts, bool $isHTMLTag
1005    ): void {
1006        if ( $openNowiki && ( !$checkNowiki || $isHTMLTag ) ) {
1007            $buf .= '</nowiki>';
1008            $openNowiki = false;
1009        }
1010
1011        if ( !$checkNowiki ) {
1012            $buf .= $str;
1013            return;
1014        }
1015
1016        // Count how many reasons for nowiki
1017        $needNowikiCount = 0;
1018        $neededSubstitution = null;
1019
1020        // Protect against unmatched pairs of braces and brackets, as they
1021        // should never appear in template arguments.
1022        // FIXME: What about tplargs?
1023        $bracketPairStrippedStr = preg_replace(
1024            '/\[\[([^\[\]]*)\]\]|\{\{([^\{\}]*)\}\}|-\{([^\{\}]*)\}-/',
1025            '',
1026            $str
1027        );
1028
1029        // '=' is not allowed in positional parameters.  We can either
1030        // nowiki escape it or convert the named parameter into a
1031        // positional param to avoid the escaping.
1032        if (
1033            $isTemplate && !$serializeAsNamed &&
1034            str_contains( $bracketPairStrippedStr, '=' )
1035        ) {
1036            // In certain situations, it is better to add a nowiki escape
1037            // rather than convert this to a named param.
1038            //
1039            // Ex: Consider: {{funky-tpl|a|b|c|d|e|f|g|h}}
1040            //
1041            // If an editor changes 'a' to 'f=oo' and we convert it to
1042            // a named param 1=f=oo, we are effectively converting all
1043            // the later params into named params as well and we get
1044            // {{funky-tpl|1=f=oo|2=b|3=c|...|8=h}} instead of
1045            // {{funky-tpl|<nowiki>f=oo</nowiki>|b|c|...|h}}
1046            //
1047            // The latter is better in this case. This is a real problem
1048            // in production.
1049            //
1050            // For now, we use a simple heuristic below and can be
1051            // refined later, if necessary
1052            //
1053            // 1. Either there were no original positional args
1054            // 2. Or, only the last positional arg uses '='
1055            // 3. Or, = is potentially part of an html tag attribute
1056            if (
1057                $opts['numPositionalArgs'] === 0 ||
1058                $opts['numPositionalArgs'] === $opts['argPositionalIndex'] ||
1059                $isHTMLTag
1060            ) {
1061                $serializeAsNamed = true;
1062            } else {
1063                $needNowikiCount++;
1064            }
1065        }
1066
1067        // Template arg parsing has higher precendence than xml
1068        // tag attributes, so the '=' would need protection.
1069        // However, extensions are an exception.
1070        //
1071        // Note that if we nowiki escape the tag src as a string,
1072        // we're breaking the semantics so we force serializing
1073        // as a named argument.
1074        //
1075        // Also, xml tags can hide content (like extension tags)
1076        // in attributes that the naive checks here in appendStr
1077        // won't realize don't need escaping so return early.
1078        if ( $isHTMLTag ) {
1079            $buf .= $str;
1080            return;
1081        }
1082
1083        if ( preg_match( '/\{\{|\}\}|\[\[|\]\]|-\{/', $bracketPairStrippedStr ) ) {
1084            $needNowikiCount++;
1085        }
1086        // FIXME: Ideally, $bracketPairStrippedStr should be used but the last char
1087        // might not be the last char
1088        if ( $opts['argIndex'] === $opts['numArgs'] && $isLast && str_ends_with( $str, '}' ) ) {
1089            // If this is the last part of the last argument, we need to protect
1090            // against an ending }, as it would get confused with the template ending }}.
1091            $needNowikiCount++;
1092            $neededSubstitution = [ '/(\})$/D', '<nowiki>}</nowiki>' ];
1093        }
1094        if ( str_contains( $bracketPairStrippedStr, '|' ) ) {
1095            // If there's an unprotected |, guard it so it doesn't get confused
1096            // with the beginning of a different parameter.
1097            $needNowikiCount++;
1098            $neededSubstitution = [ '/\|/', '{{!}}' ];
1099        }
1100
1101        // Now, if arent' already in a <nowiki> and there's only one reason to
1102        // protect, avoid guarding too much text by just substituting.
1103        if ( !$openNowiki && $needNowikiCount === 1 && $neededSubstitution ) {
1104            $str = preg_replace( $neededSubstitution[0], $neededSubstitution[1], $str );
1105            $needNowikiCount = false;
1106        }
1107        if ( !$openNowiki && $needNowikiCount ) {
1108            $buf .= '<nowiki>';
1109            $openNowiki = true;
1110        }
1111        if ( !$needNowikiCount && $openNowiki ) {
1112            $buf .= '</nowiki>';
1113            $openNowiki = false;
1114        }
1115        $buf .= $str;
1116    }
1117
1118    /**
1119     * General strategy:
1120     *
1121     * Tokenize the arg wikitext.  Anything that parses as tags
1122     * are good and we need not bother with those. Check for harmful
1123     * characters `[[]]{{}}` or additionally `=` in positional parameters and escape
1124     * those fragments since these characters could change semantics of the entire
1125     * template transclusion.
1126     *
1127     * This function makes a couple of assumptions:
1128     *
1129     * 1. The tokenizer sets tsr on all non-string tokens.
1130     * 2. The tsr on TagTk and EndTagTk corresponds to the
1131     *    width of the opening and closing wikitext tags and not
1132     *    the entire DOM range they span in the end.
1133     *
1134     * @param string $arg
1135     * @phpcs:ignore Generic.Files.LineLength.TooLong
1136     * @param array{serializeAsNamed:bool,numPositionalArgs:int,argPositionalIndex:int,type:string,numArgs:int,argIndex:int} $opts
1137     * @return array{serializeAsNamed: bool, v: string}
1138     */
1139    public function escapeTplArgWT( string $arg, array $opts ): array {
1140        $env = $this->env;
1141        $serializeAsNamed = $opts['serializeAsNamed'];
1142        $buf = '';
1143        $openNowiki = false;
1144        $isTemplate = $opts['type'] === 'template';
1145
1146        $tokens = $this->tokenizer->tokenizeAs( $arg, 'start', sol: false );
1147
1148        for ( $i = 0, $n = count( $tokens ); $i < $n; $i++ ) {
1149            $t = $tokens[$i];
1150            $last = $i === $n - 1;
1151
1152            // For mw:Entity spans, the opening and closing tags have 0 width
1153            // and the enclosed content is the decoded entity. Hence the
1154            // special case to serialize back the entity's source.
1155            if ( $t instanceof TagTk ) {
1156                $da = $t->dataParsoid;
1157                if ( TokenUtils::matchTypeOf( $t, '#^mw:(Placeholder|Entity)(/|$)#' ) ) {
1158                    $i += 2;
1159                    $width = $tokens[$i]->dataParsoid->tsr->end - $da->tsr->start;
1160                    self::appendStr(
1161                        substr( $arg, $da->tsr->start, $width ),
1162                        $last,
1163                        false,
1164                        $buf,
1165                        $openNowiki,
1166                        $isTemplate,
1167                        $serializeAsNamed,
1168                        $opts,
1169                        false
1170                    );
1171                    continue;
1172                } elseif ( TokenUtils::hasTypeOf( $t, 'mw:Nowiki' ) ) {
1173                    $i++;
1174                    while ( $i < $n &&
1175                        ( !$tokens[$i] instanceof EndTagTk ||
1176                            !TokenUtils::hasTypeOf( $tokens[$i], 'mw:Nowiki' )
1177                        )
1178                    ) {
1179                        $i++;
1180                    }
1181                    if ( $i < $n ) {
1182                        // After tokenization, we can get here:
1183                        // * Text explicitly protected by <nowiki> in the parameter.
1184                        // * Other things that should be protected but weren't
1185                        // according to the tokenizer.
1186                        // In template argument, we only need to check for unmatched
1187                        // braces and brackets pairs (which is done in appendStr),
1188                        // but only if they weren't explicitly protected in the
1189                        // passed wikitext.
1190                        $width = $tokens[$i]->dataParsoid->tsr->end - $da->tsr->start;
1191                        $substr = substr( $arg, $da->tsr->start, $width );
1192                        self::appendStr(
1193                            $substr,
1194                            $last,
1195                            !preg_match( '#<nowiki>[^<]*</nowiki>#', $substr ),
1196                            $buf,
1197                            $openNowiki,
1198                            $isTemplate,
1199                            $serializeAsNamed,
1200                            $opts,
1201                            false
1202                        );
1203                    }
1204                    continue;
1205                }
1206            }
1207
1208            if ( is_string( $t ) ) {
1209                self::appendStr(
1210                    $t,
1211                    $last,
1212                    true,
1213                    $buf,
1214                    $openNowiki,
1215                    $isTemplate,
1216                    $serializeAsNamed,
1217                    $opts,
1218                    false
1219                );
1220                continue;
1221            }
1222
1223            switch ( true ) {
1224                case $t instanceof TagTk:
1225                case $t instanceof EmptyLineTk:
1226                case $t instanceof EndTagTk:
1227                case $t instanceof NlTk:
1228                case $t instanceof CommentTk:
1229                    $da = $t->dataParsoid;
1230                    if ( empty( $da->tsr ) ) {
1231                        $errors = [ 'Missing tsr for: ' . PHPUtils::jsonEncode( $t ) ];
1232                        $errors[] = 'Arg : ' . PHPUtils::jsonEncode( $arg );
1233                        $errors[] = 'Toks: ' . PHPUtils::jsonEncode( $tokens );
1234                        $env->log( 'error/html2wt/wtescape', implode( "\n", $errors ) );
1235                        // FIXME $da->tsr will be undefined below.
1236                        // Should we throw an explicit exception here?
1237                    }
1238                    $isHTMLTag = $t instanceof XMLTagTk &&
1239                        WTUtils::hasLiteralHTMLMarker( $da ) &&
1240                        $t->getName() !== 'extension';
1241                    self::appendStr(
1242                        $da->tsr->substr( $arg ),
1243                        $last,
1244                        $isHTMLTag,
1245                        $buf,
1246                        $openNowiki,
1247                        $isTemplate,
1248                        $serializeAsNamed,
1249                        $opts,
1250                        $isHTMLTag
1251                    );
1252                    break;
1253                case $t instanceof SelfclosingTagTk:
1254                    $da = $t->dataParsoid;
1255                    if ( empty( $da->tsr ) ) {
1256                        $errors = [ 'Missing tsr for: ' . PHPUtils::jsonEncode( $t ) ];
1257                        $errors[] = 'Arg : ' . PHPUtils::jsonEncode( $arg );
1258                        $errors[] = 'Toks: ' . PHPUtils::jsonEncode( $tokens );
1259                        $env->log( 'error/html2wt/wtescape', implode( "\n", $errors ) );
1260                        // FIXME $da->tsr will be undefined below.
1261                        // Should we throw an explicit exception here?
1262                    }
1263                    $tkSrc = $da->tsr->substr( $arg );
1264                    // Replace pipe by an entity. This is not completely safe.
1265                    if ( $t->getName() === 'extlink' || $t->getName() === 'urllink' ) {
1266                        $tkBits = $this->tokenizer->tokenizeAs(
1267                            $tkSrc,
1268                            'tplarg_or_template_or_bust',
1269                            sol: true,
1270                        );
1271                        foreach ( $tkBits as $bit ) {
1272                            if ( $bit instanceof Token ) {
1273                                self::appendStr(
1274                                    $bit->dataParsoid->src,
1275                                    $last,
1276                                    false,
1277                                    $buf,
1278                                    $openNowiki,
1279                                    $isTemplate,
1280                                    $serializeAsNamed,
1281                                    $opts,
1282                                    false
1283                                );
1284                            } else {
1285                                // Convert to a named param w/ the same reasoning
1286                                // as above for escapeStr, however, here we replace
1287                                // with an entity to avoid breaking up querystrings
1288                                // with nowikis.
1289                                if ( $isTemplate && !$serializeAsNamed && str_contains( $bit, '=' ) ) {
1290                                    if ( $opts['numPositionalArgs'] === 0
1291                                        || $opts['numPositionalArgs'] === $opts['argIndex']
1292                                    ) {
1293                                        $serializeAsNamed = true;
1294                                    } else {
1295                                        $bit = str_replace( '=', '&#61;', $bit );
1296                                    }
1297                                }
1298                                $buf .= str_replace( '|', '&#124;', $bit );
1299                            }
1300                        }
1301                    } else {
1302                        $isHTMLTag = WTUtils::hasLiteralHTMLMarker( $da ) &&
1303                            $t->getName() !== 'extension';
1304                        self::appendStr(
1305                            $tkSrc,
1306                            $last,
1307                            $isHTMLTag,
1308                            $buf,
1309                            $openNowiki,
1310                            $isTemplate,
1311                            $serializeAsNamed,
1312                            $opts,
1313                            $isHTMLTag
1314                        );
1315                    }
1316                    break;
1317                case $t instanceof EOFTk:
1318                    break;
1319            }
1320        }
1321
1322        // If nowiki still open, close it now.
1323        if ( $openNowiki ) {
1324            $buf .= '</nowiki>';
1325        }
1326
1327        return [ 'serializeAsNamed' => $serializeAsNamed, 'v' => $buf ];
1328    }
1329
1330    /**
1331     * See also `escapeLinkTarget` in LinkHandler.php
1332     *
1333     * @param SerializerState $state
1334     * @param string $str
1335     * @param bool $solState
1336     * @param Node $node
1337     * @param bool $isMedia
1338     * @return string
1339     */
1340    public function escapeLinkContent(
1341        SerializerState $state, string $str, bool $solState, Node $node, bool $isMedia
1342    ): string {
1343        // Entity-escape the content.
1344        $str = Utils::escapeWtEntities( $str );
1345
1346        // Wikitext-escape content.
1347        $state->onSOL = $solState;
1348        $state->wteHandlerStack[] = $isMedia
1349            ? [ $this, 'mediaOptionHandler' ]
1350            : [ $this, 'wikilinkHandler' ];
1351        $state->inLink = true;
1352        $res = $this->escapeWikitext( $state, $str, [ 'node' => $node ] );
1353        $state->inLink = false;
1354        array_pop( $state->wteHandlerStack );
1355
1356        return $res;
1357    }
1358}