Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 206
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
ExternalLinkHandler
0.00% covered (danger)
0.00%
0 / 206
0.00% covered (danger)
0.00%
0 / 9
2970
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 imageExtensions
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 arraySome
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 hasImageLink
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 onUrlLink
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
90
 onExtLink
0.00% covered (danger)
0.00%
0 / 83
0.00% covered (danger)
0.00%
0 / 1
462
 getTemplateInfo
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
132
 wrapReturn
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 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
4namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6use Wikimedia\Parsoid\Core\Sanitizer;
7use Wikimedia\Parsoid\DOM\Element;
8use Wikimedia\Parsoid\DOM\Node;
9use Wikimedia\Parsoid\Html2Wt\WTSUtils;
10use Wikimedia\Parsoid\NodeData\DataParsoid;
11use Wikimedia\Parsoid\NodeData\TemplateInfo;
12use Wikimedia\Parsoid\Tokens\EndTagTk;
13use Wikimedia\Parsoid\Tokens\KV;
14use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
15use Wikimedia\Parsoid\Tokens\TagTk;
16use Wikimedia\Parsoid\Tokens\Token;
17use Wikimedia\Parsoid\Tokens\XMLTagTk;
18use Wikimedia\Parsoid\Utils\DOMDataUtils;
19use Wikimedia\Parsoid\Utils\DOMUtils;
20use Wikimedia\Parsoid\Utils\PHPUtils;
21use Wikimedia\Parsoid\Utils\PipelineUtils;
22use Wikimedia\Parsoid\Utils\TokenUtils;
23use Wikimedia\Parsoid\Utils\WTUtils;
24use Wikimedia\Parsoid\Wt2Html\PegTokenizer;
25
26class ExternalLinkHandler extends XMLTagBasedHandler {
27    /** @var PegTokenizer */
28    private $urlParser;
29
30    /** @inheritDoc */
31    public function __construct( object $manager, array $options ) {
32        parent::__construct( $manager, $options );
33
34        // Create a new peg parser for image options.
35        if ( !$this->urlParser ) {
36            // Actually the regular tokenizer, but we'll call it with the
37            // url rule only.
38            $this->urlParser = new PegTokenizer( $this->env );
39        }
40    }
41
42    private static function imageExtensions( string $str ): bool {
43        return match ( $str ) {
44            'avif', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp' => true,
45            default => false
46        };
47    }
48
49    private function arraySome( array $array, callable $fn ): bool {
50        foreach ( $array as $value ) {
51            if ( $fn( $value ) ) {
52                return true;
53            }
54        }
55        return false;
56    }
57
58    private function hasImageLink( string $href ): bool {
59        $allowedPrefixes = $this->env->getSiteConfig()->allowedExternalImagePrefixes();
60        $bits = explode( '.', $href );
61        $hasImageExtension = count( $bits ) > 1 &&
62            self::imageExtensions( end( $bits ) ) &&
63            preg_match( '#^https?://#i', $href );
64        // Typical settings for mediawiki configuration variables
65        // $wgAllowExternalImages and $wgAllowExternalImagesFrom will
66        // result in values like these:
67        //  allowedPrefixes = undefined; // no external images
68        //  allowedPrefixes = [''];      // allow all external images
69        //  allowedPrefixes = ['http://127.0.0.1/', 'http://example.com'];
70        // Note that the values include the http:// or https:// protocol.
71        // See https://phabricator.wikimedia.org/T53092
72        return $hasImageExtension &&
73            // true if some prefix in the list matches href
74            self::arraySome( $allowedPrefixes, static function ( string $prefix ) use ( &$href ) {
75                return $prefix === "" || str_starts_with( $href, $prefix );
76            } );
77    }
78
79    /**
80     * @return ?array<string|Token>
81     */
82    private function onUrlLink( Token $token ): ?array {
83        $env = $this->env;
84        $origHref = $token->getAttributeV( 'href' );
85        $dataParsoid = clone $token->dataParsoid;
86        $dataMw = $token->dataMw ? clone $token->dataMw : null;
87
88        $hrefTokens = TokenUtils::tokensToString( $origHref, true, [
89            'includeEntities' => true,
90            'includeUrlLink' => true,
91        ] );
92
93        // We assume that, if $hrefTokens is an array, then some part of
94        // it is templated.  However, in some cases (like the content of
95        // templated extensions), we may be expanding templates but not
96        // wrappping them, in which case we won't find tplarginfo
97        $wrapTemplates = !$this->options['inTemplate'];
98        $tplarginfo = null;
99        if ( is_array( $hrefTokens ) ) {
100            if ( $wrapTemplates ) {
101                $tplarginfo = $this->getTemplateInfo( $token );
102            }
103            $max = count( $origHref ) - count( $hrefTokens[1] );
104            // Conservatively, only include the rest of the tokens as content
105            // if we aren't wrapping or if we find template info
106            // For example, we might have bailed on the template
107            // (convertToString) in which case we need another way to avoid
108            // dirtying when roundtripping
109            $content = ( !$wrapTemplates || $tplarginfo ) ? $hrefTokens[1] : [];
110        } else {
111            $max = null;
112            $content = [];
113        }
114        $href = TokenUtils::tokensToString( $origHref, false, [], $max );
115
116        if ( $this->hasImageLink( $href ) ) {
117            $checkAlt = explode( '/', $href );
118            $tagAttrs = [
119                new KV( 'src', $href ),
120                new KV( 'alt', end( $checkAlt ) ),
121                new KV( 'rel', 'mw:externalImage' )
122            ];
123
124            // combine with existing rdfa attrs
125            $tagAttrs = WikiLinkHandler::buildLinkAttrs(
126                $token->attribs, false, null, $tagAttrs )['attribs'];
127            return [ new SelfclosingTagTk( 'img', $tagAttrs, $dataParsoid, $dataMw ) ];
128        } else {
129            $tagAttrs = [
130                new KV( 'rel', 'mw:ExtLink' )
131            ];
132
133            // combine with existing rdfa attrs
134            // href is set explicitly below
135            $tagAttrs = WikiLinkHandler::buildLinkAttrs(
136                $token->attribs, false, null, $tagAttrs )['attribs'];
137            $builtTag = new TagTk( 'a', $tagAttrs, $dataParsoid, $dataMw );
138            $dataParsoid->stx = 'url';
139
140            if ( !$this->options['inTemplate'] ) {
141                // Since we messed with the text of the link, we need
142                // to preserve the original in the RT data. Or else.
143                $builtTag->addNormalizedAttribute(
144                    'href', $href, $token->getWTSource( $this->manager->getFrame()->getSource() )
145                );
146            } else {
147                $builtTag->addAttribute( 'href', $href );
148            }
149
150            $dp = new DataParsoid;
151            $dp->tsr = $dataParsoid->tsr->expandTsrK()->value;
152
153            $ret = array_merge( [
154                $builtTag,
155                // Make sure there are no IDN-ignored characters in the text so
156                // the user doesn't accidentally copy any.
157                Sanitizer::cleanUrl( $env->getSiteConfig(), $href, 'wikilink' ), // mode could be 'wikilink'
158                new EndTagTk( 'a', [], $dp )
159            ], $content );
160
161            if ( $tplarginfo !== null ) {
162                $this->wrapReturn( $token, $tplarginfo, $ret );
163            }
164            return $ret;
165        }
166    }
167
168    /**
169     * Bracketed external link
170     * @param Token $token
171     * @return ?array<string|Token>
172     */
173    private function onExtLink( Token $token ): ?array {
174        $env = $this->env;
175        $origHref = $token->getAttributeV( 'href' );
176        $hasExpandedAttrs = TokenUtils::hasTypeOf( $token, 'mw:ExpandedAttrs' );
177        $dataParsoid = clone $token->dataParsoid;
178        $dataMw = $token->dataMw ? clone $token->dataMw : null;
179        $magLinkType = TokenUtils::matchTypeOf(
180            $token, '#^mw:(Ext|Wiki)Link/(ISBN|RFC|PMID)$#'
181        );
182
183        $content = $token->getAttributeV( 'mw:content' );
184        if ( !is_array( $content ) ) {
185            $content = [ $content ];
186        }
187
188        $hrefTokens = TokenUtils::tokensToString( $origHref, true, [
189            'includeEntities' => true,
190            'includeUrlLink' => true,
191        ] );
192        if ( is_array( $hrefTokens ) ) {
193            $max = count( $origHref ) - count( $hrefTokens[1] );
194            $hrefWithEntities = $hrefTokens[0];
195        } else {
196            $max = null;
197            $hrefWithEntities = $hrefTokens;
198        }
199        $href = TokenUtils::tokensToString( $origHref, false, [], $max );
200
201        if ( $magLinkType ) {
202            $newHref = $href;
203            $newRel = 'mw:ExtLink';
204            if ( str_ends_with( $magLinkType, '/ISBN' ) ) {
205                $newHref = $env->getSiteConfig()->relativeLinkPrefix() . $href;
206                // ISBNs use mw:WikiLink instead of mw:ExtLink
207                $newRel = 'mw:WikiLink';
208            }
209            $newAttrs = [
210                new KV( 'href', $newHref ),
211                new KV( 'rel', $newRel )
212            ];
213            $token->removeAttribute( 'typeof' );
214
215            // SSS FIXME: Right now, Parsoid does not support templating
216            // of ISBN attributes.  So, "ISBN {{1x|1234567890}}" will not
217            // parse as you might expect it to.  As a result, this code below
218            // that attempts to combine rdf attrs from earlier is unnecessary
219            // right now.  But, it will become necessary if Parsoid starts
220            // supporting templating of ISBN attributes.
221            //
222            // combine with existing rdfa attrs
223            $newAttrs = WikiLinkHandler::buildLinkAttrs(
224                $token->attribs, false, null, $newAttrs )['attribs'];
225            $aStart = new TagTk( 'a', $newAttrs, $dataParsoid, $dataMw );
226            $tokens = array_merge( [ $aStart ], $content, [ new EndTagTk( 'a' ) ] );
227            return $tokens;
228        } elseif (
229            ( !$hasExpandedAttrs && is_string( $origHref ) ) ||
230            $this->urlParser->tokenizeURL( $hrefWithEntities ) !== false
231        ) {
232            // We assume that, if $hrefTokens is an array, then some part of
233            // it is templated.  However, in some cases (like the content of
234            // templated extensions), we may be expanding templates but not
235            // wrappping them, in which case we won't find tplarginfo
236            $wrapTemplates = !$this->options['inTemplate'];
237            $tplarginfo = null;
238            if ( is_array( $hrefTokens ) ) {
239                if ( $wrapTemplates ) {
240                    $tplarginfo = $this->getTemplateInfo( $token );
241                }
242                // Conservatively, only include the rest of the tokens as content
243                // if we aren't wrapping or if we find template info
244                // For example, we might have bailed on the template
245                // (convertToString) in which case we need another way to avoid
246                // dirtying when roundtripping
247                if ( !$wrapTemplates || $tplarginfo ) {
248                    $content = array_merge( $hrefTokens[1], $content );
249                }
250            }
251
252            if ( count( $content ) === 1 && is_string( $content[0] ) ) {
253                $src = $content[0];
254                if ( $env->getSiteConfig()->hasValidProtocol( $src ) &&
255                    $this->urlParser->tokenizeURL( $src ) !== false &&
256                    $this->hasImageLink( $src )
257                ) {
258                    $checkAlt = explode( '/', $src );
259                    $dp = new DataParsoid;
260                    $dp->type = 'extlink';
261                    $content = [ new SelfclosingTagTk( 'img', [
262                        new KV( 'src', $src ),
263                        new KV( 'alt', end( $checkAlt ) )
264                        ], $dp
265                    ) ];
266                }
267            }
268
269            $newAttrs = [ new KV( 'rel', 'mw:ExtLink' ) ];
270            // combine with existing rdfa attrs
271            // href is set explicitly below
272            $newAttrs = WikiLinkHandler::buildLinkAttrs(
273                $token->attribs, false, null, $newAttrs
274            )['attribs'];
275            $aStart = new TagTk( 'a', $newAttrs, $dataParsoid, $dataMw );
276
277            if ( !$this->options['inTemplate'] ) {
278                // If we are from a top-level page, add normalized attr info for
279                // accurate roundtripping of original content.
280                //
281                // extLinkContentOffsets->start covers all spaces before content
282                // and we need src without those spaces.
283                $tsr0a = $dataParsoid->tsr->start + 1;
284                $tsr1a = $dataParsoid->tmp->extLinkContentOffsets->start -
285                    strlen( $token->getAttributeV( 'spaces' ) ?? '' );
286                $length = $tsr1a - $tsr0a;
287                $source = $dataParsoid->tsr->source ?? $this->manager->getFrame()->getSource();
288                $aStart->addNormalizedAttribute( 'href', $href,
289                    PHPUtils::safeSubstr( $source->getSrcText(), $tsr0a, $length ) );
290            } else {
291                $aStart->addAttribute( 'href', $href );
292            }
293
294            $content = PipelineUtils::getDOMFragmentToken(
295                $content,
296                $dataParsoid->tsr ? $dataParsoid->tmp->extLinkContentOffsets : null,
297                [ 'inlineContext' => true, 'token' => $token ]
298            );
299
300            $ret = [ $aStart, $content, new EndTagTk( 'a' ) ];
301            if ( $tplarginfo !== null ) {
302                $this->wrapReturn( $token, $tplarginfo, $ret );
303            }
304            return $ret;
305        } else {
306            // Not a link, convert href to plain text.
307            return WikiLinkHandler::bailTokens( $this->manager, $token );
308        }
309    }
310
311    private function getTemplateInfo( Token $token ): ?TemplateInfo {
312        // The token should have expanded attributes
313        if ( $token->dataMw === null ) {
314            return null;
315        }
316
317        $df = WTSUtils::getAttrFromDataMw(
318            $token->dataMw, 'href', true
319        )->value['html'] ?? null;
320        if ( $df == null ) {
321            return null;
322        }
323
324        $tpl = null;
325        DOMUtils::visitDOM( $df, static function ( Node $node ) use ( &$tpl ) {
326            if (
327                $tpl == null && $node instanceof Element &&
328                WTUtils::matchTplType( $node )
329            ) {
330                $tpl = $node;
331            }
332        } );
333        if ( $tpl === null ) {
334            return null;
335        }
336
337        $tplarginfo = null;
338        foreach ( ( DOMDataUtils::getDataMw( $tpl )->parts ?? [] ) as $part ) {
339            if ( $part instanceof TemplateInfo ) {
340                $tplarginfo = clone $part;
341                $tplDsr = DOMDataUtils::getDataParsoid( $tpl )->dsr;
342                $tkTsr = $token->dataParsoid->tsr;
343                $str = $tkTsr->source->getSrcText();
344                if ( $tplDsr->start > $tkTsr->start ) {
345                    $tplarginfo->prePart = PHPUtils::safeSubstr(
346                        $str, $tkTsr->start, $tplDsr->start - $tkTsr->start
347                    );
348                }
349                if ( $tkTsr->end > $tplDsr->end ) {
350                    $tplarginfo->postPart = PHPUtils::safeSubstr(
351                        $str, $tplDsr->end, $tkTsr->end - $tplDsr->end
352                    );
353                }
354                break;
355            }
356        }
357        return $tplarginfo;
358    }
359
360    private function wrapReturn( Token $token, TemplateInfo $tplarginfo, array &$ret ) {
361        $dp = new DataParsoid;
362        $dp->tsr = clone $token->dataParsoid->tsr;
363        $dp->getTemp()->tplarginfo = $tplarginfo;
364
365        $aboutId = $this->env->newAboutId();
366        $attrs = [
367            new KV( 'typeof', 'mw:Transclusion' ),
368            new KV( 'about', $aboutId )
369        ];
370        $startMeta = new SelfclosingTagTk( 'meta', $attrs, $dp );
371        array_unshift( $ret, $startMeta );
372        $attrs = [
373            new KV( 'typeof', 'mw:Transclusion/End' ),
374            new KV( 'about', $aboutId )
375        ];
376        $endMeta = new SelfclosingTagTk( 'meta', $attrs, $dp );
377        array_push( $ret, $endMeta );
378    }
379
380    /** @inheritDoc */
381    public function onTag( XMLTagTk $token ): ?array {
382        return match ( $token->getName() ) {
383            'urllink' => $this->onUrlLink( $token ),
384            'extlink' => $this->onExtLink( $token ),
385            default => null
386        };
387    }
388}