3 * @file src/Util/Network.php
5 namespace Friendica\Util;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
14 use Friendica\Network\CurlResult;
21 * If binary flag is true, return binary results.
22 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
23 * to preserve cookies from one request to the next.
26 * @param string $url URL to fetch
27 * @param bool $binary default false
28 * TRUE if asked to return binary results (file download)
29 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
30 * @param string $accept_content supply Accept: header with 'accept_content' as the value
31 * @param string $cookiejar Path to cookie jar file
32 * @param int $redirects The recursion counter for internal use - default 0
34 * @return string The fetched content
35 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
37 public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
39 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
41 return $ret->getBody();
45 * Curl wrapper with array of return values.
47 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
48 * all the information collected during the fetch.
50 * @brief Curl wrapper with array of return values.
51 * @param string $url URL to fetch
52 * @param bool $binary default false
53 * TRUE if asked to return binary results (file download)
54 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
55 * @param string $accept_content supply Accept: header with 'accept_content' as the value
56 * @param string $cookiejar Path to cookie jar file
57 * @param int $redirects The recursion counter for internal use - default 0
59 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
68 'timeout' => $timeout,
69 'accept_content' => $accept_content,
70 'cookiejar' => $cookiejar
77 * @brief fetches an URL.
79 * @param string $url URL to fetch
80 * @param bool $binary default false
81 * TRUE if asked to return binary results (file download)
82 * @param array $opts (optional parameters) assoziative array with:
83 * 'accept_content' => supply Accept: header with 'accept_content' as the value
84 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
85 * 'http_auth' => username:password
86 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
87 * 'nobody' => only return the header
88 * 'cookiejar' => path to cookie jar file
89 * 'header' => header array
90 * @param int $redirects The recursion counter for internal use - default 0
93 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
95 public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
97 $stamp1 = microtime(true);
101 if (strlen($url) > 1000) {
102 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
103 return CurlResult::createErrorCurl(substr($url, 0, 200));
107 $parts = parse_url($url);
108 $path_parts = explode('/', $parts['path'] ?? '');
109 foreach ($path_parts as $part) {
110 if (strlen($part) <> mb_strlen($part)) {
111 $parts2[] = rawurlencode($part);
116 $parts['path'] = implode('/', $parts2);
117 $url = self::unparseURL($parts);
119 if (self::isUrlBlocked($url)) {
120 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
121 return CurlResult::createErrorCurl($url);
124 $ch = @curl_init($url);
126 if (($redirects > 8) || (!$ch)) {
127 return CurlResult::createErrorCurl($url);
130 @curl_setopt($ch, CURLOPT_HEADER, true);
132 if (!empty($opts['cookiejar'])) {
133 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
134 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
137 // These settings aren't needed. We're following the location already.
138 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
139 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
141 if (!empty($opts['accept_content'])) {
145 ['Accept: ' . $opts['accept_content']]
149 if (!empty($opts['header'])) {
150 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
153 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
154 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
156 $range = intval(Config::get('system', 'curl_range_bytes', 0));
159 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
162 // Without this setting it seems as if some webservers send compressed content
163 // This seems to confuse curl so that it shows this uncompressed.
164 /// @todo We could possibly set this value to "gzip" or something similar
165 curl_setopt($ch, CURLOPT_ENCODING, '');
167 if (!empty($opts['headers'])) {
168 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
171 if (!empty($opts['nobody'])) {
172 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
175 if (!empty($opts['timeout'])) {
176 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
178 $curl_time = Config::get('system', 'curl_timeout', 60);
179 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
182 // by default we will allow self-signed certs
183 // but you can override this
185 $check_cert = Config::get('system', 'verifyssl');
186 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
189 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
192 $proxy = Config::get('system', 'proxy');
194 if (strlen($proxy)) {
195 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
196 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
197 $proxyuser = @Config::get('system', 'proxyuser');
199 if (strlen($proxyuser)) {
200 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
204 if (Config::get('system', 'ipv4_resolve', false)) {
205 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
209 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
212 // don't let curl abort the entire application
213 // if it throws any errors.
215 $s = @curl_exec($ch);
216 $curl_info = @curl_getinfo($ch);
218 // Special treatment for HTTP Code 416
219 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
220 if (($curl_info['http_code'] == 416) && ($range > 0)) {
221 @curl_setopt($ch, CURLOPT_RANGE, '');
222 $s = @curl_exec($ch);
223 $curl_info = @curl_getinfo($ch);
226 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
228 if ($curlResponse->isRedirectUrl()) {
230 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
232 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
237 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
239 return $curlResponse;
243 * @brief Send POST request to $url
245 * @param string $url URL to post
246 * @param mixed $params array of POST variables
247 * @param array $headers HTTP headers
248 * @param int $redirects Recursion counter for internal use - default = 0
249 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
251 * @return CurlResult The content
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
256 $stamp1 = microtime(true);
258 if (self::isUrlBlocked($url)) {
259 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
260 return CurlResult::createErrorCurl($url);
264 $ch = curl_init($url);
266 if (($redirects > 8) || (!$ch)) {
267 return CurlResult::createErrorCurl($url);
270 Logger::log('post_url: start ' . $url, Logger::DATA);
272 curl_setopt($ch, CURLOPT_HEADER, true);
273 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
274 curl_setopt($ch, CURLOPT_POST, 1);
275 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
276 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
278 if (Config::get('system', 'ipv4_resolve', false)) {
279 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
282 if (intval($timeout)) {
283 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
285 $curl_time = Config::get('system', 'curl_timeout', 60);
286 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
289 if (!empty($headers)) {
290 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
293 $check_cert = Config::get('system', 'verifyssl');
294 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
297 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
300 $proxy = Config::get('system', 'proxy');
302 if (strlen($proxy)) {
303 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
304 curl_setopt($ch, CURLOPT_PROXY, $proxy);
305 $proxyuser = Config::get('system', 'proxyuser');
306 if (strlen($proxyuser)) {
307 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
311 // don't let curl abort the entire application
312 // if it throws any errors.
314 $s = @curl_exec($ch);
316 $curl_info = curl_getinfo($ch);
318 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
320 if ($curlResponse->isRedirectUrl()) {
322 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
324 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
329 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
331 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
332 if ($curlResponse->getReturnCode() == 417) {
335 if (empty($headers)) {
336 $headers = ['Expect:'];
338 if (!in_array('Expect:', $headers)) {
339 array_push($headers, 'Expect:');
342 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
343 return self::post($url, $params, $headers, $redirects, $timeout);
346 Logger::log('post_url: end ' . $url, Logger::DATA);
348 return $curlResponse;
352 * Return raw post data from a post request
354 * @return string post data
356 public static function postdata()
358 return file_get_contents('php://input');
362 * @brief Check URL to see if it's real
364 * Take a URL from the wild, prepend http:// if necessary
365 * and check DNS to see if it's real (or check if is a valid IP address)
367 * @param string $url The URL to be validated
368 * @return string|boolean The actual working URL, false else
369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
371 public static function isUrlValid(string $url)
373 if (Config::get('system', 'disable_url_validation')) {
377 // no naked subdomains (allow localhost for tests)
378 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
382 if (substr($url, 0, 4) != 'http') {
383 $url = 'http://' . $url;
386 /// @TODO Really suppress function outcomes? Why not find them + debug them?
387 $h = @parse_url($url);
389 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
397 * @brief Checks that email is an actual resolvable internet address
399 * @param string $addr The email address
400 * @return boolean True if it's a valid email address, false if it's not
402 public static function isEmailDomainValid(string $addr)
404 if (Config::get('system', 'disable_email_validation')) {
408 if (! strpos($addr, '@')) {
412 $h = substr($addr, strpos($addr, '@') + 1);
414 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
415 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
418 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
425 * @brief Check if URL is allowed
427 * Check $url against our list of allowed sites,
428 * wildcards allowed. If allowed_sites is unset return true;
430 * @param string $url URL which get tested
431 * @return boolean True if url is allowed otherwise return false
433 public static function isUrlAllowed(string $url)
435 $h = @parse_url($url);
441 $str_allowed = Config::get('system', 'allowed_sites');
442 if (! $str_allowed) {
448 $host = strtolower($h['host']);
450 // always allow our own site
451 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
455 $fnmatch = function_exists('fnmatch');
456 $allowed = explode(',', $str_allowed);
458 if (count($allowed)) {
459 foreach ($allowed as $a) {
460 $pat = strtolower(trim($a));
461 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
471 * Checks if the provided url domain is on the domain blocklist.
472 * Returns true if it is or malformed URL, false if not.
474 * @param string $url The url to check the domain from
478 public static function isUrlBlocked(string $url)
480 $host = @parse_url($url, PHP_URL_HOST);
485 $domain_blocklist = Config::get('system', 'blocklist', []);
486 if (!$domain_blocklist) {
490 foreach ($domain_blocklist as $domain_block) {
491 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
500 * @brief Check if email address is allowed to register here.
502 * Compare against our list (wildcards allowed).
504 * @param string $email email address
505 * @return boolean False if not allowed, true if allowed
506 * or if allowed list is not configured
507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
509 public static function isEmailDomainAllowed(string $email)
511 $domain = strtolower(substr($email, strpos($email, '@') + 1));
516 $str_allowed = Config::get('system', 'allowed_email', '');
517 if (empty($str_allowed)) {
521 $allowed = explode(',', $str_allowed);
523 return self::isDomainAllowed($domain, $allowed);
527 * Checks for the existence of a domain in a domain list
529 * @brief Checks for the existence of a domain in a domain list
530 * @param string $domain
531 * @param array $domain_list
534 public static function isDomainAllowed(string $domain, array $domain_list)
538 foreach ($domain_list as $item) {
539 $pat = strtolower(trim($item));
540 if (fnmatch($pat, $domain) || ($pat == $domain)) {
549 public static function lookupAvatarByEmail(string $email)
551 $avatar['size'] = 300;
552 $avatar['email'] = $email;
554 $avatar['success'] = false;
556 Hook::callAll('avatar_lookup', $avatar);
558 if (! $avatar['success']) {
559 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
562 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
563 return $avatar['url'];
567 * @brief Remove Google Analytics and other tracking platforms params from URL
569 * @param string $url Any user-submitted URL that may contain tracking params
570 * @return string The same URL stripped of tracking parameters
572 public static function stripTrackingQueryParams(string $url)
574 $urldata = parse_url($url);
575 if (!empty($urldata["query"])) {
576 $query = $urldata["query"];
577 parse_str($query, $querydata);
579 if (is_array($querydata)) {
580 foreach ($querydata as $param => $value) {
584 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
585 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
586 "fb_action_ids", "fb_action_types", "fb_ref",
588 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
591 $pair = $param . "=" . urlencode($value);
592 $url = str_replace($pair, "", $url);
594 // Second try: if the url isn't encoded completely
595 $pair = $param . "=" . str_replace(" ", "+", $value);
596 $url = str_replace($pair, "", $url);
598 // Third try: Maybey the url isn't encoded at all
599 $pair = $param . "=" . $value;
600 $url = str_replace($pair, "", $url);
602 $url = str_replace(["?&", "&&"], ["?", ""], $url);
607 if (substr($url, -1, 1) == "?") {
608 $url = substr($url, 0, -1);
616 * @brief Returns the original URL of the provided URL
618 * This function strips tracking query params and follows redirections, either
619 * through HTTP code or meta refresh tags. Stops after 10 redirections.
621 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
623 * @see ParseUrl::getSiteinfo
625 * @param string $url A user-submitted URL
626 * @param int $depth The current redirection recursion level (internal)
627 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
628 * @return string A canonical URL
629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
635 $url = self::stripTrackingQueryParams($url);
641 $url = trim($url, "'");
643 $stamp1 = microtime(true);
646 curl_setopt($ch, CURLOPT_URL, $url);
647 curl_setopt($ch, CURLOPT_HEADER, 1);
648 curl_setopt($ch, CURLOPT_NOBODY, 1);
649 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
650 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
651 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
654 $curl_info = @curl_getinfo($ch);
655 $http_code = $curl_info['http_code'];
658 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
660 if ($http_code == 0) {
664 if (in_array($http_code, ['301', '302'])) {
665 if (!empty($curl_info['redirect_url'])) {
666 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
667 } elseif (!empty($curl_info['location'])) {
668 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
672 // Check for redirects in the meta elements of the body if there are no redirects in the header.
674 return(self::finalUrl($url, ++$depth, true));
677 // if the file is too large then exit
678 if ($curl_info["download_content_length"] > 1000000) {
682 // if it isn't a HTML file then exit
683 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
687 $stamp1 = microtime(true);
690 curl_setopt($ch, CURLOPT_URL, $url);
691 curl_setopt($ch, CURLOPT_HEADER, 0);
692 curl_setopt($ch, CURLOPT_NOBODY, 0);
693 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
694 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
695 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
697 $body = curl_exec($ch);
700 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
702 if (trim($body) == "") {
706 // Check for redirect in meta elements
707 $doc = new DOMDocument();
708 @$doc->loadHTML($body);
710 $xpath = new DomXPath($doc);
712 $list = $xpath->query("//meta[@content]");
713 foreach ($list as $node) {
715 if ($node->attributes->length) {
716 foreach ($node->attributes as $attribute) {
717 $attr[$attribute->name] = $attribute->value;
721 if (@$attr["http-equiv"] == 'refresh') {
722 $path = $attr["content"];
723 $pathinfo = explode(";", $path);
724 foreach ($pathinfo as $value) {
725 if (substr(strtolower($value), 0, 4) == "url=") {
726 return self::finalUrl(substr($value, 4), ++$depth);
736 * @brief Find the matching part between two url
738 * @param string $url1
739 * @param string $url2
740 * @return string The matching part
742 public static function getUrlMatch(string $url1, string $url2)
744 if (($url1 == "") || ($url2 == "")) {
748 $url1 = Strings::normaliseLink($url1);
749 $url2 = Strings::normaliseLink($url2);
751 $parts1 = parse_url($url1);
752 $parts2 = parse_url($url2);
754 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
758 if (empty($parts1["scheme"])) {
759 $parts1["scheme"] = '';
761 if (empty($parts2["scheme"])) {
762 $parts2["scheme"] = '';
765 if ($parts1["scheme"] != $parts2["scheme"]) {
769 if (empty($parts1["host"])) {
770 $parts1["host"] = '';
772 if (empty($parts2["host"])) {
773 $parts2["host"] = '';
776 if ($parts1["host"] != $parts2["host"]) {
780 if (empty($parts1["port"])) {
781 $parts1["port"] = '';
783 if (empty($parts2["port"])) {
784 $parts2["port"] = '';
787 if ($parts1["port"] != $parts2["port"]) {
791 $match = $parts1["scheme"]."://".$parts1["host"];
793 if ($parts1["port"]) {
794 $match .= ":".$parts1["port"];
797 if (empty($parts1["path"])) {
798 $parts1["path"] = '';
800 if (empty($parts2["path"])) {
801 $parts2["path"] = '';
804 $pathparts1 = explode("/", $parts1["path"]);
805 $pathparts2 = explode("/", $parts2["path"]);
810 $path1 = $pathparts1[$i] ?? '';
811 $path2 = $pathparts2[$i] ?? '';
813 if ($path1 == $path2) {
816 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
820 return Strings::normaliseLink($match);
824 * @brief Glue url parts together
826 * @param array $parsed URL parts
828 * @return string The glued URL
830 public static function unparseURL(array $parsed)
832 $get = function ($key) use ($parsed) {
833 return isset($parsed[$key]) ? $parsed[$key] : null;
836 $pass = $get('pass');
837 $user = $get('user');
838 $userinfo = $pass !== null ? "$user:$pass" : $user;
839 $port = $get('port');
840 $scheme = $get('scheme');
841 $query = $get('query');
842 $fragment = $get('fragment');
843 $authority = ($userinfo !== null ? $userinfo."@" : '') .
845 ($port ? ":$port" : '');
847 return (strlen($scheme) ? $scheme.":" : '') .
848 (strlen($authority) ? "//".$authority : '') .
850 (strlen($query) ? "?".$query : '') .
851 (strlen($fragment) ? "#".$fragment : '');
856 * Switch the scheme of an url between http and https
858 * @param string $url URL
860 * @return string switched URL
862 public static function switchScheme(string $url)
864 $scheme = parse_url($url, PHP_URL_SCHEME);
865 if (empty($scheme)) {
869 if ($scheme === 'http') {
870 $url = str_replace('http://', 'https://', $url);
871 } elseif ($scheme === 'https') {
872 $url = str_replace('https://', 'http://', $url);