3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU APGL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Network;
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;
38 * Performs HTTP requests to a given URL
40 class HTTPClient implements IHTTPClient
42 /** @var LoggerInterface */
48 /** @var URLResolver */
51 public function __construct(LoggerInterface $logger, Profiler $profiler, Client $client, URLResolver $resolver)
53 $this->logger = $logger;
54 $this->profiler = $profiler;
55 $this->client = $client;
56 $this->resolver = $resolver;
62 public function request(string $method, string $url, array $opts = []): IHTTPResult
64 $this->profiler->startRecording('network');
65 $this->logger->debug('Request start.', ['url' => $url, 'method' => $method]);
67 if (Network::isLocalLink($url)) {
68 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
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));
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);
87 $parts['path'] = implode('/', $parts2);
88 $url = Network::unparseURL($parts);
90 if (Network::isUrlBlocked($url)) {
91 $this->logger->info('Domain is blocked.', ['url' => $url]);
92 $this->profiler->stopRecording();
93 return CurlResult::createErrorCurl($url);
98 if (!empty($opts[HTTPClientOptions::COOKIEJAR])) {
99 $jar = new FileCookieJar($opts[HTTPClientOptions::COOKIEJAR]);
100 $conf[RequestOptions::COOKIES] = $jar;
105 if (!empty($opts[HTTPClientOptions::ACCEPT_CONTENT])) {
106 $headers['Accept'] = $opts[HTTPClientOptions::ACCEPT_CONTENT];
109 if (!empty($opts[HTTPClientOptions::LEGACY_HEADER])) {
110 $this->logger->notice('Wrong option \'headers\' used.');
111 $headers = array_merge($opts[HTTPClientOptions::LEGACY_HEADER], $headers);
114 if (!empty($opts[HTTPClientOptions::HEADERS])) {
115 $headers = array_merge($opts[HTTPClientOptions::HEADERS], $headers);
118 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $headers);
120 if (!empty($opts[HTTPClientOptions::TIMEOUT])) {
121 $conf[RequestOptions::TIMEOUT] = $opts[HTTPClientOptions::TIMEOUT];
124 if (!empty($opts[HTTPClientOptions::BODY])) {
125 $conf[RequestOptions::BODY] = $opts[HTTPClientOptions::BODY];
128 if (!empty($opts[HTTPClientOptions::AUTH])) {
129 $conf[RequestOptions::AUTH] = $opts[HTTPClientOptions::AUTH];
132 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
133 if (!empty($opts[HTTPClientOptions::CONTENT_LENGTH]) &&
134 (int)$response->getHeaderLine('Content-Length') > $opts[HTTPClientOptions::CONTENT_LENGTH]) {
135 throw new TransferException('The file is too big!');
140 $this->logger->debug('http request config.', ['url' => $url, 'method' => $method, 'options' => $conf]);
142 $response = $this->client->request($method, $url, $conf);
143 return new GuzzleResponse($response, $url);
144 } catch (TransferException $exception) {
145 if ($exception instanceof RequestException &&
146 $exception->hasResponse()) {
147 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
149 return new CurlResult($url, '', ['http_code' => 500], $exception->getCode(), '');
151 } catch (InvalidArgumentException | \InvalidArgumentException $argumentException) {
152 $this->logger->info('Invalid Argument for HTTP call.', ['url' => $url, 'method' => $method, 'exception' => $argumentException]);
153 return new CurlResult($url, '', ['http_code' => 500], $argumentException->getCode(), $argumentException->getMessage());
155 $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
156 $this->profiler->stopRecording();
162 public function head(string $url, array $opts = []): IHTTPResult
164 return $this->request('head', $url, $opts);
170 public function get(string $url, array $opts = []): IHTTPResult
172 return $this->request('get', $url, $opts);
178 public function post(string $url, $params, array $headers = [], int $timeout = 0): IHTTPResult
182 $opts[HTTPClientOptions::BODY] = $params;
184 if (!empty($headers)) {
185 $opts[HTTPClientOptions::HEADERS] = $headers;
188 if (!empty($timeout)) {
189 $opts[HTTPClientOptions::TIMEOUT] = $timeout;
192 return $this->request('post', $url, $opts);
198 public function finalUrl(string $url)
200 $this->profiler->startRecording('network');
202 if (Network::isLocalLink($url)) {
203 $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
206 if (Network::isUrlBlocked($url)) {
207 $this->logger->info('Domain is blocked.', ['url' => $url]);
211 if (Network::isRedirectBlocked($url)) {
212 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
216 $url = Network::stripTrackingQueryParams($url);
218 $url = trim($url, "'");
220 $urlResult = $this->resolver->resolveURL($url);
222 if ($urlResult->didErrorOccur()) {
223 throw new TransferException($urlResult->getErrorMessageString(), $urlResult->getHTTPStatusCode());
226 return $urlResult->getURL();
232 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
234 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
236 return $ret->getBody();
242 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
247 'timeout' => $timeout,
248 'accept_content' => $accept_content,
249 'cookiejar' => $cookiejar