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;
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
27 use Friendica\Util\Network;
30 * Performs HTTP requests to a given URL
37 * @param string $url URL to fetch
38 * @param bool $binary default false
39 * TRUE if asked to return binary results (file download)
40 * @param array $opts (optional parameters) assoziative array with:
41 * 'accept_content' => supply Accept: header with 'accept_content' as the value
42 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
43 * 'http_auth' => username:password
44 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
45 * 'nobody' => only return the header
46 * 'cookiejar' => path to cookie jar file
47 * 'header' => header array
48 * @param int $redirects The recursion counter for internal use - default 0
51 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
53 public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
55 $stamp1 = microtime(true);
59 if (strlen($url) > 1000) {
60 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
61 return CurlResult::createErrorCurl(substr($url, 0, 200));
65 $parts = parse_url($url);
66 $path_parts = explode('/', $parts['path'] ?? '');
67 foreach ($path_parts as $part) {
68 if (strlen($part) <> mb_strlen($part)) {
69 $parts2[] = rawurlencode($part);
74 $parts['path'] = implode('/', $parts2);
75 $url = Network::unparseURL($parts);
77 if (Network::isUrlBlocked($url)) {
78 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
79 return CurlResult::createErrorCurl($url);
82 $ch = @curl_init($url);
84 if (($redirects > 8) || (!$ch)) {
85 return CurlResult::createErrorCurl($url);
88 @curl_setopt($ch, CURLOPT_HEADER, true);
90 if (!empty($opts['cookiejar'])) {
91 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
92 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
95 // These settings aren't needed. We're following the location already.
96 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
97 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
99 if (!empty($opts['accept_content'])) {
103 ['Accept: ' . $opts['accept_content']]
107 if (!empty($opts['header'])) {
108 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
111 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
112 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
114 $range = intval(DI::config()->get('system', 'curl_range_bytes', 0));
117 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
120 // Without this setting it seems as if some webservers send compressed content
121 // This seems to confuse curl so that it shows this uncompressed.
122 /// @todo We could possibly set this value to "gzip" or something similar
123 curl_setopt($ch, CURLOPT_ENCODING, '');
125 if (!empty($opts['headers'])) {
126 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
129 if (!empty($opts['nobody'])) {
130 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
133 if (!empty($opts['timeout'])) {
134 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
136 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
137 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
140 // by default we will allow self-signed certs
141 // but you can override this
143 $check_cert = DI::config()->get('system', 'verifyssl');
144 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
147 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
150 $proxy = DI::config()->get('system', 'proxy');
152 if (strlen($proxy)) {
153 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
154 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
155 $proxyuser = @DI::config()->get('system', 'proxyuser');
157 if (strlen($proxyuser)) {
158 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
162 if (DI::config()->get('system', 'ipv4_resolve', false)) {
163 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
167 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
170 // don't let curl abort the entire application
171 // if it throws any errors.
173 $s = @curl_exec($ch);
174 $curl_info = @curl_getinfo($ch);
176 // Special treatment for HTTP Code 416
177 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
178 if (($curl_info['http_code'] == 416) && ($range > 0)) {
179 @curl_setopt($ch, CURLOPT_RANGE, '');
180 $s = @curl_exec($ch);
181 $curl_info = @curl_getinfo($ch);
184 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
186 if ($curlResponse->isRedirectUrl()) {
188 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
190 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
195 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
197 return $curlResponse;
201 * Send POST request to $url
203 * @param string $url URL to post
204 * @param mixed $params array of POST variables
205 * @param array $headers HTTP headers
206 * @param int $redirects Recursion counter for internal use - default = 0
207 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
209 * @return CurlResult The content
210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
214 $stamp1 = microtime(true);
216 if (Network::isUrlBlocked($url)) {
217 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
218 return CurlResult::createErrorCurl($url);
222 $ch = curl_init($url);
224 if (($redirects > 8) || (!$ch)) {
225 return CurlResult::createErrorCurl($url);
228 Logger::log('post_url: start ' . $url, Logger::DATA);
230 curl_setopt($ch, CURLOPT_HEADER, true);
231 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
232 curl_setopt($ch, CURLOPT_POST, 1);
233 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
234 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
236 if (DI::config()->get('system', 'ipv4_resolve', false)) {
237 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
240 if (intval($timeout)) {
241 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
243 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
244 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
247 if (!empty($headers)) {
248 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
251 $check_cert = DI::config()->get('system', 'verifyssl');
252 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
255 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
258 $proxy = DI::config()->get('system', 'proxy');
260 if (strlen($proxy)) {
261 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
262 curl_setopt($ch, CURLOPT_PROXY, $proxy);
263 $proxyuser = DI::config()->get('system', 'proxyuser');
264 if (strlen($proxyuser)) {
265 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
269 // don't let curl abort the entire application
270 // if it throws any errors.
272 $s = @curl_exec($ch);
274 $curl_info = curl_getinfo($ch);
276 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
278 if ($curlResponse->isRedirectUrl()) {
280 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
282 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
287 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
289 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
290 if ($curlResponse->getReturnCode() == 417) {
293 if (empty($headers)) {
294 $headers = ['Expect:'];
296 if (!in_array('Expect:', $headers)) {
297 array_push($headers, 'Expect:');
300 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
301 return self::post($url, $params, $headers, $redirects, $timeout);
304 Logger::log('post_url: end ' . $url, Logger::DATA);
306 return $curlResponse;
312 * If binary flag is true, return binary results.
313 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
314 * to preserve cookies from one request to the next.
316 * @param string $url URL to fetch
317 * @param bool $binary default false
318 * TRUE if asked to return binary results (file download)
319 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
320 * @param string $accept_content supply Accept: header with 'accept_content' as the value
321 * @param string $cookiejar Path to cookie jar file
322 * @param int $redirects The recursion counter for internal use - default 0
324 * @return string The fetched content
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
329 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
331 return $ret->getBody();
335 * Curl wrapper with array of return values.
337 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
338 * all the information collected during the fetch.
340 * @param string $url URL to fetch
341 * @param bool $binary default false
342 * TRUE if asked to return binary results (file download)
343 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
344 * @param string $accept_content supply Accept: header with 'accept_content' as the value
345 * @param string $cookiejar Path to cookie jar file
346 * @param int $redirects The recursion counter for internal use - default 0
348 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
351 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
357 'timeout' => $timeout,
358 'accept_content' => $accept_content,
359 'cookiejar' => $cookiejar