]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPClient/Client/HttpClient.php
Update function / rearrange tab order
[friendica.git] / src / Network / HTTPClient / Client / HttpClient.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL 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\HTTPClient\Client;
23
24 use Friendica\Core\System;
25 use Friendica\Network\HTTPClient\Response\CurlResult;
26 use Friendica\Network\HTTPClient\Response\GuzzleResponse;
27 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
28 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use GuzzleHttp\Client;
32 use GuzzleHttp\Cookie\FileCookieJar;
33 use GuzzleHttp\Exception\RequestException;
34 use GuzzleHttp\Exception\TransferException;
35 use GuzzleHttp\RequestOptions;
36 use mattwright\URLResolver;
37 use Psr\Http\Message\ResponseInterface;
38 use Psr\Log\InvalidArgumentException;
39 use Psr\Log\LoggerInterface;
40
41 /**
42  * Performs HTTP requests to a given URL
43  */
44 class HttpClient implements ICanSendHttpRequests
45 {
46         /** @var LoggerInterface */
47         private $logger;
48         /** @var Profiler */
49         private $profiler;
50         /** @var Client */
51         private $client;
52         /** @var URLResolver */
53         private $resolver;
54
55         public function __construct(LoggerInterface $logger, Profiler $profiler, Client $client, URLResolver $resolver)
56         {
57                 $this->logger   = $logger;
58                 $this->profiler = $profiler;
59                 $this->client   = $client;
60                 $this->resolver = $resolver;
61         }
62
63         /**
64          * {@inheritDoc}
65          */
66         public function request(string $method, string $url, array $opts = []): ICanHandleHttpResponses
67         {
68                 $this->profiler->startRecording('network');
69                 $this->logger->debug('Request start.', ['url' => $url, 'method' => $method]);
70
71                 $host = parse_url($url, PHP_URL_HOST);
72                 if (empty($host)) {
73                         throw new \InvalidArgumentException('Unable to retrieve the host in URL: ' . $url);
74                 }
75
76                 if(!filter_var($host, FILTER_VALIDATE_IP) && !@dns_get_record($host . '.', DNS_A + DNS_AAAA)) {
77                         $this->logger->debug('URL cannot be resolved.', ['url' => $url, 'callstack' => System::callstack(20)]);
78                         $this->profiler->stopRecording();
79                         return CurlResult::createErrorCurl($this->logger, $url);
80                 }
81
82                 if (Network::isLocalLink($url)) {
83                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
84                 }
85
86                 if (strlen($url) > 1000) {
87                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
88                         $this->profiler->stopRecording();
89                         return CurlResult::createErrorCurl($this->logger, substr($url, 0, 200));
90                 }
91
92                 $parts2     = [];
93                 $parts      = parse_url($url);
94                 $path_parts = explode('/', $parts['path'] ?? '');
95                 foreach ($path_parts as $part) {
96                         if (strlen($part) <> mb_strlen($part)) {
97                                 $parts2[] = rawurlencode($part);
98                         } else {
99                                 $parts2[] = $part;
100                         }
101                 }
102                 $parts['path'] = implode('/', $parts2);
103                 $url           = Network::unparseURL($parts);
104
105                 if (Network::isUrlBlocked($url)) {
106                         $this->logger->info('Domain is blocked.', ['url' => $url]);
107                         $this->profiler->stopRecording();
108                         return CurlResult::createErrorCurl($this->logger, $url);
109                 }
110
111                 $conf = [];
112
113                 if (!empty($opts[HttpClientOptions::COOKIEJAR])) {
114                         $jar                           = new FileCookieJar($opts[HttpClientOptions::COOKIEJAR]);
115                         $conf[RequestOptions::COOKIES] = $jar;
116                 }
117
118                 $headers = [];
119
120                 if (!empty($opts[HttpClientOptions::ACCEPT_CONTENT])) {
121                         $headers['Accept'] = $opts[HttpClientOptions::ACCEPT_CONTENT];
122                 }
123
124                 if (!empty($opts[HttpClientOptions::LEGACY_HEADER])) {
125                         $this->logger->notice('Wrong option \'headers\' used.');
126                         $headers = array_merge($opts[HttpClientOptions::LEGACY_HEADER], $headers);
127                 }
128
129                 if (!empty($opts[HttpClientOptions::HEADERS])) {
130                         $headers = array_merge($opts[HttpClientOptions::HEADERS], $headers);
131                 }
132
133                 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $headers);
134
135                 if (!empty($opts[HttpClientOptions::TIMEOUT])) {
136                         $conf[RequestOptions::TIMEOUT] = $opts[HttpClientOptions::TIMEOUT];
137                 }
138
139                 if (isset($opts[HttpClientOptions::VERIFY])) {
140                         $conf[RequestOptions::VERIFY] = $opts[HttpClientOptions::VERIFY];
141                 }
142
143                 if (!empty($opts[HttpClientOptions::BODY])) {
144                         $conf[RequestOptions::BODY] = $opts[HttpClientOptions::BODY];
145                 }
146
147                 if (!empty($opts[HttpClientOptions::FORM_PARAMS])) {
148                         $conf[RequestOptions::FORM_PARAMS] = $opts[HttpClientOptions::FORM_PARAMS];
149                 }
150
151                 if (!empty($opts[HttpClientOptions::AUTH])) {
152                         $conf[RequestOptions::AUTH] = $opts[HttpClientOptions::AUTH];
153                 }
154
155                 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
156                         if (!empty($opts[HttpClientOptions::CONTENT_LENGTH]) &&
157                                 (int)$response->getHeaderLine('Content-Length') > $opts[HttpClientOptions::CONTENT_LENGTH]) {
158                                 throw new TransferException('The file is too big!');
159                         }
160                 };
161
162                 if (empty($conf[HttpClientOptions::HEADERS]['Accept']) && in_array($method, ['get', 'head'])) {
163                         $this->logger->info('Accept header was missing, using default.', ['url' => $url, 'callstack' => System::callstack()]);
164                         $conf[HttpClientOptions::HEADERS]['Accept'] = HttpClientAccept::DEFAULT;
165                 }
166
167                 $conf['sink'] = tempnam(System::getTempPath(), 'http-');
168
169                 try {
170                         $this->logger->debug('http request config.', ['url' => $url, 'method' => $method, 'options' => $conf]);
171
172                         $response = $this->client->request($method, $url, $conf);
173                         return new GuzzleResponse($response, $url);
174                 } catch (TransferException $exception) {
175                         if ($exception instanceof RequestException &&
176                                 $exception->hasResponse()) {
177                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
178                         } else {
179                                 return new CurlResult($this->logger, $url, '', ['http_code' => 500], $exception->getCode(), '');
180                         }
181                 } catch (InvalidArgumentException | \InvalidArgumentException $argumentException) {
182                         $this->logger->info('Invalid Argument for HTTP call.', ['url' => $url, 'method' => $method, 'exception' => $argumentException]);
183                         return new CurlResult($this->logger, $url, '', ['http_code' => 500], $argumentException->getCode(), $argumentException->getMessage());
184                 } finally {
185                         unlink($conf['sink']);
186                         $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
187                         $this->profiler->stopRecording();
188                 }
189         }
190
191         /** {@inheritDoc}
192          */
193         public function head(string $url, array $opts = []): ICanHandleHttpResponses
194         {
195                 return $this->request('head', $url, $opts);
196         }
197
198         /**
199          * {@inheritDoc}
200          */
201         public function get(string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ICanHandleHttpResponses
202         {
203                 // In case there is no
204                 $opts[HttpClientOptions::ACCEPT_CONTENT] = $opts[HttpClientOptions::ACCEPT_CONTENT] ?? $accept_content;
205
206                 return $this->request('get', $url, $opts);
207         }
208
209         /**
210          * {@inheritDoc}
211          */
212         public function post(string $url, $params, array $headers = [], int $timeout = 0): ICanHandleHttpResponses
213         {
214                 $opts = [];
215
216                 if (!is_array($params)) {
217                         $opts[HttpClientOptions::BODY] = $params;
218                 } else {
219                         $opts[HttpClientOptions::FORM_PARAMS] = $params;
220                 }
221
222                 if (!empty($headers)) {
223                         $opts[HttpClientOptions::HEADERS] = $headers;
224                 }
225
226                 if (!empty($timeout)) {
227                         $opts[HttpClientOptions::TIMEOUT] = $timeout;
228                 }
229
230                 return $this->request('post', $url, $opts);
231         }
232
233         /**
234          * {@inheritDoc}
235          */
236         public function finalUrl(string $url): string
237         {
238                 $this->profiler->startRecording('network');
239
240                 if (Network::isLocalLink($url)) {
241                         $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
242                 }
243
244                 if (Network::isUrlBlocked($url)) {
245                         $this->logger->info('Domain is blocked.', ['url' => $url]);
246                         return $url;
247                 }
248
249                 if (Network::isRedirectBlocked($url)) {
250                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
251                         return $url;
252                 }
253
254                 $url = Network::stripTrackingQueryParams($url);
255
256                 $url = trim($url, "'");
257
258                 $urlResult = $this->resolver->resolveURL($url);
259
260                 if ($urlResult->didErrorOccur()) {
261                         throw new TransferException($urlResult->getErrorMessageString(), $urlResult->getHTTPStatusCode() ?? 0);
262                 }
263
264                 return $urlResult->getUrl();
265         }
266
267         /**
268          * {@inheritDoc}
269          */
270         public function fetch(string $url, string $accept_content = HttpClientAccept::DEFAULT, int $timeout = 0, string $cookiejar = ''): string
271         {
272                 $ret = $this->fetchFull($url, $accept_content, $timeout, $cookiejar);
273
274                 return $ret->getBody();
275         }
276
277         /**
278          * {@inheritDoc}
279          */
280         public function fetchFull(string $url, string $accept_content = HttpClientAccept::DEFAULT, int $timeout = 0, string $cookiejar = ''): ICanHandleHttpResponses
281         {
282                 return $this->get(
283                         $url,
284                         $accept_content,
285                         [
286                                 HttpClientOptions::TIMEOUT   => $timeout,
287                                 HttpClientOptions::COOKIEJAR => $cookiejar
288                         ]
289                 );
290         }
291 }