Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| Hooks | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
7 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| onLinkerMakeExternalLink | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
6 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Copyright (C) 2018 Kunal Mehta <legoktm@debian.org> |
| 4 | * |
| 5 | * This program is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation; either version 3 of the License, or |
| 8 | * (at your option) any later version. |
| 9 | * |
| 10 | * This program is distributed in the hope that it will be useful, |
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | * GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | namespace MediaWiki\SecureLinkFixer; |
| 20 | |
| 21 | use MediaWiki\Hook\LinkerMakeExternalLinkHook; |
| 22 | use MediaWiki\Utils\UrlUtils; |
| 23 | |
| 24 | class Hooks implements LinkerMakeExternalLinkHook { |
| 25 | |
| 26 | public function __construct( |
| 27 | private readonly HSTSPreloadLookup $lookup, |
| 28 | private readonly UrlUtils $urlUtils, |
| 29 | ) { |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Hook: LinkerMakeExternalLink |
| 34 | * |
| 35 | * Changes the scheme of the URL to HTTPS if necessary |
| 36 | * |
| 37 | * @param string &$url Link URL |
| 38 | * @param string &$text Link text |
| 39 | * @param string &$link New link HTML (if returning false) |
| 40 | * @param string[] &$attribs Attributes to be applied |
| 41 | * @param string $linkType External link type |
| 42 | * @return bool|void True or no return value to continue or false to abort |
| 43 | */ |
| 44 | public function onLinkerMakeExternalLink( |
| 45 | &$url, &$text, &$link, &$attribs, $linkType |
| 46 | ) { |
| 47 | if ( str_starts_with( $url, 'https://' ) ) { |
| 48 | // Already HTTPS |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | $parsed = $this->urlUtils->parse( $url ); |
| 53 | if ( !$parsed ) { |
| 54 | return; |
| 55 | } |
| 56 | |
| 57 | if ( $parsed['scheme'] !== 'http' && $parsed['scheme'] !== '' ) { |
| 58 | // We only want http:// and proto-rel |
| 59 | return; |
| 60 | } |
| 61 | |
| 62 | if ( $this->lookup->isPreloaded( $parsed['host'] ) ) { |
| 63 | $parsed['scheme'] = 'https'; |
| 64 | $parsed['delimiter'] = '://'; |
| 65 | $url = UrlUtils::assemble( $parsed ); |
| 66 | } |
| 67 | } |
| 68 | } |