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\LoggerInterface;
37 * Performs HTTP requests to a given URL
39 class HTTPClient implements IHTTPClient
41 /** @var LoggerInterface */
47 /** @var URLResolver */
50 public function __construct(LoggerInterface $logger, Profiler $profiler, Client $client, URLResolver $resolver)
52 $this->logger = $logger;
53 $this->profiler = $profiler;
54 $this->client = $client;
55 $this->resolver = $resolver;
59 * @throws HTTPException\InternalServerErrorException
61 protected function request(string $method, string $url, array $opts = []): IHTTPResult
63 $this->profiler->startRecording('network');
64 $this->logger->debug('Request start.', ['url' => $url, 'method' => $method]);
66 if (Network::isLocalLink($url)) {
67 $this->logger->info('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
70 if (strlen($url) > 1000) {
71 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
72 $this->profiler->stopRecording();
73 return CurlResult::createErrorCurl(substr($url, 0, 200));
77 $parts = parse_url($url);
78 $path_parts = explode('/', $parts['path'] ?? '');
79 foreach ($path_parts as $part) {
80 if (strlen($part) <> mb_strlen($part)) {
81 $parts2[] = rawurlencode($part);
86 $parts['path'] = implode('/', $parts2);
87 $url = Network::unparseURL($parts);
89 if (Network::isUrlBlocked($url)) {
90 $this->logger->info('Domain is blocked.', ['url' => $url]);
91 $this->profiler->stopRecording();
92 return CurlResult::createErrorCurl($url);
95 if (Network::isRedirectBlocked($url)) {
96 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
97 return CurlResult::createErrorCurl($url);
102 if (!empty($opts['cookiejar'])) {
103 $jar = new FileCookieJar($opts['cookiejar']);
104 $conf[RequestOptions::COOKIES] = $jar;
109 if (!empty($opts['accept_content'])) {
110 array_push($header, 'Accept: ' . $opts['accept_content']);
113 if (!empty($opts['header'])) {
114 $header = array_merge($opts['header'], $header);
117 if (!empty($opts['headers'])) {
118 $this->logger->notice('Wrong option \'headers\' used.');
119 $header = array_merge($opts['headers'], $header);
122 $conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $header);
124 if (!empty($opts['timeout'])) {
125 $conf[RequestOptions::TIMEOUT] = $opts['timeout'];
128 $conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
129 if (!empty($opts['content_length']) &&
130 $response->getHeaderLine('Content-Length') > $opts['content_length']) {
131 throw new TransferException('The file is too big!');
138 $response = $this->client->get($url, $conf);
141 $response = $this->client->head($url, $conf);
144 throw new TransferException('Invalid method');
146 return new GuzzleResponse($response, $url);
147 } catch (TransferException $exception) {
148 if ($exception instanceof RequestException &&
149 $exception->hasResponse()) {
150 return new GuzzleResponse($exception->getResponse(), $url, $exception->getCode(), '');
152 return new CurlResult($url, '', ['http_code' => $exception->getCode()], $exception->getCode(), '');
155 $this->logger->debug('Request stop.', ['url' => $url, 'method' => $method]);
156 $this->profiler->stopRecording();
162 * @throws HTTPException\InternalServerErrorException
164 public function head(string $url, array $opts = []): IHTTPResult
166 return $this->request('head', $url, $opts);
172 public function get(string $url, array $opts = []): IHTTPResult
174 return $this->request('get', $url, $opts);
180 public function post(string $url, $params, array $headers = [], int $timeout = 0): IHTTPResult
184 $opts[RequestOptions::JSON] = $params;
186 if (!empty($headers)) {
187 $opts['headers'] = $headers;
190 if (!empty($timeout)) {
191 $opts[RequestOptions::TIMEOUT] = $timeout;
194 return $this->request('post', $url, $opts);
200 public function finalUrl(string $url)
202 $this->profiler->startRecording('network');
204 if (Network::isLocalLink($url)) {
205 $this->logger->debug('Local link', ['url' => $url, 'callstack' => System::callstack(20)]);
208 if (Network::isUrlBlocked($url)) {
209 $this->logger->info('Domain is blocked.', ['url' => $url]);
213 if (Network::isRedirectBlocked($url)) {
214 $this->logger->info('Domain should not be redirected.', ['url' => $url]);
218 $url = Network::stripTrackingQueryParams($url);
220 $url = trim($url, "'");
222 // Designate a temporary file that will store cookies during the session.
223 // Some websites test the browser for cookie support, so this enhances results.
224 $this->resolver->setCookieJar(tempnam(get_temppath() , 'url_resolver-'));
226 $urlResult = $this->resolver->resolveURL($url);
228 if ($urlResult->didErrorOccur()) {
229 throw new TransferException($urlResult->getErrorMessageString());
232 return $urlResult->getURL();
238 public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
240 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
242 return $ret->getBody();
248 public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
253 'timeout' => $timeout,
254 'accept_content' => $accept_content,
255 'cookiejar' => $cookiejar