]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPClient/Client/HttpClient.php
Move ACCEPT constants to own "enum" class
[friendica.git] / src / Network / HTTPClient / Client / HttpClient.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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                 if (Network::isLocalLink($url)) {
72                         $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
73                 }
74
75                 if (strlen($url) > 1000) {
76                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
77                         $this->profiler->stopRecording();
78                         return CurlResult::createErrorCurl(substr($url, 0, 200));
79                 }
80
81                 $parts2     = [];
82                 $parts      = parse_url($url);
83                 $path_parts = explode('/', $parts['path'] ?? '');
84                 foreach ($path_parts as $part) {
85                         if (strlen($part) <> mb_strlen($part)) {
86                                 $parts2[] = rawurlencode($part);
87                         } else {
88                                 $parts2[] = $part;
89                         }
90                 }
91                 $parts['path'] = implode('/', $parts2);
92                 $url           = Network::unparseURL($parts);
93
94                 if (Network::isUrlBlocked($url)) {
95                         $this->logger->info('Domain is blocked.', ['url' => $url]);
96                         $this->profiler->stopRecording();
97                         return CurlResult::createErrorCurl($url);
98                 }
99
100                 $conf = [];
101
102                 if (!empty($opts[HttpClientOptions::COOKIEJAR])) {
103                         $jar                           = new FileCookieJar($opts[HttpClientOptions::COOKIEJAR]);
104                         $conf[RequestOptions::COOKIES] = $jar;
105                 }
106
107                 $headers = [];
108
109                 if (!empty($opts[HttpClientOptions::ACCEPT_CONTENT])) {
110                         $headers['Accept'] = $opts[HttpClientOptions::ACCEPT_CONTENT];
111                 }
112
113                 if (!empty($opts[HttpClientOptions::LEGACY_HEADER])) {
114                         $this->logger->notice('Wrong option \'headers\' used.');
115                         $headers = array_merge($opts[HttpClientOptions::LEGACY_HEADER], $headers);
116                 }
117
118                 if (!empty($opts[HttpClientOptions::HEADERS])) {
119                         $headers = array_merge($opts[HttpClientOptions::HEADERS], $headers);
120                 }
121
122                 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $headers);
123
124                 if (!empty($opts[HttpClientOptions::TIMEOUT])) {
125                         $conf[RequestOptions::TIMEOUT] = $opts[HttpClientOptions::TIMEOUT];
126                 }
127
128                 if (!empty($opts[HttpClientOptions::BODY])) {
129                         $conf[RequestOptions::BODY] = $opts[HttpClientOptions::BODY];
130                 }
131
132                 if (!empty($opts[HttpClientOptions::AUTH])) {
133                         $conf[RequestOptions::AUTH] = $opts[HttpClientOptions::AUTH];
134                 }
135
136                 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
137                         if (!empty($opts[HttpClientOptions::CONTENT_LENGTH]) &&
138                                 (int)$response->getHeaderLine('Content-Length') > $opts[HttpClientOptions::CONTENT_LENGTH]) {
139                                 throw new TransferException('The file is too big!');
140                         }
141                 };
142
143                 if (empty($conf[HttpClientOptions::HEADERS]['Accept'])) {
144                         $conf[HttpClientOptions::HEADERS]['Accept'] = HttpClientAccept::DEFAULT;
145                 }
146
147                 try {
148                         $this->logger->debug('http request config.', ['url' => $url, 'method' => $method, 'options' => $conf]);
149
150                         $response = $this->client->request($method, $url, $conf);
151                         return new GuzzleResponse($response, $url);
152                 } catch (TransferException $exception) {
153                         if ($exception instanceof RequestException &&
154                                 $exception->hasResponse()) {
155                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
156                         } else {
157                                 return new CurlResult($url, '', ['http_code' => 500], $exception->getCode(), '');
158                         }
159                 } catch (InvalidArgumentException | \InvalidArgumentException $argumentException) {
160                         $this->logger->info('Invalid Argument for HTTP call.', ['url' => $url, 'method' => $method, 'exception' => $argumentException]);
161                         return new CurlResult($url, '', ['http_code' => 500], $argumentException->getCode(), $argumentException->getMessage());
162                 } finally {
163                         $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
164                         $this->profiler->stopRecording();
165                 }
166         }
167
168         /** {@inheritDoc}
169          */
170         public function head(string $url, array $opts = []): ICanHandleHttpResponses
171         {
172                 return $this->request('head', $url, $opts);
173         }
174
175         /**
176          * {@inheritDoc}
177          */
178         public function get(string $url, array $opts = []): ICanHandleHttpResponses
179         {
180                 return $this->request('get', $url, $opts);
181         }
182
183         /**
184          * {@inheritDoc}
185          */
186         public function post(string $url, $params, array $headers = [], int $timeout = 0): ICanHandleHttpResponses
187         {
188                 $opts = [];
189
190                 $opts[HttpClientOptions::BODY] = $params;
191
192                 if (!empty($headers)) {
193                         $opts[HttpClientOptions::HEADERS] = $headers;
194                 }
195
196                 if (!empty($timeout)) {
197                         $opts[HttpClientOptions::TIMEOUT] = $timeout;
198                 }
199
200                 return $this->request('post', $url, $opts);
201         }
202
203         /**
204          * {@inheritDoc}
205          */
206         public function finalUrl(string $url): string
207         {
208                 $this->profiler->startRecording('network');
209
210                 if (Network::isLocalLink($url)) {
211                         $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
212                 }
213
214                 if (Network::isUrlBlocked($url)) {
215                         $this->logger->info('Domain is blocked.', ['url' => $url]);
216                         return $url;
217                 }
218
219                 if (Network::isRedirectBlocked($url)) {
220                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
221                         return $url;
222                 }
223
224                 $url = Network::stripTrackingQueryParams($url);
225
226                 $url = trim($url, "'");
227
228                 $urlResult = $this->resolver->resolveURL($url);
229
230                 if ($urlResult->didErrorOccur()) {
231                         throw new TransferException($urlResult->getErrorMessageString(), $urlResult->getHTTPStatusCode());
232                 }
233
234                 return $urlResult->getURL();
235         }
236
237         /**
238          * {@inheritDoc}
239          */
240         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = ''): string
241         {
242                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
243
244                 return $ret->getBody();
245         }
246
247         /**
248          * {@inheritDoc}
249          */
250         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = ''): ICanHandleHttpResponses
251         {
252                 return $this->get(
253                         $url,
254                         [
255                                 HttpClientOptions::TIMEOUT        => $timeout,
256                                 HttpClientOptions::ACCEPT_CONTENT => $accept_content,
257                                 HttpClientOptions::COOKIEJAR      => $cookiejar
258                         ]
259                 );
260         }
261 }