Debian Codegraph @

vendor/wikimedia/parsoid/src/Html2Wt/WikitextSerializer.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Html2Wt;
5
6 use Closure;
7 use Exception;
8 use Wikimedia\Assert\Assert;
9 use Wikimedia\Parsoid\Config\Env;
10 use Wikimedia\Parsoid\Core\InternalException;
11 use Wikimedia\Parsoid\DOM\Comment;
12 use Wikimedia\Parsoid\DOM\Document;
13 use Wikimedia\Parsoid\DOM\DocumentFragment;
14 use Wikimedia\Parsoid\DOM\Element;
15 use Wikimedia\Parsoid\DOM\Node;
16 use Wikimedia\Parsoid\DOM\Text;
17 use Wikimedia\Parsoid\Html2Wt\ConstrainedText\ConstrainedText;
18 use Wikimedia\Parsoid\Html2Wt\DOMHandlers\DOMHandler;
19 use Wikimedia\Parsoid\Html2Wt\DOMHandlers\DOMHandlerFactory;
20 use Wikimedia\Parsoid\NodeData\ParamInfo;
21 use Wikimedia\Parsoid\NodeData\TemplateInfo;
22 use Wikimedia\Parsoid\Tokens\KV;
23 use Wikimedia\Parsoid\Tokens\TagTk;
24 use Wikimedia\Parsoid\Tokens\Token;
25 use Wikimedia\Parsoid\Utils\ContentUtils;
26 use Wikimedia\Parsoid\Utils\DiffDOMUtils;
27 use Wikimedia\Parsoid\Utils\DOMCompat;
28 use Wikimedia\Parsoid\Utils\DOMDataUtils;
29 use Wikimedia\Parsoid\Utils\DOMUtils;
30 use Wikimedia\Parsoid\Utils\PHPUtils;
31 use Wikimedia\Parsoid\Utils\Title;
32 use Wikimedia\Parsoid\Utils\TokenUtils;
33 use Wikimedia\Parsoid\Utils\Utils;
34 use Wikimedia\Parsoid\Utils\WTUtils;
35 use 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 */
66 class 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->topLevelDoc, $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 // PORT-FIXME check type
481 if ( $v !== null && $v !== '' ) {
482 $out[] = $k . '="' . str_replace( '"', '&quot;', $v ) . '"';
483 } else {
484 // at least preserve the key
485 $out[] = $k;
486 }
487 }
488 }
489 }
490 // XXX: round-trip optional whitespace / line breaks etc
491 return implode( ' ', $out );
492 }
493
494 /**
495 * FIXME: Get rid of this function after content version 2.2.0 has expired from caches.
496 *
497 * @param Element $node
498 */
499 public function handleLIHackIfApplicable( Element $node ): void {
500 $liHackSrc = DOMDataUtils::getDataParsoid( $node )->liHackSrc ?? null;
501 $prev = DiffDOMUtils::previousNonSepSibling( $node );
502
503 // If we are dealing with an LI hack, then we must ensure that
504 // we are dealing with either
505 //
506 // 1. A node with no previous sibling inside of a list.
507 //
508 // 2. A node whose previous sibling is a list element.
509 if ( $liHackSrc !== null
510 // Case 1
511 && ( ( $prev === null && DOMUtils::isList( $node->parentNode ) )
512 // Case 2
513 || ( $prev !== null && DOMUtils::isListItem( $prev ) ) )
514 ) {
515 $this->state->emitChunk( $liHackSrc, $node );
516 }
517 }
518
519 private function formatStringSubst( string $format, string $value, bool $forceTrim ): string {
520 // PORT-FIXME: JS is more agressive and removes various unicode whitespaces
521 // (most notably nbsp). Does that matter?
522 if ( $forceTrim ) {
523 $value = trim( $value );
524 }
525 return preg_replace_callback( '/_+/', static function ( $m ) use ( $value ) {
526 if ( $value === '' ) {
527 return $value;
528 }
529 $hole = $m[0];
530 $holeLen = strlen( $hole );
531 $valueLen = mb_strlen( $value );
532 return $holeLen <= $valueLen ? $value : $value . str_repeat( ' ', $holeLen - $valueLen );
533 }, $format, 1 );
534 }
535
536 /**
537 * Generates a template parameter sort function that tries to preserve existing ordering
538 * but also to follow the order prescribed by the templatedata.
539 * @param array $dpArgInfo
540 * @param ?array $tplData
541 * @param array $dataMwKeys
542 * @return Closure
543 */
544 private function createParamComparator(
545 array $dpArgInfo, ?array $tplData, array $dataMwKeys
546 ): Closure {
547 // Record order of parameters in new data-mw
548 $newOrder = [];
549 foreach ( $dataMwKeys as $i => $key ) {
550 $newOrder[$key] = [ 'order' => $i ];
551 }
552 // Record order of parameters in templatedata (if present)
553 $tplDataOrder = [];
554 $aliasMap = [];
555 $keys = [];
556 if ( $tplData && isset( $tplData['paramOrder'] ) ) {
557 foreach ( $tplData['paramOrder'] as $i => $key ) {
558 $tplDataOrder[$key] = [ 'order' => $i ];
559 $aliasMap[$key] = [ 'key' => $key, 'order' => -1 ];
560 $keys[] = $key;
561 // Aliases have the same sort order as the main name.
562 $aliases = $tplData['params'][$key]['aliases'] ?? [];
563 foreach ( $aliases as $j => $alias ) {
564 $aliasMap[$alias] = [ 'key' => $key, 'order' => $j ];
565 }
566 }
567 }
568 // Record order of parameters in original wikitext (from data-parsoid)
569 $origOrder = [];
570 foreach ( $dpArgInfo as $i => $argInfo ) {
571 $origOrder[$argInfo->k] = [ 'order' => $i, 'dist' => 0 ];
572 }
573 // Canonical parameter key gets the same order as an alias parameter
574 // found in the original wikitext.
575 foreach ( $dpArgInfo as $i => $argInfo ) {
576 $canon = $aliasMap[$argInfo->k] ?? null;
577 if ( $canon !== null && !array_key_exists( $canon['key'], $origOrder ) ) {
578 $origOrder[$canon['key']] = $origOrder[$argInfo->k];
579 }
580 }
581 // Find the closest "original parameter" for each templatedata parameter,
582 // so that newly-added parameters are placed near the parameters which
583 // templatedata says they should be adjacent to.
584 $nearestOrder = $origOrder;
585 $reduceF = static function ( $acc, $val ) use ( &$origOrder, &$nearestOrder ) {
586 if ( isset( $origOrder[$val] ) ) {
587 $acc = $origOrder[$val];
588 }
589 if ( !( isset( $nearestOrder[$val] ) && $nearestOrder[$val]['dist'] < $acc['dist'] ) ) {
590 $nearestOrder[$val] = $acc;
591 }
592 return [ 'order' => $acc['order'], 'dist' => $acc['dist'] + 1 ];
593 };
594 // Find closest original parameter before the key.
595 // @phan-suppress-next-line PhanPluginUseReturnValueInternalKnown
596 array_reduce( $keys, $reduceF, [ 'order' => -1, 'dist' => 2 * count( $keys ) ] );
597 // Find closest original parameter after the key.
598 // @phan-suppress-next-line PhanPluginUseReturnValueInternalKnown
599 array_reduce( array_reverse( $keys ), $reduceF,
600 [ 'order' => count( $origOrder ), 'dist' => count( $keys ) ] );
601
602 // Helper function to return a large number if the given key isn't
603 // in the sort order map
604 $big = max( count( $nearestOrder ), count( $newOrder ) );
605 $defaultGet = static function ( $map, $key1, $key2 = null ) use ( &$big ) {
606 $key = ( !$key2 || isset( $map[$key1] ) ) ? $key1 : $key2;
607 return $map[$key]['order'] ?? $big;
608 };
609
610 return static function ( $a, $b ) use (
611 &$aliasMap, &$defaultGet, &$nearestOrder, &$tplDataOrder, &$newOrder
612 ) {
613 $aCanon = $aliasMap[$a] ?? [ 'key' => $a, 'order' => -1 ];
614 $bCanon = $aliasMap[$b] ?? [ 'key' => $b, 'order' => -1 ];
615 // primary key is `nearestOrder` (nearest original parameter)
616 $aOrder = $defaultGet( $nearestOrder, $a, $aCanon['key'] );
617 $bOrder = $defaultGet( $nearestOrder, $b, $bCanon['key'] );
618 if ( $aOrder !== $bOrder ) {
619 return $aOrder - $bOrder;
620 }
621 // secondary key is templatedata order
622 if ( $aCanon['key'] === $bCanon['key'] ) {
623 return $aCanon['order'] - $bCanon['order'];
624 }
625 $aOrder = $defaultGet( $tplDataOrder, $aCanon['key'] );
626 $bOrder = $defaultGet( $tplDataOrder, $bCanon['key'] );
627 if ( $aOrder !== $bOrder ) {
628 return $aOrder - $bOrder;
629 }
630 // tertiary key is original input order (makes sort stable)
631 $aOrder = $defaultGet( $newOrder, $a );
632 $bOrder = $defaultGet( $newOrder, $b );
633 return $aOrder - $bOrder;
634 };
635 }
636
637 /**
638 * Serialize part of a templatelike expression.
639 * @param SerializerState $state
640 * @param string $buf
641 * @param Element $node
642 * @param TemplateInfo $part The expression fragment to serialize. See $srcParts
643 * in serializeFromParts() for format.
644 * @param ?array $tplData Templatedata, see
645 * https://github.com/wikimedia/mediawiki-extensions-TemplateData/blob/master/Specification.md
646 * @param string|TemplateInfo $prevPart Previous part. See $srcParts in serializeFromParts().
647 * @param string|TemplateInfo $nextPart Next part. See $srcParts in serializeFromParts().
648 * @return string
649 */
650 private function serializePart(
651 SerializerState $state, string $buf, Element $node, TemplateInfo $part,
652 ?array $tplData, $prevPart, $nextPart
653 ): string {
654 // Parse custom format specification, if present.
655 $defaultBlockSpc = "{{_\n| _ = _\n}}"; // "block"
656 $defaultInlineSpc = '{{_|_=_}}'; // "inline"
657
658 $format = isset( $tplData['format'] ) ? strtolower( $tplData['format'] ) : null;
659 if ( $format === 'block' ) {
660 $format = $defaultBlockSpc;
661 } elseif ( $format === 'inline' ) {
662 $format = $defaultInlineSpc;
663 }
664 // Check format string for validity.
665 preg_match( self::FORMATSTRING_REGEXP, $format ?? '', $parsedFormat );
666 if ( !$parsedFormat ) {
667 preg_match( self::FORMATSTRING_REGEXP, $defaultInlineSpc, $parsedFormat );
668 $format = null; // Indicates that no valid custom format was present.
669 }
670 $formatSOL = $parsedFormat[1] ?? '';
671 $formatStart = $parsedFormat[2] ?? '';
672 $formatParamName = $parsedFormat[3] ?? '';
673 $formatParamValue = $parsedFormat[4] ?? '';
674 $formatEnd = $parsedFormat[5] ?? '';
675 $formatEOL = $parsedFormat[6] ?? '';
676 $forceTrim = ( $format !== null ) || WTUtils::isNewElt( $node );
677
678 // Shoehorn formatting of top-level templatearg wikitext into this code.
679 if ( $part->type === 'templatearg' ) {
680 $formatStart = preg_replace( '/{{/', '{{{', $formatStart, 1 );
681 $formatEnd = preg_replace( '/}}/', '}}}', $formatEnd, 1 );
682 }
683
684 // handle SOL newline requirement
685 if ( $formatSOL && !str_ends_with( ( $prevPart !== null ) ? $buf : ( $state->sep->src ?? '' ), "\n" ) ) {
686 $buf .= "\n";
687 }
688
689 // open the transclusion
690 $buf .= $this->formatStringSubst( $formatStart, $part->targetWt, $forceTrim );
691
692 // Short-circuit transclusions without params
693 $paramKeys = array_map( fn ( ParamInfo $pi ) => $pi->k, $part->paramInfos );
694 if ( !$paramKeys ) {
695 if ( substr( $formatEnd, 0, 1 ) === "\n" ) {
696 $formatEnd = substr( $formatEnd, 1 );
697 }
698 return $buf . $formatEnd;
699 }
700
701 // Trim whitespace from data-mw keys to deal with non-compliant
702 // clients. Make sure param info is accessible for the stripped key
703 // since later code will be using the stripped key always.
704 $tplKeysFromDataMw = [];
705 foreach ( $part->paramInfos as $pi ) {
706 $strippedKey = trim( $pi->k );
707 $tplKeysFromDataMw[$strippedKey] = $pi;
708 }
709
710 // Per-parameter info from data-parsoid for pre-existing parameters
711 $dp = DOMDataUtils::getDataParsoid( $node );
712 // Account for clients not setting the `i`, see T238721
713 $dpArgInfo = isset( $part->i ) ? ( $dp->pi[$part->i] ?? [] ) : [];
714
715 // Build a key -> arg info map
716 $dpArgInfoMap = [];
717 foreach ( $dpArgInfo as $info ) {
718 $dpArgInfoMap[$info->k] = $info;
719 }
720
721 // 1. Process all parameters and build a map of
722 // arg-name -> [serializeAsNamed, name, value]
723 //
724 // 2. Serialize tpl args in required order
725 //
726 // 3. Format them according to formatParamName/formatParamValue
727
728 $kvMap = [];
729 foreach ( $tplKeysFromDataMw as $key => $param ) {
730 // Storing keys in an array can turn them into ints; stringify.
731 $key = (string)$key;
732 $argInfo = $dpArgInfoMap[$key] ?? [];
733
734 // TODO: Other formats?
735 // Only consider the html parameter if the wikitext one
736 // isn't present at all. If it's present but empty,
737 // that's still considered a valid parameter.
738 if ( $param->valueWt !== null ) {
739 $value = $param->valueWt;
740 } elseif ( $param->html !== null ) {
741 $value = $this->htmlToWikitext( [ 'env' => $this->env ], $param->html );
742 } else {
743 $this->env->log(
744 'error',
745 "params in data-mw part is missing wt/html for $key. " .
746 "Serializing as empty string.",
747 "data-mw part: " . json_encode( $part->toJsonArray() )
748 );
749 $value = "";
750 }
751
752 Assert::invariant( is_string( $value ), "For param: $key, wt property should be a string '
753 . 'but got: $value" );
754
755 $serializeAsNamed = !empty( $argInfo->named );
756
757 // The name is usually equal to the parameter key, but
758 // if there's a key->wt attribute, use that.
759 $name = null;
760 if ( $param->keyWt !== null ) {
761 $name = $param->keyWt;
762 // And make it appear even if there wasn't any data-parsoid information.
763 $serializeAsNamed = true;
764 } else {
765 $name = $key;
766 }
767
768 // Use 'k' as the key, not 'name'.
769 //
770 // The normalized form of 'k' is used as the key in both
771 // data-parsoid and data-mw. The full non-normalized form
772 // is present in '$param->keyWt'
773 $kvMap[$key] = [ 'serializeAsNamed' => $serializeAsNamed, 'name' => $name, 'value' => $value ];
774 }
775
776 $argOrder = array_keys( $kvMap );
777 usort( $argOrder, $this->createParamComparator( $dpArgInfo, $tplData, $argOrder ) );
778
779 $argIndex = 1;
780 $numericIndex = 1;
781
782 $numPositionalArgs = 0;
783 foreach ( $dpArgInfo as $pi ) {
784 if ( isset( $tplKeysFromDataMw[trim( $pi->k )] ) && empty( $pi->named ) ) {
785 $numPositionalArgs++;
786 }
787 }
788
789 $argBuf = [];
790 foreach ( $argOrder as $param ) {
791 $kv = $kvMap[$param];
792 // Add nowiki escapes for the arg value, as required
793 $escapedValue = $this->wteHandlers->escapeTplArgWT( $kv['value'], [
794 'serializeAsNamed' => $kv['serializeAsNamed'] || $param !== $numericIndex,
795 'type' => $part->type,
796 'argPositionalIndex' => $numericIndex,
797 'numPositionalArgs' => $numPositionalArgs,
798 'argIndex' => $argIndex++,
799 'numArgs' => count( $tplKeysFromDataMw ),
800 ] );
801 if ( $escapedValue['serializeAsNamed'] ) {
802 // WS trimming for values of named args
803 $argBuf[] = [ 'dpKey' => $param, 'name' => $kv['name'], 'value' => trim( $escapedValue['v'] ) ];
804 } else {
805 $numericIndex++;
806 // No WS trimming for positional args
807 $argBuf[] = [ 'dpKey' => $param, 'name' => null, 'value' => $escapedValue['v'] ];
808 }
809 }
810
811 // If no explicit format is provided, default format is:
812 // - 'inline' for new args
813 // - whatever format is available from data-parsoid for old args
814 // (aka, overriding formatParamName/formatParamValue)
815 //
816 // If an unedited node OR if paramFormat is unspecified,
817 // this strategy prevents unnecessary normalization
818 // of edited transclusions which don't have valid
819 // templatedata formatting information.
820
821 // "magic case": If the format string ends with a newline, an extra newline is added
822 // between the template name and the first parameter.
823
824 foreach ( $argBuf as $arg ) {
825 $name = $arg['name'];
826 $val = $arg['value'];
827 if ( $name === null ) {
828 // We are serializing a positional parameter.
829 // Whitespace is significant for these and
830 // formatting would change semantics.
831 $name = '';
832 $modFormatParamName = '|_';
833 $modFormatParamValue = '_';
834 } elseif ( $name === '' ) {
835 // No spacing for blank parameters ({{foo|=bar}})
836 // This should be an edge case and probably only for
837 // inline-formatted templates, but we are consciously
838 // forcing this default here. Can revisit if this is
839 // ever a problem.
840 $modFormatParamName = '|_=';
841 $modFormatParamValue = '_';
842 } else {
843 // Preserve existing spacing, esp if there was a comment
844 // embedded in it. Otherwise, follow TemplateData's lead.
845 // NOTE: In either case, we are forcibly normalizing
846 // non-block-formatted transclusions into block formats
847 // by adding missing newlines.
848 $spc = $dpArgInfoMap[$arg['dpKey']]->spc ?? null;
849 if ( $spc && ( !$format || preg_match( Utils::COMMENT_REGEXP, $spc[3] ?? '' ) ) ) {
850 $nl = ( substr( $formatParamName, 0, 1 ) === "\n" ) ? "\n" : '';
851 $modFormatParamName = $nl . '|' . $spc[0] . '_' . $spc[1] . '=' . $spc[2];
852 $modFormatParamValue = '_' . $spc[3];
853 } else {
854 $modFormatParamName = $formatParamName;
855 $modFormatParamValue = $formatParamValue;
856 }
857 }
858
859 // Don't create duplicate newlines.
860 $trailing = preg_match( self::TRAILING_COMMENT_OR_WS_AFTER_NL_REGEXP, $buf );
861 if ( $trailing && substr( $formatParamName, 0, 1 ) === "\n" ) {
862 $modFormatParamName = substr( $formatParamName, 1 );
863 }
864
865 $buf .= $this->formatStringSubst( $modFormatParamName, $name, $forceTrim );
866 $buf .= $this->formatStringSubst( $modFormatParamValue, $val, $forceTrim );
867 }
868
869 // Don't create duplicate newlines.
870 if ( preg_match( self::TRAILING_COMMENT_OR_WS_AFTER_NL_REGEXP, $buf )
871 && substr( $formatEnd, 0, 1 ) === "\n"
872 ) {
873 $buf .= substr( $formatEnd, 1 );
874 } else {
875 $buf .= $formatEnd;
876 }
877
878 if ( $formatEOL ) {
879 if ( $nextPart === null ) {
880 // This is the last part of the block. Add the \n only
881 // if the next non-comment node is not a text node
882 // of if the text node doesn't have a leading \n.
883 $next = DiffDOMUtils::nextNonDeletedSibling( $node );
884 while ( $next instanceof Comment ) {
885 $next = DiffDOMUtils::nextNonDeletedSibling( $next );
886 }
887 if ( !( $next instanceof Text ) || substr( $next->nodeValue, 0, 1 ) !== "\n" ) {
888 $buf .= "\n";
889 }
890 } elseif ( !is_string( $nextPart ) || substr( $nextPart, 0, 1 ) !== "\n" ) {
891 // If nextPart is another template, and it wants a leading nl,
892 // this \n we add here will count towards that because of the
893 // formatSOL check at the top.
894 $buf .= "\n";
895 }
896 }
897
898 return $buf;
899 }
900
901 /**
902 * Serialize a template from its parts.
903 * @param SerializerState $state
904 * @param Element $node
905 * @param list<string|TemplateInfo> $srcParts Template parts
906 * @return string
907 */
908 public function serializeFromParts(
909 SerializerState $state, Element $node, array $srcParts
910 ): string {
911 $useTplData = WTUtils::isNewElt( $node ) || DiffUtils::hasDiffMarkers( $node );
912 $buf = '';
913 foreach ( $srcParts as $i => $part ) {
914 if ( is_string( $part ) ) {
915 $buf .= $part;
916 continue;
917 }
918
919 $prevPart = $srcParts[$i - 1] ?? null;
920 $nextPart = $srcParts[$i + 1] ?? null;
921
922 if ( !isset( $part->targetWt ) ) {
923 // Maybe we should just raise a ClientError
924 $this->env->log( 'error', 'data-mw.parts array is malformed: ',
925 DOMCompat::getOuterHTML( $node ), PHPUtils::jsonEncode( $srcParts ) );
926 continue;
927 }
928
929 // Account for clients leaving off the params array, presumably when empty.
930 // See T291741
931 $part->paramInfos ??= [];
932
933 if ( $part->type === 'templatearg' ) {
934 $buf = $this->serializePart(
935 $state, $buf, $node, $part, null, $prevPart,
936 $nextPart
937 );
938 continue;
939 }
940
941 // transclusion: tpl or parser function?
942 // templates have $part->href
943 // parser functions have $part->func
944
945 // While the API supports fetching multiple template data objects in one call,
946 // we will fetch one at a time to benefit from cached responses.
947 //
948 // Fetch template data for the template
949 $tplData = null;
950 $apiResp = null;
951 if ( isset( $part->href ) && $useTplData ) {
952 // Not a parser function
953 try {
954 $title = Title::newFromText(
955 PHPUtils::stripPrefix( Utils::decodeURIComponent( $part->href ), './' ),
956 $this->env->getSiteConfig()
957 );
958 $tplData = $this->env->getDataAccess()->fetchTemplateData( $this->env->getPageConfig(), $title );
959 } catch ( Exception $err ) {
960 // Log the error, and use default serialization mode.
961 // Better to misformat a transclusion than to lose an edit.
962 $this->env->log( 'error/html2wt/tpldata', $err );
963 }
964 }
965 // If the template doesn't exist, or does but has no TemplateData, ignore it
966 if ( !empty( $tplData['missing'] ) || !empty( $tplData['notemplatedata'] ) ) {
967 $tplData = null;
968 }
969 $buf = $this->serializePart( $state, $buf, $node, $part, $tplData, $prevPart, $nextPart );
970 }
971 return $buf;
972 }
973
974 public function serializeExtensionStartTag( Element $node, SerializerState $state ): string {
975 $dataMw = DOMDataUtils::getDataMw( $node );
976 $extTagName = $dataMw->name;
977
978 // Serialize extension attributes in normalized form as:
979 // key='value'
980 // FIXME: with no dataParsoid, shadow info will mark it as new
981 $attrs = (array)( $dataMw->attrs ?? [] );
982 $extTok = new TagTk( $extTagName, array_map( static function ( $key ) use ( $attrs ) {
983 return new KV( $key, $attrs[$key] );
984 }, array_keys( $attrs ) ) );
985
986 $about = DOMCompat::getAttribute( $node, 'about' );
987 if ( $about !== null ) {
988 $extTok->addAttribute( 'about', $about );
989 }
990 $typeof = DOMCompat::getAttribute( $node, 'typeof' );
991 if ( $typeof !== null ) {
992 $extTok->addAttribute( 'typeof', $typeof );
993 }
994
995 $attrStr = $this->serializeAttributes( $node, $extTok );
996 $src = '<' . $extTagName;
997 if ( $attrStr ) {
998 $src .= ' ' . $attrStr;
999 }
1000 return $src . ( !empty( $dataMw->body ) ? '>' : ' />' );
1001 }
1002
1003 public function defaultExtensionHandler( Element $node, SerializerState $state ): string {
1004 $dp = DOMDataUtils::getDataParsoid( $node );
1005 $dataMw = DOMDataUtils::getDataMw( $node );
1006 $src = $this->serializeExtensionStartTag( $node, $state );
1007 if ( !isset( $dataMw->body ) ) {
1008 return $src; // We self-closed this already.
1009 } elseif ( is_string( $dataMw->body->extsrc ?? null ) ) {
1010 $src .= $dataMw->body->extsrc;
1011 } elseif ( isset( $dp->src ) ) {
1012 $this->env->log(
1013 'error/html2wt/ext',
1014 'Extension data-mw missing for: ' . DOMCompat::getOuterHTML( $node )
1015 );
1016 return $dp->src;
1017 } else {
1018 $this->env->log(
1019 'error/html2wt/ext',
1020 'Extension src unavailable for: ' . DOMCompat::getOuterHTML( $node )
1021 );
1022 }
1023 return $src . '</' . $dataMw->name . '>';
1024 }
1025
1026 /**
1027 * Consolidate separator handling when emitting text.
1028 * @param string $res
1029 * @param Node $node
1030 */
1031 private function serializeText( string $res, Node $node ): void {
1032 $state = $this->state;
1033
1034 // Deal with trailing separator-like text (at least 1 newline and other whitespace)
1035 preg_match( self::$separatorREs['sepSuffixWithNlsRE'], $res, $newSepMatch );
1036 $res = preg_replace( self::$separatorREs['sepSuffixWithNlsRE'], '', $res, 1 );
1037
1038 if ( !$state->inIndentPre ) {
1039 // Strip leading newlines and other whitespace
1040 if ( preg_match( self::$separatorREs['sepPrefixWithNlsRE'], $res, $match ) ) {
1041 $state->appendSep( $match[0] );
1042 $res = substr( $res, strlen( $match[0] ) );
1043 }
1044 }
1045
1046 if ( $state->needsEscaping ) {
1047 $res = Utils::escapeWtEntities( $res );
1048 }
1049 $state->emitChunk( $res, $node );
1050
1051 // Move trailing newlines into the next separator
1052 if ( $newSepMatch ) {
1053 if ( !$state->sep->src ) {
1054 $state->appendSep( $newSepMatch[0] );
1055 } else {
1056 /* SSS FIXME: what are we doing with the stripped NLs?? */
1057 }
1058 }
1059 }
1060
1061 /**
1062 * Serialize the content of a text node
1063 * @param Node $node
1064 * @return Node|null
1065 */
1066 private function serializeTextNode( Node $node ): ?Node {
1067 $this->state->needsEscaping = true;
1068 $this->serializeText( $node->nodeValue, $node );
1069 $this->state->needsEscaping = false;
1070 return $node->nextSibling;
1071 }
1072
1073 /**
1074 * Emit non-separator wikitext that does not need to be escaped.
1075 * @param string $res
1076 * @param Node $node
1077 */
1078 public function emitWikitext( string $res, Node $node ): void {
1079 $this->serializeText( $res, $node );
1080 }
1081
1082 /**
1083 * DOM-based serialization
1084 * @param Element $node
1085 * @param DOMHandler $domHandler
1086 * @return Node|null
1087 */
1088 private function serializeNodeInternal( Element $node, DOMHandler $domHandler ) {
1089 // To serialize a node from source, the node should satisfy these
1090 // conditions:
1091 //
1092 // 1. It should not have a diff marker or be in a modified subtree
1093 // WTS should not be in a subtree with a modification flag that
1094 // applies to every node of a subtree (rather than an indication
1095 // that some node in the subtree is modified).
1096 //
1097 // 2. It should continue to be valid in any surrounding edited context
1098 // For some nodes, modification of surrounding context
1099 // can change serialized output of this node
1100 // (ex: <td>s and whether you emit | or || for them)
1101 //
1102 // 3. It should have valid, usable DSR
1103 //
1104 // 4. Either it has non-zero positive DSR width, or meets one of the
1105 // following:
1106 //
1107 // 4a. It is content like <p><br/><p> or an automatically-inserted
1108 // wikitext <references/> (HTML <ol>) (will have dsr-width 0)
1109 // 4b. it is fostered content (will have dsr-width 0)
1110 // 4c. it is misnested content (will have dsr-width 0)
1111 //
1112 // SSS FIXME: Additionally, we can guard against buggy DSR with
1113 // some validity checks. We can test that non-sep src content
1114 // leading wikitext markup corresponds to the node type.
1115 //
1116 // Ex: If node.nodeName is 'UL', then src[0] should be '*'
1117 //
1118 // TO BE DONE
1119
1120 $state = $this->state;
1121 $wrapperUnmodified = false;
1122 $dp = DOMDataUtils::getDataParsoid( $node );
1123
1124 if ( $state->selserMode
1125 && !$state->inInsertedContent
1126 && WTSUtils::origSrcValidInEditedContext( $state, $node )
1127 && Utils::isValidDSR( $dp->dsr ?? null )
1128 && ( $dp->dsr->end > $dp->dsr->start
1129 // FIXME: <p><br/></p>
1130 // nodes that have dsr width 0 because currently,
1131 // we emit newlines outside the p-nodes. So, this check
1132 // tries to handle that scenario.
1133 || (
1134 $dp->dsr->end === $dp->dsr->start && (
1135 in_array( DOMCompat::nodeName( $node ), [ 'p', 'br' ], true )
1136 || !empty( DOMDataUtils::getDataMw( $node )->autoGenerated )
1137 // FIXME: This is only necessary while outputContentVersion
1138 // 2.1.2 - 2.2.0 are still valid
1139 || DOMUtils::hasTypeOf( $node, 'mw:Placeholder/StrippedTag' )
1140 )
1141 )
1142 || !empty( $dp->fostered )
1143 || !empty( $dp->misnested )
1144 )
1145 ) {
1146 if ( !DiffUtils::hasDiffMarkers( $node ) ) {
1147 // If this HTML node will disappear in wikitext because of
1148 // zero width, then the separator constraints will carry over
1149 // to the node's children.
1150 //
1151 // Since we dont recurse into 'node' in selser mode, we update the
1152 // separator constraintInfo to apply to 'node' and its first child.
1153 //
1154 // We could clear constraintInfo altogether which would be
1155 // correct (but could normalize separators and introduce dirty
1156 // diffs unnecessarily).
1157
1158 $state->currNodeUnmodified = true;
1159
1160 if ( WTUtils::isZeroWidthWikitextElt( $node )
1161 && $node->hasChildNodes()
1162 && ( $state->sep->constraints['constraintInfo']['sepType'] ?? null ) === 'sibling'
1163 ) {
1164 $state->sep->constraints['constraintInfo']['onSOL'] = $state->onSOL;
1165 $state->sep->constraints['constraintInfo']['sepType'] = 'parent-child';
1166 $state->sep->constraints['constraintInfo']['nodeA'] = $node;
1167 $state->sep->constraints['constraintInfo']['nodeB'] = $node->firstChild;
1168 }
1169
1170 $out = $state->getOrigSrc( $dp->dsr ) ?? '';
1171
1172 $this->trace( 'ORIG-src with DSR', static function () use ( $dp, $out ) {
1173 return '[' . $dp->dsr->start . ',' . $dp->dsr->end . '] = '
1174 . PHPUtils::jsonEncode( $out );
1175 } );
1176
1177 // When reusing source, we should only suppress serializing
1178 // to a single line for the cases we've allowed in normal serialization.
1179 // <a> tags might look surprising here, but, here is the rationale.
1180 // If some link syntax (wikilink, extlink, etc.) accepted a newline
1181 // originally, we can safely let it through here. There is no need to have
1182 // specific checks for wikilnks / extlinks / ... etc. The only concern is
1183 // if the surrounding context in which this link-syntax is embedded also
1184 // breaks the link syntax. There is no such syntax right now.
1185 // FIXME: Note the limitation here, that if these nodes are nested
1186 // in something as trivial as an i / b, the suppression won't happen
1187 // and we'll dirty the text.
1188 $suppressSLC = WTUtils::isFirstEncapsulationWrapperNode( $node )
1189 || DOMUtils::hasTypeOf( $node, 'mw:Nowiki' )
1190 || in_array( DOMCompat::nodeName( $node ), [ 'dl', 'ul', 'ol', 'a' ], true )
1191 || ( DOMCompat::nodeName( $node ) === 'table'
1192 && DOMCompat::nodeName( $node->parentNode ) === 'dd'
1193 && DiffDOMUtils::previousNonSepSibling( $node ) === null );
1194
1195 // Use selser to serialize this text! The original
1196 // wikitext is `out`. But first allow
1197 // `ConstrainedText.fromSelSer` to figure out the right
1198 // type of ConstrainedText chunk(s) to use to represent
1199 // `out`, based on the node type. Since we might actually
1200 // have to break this wikitext into multiple chunks,
1201 // `fromSelSer` returns an array.
1202 if ( $suppressSLC ) {
1203 $state->singleLineContext->disable();
1204 }
1205 foreach ( ConstrainedText::fromSelSer( $out, $node, $dp, $this->env ) as $ct ) {
1206 $state->emitChunk( $ct, $ct->node );
1207 }
1208 if ( $suppressSLC ) {
1209 $state->singleLineContext->pop();
1210 }
1211
1212 // Skip over encapsulated content since it has already been
1213 // serialized.
1214 if ( WTUtils::isFirstEncapsulationWrapperNode( $node ) ) {
1215 return WTUtils::skipOverEncapsulatedContent( $node );
1216 } else {
1217 return $node->nextSibling;
1218 }
1219 }
1220
1221 $wrapperUnmodified = DiffUtils::onlySubtreeChanged( $node ) &&
1222 WTSUtils::hasValidTagWidths( $dp->dsr ?? null );
1223 }
1224
1225 $state->currNodeUnmodified = false;
1226
1227 $currentInsertedState = $state->inInsertedContent;
1228
1229 $inInsertedContent = $state->selserMode && DiffUtils::hasInsertedDiffMark( $node );
1230
1231 if ( $inInsertedContent ) {
1232 $state->inInsertedContent = true;
1233 }
1234
1235 $next = $domHandler->handle( $node, $state, $wrapperUnmodified );
1236
1237 if ( $inInsertedContent ) {
1238 $state->inInsertedContent = $currentInsertedState;
1239 }
1240
1241 return $next;
1242 }
1243
1244 /**
1245 * Internal worker. Recursively serialize a DOM subtree.
1246 * @private
1247 * @param Node $node
1248 * @return ?Node
1249 */
1250 public function serializeNode( Node $node ): ?Node {
1251 $nodeName = DOMCompat::nodeName( $node );
1252 $domHandler = $method = null;
1253 $domHandlerFactory = new DOMHandlerFactory();
1254 $state = $this->state;
1255 $state->currNode = $node;
1256
1257 if ( $state->selserMode ) {
1258 $this->trace(
1259 static function () use ( $node ) {
1260 return WTSUtils::traceNodeName( $node );
1261 },
1262 '; prev-unmodified: ', $state->prevNodeUnmodified,
1263 '; SOL: ', $state->onSOL );
1264 } else {
1265 $this->trace(
1266 static function () use ( $node ) {
1267 return WTSUtils::traceNodeName( $node );
1268 },
1269 '; SOL: ', $state->onSOL );
1270 }
1271
1272 switch ( $node->nodeType ) {
1273 case XML_ELEMENT_NODE:
1274 '@phan-var Element $node';/** @var Element $node */
1275 // Ignore DiffMarker metas, but clear unmodified node state
1276 if ( DiffUtils::isDiffMarker( $node ) ) {
1277 $state->updateModificationFlags( $node );
1278 // `state.sep.lastSourceNode` is cleared here so that removed
1279 // separators between otherwise unmodified nodes don't get
1280 // restored.
1281 $state->updateSep( $node );
1282 return $node->nextSibling;
1283 }
1284 $domHandler = $domHandlerFactory->getDOMHandler( $node );
1285 $method = [ $this, 'serializeNodeInternal' ];
1286 break;
1287 case XML_TEXT_NODE:
1288 // This code assumes that the DOM is in normalized form with no
1289 // run of text nodes.
1290 // Accumulate whitespace from the text node into state.sep.src
1291 $text = $node->nodeValue;
1292 if ( !$state->inIndentPre
1293 // PORT-FIXME: original uses this->state->serializer->separatorREs
1294 // but that does not seem useful
1295 && preg_match( self::$separatorREs['pureSepRE'], $text )
1296 ) {
1297 $state->appendSep( $text );
1298 return $node->nextSibling;
1299 }
1300 if ( $state->selserMode ) {
1301 $prev = $node->previousSibling;
1302 if ( !$state->inInsertedContent && (
1303 ( !$prev && DOMUtils::atTheTop( $node->parentNode ) ) ||
1304 ( $prev && !DiffUtils::isDiffMarker( $prev ) )
1305 ) ) {
1306 $state->currNodeUnmodified = true;
1307 } else {
1308 $state->currNodeUnmodified = false;
1309 }
1310 }
1311
1312 $domHandler = new DOMHandler( false );
1313 $method = [ $this, 'serializeTextNode' ];
1314 break;
1315 case XML_COMMENT_NODE:
1316 // Merge this into separators
1317 $state->appendSep( WTSUtils::commentWT( $node->nodeValue ) );
1318 return $node->nextSibling;
1319 default:
1320 throw new InternalException( 'Unhandled node type: ' . $node->nodeType );
1321 }
1322
1323 $prev = DiffDOMUtils::previousNonSepSibling( $node ) ?: $node->parentNode;
1324 $this->env->log( 'debug/wts', 'Before constraints for ' . $nodeName );
1325 $state->separators->updateSeparatorConstraints(
1326 $prev, $domHandlerFactory->getDOMHandler( $prev ),
1327 $node, $domHandler
1328 );
1329
1330 $this->env->log( 'debug/wts', 'Calling serialization handler for ' . $nodeName );
1331 $nextNode = call_user_func( $method, $node, $domHandler );
1332
1333 $next = DiffDOMUtils::nextNonSepSibling( $node ) ?: $node->parentNode;
1334 $this->env->log( 'debug/wts', 'After constraints for ' . $nodeName );
1335 $state->separators->updateSeparatorConstraints(
1336 $node, $domHandler,
1337 $next, $domHandlerFactory->getDOMHandler( $next )
1338 );
1339
1340 // Update modification flags
1341 $state->updateModificationFlags( $node );
1342
1343 return $nextNode;
1344 }
1345
1346 private function stripUnnecessaryHeadingNowikis( string $line ): string {
1347 $state = $this->state;
1348 if ( !$state->hasHeadingEscapes ) {
1349 return $line;
1350 }
1351
1352 $escaper = static function ( string $wt ) use ( $state ) {
1353 $ret = $state->serializer->wteHandlers->escapedText( $state, false, $wt, false, true );
1354 return $ret;
1355 };
1356
1357 preg_match( self::HEADING_NOWIKI_REGEXP, $line, $match );
1358 if ( $match && !preg_match( self::COMMENT_OR_WS_REGEXP, $match[2] ) ) {
1359 // The nowikiing was spurious since the trailing = is not in EOL position
1360 return $escaper( $match[1] ) . $match[2];
1361 } else {
1362 // All is good.
1363 return $line;
1364 }
1365 }
1366
1367 private function stripUnnecessaryIndentPreNowikis(): void {
1368 // FIXME: The solTransparentWikitextRegexp includes redirects, which really
1369 // only belong at the SOF and should be unique. See the "New redirect" test.
1370 $noWikiRegexp = '@^'
1371 . PHPUtils::reStrip( $this->env->getSiteConfig()->solTransparentWikitextNoWsRegexp(), '@' )
1372 . '((?i:<nowiki>\s+</nowiki>))([^\n]*(?:\n|$))' . '@Dm';
1373 $pieces = preg_split( $noWikiRegexp, $this->state->out, -1, PREG_SPLIT_DELIM_CAPTURE );
1374 $out = $pieces[0];
1375 for ( $i = 1; $i < count( $pieces ); $i += 4 ) {
1376 $out .= $pieces[$i];
1377 $nowiki = $pieces[$i + 1];
1378 $rest = $pieces[$i + 2];
1379 // Ignore comments
1380 preg_match_all( '/<[^!][^<>]*>/', $rest, $htmlTags );
1381
1382 // Not required if just sol transparent wt.
1383 $reqd = !preg_match( $this->env->getSiteConfig()->solTransparentWikitextRegexp(), $rest );
1384
1385 if ( $reqd ) {
1386 foreach ( $htmlTags[0] as $j => $rawTagName ) {
1387 // Strip </, attributes, and > to get the tagname
1388 $tagName = preg_replace( '/<\/?|\s.*|>/', '', $rawTagName );
1389 if ( !isset( Consts::$HTML['HTML5Tags'][$tagName] ) ) {
1390 // If we encounter any tag that is not a html5 tag,
1391 // it could be an extension tag. We could do a more complex
1392 // regexp or tokenize the string to determine if any block tags
1393 // show up outside the extension tag. But, for now, we just
1394 // conservatively bail and leave the nowiki as is.
1395 $reqd = true;
1396 break;
1397 } elseif ( TokenUtils::isWikitextBlockTag( $tagName ) ) {
1398 // FIXME: Extension tags shadowing html5 tags might not
1399 // have block semantics.
1400 // Block tags on a line suppress nowikis
1401 $reqd = false;
1402 }
1403 }
1404 }
1405
1406 if ( !$reqd ) {
1407 $nowiki = preg_replace( '#^<nowiki>(\s+)</nowiki>#', '$1', $nowiki, 1 );
1408 } else {
1409 $solTransparentWikitextNoWsRegexpFragment = PHPUtils::reStrip(
1410 $this->env->getSiteConfig()->solTransparentWikitextNoWsRegexp(), '/' );
1411 $wsReplacementRE = '/^(' . $solTransparentWikitextNoWsRegexpFragment . ')\s+/';
1412 // Replace all leading whitespace
1413 do {
1414 $oldRest = $rest;
1415 $rest = preg_replace( $wsReplacementRE, '$1', $rest );
1416 } while ( $rest !== $oldRest );
1417
1418 // Protect against sol-sensitive wikitext characters
1419 $solCharsTest = '/^' . $solTransparentWikitextNoWsRegexpFragment . '[=*#:;]/';
1420 $nowiki = preg_replace( '#^<nowiki>(\s+)</nowiki>#',
1421 preg_match( $solCharsTest, $rest ) ? '<nowiki/>' : '', $nowiki, 1 );
1422 }
1423 $out = $out . $nowiki . $rest . $pieces[$i + 3];
1424 }
1425 $this->state->out = $out;
1426 }
1427
1428 /**
1429 * This implements a heuristic to strip two common sources of <nowiki/>s.
1430 * When <i> and <b> tags are matched up properly,
1431 * - any single ' char before <i> or <b> does not need <nowiki/> protection.
1432 * - any single ' char before </i> or </b> does not need <nowiki/> protection.
1433 * @param string $line
1434 * @return string
1435 */
1436 private function stripUnnecessaryQuoteNowikis( string $line ): string {
1437 if ( !$this->state->hasQuoteNowikis ) {
1438 return $line;
1439 }
1440
1441 // Optimization: We are interested in <nowiki/>s before quote chars.
1442 // So, skip this if we don't have both.
1443 if ( !( preg_match( '#<nowiki\s*/>#', $line ) && preg_match( "/'/", $line ) ) ) {
1444 return $line;
1445 }
1446
1447 // * Split out all the [[ ]] {{ }} '' ''' ''''' <..> </...>
1448 // parens in the regexp mean that the split segments will
1449 // be spliced into the result array as the odd elements.
1450 // * If we match up the tags properly and we see opening
1451 // <i> / <b> / <i><b> tags preceded by a '<nowiki/>, we
1452 // can remove all those nowikis.
1453 // Ex: '<nowiki/>''foo'' bar '<nowiki/>'''baz'''
1454 // * If we match up the tags properly and we see closing
1455 // <i> / <b> / <i><b> tags preceded by a '<nowiki/>, we
1456 // can remove all those nowikis.
1457 // Ex: ''foo'<nowiki/>'' bar '''baz'<nowiki/>'''
1458 // phpcs:ignore Generic.Files.LineLength.TooLong
1459 $p = preg_split( "#('''''|'''|''|\[\[|\]\]|\{\{|\}\}|<\w+(?:\s+[^>]*?|\s*?)/?>|</\w+\s*>)#", $line, -1, PREG_SPLIT_DELIM_CAPTURE );
1460
1461 // Which nowiki do we strip out?
1462 $nowikiIndex = -1;
1463
1464 // Verify that everything else is properly paired up.
1465 $stack = [];
1466 $quotesOnStack = 0;
1467 $n = count( $p );
1468 $nonHtmlTag = null;
1469 for ( $j = 1; $j < $n; $j += 2 ) {
1470 // For HTML tags, pull out just the tag name for clearer code below.
1471 preg_match( '#^<(/?\w+)#', $p[$j], $matches );
1472 $tag = mb_strtolower( $matches[1] ?? $p[$j] );
1473 $tagLen = strlen( $tag );
1474 $selfClose = false;
1475 if ( str_ends_with( $p[$j], '/>' ) ) {
1476 $tag .= '/';
1477 $selfClose = true;
1478 }
1479
1480 // Ignore non-html-tag (<nowiki> OR extension tag) blocks
1481 if ( !$nonHtmlTag ) {
1482 if ( isset( $this->env->getSiteConfig()->getExtensionTagNameMap()[$tag] ) ) {
1483 $nonHtmlTag = $tag;
1484 continue;
1485 }
1486 } else {
1487 if ( $tagLen > 0 && $tag[0] === '/' && substr( $tag, 1 ) === $nonHtmlTag ) {
1488 $nonHtmlTag = null;
1489 }
1490 continue;
1491 }
1492
1493 if ( $tag === ']]' ) {
1494 if ( array_pop( $stack ) !== '[[' ) {
1495 return $line;
1496 }
1497 } elseif ( $tag === '}}' ) {
1498 if ( array_pop( $stack ) !== '{{' ) {
1499 return $line;
1500 }
1501 } elseif ( $tagLen > 0 && $tag[0] === '/' ) { // closing html tag
1502 // match html/ext tags
1503 $openTag = array_pop( $stack );
1504 if ( $tag !== ( '/' . $openTag ) ) {
1505 return $line;
1506 }
1507 } elseif ( $tag === 'nowiki/' ) {
1508 // We only want to process:
1509 // - trailing single quotes (bar')
1510 // - or single quotes by themselves without a preceding '' sequence
1511 if ( substr( $p[$j - 1], -1 ) === "'"
1512 && !( $p[$j - 1] === "'" && $j > 1 && substr( $p[$j - 2], -2 ) === "''" )
1513 // Consider <b>foo<i>bar'</i>baz</b> or <b>foo'<i>bar'</i>baz</b>.
1514 // The <nowiki/> before the <i> or </i> cannot be stripped
1515 // if the <i> is embedded inside another quote.
1516 && ( $quotesOnStack === 0
1517 // The only strippable scenario with a single quote elt on stack
1518 // is: ''bar'<nowiki/>''
1519 // -> ["", "''", "bar'", "<nowiki/>", "", "''"]
1520 || ( $quotesOnStack === 1
1521 && $j + 2 < $n
1522 && $p[$j + 1] === ''
1523 && $p[$j + 2][0] === "'"
1524 && $p[$j + 2] === PHPUtils::lastItem( $stack ) ) )
1525 ) {
1526 $nowikiIndex = $j;
1527 }
1528 continue;
1529 } elseif ( $selfClose || $tag === 'br' ) {
1530 // Skip over self-closing tags or what should have been self-closed.
1531 // ( While we could do this for all void tags defined in
1532 // mediawiki.wikitext.constants.js, <br> is the most common
1533 // culprit. )
1534 continue;
1535 } elseif ( $tagLen > 0 && $tag[0] === "'" && PHPUtils::lastItem( $stack ) === $tag ) {
1536 array_pop( $stack );
1537 $quotesOnStack--;
1538 } else {
1539 $stack[] = $tag;
1540 if ( $tagLen > 0 && $tag[0] === "'" ) {
1541 $quotesOnStack++;
1542 }
1543 }
1544 }
1545
1546 if ( count( $stack ) ) {
1547 return $line;
1548 }
1549
1550 if ( $nowikiIndex !== -1 ) {
1551 // We can only remove the final trailing nowiki.
1552 //
1553 // HTML : <i>'foo'</i>
1554 // line : ''<nowiki/>'foo'<nowiki/>''
1555 $p[$nowikiIndex] = '';
1556 return implode( '', $p );
1557 } else {
1558 return $line;
1559 }
1560 }
1561
1562 /**
1563 * Serialize an HTML DOM.
1564 *
1565 * WARNING: You probably want to use WikitextContentModelHandler::fromDOM instead.
1566 *
1567 * @param Document|DocumentFragment $node
1568 * @param bool $selserMode
1569 * @return string
1570 */
1571 public function serializeDOM(
1572 Node $node, bool $selserMode = false
1573 ): string {
1574 Assert::parameterType(
1575 Document::class . '|' . DocumentFragment::class,
1576 $node, '$node' );
1577
1578 if ( $node instanceof Document ) {
1579 $node = DOMCompat::getBody( $node );
1580 }
1581
1582 $this->logType = $selserMode ? 'trace/selser' : 'trace/wts';
1583
1584 $state = $this->state;
1585 $state->initMode( $selserMode );
1586
1587 $domNormalizer = new DOMNormalizer( $state );
1588 $domNormalizer->normalize( $node );
1589
1590 if ( $this->env->hasDumpFlag( 'dom:post-normal' ) ) {
1591 $options = [ 'storeDiffMark' => true ];
1592 $this->env->writeDump( ContentUtils::dumpDOM( $node, 'DOM: post-normal', $options ) );
1593 }
1594
1595 $state->kickOffSerialize( $node );
1596
1597 if ( $state->hasIndentPreNowikis ) {
1598 // FIXME: Perhaps this can be done on a per-line basis
1599 // rather than do one post-pass on the entire document.
1600 $this->stripUnnecessaryIndentPreNowikis();
1601 }
1602
1603 $splitLines = $state->selserMode
1604 || $state->hasQuoteNowikis
1605 || $state->hasSelfClosingNowikis
1606 || $state->hasHeadingEscapes;
1607
1608 if ( $splitLines ) {
1609 $state->out = implode( "\n", array_map( function ( $line ) {
1610 // FIXME: Perhaps this can be done on a per-line basis
1611 // rather than do one post-pass on the entire document.
1612 $line = $this->stripUnnecessaryQuoteNowikis( $line );
1613
1614 return $this->stripUnnecessaryHeadingNowikis( $line );
1615 }, explode( "\n", $state->out ) ) );
1616 }
1617
1618 if ( $state->redirectText && $state->redirectText !== 'unbuffered' ) {
1619 $firstLine = explode( "\n", $state->out, 1 )[0];
1620 $nl = preg_match( '/^(\s|$)/D', $firstLine ) ? '' : "\n";
1621 $state->out = $state->redirectText . $nl . $state->out;
1622 }
1623
1624 return $state->out;
1625 }
1626
1627 /**
1628 * @note Porting note: this replaces the pattern $serializer->env->log( $serializer->logType, ... )
1629 * @param mixed ...$args
1630 */
1631 public function trace( ...$args ) {
1632 $this->env->log( $this->logType, ...$args );
1633 }
1634
1635 }