]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPClient.php
Create HTTPClientFactory and introduce ImageTest
[friendica.git] / src / Network / HTTPClient.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU APGL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Network;
23
24 use DOMDocument;
25 use DomXPath;
26 use Friendica\Core\Config\IConfig;
27 use Friendica\Core\System;
28 use Friendica\Util\Network;
29 use Friendica\Util\Profiler;
30 use GuzzleHttp\Client;
31 use GuzzleHttp\Cookie\FileCookieJar;
32 use GuzzleHttp\Exception\RequestException;
33 use GuzzleHttp\Exception\TransferException;
34 use GuzzleHttp\RequestOptions;
35 use Psr\Http\Message\ResponseInterface;
36 use Psr\Log\LoggerInterface;
37
38 /**
39  * Performs HTTP requests to a given URL
40  */
41 class HTTPClient implements IHTTPClient
42 {
43         /** @var LoggerInterface */
44         private $logger;
45         /** @var Profiler */
46         private $profiler;
47         /** @var IConfig */
48         private $config;
49         /** @var string */
50         private $userAgent;
51         /** @var Client */
52         private $client;
53
54         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, string $userAgent, Client $client)
55         {
56                 $this->logger    = $logger;
57                 $this->profiler  = $profiler;
58                 $this->config    = $config;
59                 $this->userAgent = $userAgent;
60                 $this->client    = $client;
61         }
62
63         protected function request(string $method, string $url, array $opts = [])
64         {
65                 $this->profiler->startRecording('network');
66
67                 if (Network::isLocalLink($url)) {
68                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
69                 }
70
71                 if (strlen($url) > 1000) {
72                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
73                         $this->profiler->stopRecording();
74                         return CurlResult::createErrorCurl(substr($url, 0, 200));
75                 }
76
77                 $parts2     = [];
78                 $parts      = parse_url($url);
79                 $path_parts = explode('/', $parts['path'] ?? '');
80                 foreach ($path_parts as $part) {
81                         if (strlen($part) <> mb_strlen($part)) {
82                                 $parts2[] = rawurlencode($part);
83                         } else {
84                                 $parts2[] = $part;
85                         }
86                 }
87                 $parts['path'] = implode('/', $parts2);
88                 $url           = Network::unparseURL($parts);
89
90                 if (Network::isUrlBlocked($url)) {
91                         $this->logger->info('Domain is blocked.', ['url' => $url]);
92                         $this->profiler->stopRecording();
93                         return CurlResult::createErrorCurl($url);
94                 }
95
96                 $conf = [];
97
98                 if (!empty($opts['cookiejar'])) {
99                         $jar = new FileCookieJar($opts['cookiejar']);
100                         $conf[RequestOptions::COOKIES] = $jar;
101                 }
102
103                 if (!empty($opts['accept_content'])) {
104                         array_push($curlOptions[CURLOPT_HTTPHEADER], 'Accept: ' . $opts['accept_content']);
105                 }
106
107                 if (!empty($opts['header'])) {
108                         $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['header'], $curlOptions[CURLOPT_HTTPHEADER]);
109                 }
110
111                 $curlOptions[CURLOPT_USERAGENT] = $this->userAgent;
112
113                 if (!empty($opts['headers'])) {
114                         $this->logger->notice('Wrong option \'headers\' used.');
115                         $curlOptions[CURLOPT_HTTPHEADER] = array_merge($opts['headers'], $curlOptions[CURLOPT_HTTPHEADER]);
116                 }
117
118                 if (!empty($opts['timeout'])) {
119                         $curlOptions[CURLOPT_TIMEOUT] = $opts['timeout'];
120                 }
121
122                 $onHeaders = function (ResponseInterface $response) use ($opts) {
123                         if (!empty($opts['content_length']) &&
124                                 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
125                                 throw new TransferException('The file is too big!');
126                         }
127                 };
128
129                 try {
130                         $response = $this->client->$method($url, [
131                                 'on_headers' => $onHeaders,
132                                 'curl'       => $curlOptions,
133                         ]);
134                         return new GuzzleResponse($response, $url);
135                 } catch (TransferException $exception) {
136                         if ($exception instanceof RequestException &&
137                                 $exception->hasResponse()) {
138                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
139                         } else {
140                                 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
141                         }
142                 } finally {
143                         $this->profiler->stopRecording();
144                 }
145         }
146
147         /** {@inheritDoc}
148          *
149          * @throws HTTPException\InternalServerErrorException
150          */
151         public function head(string $url, array $opts = [])
152         {
153                 return $this->request('head', $url, $opts);
154         }
155
156         /**
157          * {@inheritDoc}
158          */
159         public function get(string $url, array $opts = [])
160         {
161                 return $this->request('get', $url, $opts);
162         }
163
164         /**
165          * {@inheritDoc}
166          *
167          * @param int $redirects The recursion counter for internal use - default 0
168          *
169          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170          */
171         public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
172         {
173                 $this->profiler->startRecording('network');
174
175                 if (Network::isLocalLink($url)) {
176                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
177                 }
178
179                 if (Network::isUrlBlocked($url)) {
180                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
181                         $this->profiler->stopRecording();
182                         return CurlResult::createErrorCurl($url);
183                 }
184
185                 $ch = curl_init($url);
186
187                 if (($redirects > 8) || (!$ch)) {
188                         $this->profiler->stopRecording();
189                         return CurlResult::createErrorCurl($url);
190                 }
191
192                 $this->logger->debug('Post_url: start.', ['url' => $url]);
193
194                 curl_setopt($ch, CURLOPT_HEADER, true);
195                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
196                 curl_setopt($ch, CURLOPT_POST, 1);
197                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
198                 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
199
200                 if ($this->config->get('system', 'ipv4_resolve', false)) {
201                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
202                 }
203
204                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
205
206                 if (intval($timeout)) {
207                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
208                 } else {
209                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
210                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
211                 }
212
213                 if (!empty($headers)) {
214                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
215                 }
216
217                 $check_cert = $this->config->get('system', 'verifyssl');
218                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
219
220                 if ($check_cert) {
221                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
222                 }
223
224                 $proxy = $this->config->get('system', 'proxy');
225
226                 if (!empty($proxy)) {
227                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
228                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
229                         $proxyuser = $this->config->get('system', 'proxyuser');
230                         if (!empty($proxyuser)) {
231                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
232                         }
233                 }
234
235                 // don't let curl abort the entire application
236                 // if it throws any errors.
237
238                 $s = @curl_exec($ch);
239
240                 $curl_info = curl_getinfo($ch);
241
242                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
243
244                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
245                         $redirects++;
246                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
247                         curl_close($ch);
248                         $this->profiler->stopRecording();
249                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
250                 }
251
252                 curl_close($ch);
253
254                 $this->profiler->stopRecording();
255
256                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
257                 if ($curlResponse->getReturnCode() == 417) {
258                         $redirects++;
259
260                         if (empty($headers)) {
261                                 $headers = ['Expect:'];
262                         } else {
263                                 if (!in_array('Expect:', $headers)) {
264                                         array_push($headers, 'Expect:');
265                                 }
266                         }
267                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
268                         return $this->post($url, $params, $headers, $redirects, $timeout);
269                 }
270
271                 $this->logger->debug('Post_url: End.', ['url' => $url]);
272
273                 return $curlResponse;
274         }
275
276         /**
277          * {@inheritDoc}
278          */
279         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
280         {
281                 if (Network::isLocalLink($url)) {
282                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
283                 }
284
285                 if (Network::isUrlBlocked($url)) {
286                         $this->logger->info('Domain is blocked.', ['url' => $url]);
287                         return $url;
288                 }
289
290                 if (Network::isRedirectBlocked($url)) {
291                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
292                         return $url;
293                 }
294
295                 $url = Network::stripTrackingQueryParams($url);
296
297                 if ($depth > 10) {
298                         return $url;
299                 }
300
301                 $url = trim($url, "'");
302
303                 $this->profiler->startRecording('network');
304
305                 $ch = curl_init();
306                 curl_setopt($ch, CURLOPT_URL, $url);
307                 curl_setopt($ch, CURLOPT_HEADER, 1);
308                 curl_setopt($ch, CURLOPT_NOBODY, 1);
309                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
310                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
311                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
312                 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
313
314                 curl_exec($ch);
315                 $curl_info = @curl_getinfo($ch);
316                 $http_code = $curl_info['http_code'];
317                 curl_close($ch);
318
319                 $this->profiler->stopRecording();
320
321                 if ($http_code == 0) {
322                         return $url;
323                 }
324
325                 if (in_array($http_code, ['301', '302'])) {
326                         if (!empty($curl_info['redirect_url'])) {
327                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
328                         } elseif (!empty($curl_info['location'])) {
329                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
330                         }
331                 }
332
333                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
334                 if (!$fetchbody) {
335                         return $this->finalUrl($url, ++$depth, true);
336                 }
337
338                 // if the file is too large then exit
339                 if ($curl_info["download_content_length"] > 1000000) {
340                         return $url;
341                 }
342
343                 // if it isn't a HTML file then exit
344                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
345                         return $url;
346                 }
347
348                 $this->profiler->startRecording('network');
349
350                 $ch = curl_init();
351                 curl_setopt($ch, CURLOPT_URL, $url);
352                 curl_setopt($ch, CURLOPT_HEADER, 0);
353                 curl_setopt($ch, CURLOPT_NOBODY, 0);
354                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
355                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
356                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
357                 curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
358
359                 $body = curl_exec($ch);
360                 curl_close($ch);
361
362                 $this->profiler->stopRecording();
363
364                 if (trim($body) == "") {
365                         return $url;
366                 }
367
368                 // Check for redirect in meta elements
369                 $doc = new DOMDocument();
370                 @$doc->loadHTML($body);
371
372                 $xpath = new DomXPath($doc);
373
374                 $list = $xpath->query("//meta[@content]");
375                 foreach ($list as $node) {
376                         $attr = [];
377                         if ($node->attributes->length) {
378                                 foreach ($node->attributes as $attribute) {
379                                         $attr[$attribute->name] = $attribute->value;
380                                 }
381                         }
382
383                         if (@$attr["http-equiv"] == 'refresh') {
384                                 $path = $attr["content"];
385                                 $pathinfo = explode(";", $path);
386                                 foreach ($pathinfo as $value) {
387                                         if (substr(strtolower($value), 0, 4) == "url=") {
388                                                 return $this->finalUrl(substr($value, 4), ++$depth);
389                                         }
390                                 }
391                         }
392                 }
393
394                 return $url;
395         }
396
397         /**
398          * {@inheritDoc}
399          */
400         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
401         {
402                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
403
404                 return $ret->getBody();
405         }
406
407         /**
408          * {@inheritDoc}
409          */
410         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
411         {
412                 return $this->get(
413                         $url,
414                         [
415                                 'timeout'        => $timeout,
416                                 'accept_content' => $accept_content,
417                                 'cookiejar'      => $cookiejar
418                         ]
419                 );
420         }
421 }