Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
4.26% covered (danger)
4.26%
34 / 798
0.00% covered (danger)
0.00%
0 / 25
CRAP
0.00% covered (danger)
0.00%
0 / 1
WikiLinkHandler
4.26% covered (danger)
4.26%
34 / 798
0.00% covered (danger)
0.00%
0 / 25
50365.48
0.00% covered (danger)
0.00%
0 / 1
 hrefParts
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 __construct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 getWikiLinkTargetInfo
55.74% covered (warning)
55.74%
34 / 61
0.00% covered (danger)
0.00%
0 / 1
38.20
 onRedirect
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
30
 bailTokens
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
6
 onWikiLink
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
182
 wikiLinkHandler
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
156
 buildLinkAttrs
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
156
 addLinkAttributesAndGetContent
0.00% covered (danger)
0.00%
0 / 77
0.00% covered (danger)
0.00%
0 / 1
1056
 renderWikiLink
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 renderCategory
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
42
 renderLanguageLink
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 renderInterwikiLink
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
 getWrapperInfo
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
72
 getOptionInfo
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
42
 isWikitextOpt
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 stringifyOptionTokens
0.00% covered (danger)
0.00%
0 / 61
0.00% covered (danger)
0.00%
0 / 1
702
 getFormat
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getUsed
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 hasTransclusion
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 renderFile
0.00% covered (danger)
0.00%
0 / 243
0.00% covered (danger)
0.00%
0 / 1
4032
 getUploadUrl
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 linkToMedia
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
42
 renderMedia
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 onTag
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2declare( strict_types = 1 );
3
4/**
5 * Simple link handler.
6 *
7 * TODO: keep round-trip information in meta tag or the like
8 */
9
10namespace Wikimedia\Parsoid\Wt2Html\TT;
11
12use stdClass;
13use Wikimedia\Assert\Assert;
14use Wikimedia\Parsoid\Config\Env;
15use Wikimedia\Parsoid\Core\DOMCompat;
16use Wikimedia\Parsoid\Core\DomSourceRange;
17use Wikimedia\Parsoid\Core\InternalException;
18use Wikimedia\Parsoid\Core\LinkTarget;
19use Wikimedia\Parsoid\Core\Sanitizer;
20use Wikimedia\Parsoid\Core\SourceRange;
21use Wikimedia\Parsoid\Language\Language;
22use Wikimedia\Parsoid\NodeData\DataMw;
23use Wikimedia\Parsoid\NodeData\DataMwAttrib;
24use Wikimedia\Parsoid\NodeData\DataMwError;
25use Wikimedia\Parsoid\NodeData\DataParsoid;
26use Wikimedia\Parsoid\NodeData\TempData;
27use Wikimedia\Parsoid\Tokens\EndTagTk;
28use Wikimedia\Parsoid\Tokens\EOFTk;
29use Wikimedia\Parsoid\Tokens\KV;
30use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
31use Wikimedia\Parsoid\Tokens\TagTk;
32use Wikimedia\Parsoid\Tokens\Token;
33use Wikimedia\Parsoid\Tokens\XMLTagTk;
34use Wikimedia\Parsoid\Utils\DOMUtils;
35use Wikimedia\Parsoid\Utils\PHPUtils;
36use Wikimedia\Parsoid\Utils\PipelineUtils;
37use Wikimedia\Parsoid\Utils\Title;
38use Wikimedia\Parsoid\Utils\TitleException;
39use Wikimedia\Parsoid\Utils\TokenUtils;
40use Wikimedia\Parsoid\Utils\Utils;
41use Wikimedia\Parsoid\Wikitext\Consts;
42use Wikimedia\Parsoid\Wt2Html\PipelineContentCache;
43use Wikimedia\Parsoid\Wt2Html\TokenHandlerPipeline;
44
45class WikiLinkHandler extends XMLTagBasedHandler {
46    private static bool $cachingEnabled = true;
47
48    /**
49     * @return ?array{prefix: string, title: string}
50     */
51    private static function hrefParts( string $str ): ?array {
52        if ( preg_match( '/^([^:]+):(.*)$/D', $str, $matches ) ) {
53            return [ 'prefix' => $matches[1], 'title' => $matches[2] ];
54        } else {
55            return null;
56        }
57    }
58
59    private ?PipelineContentCache $wikilinkCache = null;
60
61    /** @inheritDoc */
62    public function __construct( TokenHandlerPipeline $manager, array $options ) {
63        parent::__construct( $manager, $options );
64
65        // Cache only on seeing the same source the fourth time.
66        // This minimizes cache bloat & token cloning penalties
67        // and reserving benefits for links seen at least 5 times.
68        if ( self::$cachingEnabled ) {
69            $this->wikilinkCache = $this->manager->getEnv()->getCache(
70                "wikilink",
71                [ "repeatThreshold" => 3, "cloneValue" => true ]
72            );
73        }
74    }
75
76    /**
77     * Normalize and analyze a wikilink target.
78     *
79     * Returns an object containing
80     * - href: The expanded target string
81     * - hrefSrc: The original target wikitext
82     * - title: A title object *or*
83     * - language: An interwikiInfo object *or*
84     * - interwiki: An interwikiInfo object.
85     * - localprefix: Set if the link had a localinterwiki prefix (or prefixes)
86     * - fromColonEscapedText: Target was colon-escaped ([[:en:foo]])
87     * - prefix: The original namespace or language/interwiki prefix without a
88     *   colon escape.
89     *
90     * @param Token $token
91     * @param string $href
92     * @param string $hrefSrc
93     * @return stdClass The target info.
94     * @throws InternalException
95     */
96    private function getWikiLinkTargetInfo( Token $token, string $href, string $hrefSrc ): stdClass {
97        $env = $this->env;
98        $siteConfig = $env->getSiteConfig();
99        $info = (object)[
100            'href' => $href,
101            'hrefSrc' => $hrefSrc,
102            // Initialize these properties to avoid isset checks
103            'interwiki' => null,
104            'language' => null,
105            'localprefix' => null,
106            'fromColonEscapedText' => null
107        ];
108
109        // Capture the title to resolve before handling colon escape
110        $title = Utils::decodeURIComponent( $info->href );
111
112        if ( str_starts_with( ltrim( $info->href ), ':' ) ) {
113            $info->fromColonEscapedText = true;
114            // Remove the colon escape
115            $info->href = substr( ltrim( $info->href ), 1 );
116        }
117        if ( str_starts_with( $info->href, ':' ) ) {
118            if ( $env->linting( 'multi-colon-escape' ) ) {
119                $lint = [
120                    'dsr' => DomSourceRange::fromTsr( $token->dataParsoid->tsr ),
121                    'params' => [ 'href' => ':' . $info->href ],
122                    'templateInfo' => null
123                ];
124                if ( $this->options['inTemplate'] ) {
125                    // Match Linter.findEnclosingTemplateName(), by first
126                    // converting the title to an href using env.makeLink
127                    $name = PHPUtils::stripPrefix(
128                        $env->makeLink( $this->manager->getFrame()->getTitle() ),
129                        './'
130                    );
131                    $lint['templateInfo'] = [ 'name' => $name ];
132                    // TODO(arlolra): Pass tsr info to the frame (T405759)
133                    $lint['dsr'] = new DomSourceRange( 0, 0, null, null, source: null );
134                }
135                $env->recordLint( 'multi-colon-escape', $lint );
136            }
137            // This will get caught by the caller, and mark the target as invalid
138            throw new InternalException( 'Multiple colons prefixing href.' );
139        }
140
141        $hrefBits = self::hrefParts( $info->href );
142        if ( $hrefBits ) {
143            $nsPrefix = $hrefBits['prefix'];
144            $info->prefix = $nsPrefix;
145            $nnn = Utils::normalizeNamespaceName( trim( $nsPrefix ) );
146            $interwikiInfo = $siteConfig->interwikiMapNoNamespaces()[$nnn] ?? null;
147            // check for interwiki / language links
148            $ns = $siteConfig->namespaceId( $nnn );
149            // also check for url to protect against [[constructor:foo]]
150            if ( $ns !== null ) {
151                $info->title = $env->makeTitleFromURLDecodedStr( $title );
152            } elseif ( isset( $interwikiInfo['localinterwiki'] ) ) {
153                if ( $hrefBits['title'] === '' ) {
154                    // Empty title => main page (T66167)
155                    $info->title = Title::newFromLinkTarget(
156                        $siteConfig->mainPageLinkTarget(), $siteConfig
157                    );
158                } else {
159                    $info->href = str_contains( $hrefBits['title'], ':' )
160                        ? ':' . $hrefBits['title'] : $hrefBits['title'];
161                    // Recurse!
162                    $info = $this->getWikiLinkTargetInfo( $token, $info->href, $info->hrefSrc );
163                    $info->localprefix = $nsPrefix .
164                        ( $info->localprefix ? ( ':' . $info->localprefix ) : '' );
165                }
166            } elseif ( !empty( $interwikiInfo['url'] ) ) {
167                $info->href = $hrefBits['title'];
168                // Ensure a valid title and store it for later use.
169                // (don't store as $info->title because that signals a wikilink)
170                $interwikiInfo['title'] = $env->makeTitleFromURLDecodedStr( $title );
171                // Interwiki or language link? If no language info, or if it starts
172                // with an explicit ':' (like [[:en:Foo]]), it's not a language link.
173                if ( $info->fromColonEscapedText ||
174                    ( !isset( $interwikiInfo['language'] ) && !isset( $interwikiInfo['extralanglink'] ) )
175                ) {
176                    // An interwiki link.
177                    $info->interwiki = $interwikiInfo;
178                    // Remove the colon escape after an interwiki prefix
179                    if ( str_starts_with( ltrim( $info->href ), ':' ) ) {
180                        $info->href = substr( ltrim( $info->href ), 1 );
181                    }
182                } else {
183                    // A language link.
184                    $info->language = $interwikiInfo;
185                }
186            } else {
187                $info->title = $env->makeTitleFromURLDecodedStr( $title );
188            }
189        } else {
190            $info->title = $env->makeTitleFromURLDecodedStr( $title );
191        }
192
193        return $info;
194    }
195
196    /**
197     * Handle mw:redirect tokens
198     *
199     * @param Token $token
200     * @return array<string|Token>
201     * @throws InternalException
202     */
203    private function onRedirect( Token $token ): array {
204        // Avoid duplicating the link-processing code by invoking the
205        // standard onWikiLink handler on the embedded link, intercepting
206        // the generated tokens using the callback mechanism, reading
207        // the href from the result, and then creating a
208        // <link rel="mw:PageProp/redirect"> token from it.
209
210        $rlink = new SelfclosingTagTk( 'link',
211            Utils::cloneArray( $token->attribs ?? [] ),
212            clone $token->dataParsoid,
213            $token->dataMw ? clone $token->dataMw : null );
214        $wikiLinkTk = $rlink->dataParsoid->linkTk;
215        $rlink->setAttribute( 'rel', 'mw:PageProp/redirect' );
216
217        // Remove the nested wikiLinkTk token and the cloned href attribute
218        unset( $rlink->dataParsoid->linkTk );
219        $rlink->removeAttribute( 'href' );
220
221        // Transfer href attribute back to wikiLinkTk, since it may have been
222        // template-expanded in the pipeline prior to this point.
223        $wikiLinkTk->attribs = Utils::cloneArray( $token->attribs ?? [] );
224
225        // Set "redirect" attribute on the wikilink token to indicate that
226        // image and category links should be handled as plain links.
227        $wikiLinkTk->setAttribute( 'redirect', 'true' );
228
229        // Render the wikilink (including interwiki links, etc) then collect
230        // the resulting href and transfer it to rlink.
231        $r = $this->onWikiLink( $wikiLinkTk );
232        $firstToken = ( $r[0] ?? null );
233        $isValid = $firstToken instanceof XMLTagTk &&
234            in_array( $firstToken->getName(), [ 'a', 'link' ], true );
235        if ( $isValid ) {
236            $da = $r[0]->dataParsoid;
237            $rlink->addNormalizedAttribute( 'href', $da->a['href'], $da->sa['href'] );
238            return [ $rlink ];
239        } else {
240            // Bail!  Emit tokens as if they were parsed as a list item:
241            // #REDIRECT....
242            $src = $rlink->dataParsoid->src;
243            $tsr = $rlink->dataParsoid->tsr;
244            preg_match( '/^([^#]*)(#)/', $src, $srcMatch );
245            $ntokens = strlen( $srcMatch[1] ) ? [ $srcMatch[1] ] : [];
246            $hashPos = $tsr->start + strlen( $srcMatch[1] );
247            $tsr0 = new SourceRange( $hashPos, $hashPos + 1, $tsr->source );
248            $dp = new DataParsoid;
249            $dp->tsr = $tsr0;
250            $li = new TagTk(
251                'listItem',
252                [ new KV( 'bullets', [ '#' ], $tsr0->expandTsrV() ) ],
253                $dp );
254            $ntokens[] = $li;
255            $ntokens[] = substr( $src, strlen( $srcMatch[0] ) );
256            PHPUtils::pushArray( $ntokens, $r );
257            return $ntokens;
258        }
259    }
260
261    /**
262     * @return array<string|Token>
263     */
264    public static function bailTokens( TokenHandlerPipeline $manager, Token $token ): array {
265        $frame = $manager->getFrame();
266        $tsr = $token->dataParsoid->tsr;
267        $frameSrc = $frame->getSource();
268        $linkSrc = $tsr->substr( $frameSrc );
269        $src = substr( $linkSrc, 1 );
270        if ( $src === '' ) {
271            $manager->getEnv()->log(
272                'error', 'Unable to determine link source.',
273                "frame: ", $frameSrc->getSrcText(),
274                'tsr: ', $tsr,
275                "link: $linkSrc"
276            );
277            return [ $linkSrc ];  // Forget about trying to tokenize this
278        }
279        $startOffset = $tsr->start + 1;
280        $toks = PipelineUtils::processContentInPipeline(
281            $manager->getEnv(), $frame, $src, [
282                // FIXME: Set toplevel when bailing
283                // 'toplevel' => $atTopLevel ?? false,
284                'sol' => false,
285                'pipelineType' => 'wikitext-to-expanded-tokens',
286                'srcOffsets' => new SourceRange( $startOffset, $startOffset + strlen( $src ), $tsr->source ),
287                'pipelineOpts' => [
288                    'expandTemplates' => $manager->getOptions()['expandTemplates'],
289                    'inTemplate' => $manager->getOptions()['inTemplate'],
290                ],
291            ]
292        );
293        TokenUtils::stripEOFTkFromTokens( $toks );
294        return array_merge( [ '[' ], $toks );
295    }
296
297    /**
298     * Handle a mw:WikiLink token.
299     *
300     * @param Token $token
301     * @return array<string|Token>
302     * @throws InternalException
303     */
304    private function onWikiLink( Token $token ): array {
305        $env = $this->env;
306        $tsr = $token->dataParsoid->tsr ?? null;
307        $tsrSource = $tsr->source ?? null;
308        $tsrStart = $tsr->start ?? null;
309
310        // Check if we have cached output for this wikilink source.
311        // Given wikilink-syntax source, token output is deterministic
312        // and so we can benefit from caching.
313        $src = $token->dataParsoid->src ?? '';
314        $isCacheable = ( $this->wikilinkCache && $tsrStart !== null && strlen( $src ) > 0 );
315        if ( $isCacheable ) {
316            $cachedOutput = $this->wikilinkCache->lookup( $src );
317            if ( $cachedOutput !== null ) {
318                $toks = $cachedOutput['value']['tokens'];
319                TokenUtils::shiftTokenTSR(
320                    $toks,
321                    $tsrStart - $cachedOutput['value']['start'],
322                    $tsrSource === $cachedOutput['source'] ? null : $tsrSource
323                );
324                TokenUtils::dedupeAboutIds( $env, $toks );
325                return $toks;
326            }
327        }
328
329        $hrefKV = $token->getAttributeKV( 'href' );
330        $hrefTokenStr = TokenUtils::tokensToString(
331            $hrefKV->v, false, [ 'stringifyNLs' => true ]
332        );
333
334        // Don't allow internal links to pages containing PROTO:
335        // See Parser::handleInternalLinks2()
336        if ( $env->getSiteConfig()->hasValidProtocol( $hrefTokenStr ) ) {
337            return self::bailTokens( $this->manager, $token );
338        }
339
340        // Xmlish tags in title position are invalid.  Not according to the
341        // preprocessor ABNF but at later stages in the legacy parser,
342        // namely handleInternalLinks.
343        if ( is_array( $hrefKV->v ) ) {
344            // Use the expanded attr instead of trying to unpackDOMFragments
345            // since the fragment will have been released when expanding to DOM
346            $expandedDom = $token->fetchExpandedAttrValue( 'href' )
347                ?? $env->getTopLevelDoc()->createDocumentFragment();
348            foreach ( DOMCompat::querySelectorAll( $expandedDom, '[typeof]' ) as $el ) {
349                if ( DOMUtils::matchTypeOf( $el, '#^mw:(Nowiki|Extension|DOMFragment/sealed)#' ) !== null ) {
350                    return self::bailTokens( $this->manager, $token );
351                }
352            }
353        }
354
355        // First check if the expanded href contains a pipe.
356        // But, pipes are valid in fragment position.
357        if ( preg_match( "/^[^#]*\|/", $hrefTokenStr ) ) {
358            // It does. This 'href' was templated and also returned other
359            // parameters separated by a pipe. We don't have any sensible way to
360            // handle such a construct currently, so prevent people from editing
361            // it.  See T226523
362            // TODO: add useful debugging info for editors ('if you would like to
363            // make this content editable, then fix template X..')
364            // TODO: also check other parameters for pipes!
365            // NOTE: We'd need to clear firstPipeSrc if this case gets supported
366            return self::bailTokens( $this->manager, $token );
367        }
368
369        try {
370            $target = $this->getWikiLinkTargetInfo( $token, $hrefTokenStr, $hrefKV->vsrc );
371        } catch ( TitleException | InternalException ) {
372            // Invalid title
373            return self::bailTokens( $this->manager, $token );
374        }
375
376        // Ok, it looks like we have a sensible href. Figure out which handler to use.
377        $isRedirect = (bool)$token->getAttributeV( 'redirect' );
378        $toks = $this->wikiLinkHandler( $token, $target, $isRedirect );
379        if ( $isCacheable ) {
380            $this->wikilinkCache->cache( $src, [ 'start' => $tsrStart, 'tokens' => $toks ], $tsrSource );
381        }
382
383        return $toks;
384    }
385
386    /**
387     * Figure out which handler to use to render a given WikiLink token. Override
388     * this method to add new handlers or swap out existing handlers based on the
389     * target structure.
390     *
391     * @param Token $token
392     * @param stdClass $target
393     * @param bool $isRedirect
394     * @return array<string|Token>
395     * @throws InternalException
396     */
397    private function wikiLinkHandler(
398        Token $token, stdClass $target, bool $isRedirect
399    ): array {
400        $title = $target->title ?? null;
401        if ( $title ) {
402            if ( $isRedirect ) {
403                return $this->renderWikiLink( $token, $target );
404            }
405            $siteConfig = $this->env->getSiteConfig();
406            $nsId = $title->getNamespace();
407            if ( $nsId === $siteConfig->canonicalNamespaceId( 'media' ) ) {
408                // Render as a media link.
409                return $this->renderMedia( $token, $target );
410            }
411            if (
412                !$target->fromColonEscapedText &&
413                // Protect from purely fragment links on pages in these namespaces
414                ( $target->href[0] ?? '' ) !== '#'
415            ) {
416                if ( $nsId === $siteConfig->canonicalNamespaceId( 'file' ) ) {
417                    // Render as a file.
418                    return $this->renderFile( $token, $target );
419                }
420                if ( $nsId === $siteConfig->canonicalNamespaceId( 'category' ) ) {
421                    // Render as a category membership.
422                    return $this->renderCategory( $token, $target );
423                }
424            }
425
426            // Render as plain wiki links.
427            return $this->renderWikiLink( $token, $target );
428        }
429
430        // language and interwiki links
431        if ( $target->interwiki ) {
432            return $this->renderInterwikiLink( $token, $target );
433        }
434        if ( $target->language ) {
435            $ns = $this->env->getContextTitle()->getNamespace();
436            $noLanguageLinks = $this->env->getSiteConfig()->namespaceIsTalk( $ns ) ||
437                !$this->env->getSiteConfig()->interwikiMagic();
438            if ( $noLanguageLinks ) {
439                $target->interwiki = $target->language;
440                return $this->renderInterwikiLink( $token, $target );
441            }
442
443            return $this->renderLanguageLink( $token, $target );
444        }
445
446        // Neither a title, nor a language or interwiki. Should not happen.
447        throw new InternalException( 'Unknown link type' );
448    }
449
450    /** ------------------------------------------------------------
451     * This (overloaded) function does three different things:
452     * - Extracts link text from attrs (when k === "mw:maybeContent").
453     *   As a performance micro-opt, only does if asked to (getLinkText)
454     * - Updates existing rdfa type with an additional rdf-type,
455     *   if one is provided (rdfaType)
456     * - Collates about, typeof, and linkAttrs into a new attr. array
457     *
458     * @param list<KV> $attrs
459     * @param bool $getLinkText
460     * @param ?string $rdfaType
461     * @param ?list<KV> $linkAttrs
462     *
463     * @return array{attribs: list<KV>, contentKVs: list<KV>, hasRdfaType: bool}
464     */
465    public static function buildLinkAttrs(
466        array $attrs, bool $getLinkText, ?string $rdfaType,
467        ?array $linkAttrs
468    ): array {
469        $newAttrs = [];
470        $linkTextKVs = [];
471        $about = null;
472
473        // In one pass through the attribute array, fetch about, typeof, and linkText
474        //
475        // about && typeof are usually at the end of the array if at all present
476        foreach ( $attrs as $kv ) {
477            $k = $kv->k;
478            $v = $kv->v;
479
480            // link-text attrs have the key "maybeContent"
481            if ( $getLinkText && $k === 'mw:maybeContent' ) {
482                $linkTextKVs[] = $kv;
483            } elseif ( is_string( $k ) && $k ) {
484                if ( trim( $k ) === 'typeof' ) {
485                    $rdfaType = $rdfaType ? $rdfaType . ' ' . $v : $v;
486                } elseif ( trim( $k ) === 'about' ) {
487                    $about = $v;
488                }
489            }
490        }
491
492        if ( $rdfaType ) {
493            $newAttrs[] = new KV( 'typeof', $rdfaType );
494        }
495
496        if ( $about ) {
497            $newAttrs[] = new KV( 'about', $about );
498        }
499
500        if ( $linkAttrs ) {
501            PHPUtils::pushArray( $newAttrs, $linkAttrs );
502        }
503
504        return [
505            'attribs' => $newAttrs,
506            'contentKVs' => $linkTextKVs,
507            'hasRdfaType' => $rdfaType !== null
508        ];
509    }
510
511    /**
512     * Generic wiki link attribute setup on a passed-in new token based on the
513     * wikilink token and target. As a side effect, this method also extracts the
514     * link content tokens and returns them.
515     *
516     * @param Token $newTk
517     * @param Token $token
518     * @param stdClass $target
519     * @param bool $buildDOMFragment
520     * @return array<string|Token>
521     * @throws InternalException
522     */
523    private function addLinkAttributesAndGetContent(
524        Token $newTk, Token $token, stdClass $target, bool $buildDOMFragment = false
525    ): array {
526        $attribs = $token->attribs;
527        $dataParsoid = $token->dataParsoid;
528        $dataMw = $token->dataMw;
529        $newAttrData = self::buildLinkAttrs( $attribs, true, null, [ new KV( 'rel', 'mw:WikiLink' ) ] );
530        $content = $newAttrData['contentKVs'];
531        $env = $this->env;
532
533        // Set attribs and dataParsoid
534        $newTk->attribs = $newAttrData['attribs'];
535        $newTk->dataParsoid = clone $dataParsoid;
536        $newTk->dataMw = $dataMw !== null ? clone $dataMw : null;
537        unset( $newTk->dataParsoid->src ); // clear src string since we can serialize this
538
539        // Note: Link tails are handled on the DOM in handleLinkNeighbours, so no
540        // need to handle them here.
541        $l = count( $content );
542        if ( $l > 0 ) {
543            $newTk->dataParsoid->stx = 'piped';
544            $out = [];
545            // re-join content bits
546            foreach ( $content as $i => $kv ) {
547                $toks = $kv->v;
548                // since this is already a link, strip autolinks from content
549                // FIXME: Maybe add a stop in the grammar so that autolinks
550                // aren't tokenized in link content to begin with?
551                if ( !is_array( $toks ) ) {
552                    $toks = [ $toks ];
553                }
554
555                $toks = array_values( array_filter( $toks, static function ( $t ) {
556                    return $t !== '';
557                } ) );
558                $n = count( $toks );
559                foreach ( $toks as $j => $t ) {
560                    // Bail on media-syntax in wikilink-syntax scenarios,
561                    // since the legacy parser explodes on [[, last one wins.
562                    // Note that without this, anchors tags in media output
563                    // will be stripped and we won't have the right structure
564                    // when we get to the dom pass to add media info.
565                    if (
566                        $t instanceof TagTk &&
567                        ( $t->getName() === 'figure' || $t->getName() === 'span' ) &&
568                        TokenUtils::matchTypeOf( $t, '#^mw:File($|/)#D' ) !== null
569                    ) {
570                        throw new InternalException( 'Media-in-link' );
571                    }
572
573                    if ( $t instanceof TagTk && $t->getName() === 'a' ) {
574                        // Bail on wikilink-syntax in wiklink-syntax scenarios,
575                        // since the legacy parser explodes on [[, last one wins
576                        if (
577                            preg_match(
578                                '#^mw:WikiLink(/Interwiki)?$#D',
579                                $t->getAttributeV( 'rel' ) ?? ''
580                            ) &&
581                            // ISBN links don't use wikilink-syntax but still
582                            // get the same "rel", so should be ignored
583                            ( $t->dataParsoid->stx ?? '' ) !== 'magiclink'
584                        ) {
585                            throw new InternalException( 'Link-in-link' );
586                        }
587                        if ( $j + 1 < $n && $toks[$j + 1] instanceof EndTagTk &&
588                            $toks[$j + 1]->getName() === 'a'
589                        ) {
590                            // autonumbered links in the stream get rendered
591                            // as an <a> tag with no content -- but these ought
592                            // to be treated as plaintext since we don't allow
593                            // nested links.
594                            $out[] = '[' . $t->getAttributeV( 'href' ) . ']';
595                        }
596                        // suppress <a>
597                        continue;
598                    }
599
600                    // Categories also use wikilink syntax so we bail to match
601                    // legacy output.  However, this isn't an a-in-a scenario
602                    // so maybe should be permitted in the future.
603                    if (
604                        $t instanceof SelfclosingTagTk && $t->getName() === 'link' &&
605                        preg_match(
606                            '#^mw:PageProp/Category$#D',
607                            $t->getAttributeV( 'rel' ) ?? ''
608                        )
609                    ) {
610                        throw new InternalException( 'Category-in-link' );
611                    }
612
613                    if ( $t instanceof EndTagTk && $t->getName() === 'a' ) {
614                        continue; // suppress </a>
615                    }
616
617                    $out[] = $t;
618                }
619                if ( $i < $l - 1 ) {
620                    $out[] = '|';
621                }
622            }
623
624            if ( $buildDOMFragment ) {
625                // content = [part 0, .. part l-1]
626                // offsets = [start(part-0), end(part l-1)]
627                $offsets = isset( $dataParsoid->tsr ) ?
628                    new SourceRange(
629                        $content[0]->srcOffsets->value->start,
630                        $content[$l - 1]->srcOffsets->value->end,
631                        $dataParsoid->tsr->source ) :
632                    null;
633                $content = [ PipelineUtils::getDOMFragmentToken( $out, $offsets,
634                    [ 'inlineContext' => true, 'token' => $token ] ) ];
635            } else {
636                $content = $out;
637            }
638        } else {
639            $newTk->dataParsoid->stx = 'simple';
640            $morecontent = Utils::decodeURIComponent( $target->href );
641
642            // Try to match labeling in core
643            if (
644                !$target->fromColonEscapedText &&
645                $env->getSiteConfig()->namespaceHasSubpages(
646                    $env->getContextTitle()->getNamespace()
647                )
648            ) {
649                // subpage links with a trailing slash get the trailing slashes stripped.
650                // See https://gerrit.wikimedia.org/r/173431
651                if ( preg_match( '#^((\.\./)+|/)(?!\.\./)(.*?[^/])/+$#D', $morecontent, $match ) ) {
652                    $morecontent = $match[3];
653                } elseif ( str_starts_with( $morecontent, '../' ) ) {
654                    // Subpages on interwiki / language links aren't valid,
655                    // so $target->title should always be present here
656                    $hash = strpos( $morecontent, '#' );
657                    $suffix = ( $hash !== false ) ? substr( $morecontent, $hash ) : '';
658                    $morecontent = $target->title->getPrefixedText() . $suffix;
659                }
660            }
661
662            // for interwiki links, include the interwiki prefix in the link text
663            if ( $target->interwiki ) {
664                $morecontent = $target->prefix . ':' . $morecontent;
665            }
666
667            // for local links, include the local prefix in the link text
668            if ( $target->localprefix ) {
669                $morecontent = $target->localprefix . ':' . $morecontent;
670            }
671
672            $content = [ $morecontent ];
673        }
674        return $content;
675    }
676
677    /**
678     * Render a plain wiki link.
679     *
680     * @param Token $token
681     * @param stdClass $target
682     * @return array<string|Token>
683     */
684    private function renderWikiLink( Token $token, stdClass $target ): array {
685        $newTk = new TagTk( 'a' );
686        try {
687            $content = $this->addLinkAttributesAndGetContent( $newTk, $token, $target, true );
688        } catch ( InternalException ) {
689            return self::bailTokens( $this->manager, $token );
690        }
691
692        $newTk->addNormalizedAttribute( 'href', $this->env->makeLink( $target->title ),
693            $target->hrefSrc );
694
695        $newTk->setAttribute( 'title', $target->title->getPrefixedText() );
696
697        return array_merge( [ $newTk ], $content, [ new EndTagTk( 'a' ) ] );
698    }
699
700    /**
701     * Render a category 'link'. Categories are really page properties, and are
702     * normally rendered in a box at the bottom of an article.
703     *
704     * @param Token $token
705     * @param stdClass $target
706     * @return array<string|Token>
707     */
708    private function renderCategory( Token $token, stdClass $target ): array {
709        $newTk = new SelfclosingTagTk( 'link' );
710        try {
711            $content = $this->addLinkAttributesAndGetContent( $newTk, $token, $target );
712        } catch ( InternalException ) {
713            return self::bailTokens( $this->manager, $token );
714        }
715        $env = $this->env;
716
717        // Change the rel to be mw:PageProp/Category
718        $newTk->getAttributeKV( 'rel' )->v = 'mw:PageProp/Category';
719
720        $newTk->addNormalizedAttribute( 'href', $env->makeLink( $target->title ), $target->hrefSrc );
721
722        // Change the href to include the sort key, if any (but don't update the rt info)
723        // Fallback to empty string for default sorting
724        $categorySort = '';
725        $strContent = str_replace( "\n", '', TokenUtils::tokensToString( $content ) );
726        if ( $strContent !== '' && $strContent !== $target->href ) {
727            $categorySort = $strContent;
728            $hrefkv = $newTk->getAttributeKV( 'href' );
729            $hrefkv->v .= '#';
730            $hrefkv->v .= str_replace( '#', '%23', Sanitizer::sanitizeTitleURI( $categorySort, false ) );
731        }
732
733        if ( count( $content ) !== 1 ) {
734            // Deal with sort keys that come from generated content (transclusions, etc.)
735            $key = [ 'txt' => 'mw:sortKey' ];
736            $contentKV = $token->getAttributeKV( 'mw:maybeContent' );
737            $so = $contentKV->valueOffset();
738            $val = PipelineUtils::expandAttrValueToDOM(
739                $this->env,
740                $this->manager->getFrame(),
741                [ 'html' => $content, 'srcOffsets' => $so ],
742                $this->options['expandTemplates'],
743                $this->options['inTemplate']
744            );
745            $attr = new DataMwAttrib( $key, $val );
746            $dataMw = $newTk->dataMw;
747            if ( $dataMw ) {
748                $dataMw->attribs[] = $attr;
749            } else {
750                $dataMw = new DataMw( [ 'attribs' => [ $attr ] ] );
751            }
752
753            // Mark token as having expanded attrs
754            $newTk->addAttribute( 'about', $env->newAboutId() );
755            $newTk->addSpaceSeparatedAttribute( 'typeof', 'mw:ExpandedAttrs' );
756            $newTk->dataMw = $dataMw;
757        }
758        $this->env->getMetadata()->addCategory( $target->title, $categorySort );
759        return [ $newTk ];
760    }
761
762    /**
763     * Render a language link. Those normally appear in the list of alternate
764     * languages for an article in the sidebar, so are really a page property.
765     *
766     * @param Token $token
767     * @param stdClass $target
768     * @return array<string|Token>
769     */
770    private function renderLanguageLink( Token $token, stdClass $target ): array {
771        // The prefix is listed in the interwiki map
772
773        // TODO: If $target->language['deprecated'] is set and
774        // $target->language['extralanglink'] is *not* set, then we
775        // should use the normalized language name/prefix (from
776        // 'deprecated') when calling
777        // ContentMetadataCollector::addLanguageLink() here (which
778        // we should eventualy be doing)
779
780        // TODO: might also want to add the language *code* here,
781        // which would be the language['bcp47'] property (added in
782        // change I82465261bc66f0b0cd30d361c299f08066494762) for an
783        // extralanglink, or the interwiki prefix otherwise; the
784        // latter is mediawiki-internal and maybe not BCP-47 compliant.
785        // This is for clients of the MediaWiki DOM spec HTML: the
786        // WMF domain prefix, the MediaWiki internal language code,
787        // and the actual *language* (ie bcp-47 code) can all differ
788        // from each other, due to various historical infelicities.
789        // Perhaps a `lang` attribute on the `link` would be appropriate.
790
791        $newTk = new SelfclosingTagTk( 'link', [], $token->dataParsoid );
792        try {
793            $this->addLinkAttributesAndGetContent( $newTk, $token, $target );
794        } catch ( InternalException ) {
795            return self::bailTokens( $this->manager, $token );
796        }
797
798        // add title attribute giving the presentation name of the
799        // "extra language link"
800        // T329303: the 'linktext' comes from the system message
801        // `interlanguage-link-$prefix` and should be set in integrated mode
802        // using the localization features; the integrated-mode SiteConfig
803        // currently never sets the `linktext` property in
804        // SiteConfig::interwikiMap().
805        // I52d50e2f75942a849908c6be7fc5169f00a5983a has some partial work
806        // on this.
807        if ( isset( $target->language['extralanglink'] ) &&
808            !empty( $target->language['linktext'] )
809        ) {
810            // XXX in standalone mode, this is user-interface-language text,
811            // not "content language" text.
812            $newTk->addNormalizedAttribute( 'title', $target->language['linktext'], null );
813        }
814
815        // We set an absolute link to the article in the other wiki/language
816        $title = Sanitizer::sanitizeTitleURI( Utils::decodeURIComponent( $target->href ), false );
817        $absHref = str_replace( '$1', $title, $target->language['url'] );
818        if ( isset( $target->language['protorel'] ) ) {
819            $absHref = preg_replace( '/^https?:/', '', $absHref, 1 );
820        }
821        $newTk->addNormalizedAttribute( 'href', $absHref, $target->hrefSrc );
822
823        // Change the rel to be mw:PageProp/Language
824        $newTk->getAttributeKV( 'rel' )->v = 'mw:PageProp/Language';
825
826        // Add language link(s) to metadata
827        $this->env->getMetadata()->addLanguageLink( $target->language['title'] );
828
829        return [ $newTk ];
830    }
831
832    /**
833     * Render an interwiki link.
834     *
835     * @param Token $token
836     * @param stdClass $target
837     * @return array<string|Token>
838     */
839    private function renderInterwikiLink( Token $token, stdClass $target ): array {
840        // The prefix is listed in the interwiki map
841
842        $tokens = [];
843        $newTk = new TagTk( 'a', [], $token->dataParsoid );
844        try {
845            $content = $this->addLinkAttributesAndGetContent( $newTk, $token, $target, true );
846        } catch ( InternalException ) {
847            return self::bailTokens( $this->manager, $token );
848        }
849
850        // We set an absolute link to the article in the other wiki/language
851        $isLocal = !empty( $target->interwiki['local'] );
852        $trimmedHref = trim( $target->href );
853        $title = Sanitizer::sanitizeTitleURI(
854            Utils::decodeURIComponent( $trimmedHref ),
855            !$isLocal
856        );
857        $absHref = str_replace( '$1', $title, $target->interwiki['url'] );
858        if ( isset( $target->interwiki['protorel'] ) ) {
859            $absHref = preg_replace( '/^https?:/', '', $absHref, 1 );
860        }
861        $newTk->addNormalizedAttribute( 'href', $absHref, $target->hrefSrc );
862
863        $newTk->getAttributeKV( 'rel' )->v = 'mw:WikiLink/Interwiki';
864
865        // Add title unless it's just a fragment (and trim off fragment)
866        // (The normalization here is similar to what Title#getPrefixedDBKey() does.)
867        if ( $target->href === '' || $target->href[0] !== '#' ) {
868            $titleAttr = $target->interwiki['prefix'] . ':' .
869                Utils::decodeURIComponent( str_replace( '_', ' ',
870                    preg_replace( '/#.*/s', '', $trimmedHref, 1 ) ) );
871            $newTk->setAttribute( 'title', $titleAttr );
872        }
873        $tokens[] = $newTk;
874
875        PHPUtils::pushArray( $tokens, $content );
876        $tokens[] = new EndTagTk( 'a' );
877        return $tokens;
878    }
879
880    private const HORIZONTAL_ALIGNS = [
881        // PHP parser wraps in <div class="floatnone">
882        'left',
883        // PHP parser wraps in <div class="center"><div class="floatnone">
884        'right',
885        // PHP parser wraps in <div class="floatleft">
886        'center',
887        // PHP parser wraps in <div class="floatright">
888        'none',
889    ];
890    private const VERTICAL_ALIGNS = [ 'baseline', 'sub', 'super', 'top', 'text_top', 'middle',
891        'bottom', 'text_bottom' ];
892
893    /**
894     * Get the style and class lists for an image's wrapper element.
895     *
896     * @param array $opts The option hash from renderFile.
897     *
898     * @return array{classes: list<string>, isInline: bool}
899     *  - isInline: Whether the image is inline after handling options
900     *  - classes: The list of classes for the wrapper.
901     */
902    private static function getWrapperInfo( array $opts ): array {
903        $format = self::getFormat( $opts );
904        $isInline = !in_array( $format, [ 'thumbnail', 'manualthumb', 'framed' ], true );
905        $classes = [];
906
907        if (
908            !isset( $opts['size']['src'] ) &&
909            // Framed and manualthumb images aren't scaled
910            !in_array( $format, [ 'manualthumb', 'framed' ], true )
911        ) {
912            $classes[] = 'mw-default-size';
913        }
914
915        // Border isn't applicable to 'thumbnail', 'manualthumb', or 'framed' formats
916        // Using $isInline as a shorthand for that here (see above),
917        // but this isn't about being *inline* per se
918        if ( $isInline && isset( $opts['border'] ) ) {
919            $classes[] = 'mw-image-border';
920        }
921
922        $halign = $opts['halign']['v'] ?? null;
923        if ( in_array( $halign, self::HORIZONTAL_ALIGNS, true ) ) {
924            $isInline = false;
925            $classes[] = "mw-halign-$halign";
926        }
927
928        if ( $isInline ) {
929            $valignOpt = $opts['valign']['v'] ?? null;
930            if ( in_array( $valignOpt, self::VERTICAL_ALIGNS, true ) ) {
931                $classes[] = str_replace( '_', '-', "mw-valign-$valignOpt" );
932            }
933        }
934
935        return [ 'classes' => $classes, 'isInline' => $isInline ];
936    }
937
938    /**
939     * Determine the name of an option.
940     *
941     * @param string $optStr
942     * @param Env $env
943     * @return ?array{ck: string, v: string, ak: string, s: bool}
944     * - ck: Canonical key for the image option.
945     * - v: Value of the option.
946     * - ak: Aliased key for the image option; includes `"$1"` for placeholder.
947     * - s: Whether it's a simple option or one with a value.
948     */
949    private static function getOptionInfo( string $optStr, Env $env ): ?array {
950        $oText = trim( $optStr );
951        $siteConfig = $env->getSiteConfig();
952        $getOption = $siteConfig->getMediaPrefixParameterizedAliasMatcher();
953        // oText contains the localized name of this option.  the
954        // canonical option names (from mediawiki upstream) are in
955        // English and contain an '(img|timedmedia)_' prefix.  We drop the
956        // prefix before stuffing them in data-parsoid in order to
957        // save space (that's shortCanonicalOption)
958        $canonicalOption = $siteConfig->getMagicWordForMediaOption( $oText ) ?? '';
959        $shortCanonicalOption = preg_replace( '/^(img|timedmedia)_/', '', $canonicalOption, 1 );
960        // 'imgOption' is the key we'd put in opts; it names the 'group'
961        // for the option, and doesn't have an img_ prefix.
962        $imgOption = Consts::$Media['SimpleOptions'][$canonicalOption] ?? null;
963        if ( $imgOption !== null ) {
964            return [
965                'ck' => $imgOption,
966                'v' => $shortCanonicalOption,
967                'ak' => $optStr,
968                's' => true
969            ];
970        }
971        // If there isn't a literal match for the option, look for a
972        // prefix match (ie, img_width => `$1px`)
973
974        // *Note* that the legacy parser doesn't have a "principled"
975        // precedence here (T372935), it just so happens that members
976        // of Consts::PrefixOptions like
977        // img_width/img_page/img_lang/timedmedia_* are added last (as
978        // handler parameters), and other prefixed options like
979        // img_link/img_alt/img_class *happen* to be last in the
980        // $internalParamMap.  But the possibility for conflicts
981        // between prefixed parameters and literal options still
982        // exists in the legacy parser.
983        $bits = $getOption( $oText );
984        $normalizedBit0 = $bits ? mb_strtolower( trim( $bits['k'] ) ) : null;
985        $key = $bits ? ( Consts::$Media['PrefixOptions'][$normalizedBit0] ?? null ) : null;
986
987        // bits.a *used to have* the localized name for the prefix option
988        // (see SiteConfig::getMediaPrefixParameterizedAliasMatcher, this was
989        // dropped in the port from JS.)
990        // with $1 as a placeholder for the value, which is in bits.v
991        // 'normalizedBit0' is the canonical English option name
992        // (from mediawiki upstream) with a prefix.
993        // 'key' is the parsoid 'group' for the option; it doesn't
994        // have a prefix (it's the key we'd put in opts)
995        if ( $bits && $key ) {
996            $shortCanonicalOption = preg_replace( '/^(img|timedmedia)_/', '', $normalizedBit0, 1 );
997            // map short canonical name to the localized version used
998
999            // Note that we deliberately do entity decoding
1000            // *after* splitting so that HTML-encoded pipes don't
1001            // separate options.  This matches PHP, whether or
1002            // not it's a good idea.
1003            return [
1004                'ck' => $shortCanonicalOption,
1005                'v' => Utils::decodeWtEntities( $bits['v'] ),
1006                'ak' => $optStr,
1007                's' => false
1008            ];
1009        }
1010
1011        return null;
1012    }
1013
1014    private static function isWikitextOpt(
1015        Env $env, ?array &$optInfo, string $prefix, string $resultStr
1016    ): bool {
1017        // link and alt options are allowed to contain arbitrary
1018        // wikitext (even though only strings are supported in reality)
1019        // FIXME(SSS): Is this actually true of all options rather than
1020        // just link and alt?
1021        if ( $optInfo === null ) {
1022            $optInfo = self::getOptionInfo( $prefix . $resultStr, $env );
1023        }
1024        return $optInfo !== null && in_array( $optInfo['ck'], [ 'link', 'alt' ], true );
1025    }
1026
1027    /**
1028     * Make option token streams into a stringy thing that we can recognize.
1029     *
1030     * @param array $tstream
1031     * @param string $prefix Anything that came before this part of the recursive call stack.
1032     * @param Env $env
1033     * @return ?string
1034     */
1035    private static function stringifyOptionTokens( array $tstream, string $prefix, Env $env ): ?string {
1036        // Seems like this should be a more general "stripTags"-like function?
1037        $skipToEndOf = null;
1038        $optInfo = null;
1039        $resultStr = '';
1040
1041        for ( $i = 0;  $i < count( $tstream );  $i++ ) {
1042            $currentToken = $tstream[$i];
1043
1044            if ( $skipToEndOf ) {
1045                if ( $currentToken instanceof EndTagTk && $currentToken->getName() === $skipToEndOf ) {
1046                    $skipToEndOf = null;
1047                }
1048                continue;
1049            }
1050
1051            if ( is_string( $currentToken ) ) {
1052                $resultStr .= $currentToken;
1053            } elseif ( is_array( $currentToken ) ) {
1054                $nextResult = self::stringifyOptionTokens( $currentToken, $prefix . $resultStr, $env );
1055
1056                if ( $nextResult === null ) {
1057                    return null;
1058                }
1059
1060                $resultStr .= $nextResult;
1061            } elseif (
1062                ( $currentToken instanceof XMLTagTk ) &&
1063                !( $currentToken instanceof EndTagTk )
1064            ) {
1065                // This is actually a token
1066                if ( TokenUtils::hasDOMFragmentType( $currentToken ) ) {
1067                    if ( self::isWikitextOpt( $env, $optInfo, $prefix, $resultStr ) ) {
1068                        $str = TokenUtils::tokensToString( [ $currentToken ], false, [
1069                                // These tokens haven't been expanded to DOM yet
1070                                // so unpacking them here is justifiable
1071                                // FIXME: It's a little convoluted to figure out
1072                                // that this is actually the case in the
1073                                // AttributeExpander, but it seems like only
1074                                // target/href ever gets expanded to DOM and
1075                                // the rest of the wikilink_content/options
1076                                // become mw:maybeContent that gets expanded
1077                                // below where $hasExpandableOpt is set.
1078                                'unpackDOMFragments' => true,
1079                            ]
1080                        );
1081                        // Entity encode pipes since we wouldn't have split on
1082                        // them from fragments and we're about to attempt to
1083                        // when this function returns.
1084                        $resultStr .= str_replace( '|', '&vert;', $str );
1085                        $optInfo = null; // might change the nature of opt
1086                        continue;
1087                    } else {
1088                        // if this is a nowiki, we must be in a caption
1089                        return null;
1090                    }
1091                }
1092                if ( $currentToken->getName() === 'mw-quote' ) {
1093                    if ( self::isWikitextOpt( $env, $optInfo, $prefix, $resultStr ) ) {
1094                        // just recurse inside
1095                        $optInfo = null; // might change the nature of opt
1096                        continue;
1097                    }
1098                    return null;
1099                }
1100                // Similar to TokenUtils.tokensToString()'s includeEntities
1101                if ( TokenUtils::isEntitySpanToken( $currentToken ) ) {
1102                    $resultStr .= $currentToken->dataParsoid->src;
1103                    $skipToEndOf = 'span';
1104                    continue;
1105                }
1106                if ( $currentToken->getName() === 'a' ) {
1107                    if ( $optInfo === null ) {
1108                        $optInfo = self::getOptionInfo( $prefix . $resultStr, $env );
1109                        if ( $optInfo === null ) {
1110                            // An <a> tag before a valid option?
1111                            // This is most likely a caption.
1112                            return null;
1113                        }
1114                    }
1115
1116                    if ( self::isWikitextOpt( $env, $optInfo, $prefix, $resultStr ) ) {
1117                        $tokenType = $currentToken->getAttributeV( 'rel' );
1118                        $isLink = $optInfo && $optInfo['ck'] === 'link';
1119                        // Reset the optInfo since we're changing the nature of it
1120                        $optInfo = null;
1121                        // Figure out the proper string to put here and break.
1122                        if (
1123                            $tokenType === 'mw:ExtLink' &&
1124                            ( $currentToken->dataParsoid->stx ?? '' ) === 'url'
1125                        ) {
1126                            // Add the URL and entity encode any pipes
1127                            // If the pipes are from entity decoding in the href,
1128                            // we don't want to split media options on them
1129                            // If the pipes are from template expansion, legacy
1130                            // would have considered them delineating a media option
1131                            // but let's not support that combination with the url
1132                            $resultStr .= str_replace(
1133                                '|', '&vert;', $currentToken->getAttributeV( 'href' )
1134                            );
1135                            // Tell our loop to skip to the end of this tag
1136                            $skipToEndOf = 'a';
1137                        } elseif ( $tokenType === 'mw:WikiLink/Interwiki' ) {
1138                            if ( $isLink ) {
1139                                $resultStr .= $currentToken->getAttributeV( 'href' );
1140                                $i += 2;
1141                                continue;
1142                            }
1143                            // Nothing to do -- the link content will be
1144                            // captured by walking the rest of the tokens.
1145                        } elseif ( $tokenType === 'mw:WikiLink' || $tokenType === 'mw:MediaLink' ) {
1146
1147                            // Nothing to do -- the link content will be
1148                            // captured by walking the rest of the tokens.
1149                        } else {
1150                            // There shouldn't be any other kind of link...
1151                            // This is likely a caption.
1152                            return null;
1153                        }
1154                    } else {
1155                        // Why would there be an a tag without a link?
1156                        return null;
1157                    }
1158                }
1159            }
1160        }
1161
1162        return $resultStr;
1163    }
1164
1165    /**
1166     * Get the format for media.
1167     *
1168     * @param array $opts
1169     * @return string|null
1170     */
1171    private static function getFormat( array $opts ): ?string {
1172        if ( $opts['manualthumb'] ) {
1173            return 'manualthumb';
1174        }
1175        return $opts['format']['v'] ?? null;
1176    }
1177
1178    private array $used = [];
1179
1180    /**
1181     * This is the set of file options that apply to the container, rather
1182     * than the media element itself (or, apply generically to a span).
1183     * Other options depend on the fetched media type and won't necessary be
1184     * applied.
1185     *
1186     * @return array
1187     */
1188    private function getUsed(): array {
1189        if ( $this->used ) {
1190            return $this->used;
1191        }
1192        $this->used = PHPUtils::makeSet(
1193            array_merge(
1194                [
1195                    'lang', 'width', 'class', 'upright',
1196                    'border', 'frameless', 'framed', 'thumbnail',
1197                ],
1198                self::HORIZONTAL_ALIGNS,
1199                self::VERTICAL_ALIGNS
1200            )
1201        );
1202        return $this->used;
1203    }
1204
1205    private function hasTransclusion( array $toks ): bool {
1206        foreach ( $toks as $t ) {
1207            if (
1208                $t instanceof SelfclosingTagTk &&
1209                TokenUtils::hasTypeOf( $t, 'mw:Transclusion' )
1210            ) {
1211                return true;
1212            }
1213        }
1214        return false;
1215    }
1216
1217    /**
1218     * Render a file. This can be an image, a sound, a PDF etc.
1219     *
1220     * @param Token $token
1221     * @param stdClass $target
1222     * @return array<string|Token>
1223     */
1224    private function renderFile( Token $token, stdClass $target ): array {
1225        $manager = $this->manager;
1226        $env = $this->env;
1227
1228        // FIXME: Re-enable use of media cache and figure out how that fits
1229        // into this new processing model. See T98995
1230
1231        $dataParsoid = clone $token->dataParsoid;
1232        $dataParsoid->optList = [];
1233
1234        // Account for the possibility of an expanded target
1235        $dataMw = $token->dataMw ?? new DataMw();
1236
1237        $opts = [
1238            'title' => [
1239                'v' => $env->makeLink( $target->title ),
1240                'src' => $token->getAttributeKV( 'href' )->vsrc
1241            ],
1242            'size' => [
1243                'v' => [
1244                    'height' => null,
1245                    'width' => null
1246                ]
1247            ],
1248            // Initialize these properties to avoid isset checks
1249            'caption' => null,
1250            'format' => null,
1251            'manualthumb' => null,
1252            'class' => null
1253        ];
1254
1255        $hasExpandableOpt = false;
1256
1257        $optKVs = self::buildLinkAttrs( $token->attribs, true, null, null )['contentKVs'];
1258        while ( count( $optKVs ) > 0 ) {
1259            $oContent = array_shift( $optKVs );
1260            Assert::invariant( $oContent instanceof KV, 'bad type' );
1261
1262            $origOptSrc = $oContent->v;
1263            if ( is_array( $origOptSrc ) && count( $origOptSrc ) === 1 ) {
1264                $origOptSrc = $origOptSrc[0];
1265            }
1266
1267            $oText = TokenUtils::tokensToString( $origOptSrc, true, [ 'includeEntities' => true ] );
1268
1269            if ( !is_string( $oText ) ) {
1270                // Might be that this is a valid option whose value is just
1271                // complicated. Try to figure it out, step through all tokens.
1272                $maybeOText = self::stringifyOptionTokens( $oText, '', $env );
1273                if ( $maybeOText !== null ) {
1274                    $oText = $maybeOText;
1275                }
1276            }
1277
1278            $optInfo = null;
1279            if ( is_string( $oText ) ) {
1280                if ( str_contains( $oText, '|' ) ) {
1281                    // Split the pipe-separated string into pieces
1282                    // and convert each one into a KV obj and add them
1283                    // to the beginning of the array. Note that this is
1284                    // a hack to support templates that provide multiple
1285                    // image options as a pipe-separated string. We aren't
1286                    // really providing editing support for this yet, or
1287                    // ever, maybe.
1288                    //
1289                    // TODO(arlolra): Tables in captions suppress breaking on
1290                    // "linkdesc" pipes so `stringifyOptionTokens` should account
1291                    // for pipes in table cell content.  For the moment, breaking
1292                    // here is acceptable since it matches the php implementation
1293                    // bug for bug.
1294                    $pieces = array_map( static function ( $s ) {
1295                        return new KV( 'mw:maybeContent', $s );
1296                    }, explode( '|', $oText ) );
1297                    $optKVs = array_merge( $pieces, $optKVs );
1298
1299                    // Record the fact that we won't provide editing support for this.
1300                    $dataParsoid->uneditable = true;
1301                    continue;
1302                } else {
1303                    // We're being overly accepting of media options at this point,
1304                    // since we don't know the type yet.  After the info request,
1305                    // we'll filter out those that aren't appropriate.
1306                    $optInfo = self::getOptionInfo( $oText, $env );
1307                }
1308            }
1309
1310            $recordCaption = static function () use ( $oContent, $oText, $dataParsoid, &$opts ): void {
1311                $optsCaption = [
1312                    'v' => $oContent->v,
1313                    'src' => $oContent->vsrc ?? $oText,
1314                    'srcOffsets' => $oContent->valueOffset(),
1315                    // remember the position
1316                    'pos' => count( $dataParsoid->optList )
1317                ];
1318                // if there was a 'caption' previously, round-trip it as a
1319                // "bogus option".
1320                if ( !empty( $opts['caption'] ) ) {
1321                    // Wrap the caption opt in an array since the option itself is an array!
1322                    // Without the wrapping, the splicing will flatten the value.
1323                    array_splice( $dataParsoid->optList, $opts['caption']['pos'], 0, [ [
1324                            'ck' => 'bogus',
1325                            'ak' => $opts['caption']['src']
1326                        ] ]
1327                    );
1328                    $optsCaption['pos']++;
1329                }
1330                $opts['caption'] = $optsCaption;
1331            };
1332
1333            // For the values of the caption and options, see
1334            // getOptionInfo's documentation above.
1335            //
1336            // If there are multiple captions, this code always
1337            // picks the last entry. This is the spec; see
1338            // "Image with multiple captions" parserTest.
1339            if ( !is_string( $oText ) || $optInfo === null ||
1340                // Deprecated options
1341                in_array( $optInfo['ck'], [ 'disablecontrols' ], true )
1342            ) {
1343                // No valid option found!?
1344                // Record for RT-ing
1345                $recordCaption();
1346                continue;
1347            }
1348
1349            // First option wins, the rest are 'bogus'
1350            // FIXME: For now, see T305628
1351            if ( isset( $opts[$optInfo['ck']] ) || (
1352                // All the formats are simple options with the key "format"
1353                // except for "manualthumb", so check if the format has been set
1354                in_array( $optInfo['ck'], [ 'format', 'manualthumb' ], true ) && (
1355                    self::getFormat( $opts ) ||
1356                    ( $this->options['extTagOpts']['suppressMediaFormats'] ?? false )
1357                )
1358            ) ) {
1359                $dataParsoid->optList[] = [
1360                    'ck' => 'bogus',
1361                    'ak' => $optInfo['ak']
1362                ];
1363                continue;
1364            }
1365
1366            $opt = [
1367                'ck' => $optInfo['v'],
1368                'ak' => $oContent->vsrc ?? $optInfo['ak']
1369            ];
1370
1371            if ( $optInfo['s'] === true ) {
1372                // Default: Simple image option
1373                $opts[$optInfo['ck']] = [ 'v' => $optInfo['v'] ];
1374            } else {
1375                // Map short canonical name to the localized version used.
1376                $opt['ck'] = $optInfo['ck'];
1377
1378                // The MediaWiki magic word for image dimensions is called 'width'
1379                // for historical reasons
1380                // Unlike other options, use last-specified width.
1381                if ( $optInfo['ck'] === 'width' ) {
1382                    // We support a trailing 'px' here for historical reasons
1383                    // (T15500, T53628, T207032)
1384                    $maybeDim = Utils::parseMediaDimensions(
1385                        $env->getSiteConfig(), $optInfo['v'], false, true
1386                    );
1387                    if ( $maybeDim !== null ) {
1388                        if ( $maybeDim['bogusPx'] ) {
1389                            // Lint away redundant unit (T207032)
1390                            $dataParsoid->setTempFlag( TempData::BOGUS_PX );
1391                        }
1392                        $opts['size']['v'] = [
1393                            'width' => Utils::validateMediaParam( $maybeDim['x'] ) ? $maybeDim['x'] : null,
1394                            'height' => array_key_exists( 'y', $maybeDim ) &&
1395                                Utils::validateMediaParam( $maybeDim['y'] ) ? $maybeDim['y'] : null
1396                        ];
1397                        // Only round-trip a valid size
1398                        $opts['size']['src'] = $oContent->vsrc ?? $optInfo['ak'];
1399                        // check for duplicated options
1400                        foreach ( $dataParsoid->optList as &$value ) {
1401                            if ( $value['ck'] === 'width' ) {
1402                                $value['ck'] = 'bogus'; // mark the previous definition as bogus, last one wins
1403                                break;
1404                            }
1405                        }
1406                    } else {
1407                        $recordCaption();
1408                        continue;
1409                    }
1410                // Lang is a global attribute and can be applied to all media elements
1411                // for editing and roundtripping.  However, not all file handlers will
1412                // make use of it.  This param validation is from the SVG handler but
1413                // seems generally applicable.
1414                } elseif ( $optInfo['ck'] === 'lang' && !Language::isValidInternalCode( $optInfo['v'] ) ) {
1415                    $opt['ck'] = 'bogus';
1416                } elseif (
1417                    $optInfo['ck'] === 'upright' &&
1418                    ( !is_numeric( $optInfo['v'] ) || $optInfo['v'] <= 0 )
1419                ) {
1420                    $opt['ck'] = 'bogus';
1421                } else {
1422                    $opts[$optInfo['ck']] = [
1423                        'v' => $optInfo['v'],
1424                        'src' => $oContent->vsrc ?? $optInfo['ak'],
1425                        'srcOffsets' => $oContent->valueOffset(),
1426                    ];
1427                }
1428            }
1429
1430            // Collect option in dataParsoid (becomes data-parsoid later on)
1431            // for faithful serialization.
1432            $dataParsoid->optList[] = $opt;
1433
1434            // Collect source wikitext for image options for possible template expansion.
1435            $maybeOpt = !isset( self::getUsed()[$opt['ck']] );
1436            // Links more often than not show up as arrays here because they're
1437            // tokenized as `autourl`.  To avoid unnecessarily considering them
1438            // expanded, we'll use a more restrictive test, at the cost of
1439            // perhaps missing some edgy behaviour.
1440            if ( $opt['ck'] === 'link' ) {
1441                $expOpt = is_array( $origOptSrc ) &&
1442                    $this->hasTransclusion( $origOptSrc );
1443            } else {
1444                $expOpt = is_array( $origOptSrc );
1445            }
1446            if ( $maybeOpt || $expOpt ) {
1447                $val = [];
1448                if ( $expOpt ) {
1449                    $hasExpandableOpt = true;
1450                    $val['html'] = $origOptSrc;
1451                    $val['srcOffsets'] = $oContent->valueOffset();
1452                    $val = PipelineUtils::expandAttrValueToDOM(
1453                        $env, $manager->getFrame(), $val,
1454                        $this->options['expandTemplates'],
1455                        $this->options['inTemplate']
1456                    );
1457                }
1458
1459                // This is a bit of an abuse of the "txt" property since
1460                // `optInfo.v` isn't necessarily wikitext from source.
1461                // It's a result of the specialized stringifying above, which
1462                // if interpreted as wikitext upon serialization will result
1463                // in some (acceptable) normalization.
1464                //
1465                // We're storing these options in data-mw because they aren't
1466                // guaranteed to apply to all media types and we'd like to
1467                // avoid the need to back them out later.
1468                //
1469                // Note that the caption in the legacy parser depends on the
1470                // exact set of options parsed, which we aren't attempting to
1471                // try and replicate after fetching the media info, since we
1472                // consider that more of bug than a feature.  It prevent anyone
1473                // from ever safely adding media options in the future.
1474                //
1475                // See T163582
1476                if ( $maybeOpt ) {
1477                    $val['txt'] = $optInfo['v'];
1478                }
1479                $dataMw->attribs ??= [];
1480                $dataMw->attribs[] = new DataMwAttrib( $opt['ck'], $val );
1481            }
1482        }
1483
1484        // Add the last caption in the right position if there is one
1485        if ( isset( $opts['caption'] ) ) {
1486            // Wrap the caption opt in an array since the option itself is an array!
1487            // Without the wrapping, the splicing will flatten the value.
1488            array_splice( $dataParsoid->optList, $opts['caption']['pos'], 0, [ [
1489                    'ck' => 'caption',
1490                    'ak' => $opts['caption']['src']
1491                ] ]
1492            );
1493        }
1494
1495        $format = self::getFormat( $opts );
1496
1497        // Handle image default sizes and upright option after extracting all
1498        // options
1499        $uprightFactor = null;
1500        if ( $format === 'framed' || $format === 'manualthumb' ) {
1501            // width and height is ignored for framed and manualthumb images
1502            // https://phabricator.wikimedia.org/T64258
1503            $opts['size']['v'] = [ 'width' => null, 'height' => null ];
1504            // Mark any definitions as bogus
1505            foreach ( $dataParsoid->optList as &$value ) {
1506                if ( $value['ck'] === 'width' ) {
1507                    $value['ck'] = 'bogus';
1508                }
1509            }
1510        } elseif ( $format ) {
1511            if ( !$opts['size']['v']['height'] && !$opts['size']['v']['width'] ) {
1512                $defaultWidth = $env->getSiteConfig()->widthOption();
1513                if ( isset( $opts['upright'] ) ) {
1514                    if ( $opts['upright']['v'] === 'upright' ) {  // Simple option
1515                        $uprightFactor = 0.75;
1516                    } else {
1517                        $uprightFactor = (float)$opts['upright']['v'];
1518                    }
1519                    $defaultWidth *= $uprightFactor;
1520                    // round to nearest 10 pixels
1521                    $defaultWidth = 10 * round( $defaultWidth / 10 );
1522                }
1523                $opts['size']['v']['width'] = $defaultWidth;
1524            }
1525        }
1526
1527        // If the format is something we *recognize*, add the subtype
1528        $rdfaType = 'mw:File' . match ( $format ) {
1529            'manualthumb', // FIXME(T305759): Does it deserve its own type?
1530            'thumbnail' => '/Thumb',
1531            'framed' => '/Frame',
1532            'frameless' => '/Frameless',
1533            default => ''
1534        };
1535
1536        // Tell VE that it shouldn't try to edit this
1537        if ( !empty( $dataParsoid->uneditable ) ) {
1538            $rdfaType .= ' mw:Placeholder';
1539        } else {
1540            unset( $dataParsoid->src );
1541        }
1542
1543        $wrapperInfo = self::getWrapperInfo( $opts );
1544
1545        $isInline = $wrapperInfo['isInline'];
1546        $containerName = $isInline ? 'span' : 'figure';
1547
1548        $classes = $wrapperInfo['classes'];
1549        if ( !empty( $opts['class'] ) ) {
1550            PHPUtils::pushArray( $classes, explode( ' ', $opts['class']['v'] ) );
1551        }
1552
1553        $attribs = [ new KV( 'typeof', $rdfaType ) ];
1554        if ( count( $classes ) > 0 ) {
1555            array_unshift( $attribs, new KV( 'class', implode( ' ', $classes ) ) );
1556        }
1557
1558        $container = new TagTk( $containerName, $attribs, $dataParsoid );
1559        $containerClose = new EndTagTk( $containerName );
1560
1561        if ( $hasExpandableOpt ) {
1562            $container->addAttribute( 'about', $env->newAboutId() );
1563            $container->addSpaceSeparatedAttribute( 'typeof', 'mw:ExpandedAttrs' );
1564        } elseif ( preg_match( '/\bmw:ExpandedAttrs\b/', $token->getAttributeV( 'typeof' ) ?? '' ) ) {
1565            $container->addSpaceSeparatedAttribute( 'typeof', 'mw:ExpandedAttrs' );
1566        }
1567
1568        if ( !$this->env->bumpWt2HtmlResourceUse( 'image' ) ) {
1569            $container->dataParsoid->getTemp()->setFlag( TempData::MEDIA_OVER_LIMIT );
1570        }
1571
1572        // Start off as broken media since we don't know if the file exists.
1573        // In the AddMediaInfo pass, we'll replace the node after calling getFileInfo
1574        $span = new TagTk( 'span', [ new KV( 'class', 'mw-file-element mw-broken-media' ) ] );
1575
1576        // "resource" and "lang" are allowed attributes on spans
1577        $span->addNormalizedAttribute( 'resource', $opts['title']['v'], $opts['title']['src'] );
1578        if ( isset( $opts['lang'] ) ) {
1579            $span->addNormalizedAttribute( 'lang', $opts['lang']['v'], $opts['lang']['src'] );
1580        }
1581
1582        // Token's KV attributes only accept strings, Tokens or arrays of those.
1583        $size = $opts['size']['v'];
1584        if ( !empty( $size['width'] ) ) {
1585            $span->addAttribute( 'data-width', (string)$size['width'] );
1586        }
1587        if ( !empty( $size['height'] ) ) {
1588            $span->addAttribute( 'data-height', (string)$size['height'] );
1589        }
1590        if ( $uprightFactor !== null ) {
1591            $span->addAttribute( 'data-upright', (string)$uprightFactor );
1592        }
1593
1594        $anchor = new TagTk( 'a' );
1595        $anchor->setAttribute( 'href', $this->getUploadUrl( $target->title ) );
1596        $anchor->setAttribute( 'class', 'new' );
1597        $anchor->setAttribute( 'title', $target->title->getPrefixedText() );
1598
1599        $tokens = [
1600            $container,
1601            $anchor,
1602            $span,
1603            $target->title->getPrefixedText(),
1604            new EndTagTk( 'span' ),
1605            new EndTagTk( 'a' )
1606        ];
1607
1608        $optsCaption = $opts['caption'] ?? null;
1609        if ( $isInline ) {
1610            if ( $optsCaption ) {
1611                if ( !is_array( $optsCaption['v'] ) ) {
1612                    $opts['caption']['v'] = $optsCaption['v'] = [ $optsCaption['v'] ];
1613                }
1614                // Parse the caption
1615                $captionDOM = PipelineUtils::processContentInPipeline(
1616                    $this->env,
1617                    $this->manager->getFrame(),
1618                    array_merge( $optsCaption['v'], [ new EOFTk() ] ),
1619                    [
1620                        'pipelineType' => 'expanded-tokens-to-fragment',
1621                        'pipelineOpts' => [
1622                            'inlineContext' => true,
1623                            'expandTemplates' => $this->options['expandTemplates'],
1624                            'inTemplate' => $this->options['inTemplate']
1625                        ],
1626                        'srcOffsets' => $optsCaption['srcOffsets'] ?? null,
1627                        'sol' => true
1628                    ]
1629                );
1630
1631                // Use parsed DOM given in `captionDOM`
1632                // FIXME: Does this belong in `dataMw.attribs`?
1633                $dataMw->caption = $captionDOM;
1634            }
1635        } else {
1636            // We always add a figcaption for blocks
1637            $tsr = $optsCaption['srcOffsets'] ?? null;
1638            $dp = new DataParsoid;
1639            $dp->tsr = $tsr;
1640            $tokens[] = new TagTk( 'figcaption', [], $dp );
1641            if ( $optsCaption ) {
1642                if ( is_string( $optsCaption['v'] ) ) {
1643                    $tokens[] = $optsCaption['v'];
1644                } else {
1645                    $tokens[] = PipelineUtils::getDOMFragmentToken(
1646                        $optsCaption['v'],
1647                        $tsr,
1648                        [ 'inlineContext' => true, 'token' => $token ]
1649                    );
1650                }
1651            }
1652            $tokens[] = new EndTagTk( 'figcaption' );
1653        }
1654
1655        if ( !$dataMw->isEmpty() ) {
1656            $container->dataMw = $dataMw;
1657        }
1658
1659        $tokens[] = $containerClose;
1660        return $tokens;
1661    }
1662
1663    /**
1664     * Get a URL pointing to Special:Upload or a customized upload URL, depending on the site config.
1665     */
1666    private function getUploadUrl( LinkTarget $title ): string {
1667        return $this->env->getSiteConfig()->getUploadUrl( $title );
1668    }
1669
1670    /**
1671     * @param Token $token
1672     * @param stdClass $target
1673     * @param list<DataMwError> $errs
1674     * @param ?array{url?:string,canonicaltitle?:LinkTarget} $info
1675     * @return array<string|Token>
1676     */
1677    private function linkToMedia( Token $token, stdClass $target, array $errs, ?array $info ): array {
1678        // Only pass in the url, since media links should not link to the thumburl
1679        $imgHref = $info['url'] ?? $this->getUploadUrl( $target->title );  // Copied from getPath
1680
1681        $link = new TagTk( 'a' );
1682
1683        try {
1684            $content = $this->addLinkAttributesAndGetContent( $link, $token, $target );
1685        } catch ( InternalException ) {
1686            return self::bailTokens( $this->manager, $token );
1687        }
1688
1689        // Change the rel to be mw:MediaLink
1690        $link->getAttributeKV( 'rel' )->v = 'mw:MediaLink';
1691
1692        $link->addNormalizedAttribute( 'href', $imgHref, $target->hrefSrc );
1693
1694        // html2wt will use the resource rather than try to parse the href.
1695        $link->addNormalizedAttribute(
1696            'resource',
1697            $this->env->makeLink( $target->title ),
1698            $target->hrefSrc
1699        );
1700
1701        $link->setAttribute(
1702            'title', isset( $info['canonicaltitle'] ) ?
1703                $info['canonicaltitle']->getText() : $target->title->getText()
1704        );
1705
1706        if ( count( $errs ) > 0 ) {
1707            // Set RDFa type to mw:Error so VE and other clients
1708            // can use this to do client-specific action on these.
1709            if ( !TokenUtils::hasTypeOf( $link, 'mw:Error' ) ) {
1710                $link->addSpaceSeparatedAttribute( 'typeof', 'mw:Error' );
1711            }
1712
1713            // Update data-mw
1714            $dataMw = $token->dataMw ?? new DataMw;
1715            if ( is_array( $dataMw->errors ?? null ) ) {
1716                array_push( $dataMw->errors, ...$errs );
1717            } else {
1718                $dataMw->errors = $errs;
1719            }
1720            $link->dataMw = $dataMw;
1721        }
1722
1723        return array_merge( [ $link ], $content, [ new EndTagTk( 'a' ) ] );
1724    }
1725
1726    /**
1727     * FIXME: The media request here is only used to determine if this is a
1728     * redlink and deserves to be handling in the redlink post-processing pass.
1729     * @return array<string|Token>
1730     */
1731    private function renderMedia( Token $token, stdClass $target ): array {
1732        $env = $this->env;
1733        $title = $target->title;
1734        $errs = [];
1735        $info = $env->getDataAccess()->getFileInfo(
1736            $env->getPageConfig(),
1737            [ [ $title->getDBkey(), [ 'height' => null, 'width' => null ] ] ]
1738        )[0];
1739        if ( !$info ) {
1740            $errs[] = new DataMwError( 'apierror-filedoesnotexist', [], 'This image does not exist.' );
1741        } elseif ( isset( $info['thumberror'] ) ) {
1742            $errs[] = new DataMwError( 'apierror-unknownerror', [], $info['thumberror'] );
1743        }
1744        // The legacy parser records a media link in the imagelinks table.
1745        // It also records a missing file.
1746        $env->getMetadata()->addImage(
1747            $title,
1748            $info['timestamp'] ?? null,
1749            $info['sha1'] ?? null
1750        );
1751        return $this->linkToMedia( $token, $target, $errs, $info );
1752    }
1753
1754    /** @inheritDoc */
1755    public function onTag( XMLTagTk $token ): ?array {
1756        return match ( $token->getName() ) {
1757            'wikilink' => $this->onWikiLink( $token ),
1758            'mw:redirect' => $this->onRedirect( $token ),
1759            default => null
1760        };
1761    }
1762}