]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPClient.php
e982d19afcd0224b946be9e3f774659fef094e1e
[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 Friendica\Core\System;
25 use Friendica\Util\Network;
26 use Friendica\Util\Profiler;
27 use GuzzleHttp\Client;
28 use GuzzleHttp\Cookie\FileCookieJar;
29 use GuzzleHttp\Exception\RequestException;
30 use GuzzleHttp\Exception\TransferException;
31 use GuzzleHttp\RequestOptions;
32 use mattwright\URLResolver;
33 use Psr\Http\Message\ResponseInterface;
34 use Psr\Log\InvalidArgumentException;
35 use Psr\Log\LoggerInterface;
36
37 /**
38  * Performs HTTP requests to a given URL
39  */
40 class HTTPClient implements IHTTPClient
41 {
42         /** @var LoggerInterface */
43         private $logger;
44         /** @var Profiler */
45         private $profiler;
46         /** @var Client */
47         private $client;
48         /** @var URLResolver */
49         private $resolver;
50
51         public function __construct(LoggerInterface $logger, Profiler $profiler, Client $client, URLResolver $resolver)
52         {
53                 $this->logger   = $logger;
54                 $this->profiler = $profiler;
55                 $this->client   = $client;
56                 $this->resolver = $resolver;
57         }
58
59         /**
60          * {@inheritDoc}
61          */
62         public function request(string $method, string $url, array $opts = []): IHTTPResult
63         {
64                 $this->profiler->startRecording('network');
65                 $this->logger->debug('Request start.', ['url' => $url, 'method' => $method]);
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[HTTPRequestOptions::COOKIEJAR])) {
99                         $jar                           = new FileCookieJar($opts[HTTPRequestOptions::COOKIEJAR]);
100                         $conf[RequestOptions::COOKIES] = $jar;
101                 }
102
103                 $headers = [];
104
105                 if (!empty($opts[HTTPRequestOptions::ACCEPT_CONTENT])) {
106                         $headers['Accept'] = $opts[HTTPRequestOptions::ACCEPT_CONTENT];
107                 }
108
109                 if (!empty($opts[HTTPRequestOptions::LEGACY_HEADER])) {
110                         $this->logger->notice('Wrong option \'headers\' used.');
111                         $headers = array_merge($opts[HTTPRequestOptions::LEGACY_HEADER], $headers);
112                 }
113
114                 if (!empty($opts[HTTPRequestOptions::HEADERS])) {
115                         $headers = array_merge($opts[HTTPRequestOptions::HEADERS], $headers);
116                 }
117
118                 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $headers);
119
120                 if (!empty($opts[HTTPRequestOptions::TIMEOUT])) {
121                         $conf[RequestOptions::TIMEOUT] = $opts[HTTPRequestOptions::TIMEOUT];
122                 }
123
124                 if (!empty($opts[HTTPRequestOptions::BODY])) {
125                         $conf[RequestOptions::BODY] = $opts[HTTPRequestOptions::BODY];
126                 }
127
128                 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
129                         if (!empty($opts[HTTPRequestOptions::CONTENT_LENGTH]) &&
130                                 (int)$response->getHeaderLine('Content-Length') > $opts[HTTPRequestOptions::CONTENT_LENGTH]) {
131                                 throw new TransferException('The file is too big!');
132                         }
133                 };
134
135                 try {
136                         $this->logger->debug('http request config.', ['url' => $url, 'method' => $method, 'options' => $conf]);
137
138                         switch ($method) {
139                                 case 'get':
140                                 case 'head':
141                                 case 'post':
142                                 case 'put':
143                                 case 'delete':
144                                         $response = $this->client->$method($url, $conf);
145                                         break;
146                                 default:
147                                         throw new TransferException('Invalid method');
148                         }
149                         return new GuzzleResponse($response, $url);
150                 } catch (TransferException $exception) {
151                         if ($exception instanceof RequestException &&
152                                 $exception->hasResponse()) {
153                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
154                         } else {
155                                 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
156                         }
157                 } catch (InvalidArgumentException $argumentException) {
158                         $this->logger->info('Invalid Argument for HTTP call.', ['url' => $url, 'method' => $method, 'exception' => $argumentException]);
159                         return new CurlResult($url, '', ['http_code' => $argumentException->getCode()], $argumentException->getCode(), $argumentException->getMessage());
160                 } finally {
161                         $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
162                         $this->profiler->stopRecording();
163                 }
164         }
165
166         /** {@inheritDoc}
167          */
168         public function head(string $url, array $opts = []): IHTTPResult
169         {
170                 return $this->request('head', $url, $opts);
171         }
172
173         /**
174          * {@inheritDoc}
175          */
176         public function get(string $url, array $opts = []): IHTTPResult
177         {
178                 return $this->request('get', $url, $opts);
179         }
180
181         /**
182          * {@inheritDoc}
183          */
184         public function post(string $url, $params, array $headers = [], int $timeout = 0): IHTTPResult
185         {
186                 $opts = [];
187
188                 $opts[RequestOptions::BODY] = $params;
189
190                 if (!empty($headers)) {
191                         $opts[RequestOptions::HEADERS] = $headers;
192                 }
193
194                 if (!empty($timeout)) {
195                         $opts[RequestOptions::TIMEOUT] = $timeout;
196                 }
197
198                 return $this->request('post', $url, $opts);
199         }
200
201         /**
202          * {@inheritDoc}
203          */
204         public function finalUrl(string $url)
205         {
206                 $this->profiler->startRecording('network');
207
208                 if (Network::isLocalLink($url)) {
209                         $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
210                 }
211
212                 if (Network::isUrlBlocked($url)) {
213                         $this->logger->info('Domain is blocked.', ['url' => $url]);
214                         return $url;
215                 }
216
217                 if (Network::isRedirectBlocked($url)) {
218                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
219                         return $url;
220                 }
221
222                 $url = Network::stripTrackingQueryParams($url);
223
224                 $url = trim($url, "'");
225
226                 $urlResult = $this->resolver->resolveURL($url);
227
228                 if ($urlResult->didErrorOccur()) {
229                         throw new TransferException($urlResult->getErrorMessageString());
230                 }
231
232                 return $urlResult->getURL();
233         }
234
235         /**
236          * {@inheritDoc}
237          */
238         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
239         {
240                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
241
242                 return $ret->getBody();
243         }
244
245         /**
246          * {@inheritDoc}
247          */
248         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
249         {
250                 return $this->get(
251                         $url,
252                         [
253                                 'timeout'        => $timeout,
254                                 'accept_content' => $accept_content,
255                                 'cookiejar'      => $cookiejar
256                         ]
257                 );
258         }
259 }