/
ExternalLinktype.php
232 lines (218 loc) · 8.11 KB
/
ExternalLinktype.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<?php
namespace TYPO3\CMS\Linkvalidator\Linktype;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use GuzzleHttp\Cookie\CookieJar;
use Mso\IdnaConvert\IdnaConvert;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* This class provides Check External Links plugin implementation
*/
class ExternalLinktype extends AbstractLinktype
{
/**
* Cached list of the URLs, which were already checked for the current processing
*
* @var array
*/
protected $urlReports = [];
/**
* Cached list of all error parameters of the URLs, which were already checked for the current processing
*
* @var array
*/
protected $urlErrorParams = [];
/**
* List of HTTP request headers to use for checking a URL
*
* @var array
*/
protected $headers = [
'User-Agent' => 'TYPO3 linkvalidator',
'Accept' => '*/*',
'Accept-Language' => '*',
'Accept-Encoding' => '*',
];
/**
* @var RequestFactory
*/
protected $requestFactory;
/**
* @var array
*/
protected $errorParams = [];
public function __construct(RequestFactory $requestFactory = null)
{
$this->requestFactory = $requestFactory ?: GeneralUtility::makeInstance(RequestFactory::class);
}
/**
* Checks a given URL for validity
*
* @param string $origUrl The URL to check
* @param array $softRefEntry The soft reference entry which builds the context of that URL
* @param \TYPO3\CMS\Linkvalidator\LinkAnalyzer $reference Parent instance
* @return bool TRUE on success or FALSE on error
* @throws \InvalidArgumentException
*/
public function checkLink($origUrl, $softRefEntry, $reference)
{
$isValidUrl = false;
// use URL from cache, if available
if (isset($this->urlReports[$origUrl])) {
$this->setErrorParams($this->urlErrorParams[$origUrl]);
return $this->urlReports[$origUrl];
}
$options = [
'cookies' => GeneralUtility::makeInstance(CookieJar::class),
'allow_redirects' => ['strict' => true],
'headers' => $this->headers
];
$url = $this->preprocessUrl($origUrl);
if (!empty($url)) {
$isValidUrl = $this->requestUrl($url, 'HEAD', $options);
if (!$isValidUrl) {
// HEAD was not allowed or threw an error, now trying GET
$options['headers']['Range'] = 'bytes=0-4048';
$isValidUrl = $this->requestUrl($url, 'GET', $options);
}
}
$this->urlReports[$origUrl] = $isValidUrl;
$this->urlErrorParams[$origUrl] = $this->errorParams;
return $isValidUrl;
}
/**
* Check URL using the specified request methods
*
* @param string $url
* @param string $method
* @param array $options
* @return bool
*/
protected function requestUrl(string $url, string $method, array $options): bool
{
$this->errorParams = [];
$isValidUrl = false;
try {
$response = $this->requestFactory->request($url, $method, $options);
if ($response->getStatusCode() >= 300) {
$this->errorParams['errorType'] = $response->getStatusCode();
$this->errorParams['message'] = $this->getErrorMessage($this->errorParams);
} else {
$isValidUrl = true;
}
} catch (\GuzzleHttp\Exception\TooManyRedirectsException $e) {
// redirect loop or too many redirects
// todo: change errorType to 'redirect' (breaking change)
$this->errorParams['errorType'] = 'loop';
$this->errorParams['exception'] = $e->getMessage();
$this->errorParams['message'] = $this->getErrorMessage($this->errorParams);
} catch (\GuzzleHttp\Exception\ClientException $e) {
if ($e->hasResponse()) {
$this->errorParams['errorType'] = $e->getResponse()->getStatusCode();
} else {
$this->errorParams['errorType'] = 'unknown';
}
$this->errorParams['exception'] = $e->getMessage();
$this->errorParams['message'] = $this->getErrorMessage($this->errorParams);
} catch (\GuzzleHttp\Exception\RequestException $e) {
$this->errorParams['errorType'] = 'network';
$this->errorParams['exception'] = $e->getMessage();
$this->errorParams['message'] = $this->getErrorMessage($this->errorParams);
} catch (\Exception $e) {
// Generic catch for anything else that may go wrong
$this->errorParams['errorType'] = 'exception';
$this->errorParams['exception'] = $e->getMessage();
$this->errorParams['message'] = $this->getErrorMessage($this->errorParams);
}
return $isValidUrl;
}
/**
* Generate the localized error message from the error params saved from the parsing
*
* @param array $errorParams All parameters needed for the rendering of the error message
* @return string Validation error message
*/
public function getErrorMessage($errorParams)
{
$lang = $this->getLanguageService();
$errorType = $errorParams['errorType'];
switch ($errorType) {
case 300:
$message = sprintf($lang->getLL('list.report.externalerror'), $errorType);
break;
case 403:
$message = $lang->getLL('list.report.pageforbidden403');
break;
case 404:
$message = $lang->getLL('list.report.pagenotfound404');
break;
case 500:
$message = $lang->getLL('list.report.internalerror500');
break;
case 'loop':
$message = sprintf(
$lang->getLL('list.report.redirectloop'),
$errorParams['exception'],
''
);
break;
case 'exception':
$message = sprintf($lang->getLL('list.report.httpexception'), $errorParams['exception']);
break;
case 'network':
$message = $lang->getLL('list.report.networkexception');
if ($errorParams['exception']) {
$message .= ':' . $errorParams['exception'];
}
break;
default:
$message = sprintf($lang->getLL('list.report.otherhttpcode'), $errorType, $errorParams['exception']);
}
return $message;
}
/**
* Get the external type from the softRefParserObj result
*
* @param array $value Reference properties
* @param string $type Current type
* @param string $key Validator hook name
* @return string Fetched type
*/
public function fetchType($value, $type, $key)
{
preg_match_all('/((?:http|https))(?::\\/\\/)(?:[^\\s<>]+)/i', $value['tokenValue'], $urls, PREG_PATTERN_ORDER);
if (!empty($urls[0][0])) {
$type = 'external';
}
return $type;
}
/**
* Convert given URL to punycode to handle domains with non-ASCII characters
*
* @param string $url
* @return string
*/
protected function preprocessUrl(string $url): string
{
try {
return (new IdnaConvert())->encodeUri(html_entity_decode($url));
} catch (\Exception $e) {
// in case of any error, return empty url.
$this->errorParams['errorType'] = 'exception';
$this->errorParams['exception'] = $e->getMessage();
$this->errorParams['message'] = $this->getErrorMessage($this->errorParams);
return '';
}
}
}