3 * @copyright Copyright (C) 2020, Friendica
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;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use Psr\Log\LoggerInterface;
34 * Performs HTTP requests to a given URL
38 /** @var LoggerInterface */
47 public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App $a)
49 $this->logger = $logger;
50 $this->profiler = $profiler;
51 $this->config = $config;
52 $this->userAgent = $a->getUserAgent();
58 * @param string $url URL to fetch
59 * @param bool $binary default false
60 * TRUE if asked to return binary results (file download)
61 * @param array $opts (optional parameters) assoziative array with:
62 * 'accept_content' => supply Accept: header with 'accept_content' as the value
63 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
64 * 'http_auth' => username:password
65 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
66 * 'nobody' => only return the header
67 * 'cookiejar' => path to cookie jar file
68 * 'header' => header array
69 * @param int $redirects The recursion counter for internal use - default 0
72 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
74 public function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
76 $stamp1 = microtime(true);
78 if (strlen($url) > 1000) {
79 $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
80 return CurlResult::createErrorCurl(substr($url, 0, 200));
84 $parts = parse_url($url);
85 $path_parts = explode('/', $parts['path'] ?? '');
86 foreach ($path_parts as $part) {
87 if (strlen($part) <> mb_strlen($part)) {
88 $parts2[] = rawurlencode($part);
93 $parts['path'] = implode('/', $parts2);
94 $url = Network::unparseURL($parts);
96 if (Network::isUrlBlocked($url)) {
97 $this->logger->info('Domain is blocked.', ['url' => $url]);
98 return CurlResult::createErrorCurl($url);
101 $ch = @curl_init($url);
103 if (($redirects > 8) || (!$ch)) {
104 return CurlResult::createErrorCurl($url);
107 @curl_setopt($ch, CURLOPT_HEADER, true);
109 if (!empty($opts['cookiejar'])) {
110 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
111 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
114 // These settings aren't needed. We're following the location already.
115 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
116 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
118 if (!empty($opts['accept_content'])) {
122 ['Accept: ' . $opts['accept_content']]
126 if (!empty($opts['header'])) {
127 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
130 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131 @curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
133 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
136 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
139 // Without this setting it seems as if some webservers send compressed content
140 // This seems to confuse curl so that it shows this uncompressed.
141 /// @todo We could possibly set this value to "gzip" or something similar
142 curl_setopt($ch, CURLOPT_ENCODING, '');
144 if (!empty($opts['headers'])) {
145 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
148 if (!empty($opts['nobody'])) {
149 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
152 if (!empty($opts['timeout'])) {
153 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
155 $curl_time = $this->config->get('system', 'curl_timeout', 60);
156 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
159 // by default we will allow self-signed certs
160 // but you can override this
162 $check_cert = $this->config->get('system', 'verifyssl');
163 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
166 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
169 $proxy = $this->config->get('system', 'proxy');
171 if (!empty($proxy)) {
172 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
173 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
174 $proxyuser = $this->config->get('system', 'proxyuser');
176 if (!empty($proxyuser)) {
177 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
181 if ($this->config->get('system', 'ipv4_resolve', false)) {
182 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
186 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
189 // don't let curl abort the entire application
190 // if it throws any errors.
192 $s = @curl_exec($ch);
193 $curl_info = @curl_getinfo($ch);
195 // Special treatment for HTTP Code 416
196 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
197 if (($curl_info['http_code'] == 416) && ($range > 0)) {
198 @curl_setopt($ch, CURLOPT_RANGE, '');
199 $s = @curl_exec($ch);
200 $curl_info = @curl_getinfo($ch);
203 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
205 if ($curlResponse->isRedirectUrl()) {
207 $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
209 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
214 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
216 return $curlResponse;
220 * Send POST request to $url
222 * @param string $url URL to post
223 * @param mixed $params array of POST variables
224 * @param array $headers HTTP headers
225 * @param int $redirects Recursion counter for internal use - default = 0
226 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
228 * @return CurlResult The content
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
233 $stamp1 = microtime(true);
235 if (Network::isUrlBlocked($url)) {
236 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
237 return CurlResult::createErrorCurl($url);
241 $ch = curl_init($url);
243 if (($redirects > 8) || (!$ch)) {
244 return CurlResult::createErrorCurl($url);
247 Logger::log('post_url: start ' . $url, Logger::DATA);
249 curl_setopt($ch, CURLOPT_HEADER, true);
250 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
251 curl_setopt($ch, CURLOPT_POST, 1);
252 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
253 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
255 if (DI::config()->get('system', 'ipv4_resolve', false)) {
256 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
259 if (intval($timeout)) {
260 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
262 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
263 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
266 if (!empty($headers)) {
267 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
270 $check_cert = DI::config()->get('system', 'verifyssl');
271 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
274 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
277 $proxy = DI::config()->get('system', 'proxy');
279 if (strlen($proxy)) {
280 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
281 curl_setopt($ch, CURLOPT_PROXY, $proxy);
282 $proxyuser = DI::config()->get('system', 'proxyuser');
283 if (strlen($proxyuser)) {
284 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
288 // don't let curl abort the entire application
289 // if it throws any errors.
291 $s = @curl_exec($ch);
293 $curl_info = curl_getinfo($ch);
295 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
297 if ($curlResponse->isRedirectUrl()) {
299 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
301 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
306 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
308 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
309 if ($curlResponse->getReturnCode() == 417) {
312 if (empty($headers)) {
313 $headers = ['Expect:'];
315 if (!in_array('Expect:', $headers)) {
316 array_push($headers, 'Expect:');
319 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
320 return self::post($url, $params, $headers, $redirects, $timeout);
323 Logger::log('post_url: end ' . $url, Logger::DATA);
325 return $curlResponse;
331 * If binary flag is true, return binary results.
332 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
333 * to preserve cookies from one request to the next.
335 * @param string $url URL to fetch
336 * @param bool $binary default false
337 * TRUE if asked to return binary results (file download)
338 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
339 * @param string $accept_content supply Accept: header with 'accept_content' as the value
340 * @param string $cookiejar Path to cookie jar file
341 * @param int $redirects The recursion counter for internal use - default 0
343 * @return string The fetched content
344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
346 public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
348 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
350 return $ret->getBody();
354 * Curl wrapper with array of return values.
356 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
357 * all the information collected during the fetch.
359 * @param string $url URL to fetch
360 * @param bool $binary default false
361 * TRUE if asked to return binary results (file download)
362 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
363 * @param string $accept_content supply Accept: header with 'accept_content' as the value
364 * @param string $cookiejar Path to cookie jar file
365 * @param int $redirects The recursion counter for internal use - default 0
367 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
368 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
370 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
376 'timeout' => $timeout,
377 'accept_content' => $accept_content,
378 'cookiejar' => $cookiejar