Debian Codegraph @

vendor/wikimedia/parsoid/src/Wt2Html/TT/ExternalLinkHandler.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6 use Wikimedia\Parsoid\Core\Sanitizer;
7 use Wikimedia\Parsoid\NodeData\DataParsoid;
8 use Wikimedia\Parsoid\Tokens\EndTagTk;
9 use Wikimedia\Parsoid\Tokens\KV;
10 use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
11 use Wikimedia\Parsoid\Tokens\TagTk;
12 use Wikimedia\Parsoid\Tokens\Token;
13 use Wikimedia\Parsoid\Utils\PipelineUtils;
14 use Wikimedia\Parsoid\Utils\TokenUtils;
15 use Wikimedia\Parsoid\Wt2Html\PegTokenizer;
16
17 class ExternalLinkHandler extends TokenHandler {
18 /** @var PegTokenizer */
19 private $urlParser;
20
21 /** @inheritDoc */
22 public function __construct( object $manager, array $options ) {
23 parent::__construct( $manager, $options );
24
25 // Create a new peg parser for image options.
26 if ( !$this->urlParser ) {
27 // Actually the regular tokenizer, but we'll call it with the
28 // url rule only.
29 $this->urlParser = new PegTokenizer( $this->env );
30 }
31 }
32
33 private static function imageExtensions( string $str ): bool {
34 switch ( $str ) {
35 case 'avif': // fall through
36 case 'gif': // fall through
37 case 'jpeg': // fall through
38 case 'jpg': // fall through
39 case 'png': // fall through
40 case 'svg':
41 case 'webp':
42 return true;
43 default:
44 return false;
45 }
46 }
47
48 private function arraySome( array $array, callable $fn ): bool {
49 foreach ( $array as $value ) {
50 if ( $fn( $value ) ) {
51 return true;
52 }
53 }
54 return false;
55 }
56
57 private function hasImageLink( string $href ): bool {
58 $allowedPrefixes = $this->env->getSiteConfig()->allowedExternalImagePrefixes();
59 $bits = explode( '.', $href );
60 $hasImageExtension = count( $bits ) > 1 &&
61 self::imageExtensions( end( $bits ) ) &&
62 preg_match( '#^https?://#i', $href );
63 // Typical settings for mediawiki configuration variables
64 // $wgAllowExternalImages and $wgAllowExternalImagesFrom will
65 // result in values like these:
66 // allowedPrefixes = undefined; // no external images
67 // allowedPrefixes = ['']; // allow all external images
68 // allowedPrefixes = ['http://127.0.0.1/', 'http://example.com'];
69 // Note that the values include the http:// or https:// protocol.
70 // See https://phabricator.wikimedia.org/T53092
71 return $hasImageExtension &&
72 // true if some prefix in the list matches href
73 self::arraySome( $allowedPrefixes, static function ( string $prefix ) use ( &$href ) {
74 return $prefix === "" || strpos( $href, $prefix ) === 0;
75 } );
76 }
77
78 private function onUrlLink( Token $token ): ?TokenHandlerResult {
79 $tagAttrs = null;
80 $builtTag = null;
81 $env = $this->env;
82 $origHref = $token->getAttributeV( 'href' );
83 $href = TokenUtils::tokensToString( $origHref );
84 $dataParsoid = $token->dataParsoid->clone();
85 $dataMw = $token->dataMw ? $token->dataMw->clone() : null;
86
87 if ( $this->hasImageLink( $href ) ) {
88 $checkAlt = explode( '/', $href );
89 $tagAttrs = [
90 new KV( 'src', $href ),
91 new KV( 'alt', end( $checkAlt ) ),
92 new KV( 'rel', 'mw:externalImage' )
93 ];
94
95 // combine with existing rdfa attrs
96 $tagAttrs = WikiLinkHandler::buildLinkAttrs(
97 $token->attribs, false, null, $tagAttrs )['attribs'];
98 return new TokenHandlerResult(
99 [ new SelfclosingTagTk( 'img', $tagAttrs, $dataParsoid, $dataMw ) ] );
100 } else {
101 $tagAttrs = [
102 new KV( 'rel', 'mw:ExtLink' )
103 ];
104
105 // combine with existing rdfa attrs
106 // href is set explicitly below
107 $tagAttrs = WikiLinkHandler::buildLinkAttrs(
108 $token->attribs, false, null, $tagAttrs )['attribs'];
109 $builtTag = new TagTk( 'a', $tagAttrs, $dataParsoid, $dataMw );
110 $dataParsoid->stx = 'url';
111
112 if ( !$this->options['inTemplate'] ) {
113 // Since we messed with the text of the link, we need
114 // to preserve the original in the RT data. Or else.
115 $builtTag->addNormalizedAttribute(
116 'href', $href, $token->getWTSource( $this->manager->getFrame() )
117 );
118 } else {
119 $builtTag->addAttribute( 'href', $href );
120 }
121
122 $dp = new DataParsoid;
123 $dp->tsr = $dataParsoid->tsr->expandTsrK()->value;
124 return new TokenHandlerResult( [
125 $builtTag,
126 // Make sure there are no IDN-ignored characters in the text so
127 // the user doesn't accidentally copy any.
128 Sanitizer::cleanUrl( $env->getSiteConfig(), $href, '' ), // mode could be 'wikilink'
129 new EndTagTk(
130 'a',
131 [],
132 $dp
133 )
134 ]
135 );
136 }
137 }
138
139 /**
140 * Bracketed external link
141 * @param Token $token
142 * @return TokenHandlerResult|null
143 */
144 private function onExtLink( Token $token ): ?TokenHandlerResult {
145 $newAttrs = null;
146 $aStart = null;
147 $env = $this->env;
148 $origHref = $token->getAttributeV( 'href' );
149 $hasExpandedAttrs = TokenUtils::hasTypeOf( $token, 'mw:ExpandedAttrs' );
150 $href = TokenUtils::tokensToString( $origHref );
151 $hrefWithEntities = TokenUtils::tokensToString( $origHref, false, [
152 'includeEntities' => true
153 ]
154 );
155 $content = $token->getAttributeV( 'mw:content' );
156 $dataParsoid = $token->dataParsoid->clone();
157 $dataMw = $token->dataMw ? $token->dataMw->clone() : null;
158 $magLinkType = TokenUtils::matchTypeOf(
159 $token, '#^mw:(Ext|Wiki)Link/(ISBN|RFC|PMID)$#'
160 );
161 $tokens = null;
162
163 if ( $magLinkType ) {
164 $newHref = $href;
165 $newRel = 'mw:ExtLink';
166 if ( str_ends_with( $magLinkType, '/ISBN' ) ) {
167 $newHref = $env->getSiteConfig()->relativeLinkPrefix() . $href;
168 // ISBNs use mw:WikiLink instead of mw:ExtLink
169 $newRel = 'mw:WikiLink';
170 }
171 $newAttrs = [
172 new KV( 'href', $newHref ),
173 new KV( 'rel', $newRel )
174 ];
175 $token->removeAttribute( 'typeof' );
176
177 // SSS FIXME: Right now, Parsoid does not support templating
178 // of ISBN attributes. So, "ISBN {{1x|1234567890}}" will not
179 // parse as you might expect it to. As a result, this code below
180 // that attempts to combine rdf attrs from earlier is unnecessary
181 // right now. But, it will become necessary if Parsoid starts
182 // supporting templating of ISBN attributes.
183 //
184 // combine with existing rdfa attrs
185 $newAttrs = WikiLinkHandler::buildLinkAttrs(
186 $token->attribs, false, null, $newAttrs )['attribs'];
187 $aStart = new TagTk( 'a', $newAttrs, $dataParsoid, $dataMw );
188 $tokens = array_merge( [ $aStart ],
189 is_array( $content ) ? $content : [ $content ], [ new EndTagTk( 'a' ) ] );
190 return new TokenHandlerResult( $tokens );
191 } elseif ( ( !$hasExpandedAttrs && is_string( $origHref ) ) ||
192 $this->urlParser->tokenizeURL( $hrefWithEntities ) !== false
193 ) {
194 if ( is_array( $content ) && count( $content ) === 1 && is_string( $content[0] ) ) {
195 $src = $content[0];
196 if ( $env->getSiteConfig()->hasValidProtocol( $src ) &&
197 $this->urlParser->tokenizeURL( $src ) !== false &&
198 $this->hasImageLink( $src )
199 ) {
200 $checkAlt = explode( '/', $src );
201 $dp = new DataParsoid;
202 $dp->type = 'extlink';
203 $content = [ new SelfclosingTagTk( 'img', [
204 new KV( 'src', $src ),
205 new KV( 'alt', end( $checkAlt ) )
206 ], $dp
207 ) ];
208 }
209 }
210
211 $newAttrs = [ new KV( 'rel', 'mw:ExtLink' ) ];
212 // combine with existing rdfa attrs
213 // href is set explicitly below
214 $newAttrs = WikiLinkHandler::buildLinkAttrs(
215 $token->attribs, false, null, $newAttrs )['attribs'];
216 $aStart = new TagTk( 'a', $newAttrs, $dataParsoid, $dataMw );
217
218 if ( !$this->options['inTemplate'] ) {
219 // If we are from a top-level page, add normalized attr info for
220 // accurate roundtripping of original content.
221 //
222 // extLinkContentOffsets->start covers all spaces before content
223 // and we need src without those spaces.
224 $tsr0a = $dataParsoid->tsr->start + 1;
225 $tsr1a = $dataParsoid->tmp->extLinkContentOffsets->start -
226 strlen( $token->getAttributeV( 'spaces' ) ?? '' );
227 $length = $tsr1a - $tsr0a;
228 $aStart->addNormalizedAttribute( 'href', $href,
229 substr( $this->manager->getFrame()->getSrcText(), $tsr0a, $length ) );
230 } else {
231 $aStart->addAttribute( 'href', $href );
232 }
233
234 $content = PipelineUtils::getDOMFragmentToken(
235 $content,
236 $dataParsoid->tsr ? $dataParsoid->tmp->extLinkContentOffsets : null,
237 [ 'inlineContext' => true, 'token' => $token ]
238 );
239
240 $tokens = [ $aStart, $content, new EndTagTk( 'a' ) ];
241 return new TokenHandlerResult( $tokens );
242 } else {
243 // Not a link, convert href to plain text.
244 return new TokenHandlerResult( WikiLinkHandler::bailTokens( $this->manager, $token ) );
245 }
246 }
247
248 /** @inheritDoc */
249 public function onTag( Token $token ): ?TokenHandlerResult {
250 switch ( $token->getName() ) {
251 case 'urllink':
252 return $this->onUrlLink( $token );
253 case 'extlink':
254 return $this->onExtLink( $token );
255 default:
256 return null;
257 }
258 }
259 }