urlParser ) {
// Actually the regular tokenizer, but we'll call it with the
// url rule only.
$this->urlParser = new PegTokenizer( $this->env );
}
}
private static function hrefParts( string $str ): ?array {
if ( preg_match( '/^([^:]+):(.*)$/D', $str, $matches ) ) {
return [ 'prefix' => $matches[1], 'title' => $matches[2] ];
} else {
return null;
}
}
/**
* Normalize and analyze a wikilink target.
*
* Returns an object containing
* - href: The expanded target string
* - hrefSrc: The original target wikitext
* - title: A title object *or*
* - language: An interwikiInfo object *or*
* - interwiki: An interwikiInfo object.
* - localprefix: Set if the link had a localinterwiki prefix (or prefixes)
* - fromColonEscapedText: Target was colon-escaped ([[:en:foo]])
* - prefix: The original namespace or language/interwiki prefix without a
* colon escape.
*
* @param Token $token
* @param string $href
* @param string $hrefSrc
* @return stdClass The target info.
* @throws InternalException
*/
private function getWikiLinkTargetInfo( Token $token, string $href, string $hrefSrc ): stdClass {
$env = $this->env;
$siteConfig = $env->getSiteConfig();
$info = (object)[
'href' => $href,
'hrefSrc' => $hrefSrc,
// Initialize these properties to avoid isset checks
'interwiki' => null,
'language' => null,
'localprefix' => null,
'fromColonEscapedText' => null
];
if ( ( ltrim( $info->href )[0] ?? '' ) === ':' ) {
$info->fromColonEscapedText = true;
// Remove the colon escape
$info->href = substr( ltrim( $info->href ), 1 );
}
if ( ( $info->href[0] ?? '' ) === ':' ) {
if ( $env->linting( 'multi-colon-escape' ) ) {
$lint = [
'dsr' => DomSourceRange::fromTsr( $token->dataParsoid->tsr ),
'params' => [ 'href' => ':' . $info->href ],
'templateInfo' => null
];
if ( $this->options['inTemplate'] ) {
// Match Linter.findEnclosingTemplateName(), by first
// converting the title to an href using env.makeLink
$name = PHPUtils::stripPrefix(
$env->makeLink( $this->manager->getFrame()->getTitle() ),
'./'
);
$lint['templateInfo'] = [ 'name' => $name ];
// TODO(arlolra): Pass tsr info to the frame
$lint['dsr'] = new DomSourceRange( 0, 0, null, null );
}
$env->recordLint( 'multi-colon-escape', $lint );
}
// This will get caught by the caller, and mark the target as invalid
throw new InternalException( 'Multiple colons prefixing href.' );
}
$title = $env->resolveTitle( Utils::decodeURIComponent( $info->href ) );
$hrefBits = self::hrefParts( $info->href );
if ( $hrefBits ) {
$nsPrefix = $hrefBits['prefix'];
$info->prefix = $nsPrefix;
$nnn = Utils::normalizeNamespaceName( trim( $nsPrefix ) );
$interwikiInfo = $siteConfig->interwikiMapNoNamespaces()[$nnn] ?? null;
// check for interwiki / language links
$ns = $siteConfig->namespaceId( $nnn );
// also check for url to protect against [[constructor:foo]]
if ( $ns !== null ) {
$info->title = $env->makeTitleFromURLDecodedStr( $title );
} elseif ( isset( $interwikiInfo['localinterwiki'] ) ) {
if ( $hrefBits['title'] === '' ) {
// Empty title => main page (T66167)
$info->title = Title::newFromLinkTarget(
$siteConfig->mainPageLinkTarget(), $siteConfig
);
} else {
$info->href = str_contains( $hrefBits['title'], ':' )
? ':' . $hrefBits['title'] : $hrefBits['title'];
// Recurse!
$info = $this->getWikiLinkTargetInfo( $token, $info->href, $info->hrefSrc );
$info->localprefix = $nsPrefix .
( $info->localprefix ? ( ':' . $info->localprefix ) : '' );
}
} elseif ( !empty( $interwikiInfo['url'] ) ) {
$info->href = $hrefBits['title'];
// Ensure a valid title and store it for later use.
// (don't store as $info->title because that signals a wikilink)
$interwikiInfo['title'] = $env->makeTitleFromURLDecodedStr( $title );
// Interwiki or language link? If no language info, or if it starts
// with an explicit ':' (like [[:en:Foo]]), it's not a language link.
if ( $info->fromColonEscapedText ||
( !isset( $interwikiInfo['language'] ) && !isset( $interwikiInfo['extralanglink'] ) )
) {
// An interwiki link.
$info->interwiki = $interwikiInfo;
// Remove the colon escape after an interwiki prefix
if ( ( ltrim( $info->href )[0] ?? '' ) === ':' ) {
$info->href = substr( ltrim( $info->href ), 1 );
}
} else {
// A language link.
$info->language = $interwikiInfo;
}
} else {
$info->title = $env->makeTitleFromURLDecodedStr( $title );
}
} else {
$info->title = $env->makeTitleFromURLDecodedStr( $title );
}
return $info;
}
/**
* Handle mw:redirect tokens
*
* @param Token $token
* @return TokenHandlerResult
* @throws InternalException
*/
private function onRedirect( Token $token ): TokenHandlerResult {
// Avoid duplicating the link-processing code by invoking the
// standard onWikiLink handler on the embedded link, intercepting
// the generated tokens using the callback mechanism, reading
// the href from the result, and then creating a
// token from it.
$rlink = new SelfclosingTagTk( 'link',
Utils::clone( $token->attribs ),
$token->dataParsoid->clone(),
$token->dataMw ? $token->dataMw->clone() : null );
$wikiLinkTk = $rlink->dataParsoid->linkTk;
$rlink->setAttribute( 'rel', 'mw:PageProp/redirect' );
// Remove the nested wikiLinkTk token and the cloned href attribute
unset( $rlink->dataParsoid->linkTk );
$rlink->removeAttribute( 'href' );
// Transfer href attribute back to wikiLinkTk, since it may have been
// template-expanded in the pipeline prior to this point.
$wikiLinkTk->attribs = Utils::clone( $token->attribs );
// Set "redirect" attribute on the wikilink token to indicate that
// image and category links should be handled as plain links.
$wikiLinkTk->setAttribute( 'redirect', 'true' );
// Render the wikilink (including interwiki links, etc) then collect
// the resulting href and transfer it to rlink.
$r = $this->onWikiLink( $wikiLinkTk );
$firstToken = ( $r->tokens[0] ?? null );
$isValid = $firstToken instanceof Token &&
in_array( $firstToken->getName(), [ 'a', 'link' ], true );
if ( $isValid ) {
$da = $r->tokens[0]->dataParsoid;
$rlink->addNormalizedAttribute( 'href', $da->a['href'], $da->sa['href'] );
return new TokenHandlerResult( [ $rlink ] );
} else {
// Bail! Emit tokens as if they were parsed as a list item:
// #REDIRECT....
$src = $rlink->dataParsoid->src;
$tsr = $rlink->dataParsoid->tsr;
preg_match( '/^([^#]*)(#)/', $src, $srcMatch );
$ntokens = strlen( $srcMatch[1] ) ? [ $srcMatch[1] ] : [];
$hashPos = $tsr->start + strlen( $srcMatch[1] );
$tsr0 = new SourceRange( $hashPos, $hashPos + 1 );
$dp = new DataParsoid;
$dp->tsr = $tsr0;
$li = new TagTk(
'listItem',
[ new KV( 'bullets', [ '#' ], $tsr0->expandTsrV() ) ],
$dp );
$ntokens[] = $li;
$ntokens[] = substr( $src, strlen( $srcMatch[0] ) );
PHPUtils::pushArray( $ntokens, $r->tokens );
return new TokenHandlerResult( $ntokens );
}
}
public static function bailTokens( TokenTransformManager $manager, Token $token ): array {
$frame = $manager->getFrame();
$tsr = $token->dataParsoid->tsr;
$frameSrc = $frame->getSrcText();
$linkSrc = $tsr->substr( $frameSrc );
$src = substr( $linkSrc, 1 );
if ( $src === '' ) {
$manager->getEnv()->log(
'error', 'Unable to determine link source.',
"frame: $frameSrc", 'tsr: ', $tsr,
"link: $linkSrc"
);
return [ $linkSrc ]; // Forget about trying to tokenize this
}
$startOffset = $tsr->start + 1;
$toks = PipeLineUtils::processContentInPipeline(
$manager->getEnv(), $frame, $src, [
'sol' => false,
'pipelineType' => 'wikitext-to-expanded-tokens',
'srcOffsets' => new SourceRange( $startOffset, $startOffset + strlen( $src ) ),
'pipelineOpts' => [
'expandTemplates' => $manager->getOptions()['expandTemplates'],
'inTemplate' => $manager->getOptions()['inTemplate'],
],
]
);
TokenUtils::stripEOFTkfromTokens( $toks );
return array_merge( [ '[' ], $toks );
}
/**
* Handle a mw:WikiLink token.
*
* @param Token $token
* @return TokenHandlerResult
* @throws InternalException
*/
private function onWikiLink( Token $token ): TokenHandlerResult {
$env = $this->env;
$hrefKV = $token->getAttributeKV( 'href' );
$hrefTokenStr = TokenUtils::tokensToString( $hrefKV->v );
// Don't allow internal links to pages containing PROTO:
// See Parser::handleInternalLinks2()
if ( $env->getSiteConfig()->hasValidProtocol( $hrefTokenStr ) ) {
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
// Xmlish tags in title position are invalid. Not according to the
// preprocessor ABNF but at later stages in the legacy parser,
// namely handleInternalLinks.
if ( is_array( $hrefKV->v ) ) {
// Use the expanded attr instead of trying to unpackDOMFragments
// since the fragment will have been released when expanding to DOM
$expandedVal = $token->fetchExpandedAttrValue( 'href' );
$expandedDom = DOMUtils::parseHTML( $expandedVal ?? '' );
foreach ( DOMCompat::querySelectorAll( $expandedDom, '[typeof]' ) as $el ) {
if ( DOMUtils::matchTypeOf( $el, '#^mw:(Nowiki|Extension|DOMFragment/sealed)#' ) !== null ) {
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
}
}
// First check if the expanded href contains a pipe.
if ( str_contains( $hrefTokenStr, '|' ) ) {
// It does. This 'href' was templated and also returned other
// parameters separated by a pipe. We don't have any sensible way to
// handle such a construct currently, so prevent people from editing
// it. See T226523
// TODO: add useful debugging info for editors ('if you would like to
// make this content editable, then fix template X..')
// TODO: also check other parameters for pipes!
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
$target = null;
try {
$target = $this->getWikiLinkTargetInfo( $token, $hrefTokenStr, $hrefKV->vsrc );
} catch ( TitleException | InternalException $e ) {
// Invalid title
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
// Ok, it looks like we have a sensible href. Figure out which handler to use.
$isRedirect = (bool)$token->getAttributeV( 'redirect' );
return $this->wikiLinkHandler( $token, $target, $isRedirect );
}
/**
* Figure out which handler to use to render a given WikiLink token. Override
* this method to add new handlers or swap out existing handlers based on the
* target structure.
*
* @param Token $token
* @param stdClass $target
* @param bool $isRedirect
* @return TokenHandlerResult
* @throws InternalException
*/
private function wikiLinkHandler(
Token $token, stdClass $target, bool $isRedirect
): TokenHandlerResult {
$title = $target->title ?? null;
if ( $title ) {
if ( $isRedirect ) {
return $this->renderWikiLink( $token, $target );
}
$siteConfig = $this->env->getSiteConfig();
$nsId = $title->getNamespace();
if ( $nsId === $siteConfig->canonicalNamespaceId( 'media' ) ) {
// Render as a media link.
return $this->renderMedia( $token, $target );
}
if (
!$target->fromColonEscapedText &&
// Protect from purely fragment links on pages in these namespaces
( $target->href[0] ?? '' ) !== '#'
) {
if ( $nsId === $siteConfig->canonicalNamespaceId( 'file' ) ) {
// Render as a file.
return $this->renderFile( $token, $target );
}
if ( $nsId === $siteConfig->canonicalNamespaceId( 'category' ) ) {
// Render as a category membership.
return $this->renderCategory( $token, $target );
}
}
// Render as plain wiki links.
return $this->renderWikiLink( $token, $target );
}
// language and interwiki links
if ( $target->interwiki ) {
return $this->renderInterwikiLink( $token, $target );
}
if ( $target->language ) {
$ns = $this->env->getContextTitle()->getNamespace();
$noLanguageLinks = $this->env->getSiteConfig()->namespaceIsTalk( $ns ) ||
!$this->env->getSiteConfig()->interwikiMagic();
if ( $noLanguageLinks ) {
$target->interwiki = $target->language;
return $this->renderInterwikiLink( $token, $target );
}
return $this->renderLanguageLink( $token, $target );
}
// Neither a title, nor a language or interwiki. Should not happen.
throw new InternalException( 'Unknown link type' );
}
/** ------------------------------------------------------------
* This (overloaded) function does three different things:
* - Extracts link text from attrs (when k === "mw:maybeContent").
* As a performance micro-opt, only does if asked to (getLinkText)
* - Updates existing rdfa type with an additional rdf-type,
* if one is provided (rdfaType)
* - Collates about, typeof, and linkAttrs into a new attr. array
*
* @param array $attrs
* @param bool $getLinkText
* @param ?string $rdfaType
* @param ?array $linkAttrs
* @return array
*/
public static function buildLinkAttrs(
array $attrs, bool $getLinkText, ?string $rdfaType,
?array $linkAttrs
): array {
$newAttrs = [];
$linkTextKVs = [];
$about = null;
// In one pass through the attribute array, fetch about, typeof, and linkText
//
// about && typeof are usually at the end of the array if at all present
foreach ( $attrs as $kv ) {
$k = $kv->k;
$v = $kv->v;
// link-text attrs have the key "maybeContent"
if ( $getLinkText && $k === 'mw:maybeContent' ) {
$linkTextKVs[] = $kv;
} elseif ( is_string( $k ) && $k ) {
if ( trim( $k ) === 'typeof' ) {
$rdfaType = $rdfaType ? $rdfaType . ' ' . $v : $v;
} elseif ( trim( $k ) === 'about' ) {
$about = $v;
}
}
}
if ( $rdfaType ) {
$newAttrs[] = new KV( 'typeof', $rdfaType );
}
if ( $about ) {
$newAttrs[] = new KV( 'about', $about );
}
if ( $linkAttrs ) {
PHPUtils::pushArray( $newAttrs, $linkAttrs );
}
return [
'attribs' => $newAttrs,
'contentKVs' => $linkTextKVs,
'hasRdfaType' => $rdfaType !== null
];
}
/**
* Generic wiki link attribute setup on a passed-in new token based on the
* wikilink token and target. As a side effect, this method also extracts the
* link content tokens and returns them.
*
* @param Token $newTk
* @param Token $token
* @param stdClass $target
* @param bool $buildDOMFragment
* @return array
* @throws InternalException
*/
private function addLinkAttributesAndGetContent(
Token $newTk, Token $token, stdClass $target, bool $buildDOMFragment = false
): array {
$attribs = $token->attribs;
$dataParsoid = $token->dataParsoid;
$dataMw = $token->dataMw;
$newAttrData = self::buildLinkAttrs( $attribs, true, null, [ new KV( 'rel', 'mw:WikiLink' ) ] );
$content = $newAttrData['contentKVs'];
$env = $this->env;
// Set attribs and dataParsoid
$newTk->attribs = $newAttrData['attribs'];
$newTk->dataParsoid = $dataParsoid->clone();
$newTk->dataMw = $dataMw !== null ? $dataMw->clone() : null;
unset( $newTk->dataParsoid->src ); // clear src string since we can serialize this
// Note: Link tails are handled on the DOM in handleLinkNeighbours, so no
// need to handle them here.
$l = count( $content );
if ( $l > 0 ) {
$newTk->dataParsoid->stx = 'piped';
$out = [];
// re-join content bits
foreach ( $content as $i => $kv ) {
$toks = $kv->v;
// since this is already a link, strip autolinks from content
// FIXME: Maybe add a stop in the grammar so that autolinks
// aren't tokenized in link content to begin with?
if ( !is_array( $toks ) ) {
$toks = [ $toks ];
}
$toks = array_values( array_filter( $toks, static function ( $t ) {
return $t !== '';
} ) );
$n = count( $toks );
foreach ( $toks as $j => $t ) {
// Bail on media-syntax in wikilink-syntax scenarios,
// since the legacy parser explodes on [[, last one wins.
// Note that without this, anchors tags in media output
// will be stripped and we won't have the right structure
// when we get to the dom pass to add media info.
if (
$t instanceof TagTk &&
( $t->getName() === 'figure' || $t->getName() === 'span' ) &&
TokenUtils::matchTypeOf( $t, '#^mw:File($|/)#D' ) !== null
) {
throw new InternalException( 'Media-in-link' );
}
if ( $t instanceof TagTk && $t->getName() === 'a' ) {
// Bail on wikilink-syntax in wiklink-syntax scenarios,
// since the legacy parser explodes on [[, last one wins
if (
preg_match(
'#^mw:WikiLink(/Interwiki)?$#D',
$t->getAttributeV( 'rel' ) ?? ''
) &&
// ISBN links don't use wikilink-syntax but still
// get the same "rel", so should be ignored
( $t->dataParsoid->stx ?? '' ) !== 'magiclink'
) {
throw new InternalException( 'Link-in-link' );
}
if ( $j + 1 < $n && $toks[$j + 1] instanceof EndTagTk &&
$toks[$j + 1]->getName() === 'a'
) {
// autonumbered links in the stream get rendered
// as an tag with no content -- but these ought
// to be treated as plaintext since we don't allow
// nested links.
$out[] = '[' . $t->getAttributeV( 'href' ) . ']';
}
// suppress
continue;
}
if ( $t instanceof EndTagTk && $t->getName() === 'a' ) {
continue; // suppress
}
$out[] = $t;
}
if ( $i < $l - 1 ) {
$out[] = '|';
}
}
if ( $buildDOMFragment ) {
// content = [part 0, .. part l-1]
// offsets = [start(part-0), end(part l-1)]
$offsets = isset( $dataParsoid->tsr ) ?
new SourceRange( $content[0]->srcOffsets->value->start,
$content[$l - 1]->srcOffsets->value->end ) : null;
$content = [ PipelineUtils::getDOMFragmentToken( $out, $offsets,
[ 'inlineContext' => true, 'token' => $token ] ) ];
} else {
$content = $out;
}
} else {
$newTk->dataParsoid->stx = 'simple';
$morecontent = Utils::decodeURIComponent( $target->href );
// Try to match labeling in core
if ( $env->getSiteConfig()->namespaceHasSubpages(
$env->getContextTitle()->getNamespace()
) ) {
// subpage links with a trailing slash get the trailing slashes stripped.
// See https://gerrit.wikimedia.org/r/173431
if ( preg_match( '#^((\.\./)+|/)(?!\.\./)(.*?[^/])/+$#D', $morecontent, $match ) ) {
$morecontent = $match[3];
} elseif ( str_starts_with( $morecontent, '../' ) ) {
// Subpages on interwiki / language links aren't valid,
// so $target->title should always be present here
$morecontent = $target->title->getPrefixedText();
}
}
// for interwiki links, include the interwiki prefix in the link text
if ( $target->interwiki ) {
$morecontent = $target->prefix . ':' . $morecontent;
}
// for local links, include the local prefix in the link text
if ( $target->localprefix ) {
$morecontent = $target->localprefix . ':' . $morecontent;
}
$content = [ $morecontent ];
}
return $content;
}
/**
* Render a plain wiki link.
*
* @param Token $token
* @param stdClass $target
* @return TokenHandlerResult
*/
private function renderWikiLink( Token $token, stdClass $target ): TokenHandlerResult {
$newTk = new TagTk( 'a' );
try {
$content = $this->addLinkAttributesAndGetContent( $newTk, $token, $target, true );
} catch ( InternalException $e ) {
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
$newTk->addNormalizedAttribute( 'href', $this->env->makeLink( $target->title ),
$target->hrefSrc );
$newTk->setAttribute( 'title', $target->title->getPrefixedText() );
return new TokenHandlerResult( array_merge( [ $newTk ], $content, [ new EndTagTk( 'a' ) ] ) );
}
/**
* Render a category 'link'. Categories are really page properties, and are
* normally rendered in a box at the bottom of an article.
*
* @param Token $token
* @param stdClass $target
* @return TokenHandlerResult
*/
private function renderCategory( Token $token, stdClass $target ): TokenHandlerResult {
$newTk = new SelfclosingTagTk( 'link' );
try {
$content = $this->addLinkAttributesAndGetContent( $newTk, $token, $target );
} catch ( InternalException $e ) {
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
$env = $this->env;
// Change the rel to be mw:PageProp/Category
$newTk->getAttributeKV( 'rel' )->v = 'mw:PageProp/Category';
$newTk->addNormalizedAttribute( 'href', $env->makeLink( $target->title ), $target->hrefSrc );
// Change the href to include the sort key, if any (but don't update the rt info)
// Fallback to empty string for default sorting
$categorySort = '';
$strContent = str_replace( "\n", '', TokenUtils::tokensToString( $content ) );
if ( $strContent !== '' && $strContent !== $target->href ) {
$categorySort = $strContent;
$hrefkv = $newTk->getAttributeKV( 'href' );
$hrefkv->v .= '#';
$hrefkv->v .= str_replace( '#', '%23', Sanitizer::sanitizeTitleURI( $categorySort, false ) );
}
if ( count( $content ) !== 1 ) {
// Deal with sort keys that come from generated content (transclusions, etc.)
$key = [ 'txt' => 'mw:sortKey' ];
$contentKV = $token->getAttributeKV( 'mw:maybeContent' );
$so = $contentKV->valueOffset();
$val = PipelineUtils::expandAttrValueToDOM(
$this->env,
$this->manager->getFrame(),
[ 'html' => $content, 'srcOffsets' => $so ],
$this->options['expandTemplates'],
$this->options['inTemplate']
);
$attr = new DataMwAttrib( $key, $val );
$dataMw = $newTk->dataMw;
if ( $dataMw ) {
$dataMw->attribs[] = $attr;
} else {
$dataMw = new DataMw( [ 'attribs' => [ $attr ] ] );
}
// Mark token as having expanded attrs
$newTk->addAttribute( 'about', $env->newAboutId() );
$newTk->addSpaceSeparatedAttribute( 'typeof', 'mw:ExpandedAttrs' );
$newTk->dataMw = $dataMw;
}
$this->env->getMetadata()->addCategory( $target->title, $categorySort );
return new TokenHandlerResult( [ $newTk ] );
}
/**
* Render a language link. Those normally appear in the list of alternate
* languages for an article in the sidebar, so are really a page property.
*
* @param Token $token
* @param stdClass $target
* @return TokenHandlerResult
*/
private function renderLanguageLink( Token $token, stdClass $target ): TokenHandlerResult {
// The prefix is listed in the interwiki map
// TODO: If $target->language['deprecated'] is set and
// $target->language['extralanglink'] is *not* set, then we
// should use the normalized language name/prefix (from
// 'deprecated') when calling
// ContentMetadataCollector::addLanguageLink() here (which
// we should eventualy be doing)
// TODO: might also want to add the language *code* here,
// which would be the language['bcp47'] property (added in
// change I82465261bc66f0b0cd30d361c299f08066494762) for an
// extralanglink, or the interwiki prefix otherwise; the
// latter is mediawiki-internal and maybe not BCP-47 compliant.
// This is for clients of the MediaWiki DOM spec HTML: the
// WMF domain prefix, the MediaWiki internal language code,
// and the actual *language* (ie bcp-47 code) can all differ
// from each other, due to various historical infelicities.
// Perhaps a `lang` attribute on the `link` would be appropriate.
$newTk = new SelfclosingTagTk( 'link', [], $token->dataParsoid );
try {
$this->addLinkAttributesAndGetContent( $newTk, $token, $target );
} catch ( InternalException $e ) {
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
// add title attribute giving the presentation name of the
// "extra language link"
// T329303: the 'linktext' comes from the system message
// `interlanguage-link-$prefix` and should be set in integrated mode
// using the localization features; the integrated-mode SiteConfig
// currently never sets the `linktext` property in
// SiteConfig::interwikiMap().
// I52d50e2f75942a849908c6be7fc5169f00a5983a has some partial work
// on this.
if ( isset( $target->language['extralanglink'] ) &&
!empty( $target->language['linktext'] )
) {
// XXX in standalone mode, this is user-interface-language text,
// not "content language" text.
$newTk->addNormalizedAttribute( 'title', $target->language['linktext'], null );
}
// We set an absolute link to the article in the other wiki/language
$title = Sanitizer::sanitizeTitleURI( Utils::decodeURIComponent( $target->href ), false );
$absHref = str_replace( '$1', $title, $target->language['url'] );
if ( isset( $target->language['protorel'] ) ) {
$absHref = preg_replace( '/^https?:/', '', $absHref, 1 );
}
$newTk->addNormalizedAttribute( 'href', $absHref, $target->hrefSrc );
// Change the rel to be mw:PageProp/Language
$newTk->getAttributeKV( 'rel' )->v = 'mw:PageProp/Language';
// Add language link(s) to metadata
$this->env->getMetadata()->addLanguageLink( $target->language['title'] );
return new TokenHandlerResult( [ $newTk ] );
}
/**
* Render an interwiki link.
*
* @param Token $token
* @param stdClass $target
* @return TokenHandlerResult
*/
private function renderInterwikiLink( Token $token, stdClass $target ): TokenHandlerResult {
// The prefix is listed in the interwiki map
$tokens = [];
$newTk = new TagTk( 'a', [], $token->dataParsoid );
try {
$content = $this->addLinkAttributesAndGetContent( $newTk, $token, $target, true );
} catch ( InternalException $e ) {
return new TokenHandlerResult( self::bailTokens( $this->manager, $token ) );
}
// We set an absolute link to the article in the other wiki/language
$isLocal = !empty( $target->interwiki['local'] );
$trimmedHref = trim( $target->href );
$title = Sanitizer::sanitizeTitleURI(
Utils::decodeURIComponent( $trimmedHref ),
!$isLocal
);
$absHref = str_replace( '$1', $title, $target->interwiki['url'] );
if ( isset( $target->interwiki['protorel'] ) ) {
$absHref = preg_replace( '/^https?:/', '', $absHref, 1 );
}
$newTk->addNormalizedAttribute( 'href', $absHref, $target->hrefSrc );
// Change the rel to be mw:ExtLink
$newTk->getAttributeKV( 'rel' )->v = 'mw:WikiLink/Interwiki';
// Remember that this was using wikitext syntax though
$newTk->dataParsoid->isIW = true;
// Add title unless it's just a fragment (and trim off fragment)
// (The normalization here is similar to what Title#getPrefixedDBKey() does.)
if ( $target->href === '' || $target->href[0] !== '#' ) {
$titleAttr = $target->interwiki['prefix'] . ':' .
Utils::decodeURIComponent( str_replace( '_', ' ',
preg_replace( '/#.*/s', '', $trimmedHref, 1 ) ) );
$newTk->setAttribute( 'title', $titleAttr );
}
$tokens[] = $newTk;
PHPUtils::pushArray( $tokens, $content );
$tokens[] = new EndTagTk( 'a' );
return new TokenHandlerResult( $tokens );
}
private static $horizontalAligns = [
// PHP parser wraps in