Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 675
0.00% covered (danger)
0.00%
0 / 32
CRAP
0.00% covered (danger)
0.00%
0 / 1
WikitextSerializer
0.00% covered (danger)
0.00%
0 / 675
0.00% covered (danger)
0.00%
0 / 32
74256
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 linkHandler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 languageVariantHandler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 escapeWikitext
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 domToWikitext
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 htmlToWikitext
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getAttributeKey
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 getAttributeValue
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 getAttributeValueAsShadowInfo
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 serializedImageAttrVal
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 serializedAttrVal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 tagNeedsEscaping
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 wrapAngleBracket
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 serializeHTMLTag
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
72
 serializeHTMLEndTag
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 serializeAttributes
0.00% covered (danger)
0.00%
0 / 56
0.00% covered (danger)
0.00%
0 / 1
992
 formatStringSubst
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 createParamComparator
0.00% covered (danger)
0.00%
0 / 56
0.00% covered (danger)
0.00%
0 / 1
342
 serializePart
0.00% covered (danger)
0.00%
0 / 121
0.00% covered (danger)
0.00%
0 / 1
1892
 serializeFromParts
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
132
 serializeExtensionStartTag
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 defaultExtensionHandler
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
20
 serializeText
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 serializeTextNode
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 emitWikitext
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 serializeNodeInternal
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
870
 serializeNode
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
306
 stripUnnecessaryHeadingNowikis
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 stripUnnecessaryIndentPreNowikis
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
72
 stripUnnecessaryQuoteNowikis
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
1482
 serializeDOM
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
156
 trace
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Html2Wt;
5
6use Closure;
7use Exception;
8use Wikimedia\Assert\Assert;
9use Wikimedia\Parsoid\Config\Env;
10use Wikimedia\Parsoid\Core\InternalException;
11use Wikimedia\Parsoid\DOM\Comment;
12use Wikimedia\Parsoid\DOM\Document;
13use Wikimedia\Parsoid\DOM\DocumentFragment;
14use Wikimedia\Parsoid\DOM\Element;
15use Wikimedia\Parsoid\DOM\Node;
16use Wikimedia\Parsoid\DOM\Text;
17use Wikimedia\Parsoid\Html2Wt\ConstrainedText\ConstrainedText;
18use Wikimedia\Parsoid\Html2Wt\DOMHandlers\DOMHandler;
19use Wikimedia\Parsoid\Html2Wt\DOMHandlers\DOMHandlerFactory;
20use Wikimedia\Parsoid\NodeData\ParamInfo;
21use Wikimedia\Parsoid\NodeData\TemplateInfo;
22use Wikimedia\Parsoid\Tokens\KV;
23use Wikimedia\Parsoid\Tokens\TagTk;
24use Wikimedia\Parsoid\Tokens\Token;
25use Wikimedia\Parsoid\Utils\ContentUtils;
26use Wikimedia\Parsoid\Utils\DiffDOMUtils;
27use Wikimedia\Parsoid\Utils\DOMCompat;
28use Wikimedia\Parsoid\Utils\DOMDataUtils;
29use Wikimedia\Parsoid\Utils\DOMUtils;
30use Wikimedia\Parsoid\Utils\PHPUtils;
31use Wikimedia\Parsoid\Utils\Title;
32use Wikimedia\Parsoid\Utils\TokenUtils;
33use Wikimedia\Parsoid\Utils\Utils;
34use Wikimedia\Parsoid\Utils\WTUtils;
35use Wikimedia\Parsoid\Wikitext\Consts;
36
37/**
38 * Wikitext to HTML serializer.
39 * Serializes a chunk of tokens or an HTML DOM to MediaWiki's wikitext flavor.
40 *
41 * This serializer is designed to eventually
42 * - accept arbitrary HTML and
43 * - serialize that to wikitext in a way that round-trips back to the same
44 *   HTML DOM as far as possible within the limitations of wikitext.
45 *
46 * Not much effort has been invested so far on supporting
47 * non-Parsoid/VE-generated HTML. Some of this involves adaptively switching
48 * between wikitext and HTML representations based on the values of attributes
49 * and DOM context. A few special cases are already handled adaptively
50 * (multi-paragraph list item contents are serialized as HTML tags for
51 * example, generic A elements are serialized to HTML A tags), but in general
52 * support for this is mostly missing.
53 *
54 * Example issue:
55 * ```
56 * <h1><p>foo</p></h1> will serialize to =\nfoo\n= whereas the
57 *        correct serialized output would be: =<p>foo</p>=
58 * ```
59 *
60 * What to do about this?
61 * - add a generic 'can this HTML node be serialized to wikitext in this
62 *   context' detection method and use that to adaptively switch between
63 *   wikitext and HTML serialization.
64 *
65 */
66class WikitextSerializer {
67
68    /** @var string[] */
69    private const IGNORED_ATTRIBUTES = [
70        'data-parsoid' => true,
71        'data-ve-changed' => true,
72        'data-parsoid-changed' => true,
73        'data-parsoid-diff' => true,
74        'data-parsoid-serialize' => true,
75        DOMDataUtils::DATA_OBJECT_ATTR_NAME => true,
76    ];
77
78    /** @var string[] attribute name => value regexp */
79    private const PARSOID_ATTRIBUTES = [
80        'about' => '/^#mwt\d+$/D',
81        'typeof' => '/(^|\s)mw:\S+/',
82    ];
83
84    /** @var string Regexp */
85    private const TRAILING_COMMENT_OR_WS_AFTER_NL_REGEXP
86        = '/\n(\s|' . Utils::COMMENT_REGEXP_FRAGMENT . ')*$/D';
87
88    /** @var string Regexp */
89    private const FORMATSTRING_REGEXP =
90        '/^(\n)?(\{\{ *_+)(\n? *\|\n? *_+ *= *)(_+)(\n? *\}\})(\n)?$/D';
91
92    /** @var string Regexp for testing whether nowiki added around heading-like wikitext is needed */
93    private const COMMENT_OR_WS_REGEXP = '/^(\s|' . Utils::COMMENT_REGEXP_FRAGMENT . ')*$/D';
94
95    /** @var string Regexp for testing whether nowiki added around heading-like wikitext is needed */
96    private const HEADING_NOWIKI_REGEXP = '/^(?:' . Utils::COMMENT_REGEXP_FRAGMENT . ')*'
97        . '<nowiki>(=+[^=]+=+)<\/nowiki>(.+)$/D';
98
99    /** @var array string[] */
100    private static $separatorREs = [
101        'pureSepRE' => '/^[ \t\r\n]*$/D',
102        'sepPrefixWithNlsRE' => '/^[ \t]*\n+[ \t\r\n]*/',
103        'sepSuffixWithNlsRE' => '/\n[ \t\r\n]*$/D',
104    ];
105
106    /** @var WikitextEscapeHandlers */
107    public $wteHandlers;
108
109    /** @var Env */
110    public $env;
111
112    /** @var SerializerState */
113    private $state;
114
115    /** @var string Log type for trace() */
116    private $logType;
117
118    /**
119     * @param Env $env
120     * @param array $options List of options for serialization:
121     *   - logType: (string)
122     *   - extName: (string)
123     */
124    public function __construct( Env $env, $options ) {
125        $this->env = $env;
126        $this->logType = $options['logType'] ?? 'trace/wts';
127        $this->state = new SerializerState( $this, $options );
128        $this->wteHandlers = new WikitextEscapeHandlers( $env, $options['extName'] ?? null );
129    }
130
131    /**
132     * Main link handler.
133     * @param Element $node
134     * Used in multiple tag handlers (<a> and <link>), and hence added as top-level method
135     */
136    public function linkHandler( Element $node ): void {
137        LinkHandlerUtils::linkHandler( $this->state, $node );
138    }
139
140    /**
141     * @param Element $node
142     */
143    public function languageVariantHandler( Node $node ): void {
144        LanguageVariantHandler::handleLanguageVariant( $this->state, $node );
145    }
146
147    /**
148     * Escape wikitext-like strings in '$text' so that $text renders as a plain string
149     * when rendered as HTML. The escaping is done based on the context in which $text
150     * is present (ex: start-of-line, in a link, etc.)
151     *
152     * @param SerializerState $state
153     * @param string $text
154     * @param array $opts
155     *   - node: (Node)
156     *   - isLastChild: (bool)
157     * @return string
158     */
159    public function escapeWikitext( SerializerState $state, string $text, array $opts ): string {
160        return $this->wteHandlers->escapeWikitext( $state, $text, $opts );
161    }
162
163    public function domToWikitext(
164        array $opts, DocumentFragment $node
165    ): string {
166        $opts['logType'] = $this->logType;
167        $serializer = new WikitextSerializer( $this->env, $opts );
168        return $serializer->serializeDOM( $node );
169    }
170
171    public function htmlToWikitext( array $opts, string $html ): string {
172        $domFragment = ContentUtils::createAndLoadDocumentFragment(
173            $this->env->getTopLevelDoc(), $html, [ 'markNew' => true ]
174        );
175        return $this->domToWikitext( $opts, $domFragment );
176    }
177
178    public function getAttributeKey( Element $node, string $key ): string {
179        $tplAttrs = DOMDataUtils::getDataMw( $node )->attribs ?? [];
180        foreach ( $tplAttrs as $attr ) {
181            // If this attribute's key is generated content,
182            // serialize HTML back to generator wikitext.
183            if ( ( $attr->key['txt'] ?? null ) === $key && isset( $attr->key['html'] ) ) {
184                return $this->htmlToWikitext( [
185                    'env' => $this->env,
186                    'onSOL' => false,
187                ], $attr->key['html'] );
188            }
189        }
190        return $key;
191    }
192
193    /**
194     * @param Element $node
195     * @param string $key Attribute name.
196     * @return ?string The wikitext value, or null if the attribute is not present.
197     */
198    public function getAttributeValue( Element $node, string $key ): ?string {
199        $tplAttrs = DOMDataUtils::getDataMw( $node )->attribs ?? [];
200        foreach ( $tplAttrs as $attr ) {
201            // If this attribute's value is generated content,
202            // serialize HTML back to generator wikitext.
203            // PORT-FIXME: not type safe. Need documentation on attrib format.
204            if ( ( $attr->key === $key || ( $attr->key['txt'] ?? null ) === $key )
205                 // Only return here if the value is generated (ie. .html),
206                 // it may just be in .txt form.
207                 // html:"" will serialize to "" and
208                 // will be returned here. This is used to suppress the =".."
209                 // string in the attribute in scenarios where the template
210                 // generates a "k=v" string.
211                 // Ex: <div {{1x|1=style='color:red'}}>foo</div>
212                 && isset( $attr->value['html'] )
213            ) {
214                return $this->htmlToWikitext( [
215                    'env' => $this->env,
216                    'onSOL' => false,
217                    'inAttribute' => true,
218                ], $attr->value['html'] );
219            }
220        }
221        return null;
222    }
223
224    /**
225     * @param Element $node
226     * @param string $key
227     * @return array|null A tuple in {@link WTSUtils::getShadowInfo()} format,
228     *   with an extra 'fromDataMW' flag.
229     */
230    public function getAttributeValueAsShadowInfo( Element $node, string $key ): ?array {
231        $v = $this->getAttributeValue( $node, $key );
232        if ( $v === null ) {
233            return $v;
234        }
235        return [
236            'value' => $v,
237            'modified' => false,
238            'fromsrc' => true,
239            'fromDataMW' => true,
240        ];
241    }
242
243    /**
244     * @param Element $dataMWnode
245     * @param Element $htmlAttrNode
246     * @param string $key
247     * @return array A tuple in {@link WTSUtils::getShadowInfo()} format,
248     *   possibly with an extra 'fromDataMW' flag.
249     */
250    public function serializedImageAttrVal(
251        Element $dataMWnode, Element $htmlAttrNode, string $key
252    ): array {
253        $v = $this->getAttributeValueAsShadowInfo( $dataMWnode, $key );
254        return $v ?: WTSUtils::getAttributeShadowInfo( $htmlAttrNode, $key );
255    }
256
257    public function serializedAttrVal( Element $node, string $name ): array {
258        return $this->serializedImageAttrVal( $node, $node, $name );
259    }
260
261    /**
262     * Check if token needs escaping
263     *
264     * @param string $name
265     * @return bool
266     */
267    public function tagNeedsEscaping( string $name ): bool {
268        return WTUtils::isAnnOrExtTag( $this->env, $name );
269    }
270
271    public function wrapAngleBracket( Token $token, string $inner ): string {
272        if (
273            $this->tagNeedsEscaping( $token->getName() ) &&
274            !(
275                // Allow for html tags that shadow extension tags found in source
276                // to roundtrip.  They only parse as html tags if they are unclosed,
277                // since extension tags bail on parsing without closing tags.
278                //
279                // This only applies when wrapAngleBracket() is being called for
280                // start tags, but we wouldn't be here if it was autoInsertedEnd
281                // anyways.
282                isset( Consts::$Sanitizer['AllowedLiteralTags'][$token->getName()] ) &&
283                !empty( $token->dataParsoid->autoInsertedEnd )
284            )
285        ) {
286            return "&lt;{$inner}&gt;";
287        }
288        return "<$inner>";
289    }
290
291    public function serializeHTMLTag( Element $node, bool $wrapperUnmodified ): string {
292        // TODO(arlolra): As of 1.3.0, html pre is considered an extension
293        // and wrapped in encapsulation.  When that version is no longer
294        // accepted for serialization, we can remove this backwards
295        // compatibility code.
296        //
297        // 'inHTMLPre' flag has to be updated always,
298        // even when we are selsering in the wrapperUnmodified case.
299        $token = WTSUtils::mkTagTk( $node );
300        if ( $token->getName() === 'pre' ) {
301            // html-syntax pre is very similar to nowiki
302            $this->state->inHTMLPre = true;
303        }
304
305        if ( $wrapperUnmodified ) {
306            $dsr = DOMDataUtils::getDataParsoid( $node )->dsr;
307            return $this->state->getOrigSrc( $dsr->openRange() ) ?? '';
308        }
309
310        $da = $token->dataParsoid;
311        if ( !empty( $da->autoInsertedStart ) ) {
312            return '';
313        }
314
315        $close = '';
316        if ( ( Utils::isVoidElement( $token->getName() ) && empty( $da->noClose ) ) ||
317            !empty( $da->selfClose )
318        ) {
319            $close = ' /';
320        }
321
322        $sAttribs = $this->serializeAttributes( $node, $token );
323        if ( strlen( $sAttribs ) > 0 ) {
324            $sAttribs = ' ' . $sAttribs;
325        }
326
327        // srcTagName cannot be '' so, it is okay to use ?? operator
328        $tokenName = $da->srcTagName ?? $token->getName();
329        $inner = "{$tokenName}{$sAttribs}{$close}";
330        return $this->wrapAngleBracket( $token, $inner );
331    }
332
333    /**
334     * @param Element $node
335     * @param bool $wrapperUnmodified
336     * @return string
337     */
338    public function serializeHTMLEndTag( Element $node, $wrapperUnmodified ): string {
339        if ( $wrapperUnmodified ) {
340            $dsr = DOMDataUtils::getDataParsoid( $node )->dsr;
341            return $this->state->getOrigSrc( $dsr->closeRange() ) ?? '';
342        }
343
344        $token = WTSUtils::mkEndTagTk( $node );
345        if ( $token->getName() === 'pre' ) {
346            $this->state->inHTMLPre = false;
347        }
348
349        // srcTagName cannot be '' so, it is okay to use ?? operator
350        $tokenName = $token->dataParsoid->srcTagName ?? $token->getName();
351        $ret = '';
352
353        if ( empty( $token->dataParsoid->autoInsertedEnd )
354            && !Utils::isVoidElement( $token->getName() )
355            && empty( $token->dataParsoid->selfClose )
356        ) {
357            $ret = $this->wrapAngleBracket( $token, "/{$tokenName}" );
358        }
359
360        return $ret;
361    }
362
363    public function serializeAttributes( Element $node, Token $token, bool $isWt = false ): string {
364        $attribs = $token->attribs;
365
366        $out = [];
367        foreach ( $attribs as $kv ) {
368            // Tokens created during html2wt don't have nested tokens for keys.
369            // But, they could be integers but we want strings below.
370            $k = (string)$kv->k;
371            $v = null;
372            $vInfo = null;
373
374            // Unconditionally ignore
375            // (all of the IGNORED_ATTRIBUTES should be filtered out earlier,
376            // but ignore them here too just to make sure.)
377            if ( isset( self::IGNORED_ATTRIBUTES[$k] ) || $k === 'data-mw' ) {
378                continue;
379            }
380
381            // Ignore parsoid-like ids. They may have been left behind
382            // by clients and shouldn't be serialized. This can also happen
383            // in v2/v3 API when there is no matching data-parsoid entry found
384            // for this id.
385            if ( $k === 'id' && preg_match( '/^mw[\w-]{2,}$/D', $kv->v ) ) {
386                if ( WTUtils::isNewElt( $node ) ) {
387                    // Parsoid id found on element without a matching data-parsoid. Drop it!
388                } else {
389                    $vInfo = $token->getAttributeShadowInfo( $k );
390                    if ( !$vInfo['modified'] && $vInfo['fromsrc'] ) {
391                        $out[] = $k . '=' . '"' . str_replace( '"', '&quot;', $vInfo['value'] ) . '"';
392                    }
393                }
394                continue;
395            }
396
397            // Parsoid auto-generates ids for headings and they should
398            // be stripped out, except if this is not auto-generated id.
399            if ( $k === 'id' && DOMUtils::isHeading( $node ) ) {
400                if ( !empty( DOMDataUtils::getDataParsoid( $node )->reusedId ) ) {
401                    $vInfo = $token->getAttributeShadowInfo( $k );
402                    // PORT-FIXME: is this safe? value could be a token or token array
403                    $out[] = $k . '="' . str_replace( '"', '&quot;', $vInfo['value'] ) . '"';
404                }
405                continue;
406            }
407
408            // Strip Parsoid-inserted class="mw-empty-elt" attributes
409            if ( $k === 'class'
410                 && isset( Consts::$Output['FlaggedEmptyElts'][DOMCompat::nodeName( $node )] )
411            ) {
412                $kv->v = preg_replace( '/\bmw-empty-elt\b/', '', $kv->v, 1 );
413                if ( !$kv->v ) {
414                    continue;
415                }
416            }
417
418            // Strip other Parsoid-generated values
419            //
420            // FIXME: Given that we are currently escaping about/typeof keys
421            // that show up in wikitext, we could unconditionally strip these
422            // away right now.
423            $parsoidValueRegExp = self::PARSOID_ATTRIBUTES[$k] ?? null;
424            if ( $parsoidValueRegExp && preg_match( $parsoidValueRegExp, $kv->v ) ) {
425                $v = preg_replace( $parsoidValueRegExp, '', $kv->v );
426                if ( $v ) {
427                    $out[] = $k . '="' . $v . '"';
428                }
429                continue;
430            }
431
432            if ( strlen( $k ) > 0 ) {
433                $vInfo = $token->getAttributeShadowInfo( $k );
434                $v = $vInfo['value'];
435                // Deal with k/v's that were template-generated
436                $kk = $this->getAttributeKey( $node, $k );
437                // Pass in $k, not $kk since $kk can potentially
438                // be original wikitext source for 'k' rather than
439                // the string value of the key.
440                $vv = $this->getAttributeValue( $node, $k ) ?? $v;
441                // Remove encapsulation from protected attributes
442                // in pegTokenizer.pegjs:generic_newline_attribute
443                $kk = preg_replace( '/^data-x-/i', '', $kk, 1 );
444                // PORT-FIXME: is this type safe? $vv could be a ConstrainedText
445                if ( $vv !== null && strlen( $vv ) > 0 ) {
446                    if ( !$vInfo['fromsrc'] && !$isWt ) {
447                        // Escape wikitext entities
448                        $vv = str_replace( '>', '&gt;', Utils::escapeWtEntities( $vv ) );
449                    }
450                    $out[] = $kk . '="' . str_replace( '"', '&quot;', $vv ) . '"';
451                } elseif ( preg_match( '/[{<]/', $kk ) ) {
452                    // Templated, <*include*>, or <ext-tag> generated
453                    $out[] = $kk;
454                } else {
455                    $out[] = $kk . '=""';
456                }
457                continue;
458            // PORT-FIXME: is this type safe? $k->v could be a Token or Token array
459            } elseif ( strlen( $kv->v ) ) {
460                // not very likely..
461                $out[] = $kv->v;
462            }
463        }
464
465        // SSS FIXME: It can be reasonably argued that we can permanently delete
466        // dangerous and unacceptable attributes in the interest of safety/security
467        // and the resultant dirty diffs should be acceptable.  But, this is
468        // something to do in the future once we have passed the initial tests
469        // of parsoid acceptance.
470        //
471        // 'a' data attribs -- look for attributes that were removed
472        // as part of sanitization and add them back
473        $dataParsoid = $token->dataParsoid;
474        if ( isset( $dataParsoid->a ) && isset( $dataParsoid->sa ) ) {
475            $aKeys = array_keys( $dataParsoid->a );
476            foreach ( $aKeys as $k ) {
477                // Attrib not present -- sanitized away!
478                if ( !KV::lookupKV( $attribs, (string)$k ) ) {
479                    $v = $dataParsoid->sa[$k] ?? null;
480                    // FIXME: The tokenizer and attribute shadowing currently
481                    // don't make much effort towards distinguishing the use
482                    // of HTML empty attribute syntax.  We can derive whether
483                    // empty attribute syntax was used from the attributes
484                    // srcOffsets in the Sanitizer, from the key end position
485                    // and value start position being different.
486                    if ( $v !== null && $v !== '' ) {
487                        $out[] = $k . '="' . str_replace( '"', '&quot;', $v ) . '"';
488                    } else {
489                        $out[] = $k;
490                    }
491                }
492            }
493        }
494        // XXX: round-trip optional whitespace / line breaks etc
495        return implode( ' ', $out );
496    }
497
498    private function formatStringSubst( string $format, string $value, bool $forceTrim ): string {
499        // PORT-FIXME: JS is more agressive and removes various unicode whitespaces
500        // (most notably nbsp). Does that matter?
501        if ( $forceTrim ) {
502            $value = trim( $value );
503        }
504        return preg_replace_callback( '/_+/', static function ( $m ) use ( $value ) {
505            if ( $value === '' ) {
506                return $value;
507            }
508            $hole = $m[0];
509            $holeLen = strlen( $hole );
510            $valueLen = mb_strlen( $value );
511            return $holeLen <= $valueLen ? $value : $value . str_repeat( ' ', $holeLen - $valueLen );
512        }, $format, 1 );
513    }
514
515    /**
516     * Generates a template parameter sort function that tries to preserve existing ordering
517     * but also to follow the order prescribed by the templatedata.
518     * @param array $dpArgInfo
519     * @param ?array $tplData
520     * @param array $dataMwKeys
521     * @return Closure
522     */
523    private function createParamComparator(
524        array $dpArgInfo, ?array $tplData, array $dataMwKeys
525    ): Closure {
526        // Record order of parameters in new data-mw
527        $newOrder = [];
528        foreach ( $dataMwKeys as $i => $key ) {
529            $newOrder[$key] = [ 'order' => $i ];
530        }
531        // Record order of parameters in templatedata (if present)
532        $tplDataOrder = [];
533        $aliasMap = [];
534        $keys = [];
535        if ( $tplData && isset( $tplData['paramOrder'] ) ) {
536            foreach ( $tplData['paramOrder'] as $i => $key ) {
537                $tplDataOrder[$key] = [ 'order' => $i ];
538                $aliasMap[$key] = [ 'key' => $key, 'order' => -1 ];
539                $keys[] = $key;
540                // Aliases have the same sort order as the main name.
541                $aliases = $tplData['params'][$key]['aliases'] ?? [];
542                foreach ( $aliases as $j => $alias ) {
543                    $aliasMap[$alias] = [ 'key' => $key, 'order' => $j ];
544                }
545            }
546        }
547        // Record order of parameters in original wikitext (from data-parsoid)
548        $origOrder = [];
549        foreach ( $dpArgInfo as $i => $argInfo ) {
550            $origOrder[$argInfo->k] = [ 'order' => $i, 'dist' => 0 ];
551        }
552        // Canonical parameter key gets the same order as an alias parameter
553        // found in the original wikitext.
554        foreach ( $dpArgInfo as $i => $argInfo ) {
555            $canon = $aliasMap[$argInfo->k] ?? null;
556            if ( $canon !== null && !array_key_exists( $canon['key'], $origOrder ) ) {
557                $origOrder[$canon['key']] = $origOrder[$argInfo->k];
558            }
559        }
560        // Find the closest "original parameter" for each templatedata parameter,
561        // so that newly-added parameters are placed near the parameters which
562        // templatedata says they should be adjacent to.
563        $nearestOrder = $origOrder;
564        $reduceF = static function ( $acc, $val ) use ( &$origOrder, &$nearestOrder ) {
565            if ( isset( $origOrder[$val] ) ) {
566                $acc = $origOrder[$val];
567            }
568            if ( !( isset( $nearestOrder[$val] ) && $nearestOrder[$val]['dist'] < $acc['dist'] ) ) {
569                $nearestOrder[$val] = $acc;
570            }
571            return [ 'order' => $acc['order'], 'dist' => $acc['dist'] + 1 ];
572        };
573        // Find closest original parameter before the key.
574        // @phan-suppress-next-line PhanPluginUseReturnValueInternalKnown
575        array_reduce( $keys, $reduceF, [ 'order' => -1, 'dist' => 2 * count( $keys ) ] );
576        // Find closest original parameter after the key.
577        // @phan-suppress-next-line PhanPluginUseReturnValueInternalKnown
578        array_reduce( array_reverse( $keys ), $reduceF,
579            [ 'order' => count( $origOrder ), 'dist' => count( $keys ) ] );
580
581        // Helper function to return a large number if the given key isn't
582        // in the sort order map
583        $big = max( count( $nearestOrder ), count( $newOrder ) );
584        $defaultGet = static function ( $map, $key1, $key2 = null ) use ( &$big ) {
585            $key = ( !$key2 || isset( $map[$key1] ) ) ? $key1 : $key2;
586            return $map[$key]['order'] ?? $big;
587        };
588
589        return static function ( $a, $b ) use (
590            &$aliasMap, &$defaultGet, &$nearestOrder, &$tplDataOrder, &$newOrder
591        ) {
592            $aCanon = $aliasMap[$a] ?? [ 'key' => $a, 'order' => -1 ];
593            $bCanon = $aliasMap[$b] ?? [ 'key' => $b, 'order' => -1 ];
594            // primary key is `nearestOrder` (nearest original parameter)
595            $aOrder = $defaultGet( $nearestOrder, $a, $aCanon['key'] );
596            $bOrder = $defaultGet( $nearestOrder, $b, $bCanon['key'] );
597            if ( $aOrder !== $bOrder ) {
598                return $aOrder - $bOrder;
599            }
600            // secondary key is templatedata order
601            if ( $aCanon['key'] === $bCanon['key'] ) {
602                return $aCanon['order'] - $bCanon['order'];
603            }
604            $aOrder = $defaultGet( $tplDataOrder, $aCanon['key'] );
605            $bOrder = $defaultGet( $tplDataOrder, $bCanon['key'] );
606            if ( $aOrder !== $bOrder ) {
607                return $aOrder - $bOrder;
608            }
609            // tertiary key is original input order (makes sort stable)
610            $aOrder = $defaultGet( $newOrder, $a );
611            $bOrder = $defaultGet( $newOrder, $b );
612            return $aOrder - $bOrder;
613        };
614    }
615
616    /**
617     * Serialize part of a templatelike expression.
618     * @param SerializerState $state
619     * @param string $buf
620     * @param Element $node
621     * @param TemplateInfo $part The expression fragment to serialize. See $srcParts
622     *   in serializeFromParts() for format.
623     * @param ?array $tplData Templatedata, see
624     *   https://github.com/wikimedia/mediawiki-extensions-TemplateData/blob/master/Specification.md
625     * @param string|TemplateInfo $prevPart Previous part. See $srcParts in serializeFromParts().
626     * @param string|TemplateInfo $nextPart Next part. See $srcParts in serializeFromParts().
627     * @return string
628     */
629    private function serializePart(
630        SerializerState $state, string $buf, Element $node, TemplateInfo $part,
631        ?array $tplData, $prevPart, $nextPart
632    ): string {
633        // Parse custom format specification, if present.
634        $defaultBlockSpc = "{{_\n| _ = _\n}}"; // "block"
635        $defaultInlineSpc = '{{_|_=_}}'; // "inline"
636
637        $format = isset( $tplData['format'] ) ? strtolower( $tplData['format'] ) : null;
638        if ( $format === 'block' ) {
639            $format = $defaultBlockSpc;
640        } elseif ( $format === 'inline' ) {
641            $format = $defaultInlineSpc;
642        }
643        // Check format string for validity.
644        preg_match( self::FORMATSTRING_REGEXP, $format ?? '', $parsedFormat );
645        if ( !$parsedFormat ) {
646            preg_match( self::FORMATSTRING_REGEXP, $defaultInlineSpc, $parsedFormat );
647            $format = null; // Indicates that no valid custom format was present.
648        }
649        $formatSOL = $parsedFormat[1] ?? '';
650        $formatStart = $parsedFormat[2] ?? '';
651        $formatParamName = $parsedFormat[3] ?? '';
652        $formatParamValue = $parsedFormat[4] ?? '';
653        $formatEnd = $parsedFormat[5] ?? '';
654        $formatEOL = $parsedFormat[6] ?? '';
655        $forceTrim = ( $format !== null ) || WTUtils::isNewElt( $node );
656
657        // Shoehorn formatting of top-level templatearg wikitext into this code.
658        if ( $part->type === 'templatearg' ) {
659            $formatStart = preg_replace( '/{{/', '{{{', $formatStart, 1 );
660            $formatEnd = preg_replace( '/}}/', '}}}', $formatEnd, 1 );
661        }
662
663        // handle SOL newline requirement
664        if ( $formatSOL && !str_ends_with( ( $prevPart !== null ) ? $buf : ( $state->sep->src ?? '' ), "\n" ) ) {
665            $buf .= "\n";
666        }
667
668        // open the transclusion
669        $buf .= $this->formatStringSubst( $formatStart, $part->targetWt, $forceTrim );
670
671        // Short-circuit transclusions without params
672        $paramKeys = array_map( static fn ( ParamInfo $pi ) => $pi->k, $part->paramInfos );
673        if ( !$paramKeys ) {
674            if ( substr( $formatEnd, 0, 1 ) === "\n" ) {
675                $formatEnd = substr( $formatEnd, 1 );
676            }
677            return $buf . $formatEnd;
678        }
679
680        // Trim whitespace from data-mw keys to deal with non-compliant
681        // clients. Make sure param info is accessible for the stripped key
682        // since later code will be using the stripped key always.
683        $tplKeysFromDataMw = [];
684        foreach ( $part->paramInfos as $pi ) {
685            $strippedKey = trim( $pi->k );
686            $tplKeysFromDataMw[$strippedKey] = $pi;
687        }
688
689        // Per-parameter info from data-parsoid for pre-existing parameters
690        $dp = DOMDataUtils::getDataParsoid( $node );
691        // Account for clients not setting the `i`, see T238721
692        $dpArgInfo = $part->i !== null ? ( $dp->pi[$part->i] ?? [] ) : [];
693
694        // Build a key -> arg info map
695        $dpArgInfoMap = [];
696        foreach ( $dpArgInfo as $info ) {
697            $dpArgInfoMap[$info->k] = $info;
698        }
699
700        // 1. Process all parameters and build a map of
701        //    arg-name -> [serializeAsNamed, name, value]
702        //
703        // 2. Serialize tpl args in required order
704        //
705        // 3. Format them according to formatParamName/formatParamValue
706
707        $kvMap = [];
708        foreach ( $tplKeysFromDataMw as $key => $param ) {
709            // Storing keys in an array can turn them into ints; stringify.
710            $key = (string)$key;
711            $argInfo = $dpArgInfoMap[$key] ?? [];
712
713            // TODO: Other formats?
714            // Only consider the html parameter if the wikitext one
715            // isn't present at all. If it's present but empty,
716            // that's still considered a valid parameter.
717            if ( $param->valueWt !== null ) {
718                $value = $param->valueWt;
719            } elseif ( $param->html !== null ) {
720                $value = $this->htmlToWikitext( [ 'env' => $this->env ], $param->html );
721            } else {
722                $this->env->log(
723                    'error',
724                    "params in data-mw part is missing wt/html for $key" .
725                        "Serializing as empty string.",
726                    "data-mw part: " . json_encode( $part->toJsonArray() )
727                );
728                $value = "";
729            }
730
731            Assert::invariant( is_string( $value ), "For param: $key, wt property should be a string '
732                . 'but got: $value" );
733
734            $serializeAsNamed = !empty( $argInfo->named );
735
736            // The name is usually equal to the parameter key, but
737            // if there's a key->wt attribute, use that.
738            $name = null;
739            if ( $param->keyWt !== null ) {
740                $name = $param->keyWt;
741                // And make it appear even if there wasn't any data-parsoid information.
742                $serializeAsNamed = true;
743            } else {
744                $name = $key;
745            }
746
747            // Use 'k' as the key, not 'name'.
748            //
749            // The normalized form of 'k' is used as the key in both
750            // data-parsoid and data-mw. The full non-normalized form
751            // is present in '$param->keyWt'
752            $kvMap[$key] = [ 'serializeAsNamed' => $serializeAsNamed, 'name' => $name, 'value' => $value ];
753        }
754
755        $argOrder = array_keys( $kvMap );
756        usort( $argOrder, $this->createParamComparator( $dpArgInfo, $tplData, $argOrder ) );
757
758        $argIndex = 1;
759        $numericIndex = 1;
760
761        $numPositionalArgs = 0;
762        foreach ( $dpArgInfo as $pi ) {
763            if ( isset( $tplKeysFromDataMw[trim( $pi->k )] ) && empty( $pi->named ) ) {
764                $numPositionalArgs++;
765            }
766        }
767
768        $argBuf = [];
769        foreach ( $argOrder as $param ) {
770            $kv = $kvMap[$param];
771            // Add nowiki escapes for the arg value, as required
772            $escapedValue = $this->wteHandlers->escapeTplArgWT( $kv['value'], [
773                'serializeAsNamed' => $kv['serializeAsNamed'] || $param !== $numericIndex,
774                'type' => $part->type,
775                'argPositionalIndex' => $numericIndex,
776                'numPositionalArgs' => $numPositionalArgs,
777                'argIndex' => $argIndex++,
778                'numArgs' => count( $tplKeysFromDataMw ),
779            ] );
780            if ( $escapedValue['serializeAsNamed'] ) {
781                // WS trimming for values of named args
782                $argBuf[] = [ 'dpKey' => $param, 'name' => $kv['name'], 'value' => trim( $escapedValue['v'] ) ];
783            } else {
784                $numericIndex++;
785                // No WS trimming for positional args
786                $argBuf[] = [ 'dpKey' => $param, 'name' => null, 'value' => $escapedValue['v'] ];
787            }
788        }
789
790        // If no explicit format is provided, default format is:
791        // - 'inline' for new args
792        // - whatever format is available from data-parsoid for old args
793        // (aka, overriding formatParamName/formatParamValue)
794        //
795        // If an unedited node OR if paramFormat is unspecified,
796        // this strategy prevents unnecessary normalization
797        // of edited transclusions which don't have valid
798        // templatedata formatting information.
799
800        // "magic case": If the format string ends with a newline, an extra newline is added
801        // between the template name and the first parameter.
802
803        foreach ( $argBuf as $arg ) {
804            $name = $arg['name'];
805            $val = $arg['value'];
806            if ( $name === null ) {
807                // We are serializing a positional parameter.
808                // Whitespace is significant for these and
809                // formatting would change semantics.
810                $name = '';
811                $modFormatParamName = '|_';
812                $modFormatParamValue = '_';
813            } elseif ( $name === '' ) {
814                // No spacing for blank parameters ({{foo|=bar}})
815                // This should be an edge case and probably only for
816                // inline-formatted templates, but we are consciously
817                // forcing this default here. Can revisit if this is
818                // ever a problem.
819                $modFormatParamName = '|_=';
820                $modFormatParamValue = '_';
821            } else {
822                // Preserve existing spacing, esp if there was a comment
823                // embedded in it. Otherwise, follow TemplateData's lead.
824                // NOTE: In either case, we are forcibly normalizing
825                // non-block-formatted transclusions into block formats
826                // by adding missing newlines.
827                $spc = $dpArgInfoMap[$arg['dpKey']]->spc ?? null;
828                if ( $spc && ( !$format || preg_match( Utils::COMMENT_REGEXP, $spc[3] ?? '' ) ) ) {
829                    $nl = ( substr( $formatParamName, 0, 1 ) === "\n" ) ? "\n" : '';
830                    $modFormatParamName = $nl . '|' . $spc[0] . '_' . $spc[1] . '=' . $spc[2];
831                    $modFormatParamValue = '_' . $spc[3];
832                } else {
833                    $modFormatParamName = $formatParamName;
834                    $modFormatParamValue = $formatParamValue;
835                }
836            }
837
838            // Don't create duplicate newlines.
839            $trailing = preg_match( self::TRAILING_COMMENT_OR_WS_AFTER_NL_REGEXP, $buf );
840            if ( $trailing && substr( $formatParamName, 0, 1 ) === "\n" ) {
841                $modFormatParamName = substr( $formatParamName, 1 );
842            }
843
844            $buf .= $this->formatStringSubst( $modFormatParamName, $name, $forceTrim );
845            $buf .= $this->formatStringSubst( $modFormatParamValue, $val, $forceTrim );
846        }
847
848        // Don't create duplicate newlines.
849        if ( preg_match( self::TRAILING_COMMENT_OR_WS_AFTER_NL_REGEXP, $buf )
850             && substr( $formatEnd, 0, 1 ) === "\n"
851        ) {
852            $buf .= substr( $formatEnd, 1 );
853        } else {
854            $buf .= $formatEnd;
855        }
856
857        if ( $formatEOL ) {
858            if ( $nextPart === null ) {
859                // This is the last part of the block. Add the \n only
860                // if the next non-comment node is not a text node
861                // of if the text node doesn't have a leading \n.
862                $next = DiffDOMUtils::nextNonDeletedSibling( $node );
863                while ( $next instanceof Comment ) {
864                    $next = DiffDOMUtils::nextNonDeletedSibling( $next );
865                }
866                if ( !( $next instanceof Text ) || substr( $next->nodeValue, 0, 1 ) !== "\n" ) {
867                    $buf .= "\n";
868                }
869            } elseif ( !is_string( $nextPart ) || substr( $nextPart, 0, 1 ) !== "\n" ) {
870                // If nextPart is another template, and it wants a leading nl,
871                // this \n we add here will count towards that because of the
872                // formatSOL check at the top.
873                $buf .= "\n";
874            }
875        }
876
877        return $buf;
878    }
879
880    /**
881     * Serialize a template from its parts.
882     * @param SerializerState $state
883     * @param Element $node
884     * @param list<string|TemplateInfo> $srcParts Template parts
885     * @return string
886     */
887    public function serializeFromParts(
888        SerializerState $state, Element $node, array $srcParts
889    ): string {
890        $useTplData = WTUtils::isNewElt( $node ) || DiffUtils::hasDiffMarkers( $node );
891        $buf = '';
892        foreach ( $srcParts as $i => $part ) {
893            if ( is_string( $part ) ) {
894                $buf .= $part;
895                continue;
896            }
897
898            $prevPart = $srcParts[$i - 1] ?? null;
899            $nextPart = $srcParts[$i + 1] ?? null;
900
901            if ( $part->targetWt === null ) {
902                // Maybe we should just raise a ClientError
903                $this->env->log( 'error', 'data-mw.parts array is malformed: ',
904                    DOMCompat::getOuterHTML( $node ), PHPUtils::jsonEncode( $srcParts ) );
905                continue;
906            }
907
908            // Account for clients leaving off the params array, presumably when empty.
909            // See T291741
910            $part->paramInfos ??= [];
911
912            if ( $part->type === 'templatearg' ) {
913                $buf = $this->serializePart(
914                    $state, $buf, $node, $part, null, $prevPart,
915                    $nextPart
916                );
917                continue;
918            }
919
920            // transclusion: tpl or parser function?
921            // templates have $part->href
922            // parser functions have $part->func
923
924            // While the API supports fetching multiple template data objects in one call,
925            // we will fetch one at a time to benefit from cached responses.
926            //
927            // Fetch template data for the template
928            $tplData = null;
929            $apiResp = null;
930            if ( $part->href !== null && $useTplData ) {
931                // Not a parser function
932                try {
933                    $title = Title::newFromText(
934                        PHPUtils::stripPrefix( Utils::decodeURIComponent( $part->href ), './' ),
935                        $this->env->getSiteConfig()
936                    );
937                    $tplData = $this->env->getDataAccess()->fetchTemplateData( $this->env->getPageConfig(), $title );
938                } catch ( Exception $err ) {
939                    // Log the error, and use default serialization mode.
940                    // Better to misformat a transclusion than to lose an edit.
941                    $this->env->log( 'error/html2wt/tpldata', $err );
942                }
943            }
944            // If the template doesn't exist, or does but has no TemplateData, ignore it
945            if ( !empty( $tplData['missing'] ) || !empty( $tplData['notemplatedata'] ) ) {
946                $tplData = null;
947            }
948            $buf = $this->serializePart( $state, $buf, $node, $part, $tplData, $prevPart, $nextPart );
949        }
950        return $buf;
951    }
952
953    public function serializeExtensionStartTag( Element $node, SerializerState $state ): string {
954        $dataMw = DOMDataUtils::getDataMw( $node );
955        $extTagName = $dataMw->name;
956
957        // Serialize extension attributes in normalized form as:
958        // key='value'
959        // FIXME: with no dataParsoid, shadow info will mark it as new
960        $attrs = (array)( $dataMw->attrs ?? [] );
961        $extTok = new TagTk( $extTagName, array_map( static function ( $key ) use ( $attrs ) {
962            return new KV( $key, $attrs[$key] );
963        }, array_keys( $attrs ) ) );
964
965        $about = DOMCompat::getAttribute( $node, 'about' );
966        if ( $about !== null ) {
967            $extTok->addAttribute( 'about', $about );
968        }
969        $typeof = DOMCompat::getAttribute( $node, 'typeof' );
970        if ( $typeof !== null ) {
971            $extTok->addAttribute( 'typeof', $typeof );
972        }
973
974        $attrStr = $this->serializeAttributes( $node, $extTok );
975        $src = '<' . $extTagName;
976        if ( $attrStr ) {
977            $src .= ' ' . $attrStr;
978        }
979        return $src . ( !empty( $dataMw->body ) ? '>' : ' />' );
980    }
981
982    public function defaultExtensionHandler( Element $node, SerializerState $state ): string {
983        $dp = DOMDataUtils::getDataParsoid( $node );
984        $dataMw = DOMDataUtils::getDataMw( $node );
985        $src = $this->serializeExtensionStartTag( $node, $state );
986        if ( !isset( $dataMw->body ) ) {
987            return $src; // We self-closed this already.
988        } elseif ( is_string( $dataMw->body->extsrc ?? null ) ) {
989            $src .= $dataMw->body->extsrc;
990        } elseif ( isset( $dp->src ) ) {
991            $this->env->log(
992                'error/html2wt/ext',
993                'Extension data-mw missing for: ' . DOMCompat::getOuterHTML( $node )
994            );
995            return $dp->src;
996        } else {
997            $this->env->log(
998                'error/html2wt/ext',
999                'Extension src unavailable for: ' . DOMCompat::getOuterHTML( $node )
1000            );
1001        }
1002        return $src . '</' . $dataMw->name . '>';
1003    }
1004
1005    /**
1006     * Consolidate separator handling when emitting text.
1007     * @param string $res
1008     * @param Node $node
1009     */
1010    private function serializeText( string $res, Node $node ): void {
1011        $state = $this->state;
1012
1013        // Deal with trailing separator-like text (at least 1 newline and other whitespace)
1014        preg_match( self::$separatorREs['sepSuffixWithNlsRE'], $res, $newSepMatch );
1015        $res = preg_replace( self::$separatorREs['sepSuffixWithNlsRE'], '', $res, 1 );
1016
1017        if ( !$state->inIndentPre ) {
1018            // Strip leading newlines and other whitespace
1019            if ( preg_match( self::$separatorREs['sepPrefixWithNlsRE'], $res, $match ) ) {
1020                $state->appendSep( $match[0] );
1021                $res = substr( $res, strlen( $match[0] ) );
1022            }
1023        }
1024
1025        if ( $state->needsEscaping ) {
1026            $res = Utils::escapeWtEntities( $res );
1027        }
1028        $state->emitChunk( $res, $node );
1029
1030        // Move trailing newlines into the next separator
1031        if ( $newSepMatch ) {
1032            if ( !$state->sep->src ) {
1033                $state->appendSep( $newSepMatch[0] );
1034            } else {
1035                /* SSS FIXME: what are we doing with the stripped NLs?? */
1036            }
1037        }
1038    }
1039
1040    /**
1041     * Serialize the content of a text node
1042     * @param Node $node
1043     * @return Node|null
1044     */
1045    private function serializeTextNode( Node $node ): ?Node {
1046        $this->state->needsEscaping = true;
1047        $this->serializeText( $node->nodeValue, $node );
1048        $this->state->needsEscaping = false;
1049        return $node->nextSibling;
1050    }
1051
1052    /**
1053     * Emit non-separator wikitext that does not need to be escaped.
1054     * @param string $res
1055     * @param Node $node
1056     */
1057    public function emitWikitext( string $res, Node $node ): void {
1058        $this->serializeText( $res, $node );
1059    }
1060
1061    /**
1062     * DOM-based serialization
1063     * @param Element $node
1064     * @param DOMHandler $domHandler
1065     * @return Node|null
1066     */
1067    private function serializeNodeInternal( Element $node, DOMHandler $domHandler ) {
1068        // To serialize a node from source, the node should satisfy these
1069        // conditions:
1070        //
1071        // 1. It should not have a diff marker or be in a modified subtree
1072        //    WTS should not be in a subtree with a modification flag that
1073        //    applies to every node of a subtree (rather than an indication
1074        //    that some node in the subtree is modified).
1075        //
1076        // 2. It should continue to be valid in any surrounding edited context
1077        //    For some nodes, modification of surrounding context
1078        //    can change serialized output of this node
1079        //    (ex: <td>s and whether you emit | or || for them)
1080        //
1081        // 3. It should have valid, usable DSR
1082        //
1083        // 4. Either it has non-zero positive DSR width, or meets one of the
1084        //    following:
1085        //
1086        //    4a. It is content like <p><br/><p> or an automatically-inserted
1087        //        wikitext <references/> (HTML <ol>) (will have dsr-width 0)
1088        //    4b. it is fostered content (will have dsr-width 0)
1089        //    4c. it is misnested content (will have dsr-width 0)
1090        //
1091        // SSS FIXME: Additionally, we can guard against buggy DSR with
1092        // some validity checks. We can test that non-sep src content
1093        // leading wikitext markup corresponds to the node type.
1094        //
1095        // Ex: If node.nodeName is 'UL', then src[0] should be '*'
1096        //
1097        // TO BE DONE
1098
1099        $state = $this->state;
1100        $wrapperUnmodified = false;
1101        $dp = DOMDataUtils::getDataParsoid( $node );
1102
1103        if ( $state->selserMode
1104            && !$state->inInsertedContent
1105            && WTSUtils::origSrcValidInEditedContext( $state, $node )
1106            && Utils::isValidDSR( $dp->dsr ?? null )
1107            && ( $dp->dsr->end > $dp->dsr->start
1108                // FIXME: <p><br/></p>
1109                // nodes that have dsr width 0 because currently,
1110                // we emit newlines outside the p-nodes. So, this check
1111                // tries to handle that scenario.
1112                || (
1113                    $dp->dsr->end === $dp->dsr->start && (
1114                        in_array( DOMCompat::nodeName( $node ), [ 'p', 'br' ], true )
1115                        || !empty( DOMDataUtils::getDataMw( $node )->autoGenerated )
1116                        // FIXME: This is only necessary while outputContentVersion
1117                        // 2.1.2 - 2.2.0 are still valid
1118                        || DOMUtils::hasTypeOf( $node, 'mw:Placeholder/StrippedTag' )
1119                    )
1120                )
1121                || !empty( $dp->fostered )
1122                || !empty( $dp->misnested )
1123            )
1124        ) {
1125            if ( !DiffUtils::hasDiffMarkers( $node ) ) {
1126                // If this HTML node will disappear in wikitext because of
1127                // zero width, then the separator constraints will carry over
1128                // to the node's children.
1129                //
1130                // Since we dont recurse into 'node' in selser mode, we update the
1131                // separator constraintInfo to apply to 'node' and its first child.
1132                //
1133                // We could clear constraintInfo altogether which would be
1134                // correct (but could normalize separators and introduce dirty
1135                // diffs unnecessarily).
1136
1137                $state->currNodeUnmodified = true;
1138
1139                if ( WTUtils::isZeroWidthWikitextElt( $node )
1140                    && $node->hasChildNodes()
1141                    && ( $state->sep->constraints['constraintInfo']['sepType'] ?? null ) === 'sibling'
1142                ) {
1143                    $state->sep->constraints['constraintInfo']['onSOL'] = $state->onSOL;
1144                    $state->sep->constraints['constraintInfo']['sepType'] = 'parent-child';
1145                    $state->sep->constraints['constraintInfo']['nodeA'] = $node;
1146                    $state->sep->constraints['constraintInfo']['nodeB'] = $node->firstChild;
1147                }
1148
1149                $out = $state->getOrigSrc( $dp->dsr ) ?? '';
1150
1151                $this->trace( 'ORIG-src with DSR', static function () use ( $dp, $out ) {
1152                    return '[' . $dp->dsr->start . ',' . $dp->dsr->end . '] = '
1153                        . PHPUtils::jsonEncode( $out );
1154                } );
1155
1156                // When reusing source, we should only suppress serializing
1157                // to a single line for the cases we've allowed in normal serialization.
1158                // <a> tags might look surprising here, but, here is the rationale.
1159                // If some link syntax (wikilink, extlink, etc.) accepted a newline
1160                // originally, we can safely let it through here. There is no need to have
1161                // specific checks for wikilnks / extlinks / ... etc. The only concern is
1162                // if the surrounding context in which this link-syntax is embedded also
1163                // breaks the link syntax. There is no such syntax right now.
1164                // FIXME: Note the limitation here, that if these nodes are nested
1165                // in something as trivial as an i / b, the suppression won't happen
1166                // and we'll dirty the text.
1167                $suppressSLC = WTUtils::isFirstEncapsulationWrapperNode( $node )
1168                    || DOMUtils::hasTypeOf( $node, 'mw:Nowiki' )
1169                    || in_array( DOMCompat::nodeName( $node ), [ 'dl', 'ul', 'ol', 'a' ], true )
1170                    || ( DOMCompat::nodeName( $node ) === 'table'
1171                        && DOMCompat::nodeName( $node->parentNode ) === 'dd'
1172                        && DiffDOMUtils::previousNonSepSibling( $node ) === null );
1173
1174                // Use selser to serialize this text!  The original
1175                // wikitext is `out`.  But first allow
1176                // `ConstrainedText.fromSelSer` to figure out the right
1177                // type of ConstrainedText chunk(s) to use to represent
1178                // `out`, based on the node type.  Since we might actually
1179                // have to break this wikitext into multiple chunks,
1180                // `fromSelSer` returns an array.
1181                if ( $suppressSLC ) {
1182                    $state->singleLineContext->disable();
1183                }
1184                foreach ( ConstrainedText::fromSelSer( $out, $node, $dp, $this->env ) as $ct ) {
1185                    $state->emitChunk( $ct, $ct->node );
1186                }
1187                if ( $suppressSLC ) {
1188                    $state->singleLineContext->pop();
1189                }
1190
1191                // Skip over encapsulated content since it has already been
1192                // serialized.
1193                if ( WTUtils::isFirstEncapsulationWrapperNode( $node ) ) {
1194                    return WTUtils::skipOverEncapsulatedContent( $node );
1195                } else {
1196                    return $node->nextSibling;
1197                }
1198            }
1199
1200            $wrapperUnmodified = DiffUtils::onlySubtreeChanged( $node ) &&
1201                WTSUtils::hasValidTagWidths( $dp->dsr ?? null );
1202        }
1203
1204        $state->currNodeUnmodified = false;
1205
1206        $currentInsertedState = $state->inInsertedContent;
1207
1208        $inInsertedContent = $state->selserMode && DiffUtils::hasInsertedDiffMark( $node );
1209
1210        if ( $inInsertedContent ) {
1211            $state->inInsertedContent = true;
1212        }
1213
1214        $next = $domHandler->handle( $node, $state, $wrapperUnmodified );
1215
1216        if ( $inInsertedContent ) {
1217            $state->inInsertedContent = $currentInsertedState;
1218        }
1219
1220        return $next;
1221    }
1222
1223    /**
1224     * Internal worker. Recursively serialize a DOM subtree.
1225     * @private
1226     * @param Node $node
1227     * @return ?Node
1228     */
1229    public function serializeNode( Node $node ): ?Node {
1230        $nodeName = DOMCompat::nodeName( $node );
1231        $domHandler = $method = null;
1232        $domHandlerFactory = new DOMHandlerFactory();
1233        $state = $this->state;
1234        $state->currNode = $node;
1235
1236        if ( $state->selserMode ) {
1237            $this->trace(
1238                static function () use ( $node ) {
1239                    return WTSUtils::traceNodeName( $node );
1240                },
1241                '; prev-unmodified: ', $state->prevNodeUnmodified,
1242                '; SOL: ', $state->onSOL );
1243        } else {
1244            $this->trace(
1245                static function () use ( $node ) {
1246                    return WTSUtils::traceNodeName( $node );
1247                },
1248                '; SOL: ', $state->onSOL );
1249        }
1250
1251        switch ( $node->nodeType ) {
1252            case XML_ELEMENT_NODE:
1253                '@phan-var Element $node';/** @var Element $node */
1254                // Ignore DiffMarker metas, but clear unmodified node state
1255                if ( DiffUtils::isDiffMarker( $node ) ) {
1256                    $state->updateModificationFlags( $node );
1257                    // `state.sep.lastSourceNode` is cleared here so that removed
1258                    // separators between otherwise unmodified nodes don't get
1259                    // restored.
1260                    $state->updateSep( $node );
1261                    return $node->nextSibling;
1262                }
1263                $domHandler = $domHandlerFactory->getDOMHandler( $node );
1264                $method = [ $this, 'serializeNodeInternal' ];
1265                break;
1266            case XML_TEXT_NODE:
1267                // This code assumes that the DOM is in normalized form with no
1268                // run of text nodes.
1269                // Accumulate whitespace from the text node into state.sep.src
1270                $text = $node->nodeValue;
1271                if ( !$state->inIndentPre
1272                    // PORT-FIXME: original uses this->state->serializer->separatorREs
1273                    // but that does not seem useful
1274                    && preg_match( self::$separatorREs['pureSepRE'], $text )
1275                ) {
1276                    $state->appendSep( $text );
1277                    return $node->nextSibling;
1278                }
1279                if ( $state->selserMode ) {
1280                    $prev = $node->previousSibling;
1281                    if ( !$state->inInsertedContent && (
1282                        ( !$prev && DOMUtils::atTheTop( $node->parentNode ) ) ||
1283                        ( $prev && !DiffUtils::isDiffMarker( $prev ) )
1284                    ) ) {
1285                        $state->currNodeUnmodified = true;
1286                    } else {
1287                        $state->currNodeUnmodified = false;
1288                    }
1289                }
1290
1291                $domHandler = new DOMHandler( false );
1292                $method = [ $this, 'serializeTextNode' ];
1293                break;
1294            case XML_COMMENT_NODE:
1295                // Merge this into separators
1296                $state->appendSep( WTSUtils::commentWT( $node->nodeValue ) );
1297                return $node->nextSibling;
1298            default:
1299                throw new InternalException( 'Unhandled node type: ' . $node->nodeType );
1300        }
1301
1302        $prev = DiffDOMUtils::previousNonSepSibling( $node ) ?: $node->parentNode;
1303        $this->env->log( 'debug/wts', 'Before constraints for ' . $nodeName );
1304        $state->separators->updateSeparatorConstraints(
1305            $prev, $domHandlerFactory->getDOMHandler( $prev ),
1306            $node, $domHandler
1307        );
1308
1309        $this->env->log( 'debug/wts', 'Calling serialization handler for ' . $nodeName );
1310        $nextNode = $method( $node, $domHandler );
1311
1312        $next = DiffDOMUtils::nextNonSepSibling( $node ) ?: $node->parentNode;
1313        $this->env->log( 'debug/wts', 'After constraints for ' . $nodeName );
1314        $state->separators->updateSeparatorConstraints(
1315            $node, $domHandler,
1316            $next, $domHandlerFactory->getDOMHandler( $next )
1317        );
1318
1319        // Update modification flags
1320        $state->updateModificationFlags( $node );
1321
1322        return $nextNode;
1323    }
1324
1325    private function stripUnnecessaryHeadingNowikis( string $line ): string {
1326        $state = $this->state;
1327        if ( !$state->hasHeadingEscapes ) {
1328            return $line;
1329        }
1330
1331        $escaper = static function ( string $wt ) use ( $state ) {
1332            $ret = $state->serializer->wteHandlers->escapedText( $state, false, $wt, false, true );
1333            return $ret;
1334        };
1335
1336        preg_match( self::HEADING_NOWIKI_REGEXP, $line, $match );
1337        if ( $match && !preg_match( self::COMMENT_OR_WS_REGEXP, $match[2] ) ) {
1338            // The nowikiing was spurious since the trailing = is not in EOL position
1339            return $escaper( $match[1] ) . $match[2];
1340        } else {
1341            // All is good.
1342            return $line;
1343        }
1344    }
1345
1346    private function stripUnnecessaryIndentPreNowikis(): void {
1347        // FIXME: The solTransparentWikitextRegexp includes redirects, which really
1348        // only belong at the SOF and should be unique. See the "New redirect" test.
1349        $noWikiRegexp = '@^'
1350            . PHPUtils::reStrip( $this->env->getSiteConfig()->solTransparentWikitextNoWsRegexp(), '@' )
1351            . '((?i:<nowiki>\s+</nowiki>))([^\n]*(?:\n|$))' . '@Dm';
1352        $pieces = preg_split( $noWikiRegexp, $this->state->out, -1, PREG_SPLIT_DELIM_CAPTURE );
1353        $out = $pieces[0];
1354        for ( $i = 1;  $i < count( $pieces );  $i += 4 ) {
1355            $out .= $pieces[$i];
1356            $nowiki = $pieces[$i + 1];
1357            $rest = $pieces[$i + 2];
1358            // Ignore comments
1359            preg_match_all( '/<[^!][^<>]*>/', $rest, $htmlTags );
1360
1361            // Not required if just sol transparent wt.
1362            $reqd = !preg_match( $this->env->getSiteConfig()->solTransparentWikitextRegexp(), $rest );
1363
1364            if ( $reqd ) {
1365                foreach ( $htmlTags[0] as $j => $rawTagName ) {
1366                    // Strip </, attributes, and > to get the tagname
1367                    $tagName = preg_replace( '/<\/?|\s.*|>/', '', $rawTagName );
1368                    if ( !isset( Consts::$HTML['HTML5Tags'][$tagName] ) ) {
1369                        // If we encounter any tag that is not a html5 tag,
1370                        // it could be an extension tag. We could do a more complex
1371                        // regexp or tokenize the string to determine if any block tags
1372                        // show up outside the extension tag. But, for now, we just
1373                        // conservatively bail and leave the nowiki as is.
1374                        $reqd = true;
1375                        break;
1376                    } elseif ( TokenUtils::isWikitextBlockTag( $tagName ) ) {
1377                        // FIXME: Extension tags shadowing html5 tags might not
1378                        // have block semantics.
1379                        // Block tags on a line suppress nowikis
1380                        $reqd = false;
1381                    }
1382                }
1383            }
1384
1385            if ( !$reqd ) {
1386                $nowiki = preg_replace( '#^<nowiki>(\s+)</nowiki>#', '$1', $nowiki, 1 );
1387            } else {
1388                $solTransparentWikitextNoWsRegexpFragment = PHPUtils::reStrip(
1389                    $this->env->getSiteConfig()->solTransparentWikitextNoWsRegexp(), '/' );
1390                $wsReplacementRE = '/^(' . $solTransparentWikitextNoWsRegexpFragment . ')\s+/';
1391                // Replace all leading whitespace
1392                do {
1393                    $oldRest = $rest;
1394                    $rest = preg_replace( $wsReplacementRE, '$1', $rest );
1395                } while ( $rest !== $oldRest );
1396
1397                // Protect against sol-sensitive wikitext characters
1398                $solCharsTest = '/^' . $solTransparentWikitextNoWsRegexpFragment . '[=*#:;]/';
1399                $nowiki = preg_replace( '#^<nowiki>(\s+)</nowiki>#',
1400                    preg_match( $solCharsTest, $rest ) ? '<nowiki/>' : '', $nowiki, 1 );
1401            }
1402            $out = $out . $nowiki . $rest . $pieces[$i + 3];
1403        }
1404        $this->state->out = $out;
1405    }
1406
1407    /**
1408     * This implements a heuristic to strip two common sources of <nowiki/>s.
1409     * When <i> and <b> tags are matched up properly,
1410     * - any single ' char before <i> or <b> does not need <nowiki/> protection.
1411     * - any single ' char before </i> or </b> does not need <nowiki/> protection.
1412     * @param string $line
1413     * @return string
1414     */
1415    private function stripUnnecessaryQuoteNowikis( string $line ): string {
1416        if ( !$this->state->hasQuoteNowikis ) {
1417            return $line;
1418        }
1419
1420        // Optimization: We are interested in <nowiki/>s before quote chars.
1421        // So, skip this if we don't have both.
1422        if ( !( preg_match( '#<nowiki\s*/>#', $line ) && preg_match( "/'/", $line ) ) ) {
1423            return $line;
1424        }
1425
1426        // * Split out all the [[ ]] {{ }} '' ''' ''''' <..> </...>
1427        //   parens in the regexp mean that the split segments will
1428        //   be spliced into the result array as the odd elements.
1429        // * If we match up the tags properly and we see opening
1430        //   <i> / <b> / <i><b> tags preceded by a '<nowiki/>, we
1431        //   can remove all those nowikis.
1432        //   Ex: '<nowiki/>''foo'' bar '<nowiki/>'''baz'''
1433        // * If we match up the tags properly and we see closing
1434        //   <i> / <b> / <i><b> tags preceded by a '<nowiki/>, we
1435        //   can remove all those nowikis.
1436        //   Ex: ''foo'<nowiki/>'' bar '''baz'<nowiki/>'''
1437        // phpcs:ignore Generic.Files.LineLength.TooLong
1438        $p = preg_split( "#('''''|'''|''|\[\[|\]\]|\{\{|\}\}|<\w+(?:\s+[^>]*?|\s*?)/?>|</\w+\s*>)#", $line, -1, PREG_SPLIT_DELIM_CAPTURE );
1439
1440        // Which nowiki do we strip out?
1441        $nowikiIndex = -1;
1442
1443        // Verify that everything else is properly paired up.
1444        $stack = [];
1445        $quotesOnStack = 0;
1446        $n = count( $p );
1447        $nonHtmlTag = null;
1448        for ( $j = 1;  $j < $n;  $j += 2 ) {
1449            // For HTML tags, pull out just the tag name for clearer code below.
1450            preg_match( '#^<(/?\w+)#', $p[$j], $matches );
1451            $tag = mb_strtolower( $matches[1] ?? $p[$j] );
1452            $tagLen = strlen( $tag );
1453            $selfClose = false;
1454            if ( str_ends_with( $p[$j], '/>' ) ) {
1455                $tag .= '/';
1456                $selfClose = true;
1457            }
1458
1459            // Ignore non-html-tag (<nowiki> OR extension tag) blocks
1460            if ( !$nonHtmlTag ) {
1461                if ( isset( $this->env->getSiteConfig()->getExtensionTagNameMap()[$tag] ) ) {
1462                    $nonHtmlTag = $tag;
1463                    continue;
1464                }
1465            } else {
1466                if ( $tagLen > 0 && $tag[0] === '/' && substr( $tag, 1 ) === $nonHtmlTag ) {
1467                    $nonHtmlTag = null;
1468                }
1469                continue;
1470            }
1471
1472            if ( $tag === ']]' ) {
1473                if ( array_pop( $stack ) !== '[[' ) {
1474                    return $line;
1475                }
1476            } elseif ( $tag === '}}' ) {
1477                if ( array_pop( $stack ) !== '{{' ) {
1478                    return $line;
1479                }
1480            } elseif ( $tagLen > 0 && $tag[0] === '/' ) { // closing html tag
1481                // match html/ext tags
1482                $openTag = array_pop( $stack );
1483                if ( $tag !== ( '/' . $openTag ) ) {
1484                    return $line;
1485                }
1486            } elseif ( $tag === 'nowiki/' ) {
1487                // We only want to process:
1488                // - trailing single quotes (bar')
1489                // - or single quotes by themselves without a preceding '' sequence
1490                if ( substr( $p[$j - 1], -1 ) === "'"
1491                    && !( $p[$j - 1] === "'" && $j > 1 && substr( $p[$j - 2], -2 ) === "''" )
1492                    // Consider <b>foo<i>bar'</i>baz</b> or <b>foo'<i>bar'</i>baz</b>.
1493                    // The <nowiki/> before the <i> or </i> cannot be stripped
1494                    // if the <i> is embedded inside another quote.
1495                    && ( $quotesOnStack === 0
1496                        // The only strippable scenario with a single quote elt on stack
1497                        // is: ''bar'<nowiki/>''
1498                        //   -> ["", "''", "bar'", "<nowiki/>", "", "''"]
1499                        || ( $quotesOnStack === 1
1500                            && $j + 2 < $n
1501                            && $p[$j + 1] === ''
1502                            && $p[$j + 2][0] === "'"
1503                            && $p[$j + 2] === PHPUtils::lastItem( $stack ) ) )
1504                ) {
1505                    $nowikiIndex = $j;
1506                }
1507                continue;
1508            } elseif ( $selfClose || $tag === 'br' ) {
1509                // Skip over self-closing tags or what should have been self-closed.
1510                // ( While we could do this for all void tags defined in
1511                //   mediawiki.wikitext.constants.js, <br> is the most common
1512                //   culprit. )
1513                continue;
1514            } elseif ( $tagLen > 0 && $tag[0] === "'" && PHPUtils::lastItem( $stack ) === $tag ) {
1515                array_pop( $stack );
1516                $quotesOnStack--;
1517            } else {
1518                $stack[] = $tag;
1519                if ( $tagLen > 0 && $tag[0] === "'" ) {
1520                    $quotesOnStack++;
1521                }
1522            }
1523        }
1524
1525        if ( count( $stack ) ) {
1526            return $line;
1527        }
1528
1529        if ( $nowikiIndex !== -1 ) {
1530            // We can only remove the final trailing nowiki.
1531            //
1532            // HTML  : <i>'foo'</i>
1533            // line  : ''<nowiki/>'foo'<nowiki/>''
1534            $p[$nowikiIndex] = '';
1535            return implode( '', $p );
1536        } else {
1537            return $line;
1538        }
1539    }
1540
1541    /**
1542     * Serialize an HTML DOM.
1543     *
1544     * WARNING: You probably want to use WikitextContentModelHandler::fromDOM instead.
1545     *
1546     * @param Document|DocumentFragment $node
1547     * @param bool $selserMode
1548     * @return string
1549     */
1550    public function serializeDOM(
1551        Node $node, bool $selserMode = false
1552    ): string {
1553        Assert::parameterType(
1554            [ Document::class, DocumentFragment::class ],
1555            $node, '$node' );
1556
1557        if ( $node instanceof Document ) {
1558            $node = DOMCompat::getBody( $node );
1559        }
1560
1561        $this->logType = $selserMode ? 'trace/selser' : 'trace/wts';
1562
1563        $state = $this->state;
1564        $state->initMode( $selserMode );
1565
1566        $domNormalizer = new DOMNormalizer( $state );
1567        $domNormalizer->normalize( $node );
1568
1569        if ( $this->env->hasDumpFlag( 'dom:post-normal' ) ) {
1570            $options = [ 'storeDiffMark' => true ];
1571            $this->env->writeDump( ContentUtils::dumpDOM( $node, 'DOM: post-normal', $options ) );
1572        }
1573
1574        $state->kickOffSerialize( $node );
1575
1576        if ( $state->hasIndentPreNowikis ) {
1577            // FIXME: Perhaps this can be done on a per-line basis
1578            // rather than do one post-pass on the entire document.
1579            $this->stripUnnecessaryIndentPreNowikis();
1580        }
1581
1582        $splitLines = $state->selserMode
1583            || $state->hasQuoteNowikis
1584            || $state->hasSelfClosingNowikis
1585            || $state->hasHeadingEscapes;
1586
1587        if ( $splitLines ) {
1588            $state->out = implode( "\n", array_map( function ( $line ) {
1589                // FIXME: Perhaps this can be done on a per-line basis
1590                // rather than do one post-pass on the entire document.
1591                $line = $this->stripUnnecessaryQuoteNowikis( $line );
1592
1593                return $this->stripUnnecessaryHeadingNowikis( $line );
1594            }, explode( "\n", $state->out ) ) );
1595        }
1596
1597        if ( $state->redirectText && $state->redirectText !== 'unbuffered' ) {
1598            $firstLine = explode( "\n", $state->out, 1 )[0];
1599            $nl = preg_match( '/^(\s|$)/D', $firstLine ) ? '' : "\n";
1600            $state->out = $state->redirectText . $nl . $state->out;
1601        }
1602
1603        return $state->out;
1604    }
1605
1606    /**
1607     * @note Porting note: this replaces the pattern $serializer->env->log( $serializer->logType, ... )
1608     * @param mixed ...$args
1609     */
1610    public function trace( ...$args ) {
1611        $this->env->log( $this->logType, ...$args );
1612    }
1613
1614}