]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPClient.php
Fixup HTTP headers for httpClient requests
[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          * @throws HTTPException\InternalServerErrorException
61          */
62         protected 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['cookiejar'])) {
99                         $jar                           = new FileCookieJar($opts['cookiejar']);
100                         $conf[RequestOptions::COOKIES] = $jar;
101                 }
102
103                 $header = [];
104
105                 if (!empty($opts['accept_content'])) {
106                         $header['Accept'] = $opts['accept_content'];
107                 }
108
109                 if (!empty($opts['header'])) {
110                         $header = array_merge($opts['header'], $header);
111                 }
112
113                 if (!empty($opts['headers'])) {
114                         $this->logger->notice('Wrong option \'headers\' used.');
115                         $header = array_merge($opts['headers'], $header);
116                 }
117
118                 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $header);
119
120                 if (!empty($opts['timeout'])) {
121                         $conf[RequestOptions::TIMEOUT] = $opts['timeout'];
122                 }
123
124                 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
125                         if (!empty($opts['content_length']) &&
126                                 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
127                                 throw new TransferException('The file is too big!');
128                         }
129                 };
130
131                 try {
132                         switch ($method) {
133                                 case 'get':
134                                         $response = $this->client->get($url, $conf);
135                                         break;
136                                 case 'head':
137                                         $response = $this->client->head($url, $conf);
138                                         break;
139                                 default:
140                                         throw new TransferException('Invalid method');
141                         }
142                         return new GuzzleResponse($response, $url);
143                 } catch (TransferException $exception) {
144                         if ($exception instanceof RequestException &&
145                                 $exception->hasResponse()) {
146                                 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
147                         } else {
148                                 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
149                         }
150                 } catch (InvalidArgumentException $argumentException) {
151                         $this->logger->info('Invalid Argument for HTTP call.', ['url' => $url, 'method' => $method, 'exception' => $argumentException]);
152                         return new CurlResult($url, '', ['http_code' => $argumentException->getCode()], $argumentException->getCode(), $argumentException->getMessage());
153                 } finally {
154                         $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
155                         $this->profiler->stopRecording();
156                 }
157         }
158
159         /** {@inheritDoc}
160          *
161          * @throws HTTPException\InternalServerErrorException
162          */
163         public function head(string $url, array $opts = []): IHTTPResult
164         {
165                 return $this->request('head', $url, $opts);
166         }
167
168         /**
169          * {@inheritDoc}
170          */
171         public function get(string $url, array $opts = []): IHTTPResult
172         {
173                 return $this->request('get', $url, $opts);
174         }
175
176         /**
177          * {@inheritDoc}
178          */
179         public function post(string $url, $params, array $headers = [], int $timeout = 0): IHTTPResult
180         {
181                 $opts = [];
182
183                 $opts[RequestOptions::JSON] = $params;
184
185                 if (!empty($headers)) {
186                         $opts['headers'] = $headers;
187                 }
188
189                 if (!empty($timeout)) {
190                         $opts[RequestOptions::TIMEOUT] = $timeout;
191                 }
192
193                 return $this->request('post', $url, $opts);
194         }
195
196         /**
197          * {@inheritDoc}
198          */
199         public function finalUrl(string $url)
200         {
201                 $this->profiler->startRecording('network');
202
203                 if (Network::isLocalLink($url)) {
204                         $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
205                 }
206
207                 if (Network::isUrlBlocked($url)) {
208                         $this->logger->info('Domain is blocked.', ['url' => $url]);
209                         return $url;
210                 }
211
212                 if (Network::isRedirectBlocked($url)) {
213                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
214                         return $url;
215                 }
216
217                 $url = Network::stripTrackingQueryParams($url);
218
219                 $url = trim($url, "'");
220
221                 // Designate a temporary file that will store cookies during the session.
222                 // Some websites test the browser for cookie support, so this enhances results.
223                 $this->resolver->setCookieJar(tempnam(get_temppath() , 'url_resolver-'));
224
225                 $urlResult = $this->resolver->resolveURL($url);
226
227                 if ($urlResult->didErrorOccur()) {
228                         throw new TransferException($urlResult->getErrorMessageString());
229                 }
230
231                 return $urlResult->getURL();
232         }
233
234         /**
235          * {@inheritDoc}
236          */
237         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
238         {
239                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
240
241                 return $ret->getBody();
242         }
243
244         /**
245          * {@inheritDoc}
246          */
247         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
248         {
249                 return $this->get(
250                         $url,
251                         [
252                                 'timeout'        => $timeout,
253                                 'accept_content' => $accept_content,
254                                 'cookiejar'      => $cookiejar
255                         ]
256                 );
257         }
258 }