| 1 | <?php |
| 2 | /** |
| 3 | * Copyright (C) 2018 Kunal Mehta <[email protected]> |
| 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 | private HSTSPreloadLookup $lookup; |
| 27 | private UrlUtils $urlUtils; |
| 28 | |
| 29 | public function __construct( HSTSPreloadLookup $lookup, UrlUtils $urlUtils ) { |
| 30 | $this->lookup = $lookup; |
| 31 | $this->urlUtils = $urlUtils; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Hook: LinkerMakeExternalLink |
| 36 | * |
| 37 | * Changes the scheme of the URL to HTTPS if necessary |
| 38 | * |
| 39 | * @param string &$url Link URL |
| 40 | * @param string &$text Link text |
| 41 | * @param string &$link New link HTML (if returning false) |
| 42 | * @param string[] &$attribs Attributes to be applied |
| 43 | * @param string $linkType External link type |
| 44 | * @return bool|void True or no return value to continue or false to abort |
| 45 | */ |
| 46 | public function onLinkerMakeExternalLink( |
| 47 | &$url, &$text, &$link, &$attribs, $linkType |
| 48 | ) { |
| 49 | if ( str_starts_with( $url, 'https://' ) ) { |
| 50 | // Already HTTPS |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | $parsed = $this->urlUtils->parse( $url ); |
| 55 | if ( !$parsed ) { |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | if ( $parsed['scheme'] !== 'http' && $parsed['scheme'] !== '' ) { |
| 60 | // We only want http:// and proto-rel |
| 61 | return; |
| 62 | } |
| 63 | |
| 64 | if ( $this->lookup->isPreloaded( $parsed['host'] ) ) { |
| 65 | $parsed['scheme'] = 'https'; |
| 66 | $parsed['delimiter'] = '://'; |
| 67 | $url = UrlUtils::assemble( $parsed ); |
| 68 | } |
| 69 | } |
| 70 | } |