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;
13 use Friendica\Network\CurlResult;
20 * If binary flag is true, return binary results.
21 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
22 * to preserve cookies from one request to the next.
25 * @param string $url URL to fetch
26 * @param bool $binary default false
27 * TRUE if asked to return binary results (file download)
28 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
29 * @param string $accept_content supply Accept: header with 'accept_content' as the value
30 * @param string $cookiejar Path to cookie jar file
31 * @param int $redirects The recursion counter for internal use - default 0
33 * @return string The fetched content
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
36 public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
38 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
40 return $ret->getBody();
44 * Curl wrapper with array of return values.
46 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
47 * all the information collected during the fetch.
49 * @brief Curl wrapper with array of return values.
50 * @param string $url URL to fetch
51 * @param bool $binary default false
52 * TRUE if asked to return binary results (file download)
53 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
54 * @param string $accept_content supply Accept: header with 'accept_content' as the value
55 * @param string $cookiejar Path to cookie jar file
56 * @param int $redirects The recursion counter for internal use - default 0
58 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
59 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
67 'timeout' => $timeout,
68 'accept_content' => $accept_content,
69 'cookiejar' => $cookiejar
76 * @brief fetches an URL.
78 * @param string $url URL to fetch
79 * @param bool $binary default false
80 * TRUE if asked to return binary results (file download)
81 * @param array $opts (optional parameters) assoziative array with:
82 * 'accept_content' => supply Accept: header with 'accept_content' as the value
83 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
84 * 'http_auth' => username:password
85 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
86 * 'nobody' => only return the header
87 * 'cookiejar' => path to cookie jar file
88 * 'header' => header array
89 * @param int $redirects The recursion counter for internal use - default 0
92 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
94 public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
96 $stamp1 = microtime(true);
100 if (strlen($url) > 1000) {
101 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
102 return CurlResult::createErrorCurl(substr($url, 0, 200));
106 $parts = parse_url($url);
107 $path_parts = explode('/', $parts['path'] ?? '');
108 foreach ($path_parts as $part) {
109 if (strlen($part) <> mb_strlen($part)) {
110 $parts2[] = rawurlencode($part);
115 $parts['path'] = implode('/', $parts2);
116 $url = self::unparseURL($parts);
118 if (self::isUrlBlocked($url)) {
119 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
120 return CurlResult::createErrorCurl($url);
123 $ch = @curl_init($url);
125 if (($redirects > 8) || (!$ch)) {
126 return CurlResult::createErrorCurl($url);
129 @curl_setopt($ch, CURLOPT_HEADER, true);
131 if (!empty($opts['cookiejar'])) {
132 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
133 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
136 // These settings aren't needed. We're following the location already.
137 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
138 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
140 if (!empty($opts['accept_content'])) {
144 ['Accept: ' . $opts['accept_content']]
148 if (!empty($opts['header'])) {
149 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
152 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
153 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
155 $range = intval(Config::get('system', 'curl_range_bytes', 0));
158 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
161 // Without this setting it seems as if some webservers send compressed content
162 // This seems to confuse curl so that it shows this uncompressed.
163 /// @todo We could possibly set this value to "gzip" or something similar
164 curl_setopt($ch, CURLOPT_ENCODING, '');
166 if (!empty($opts['headers'])) {
167 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
170 if (!empty($opts['nobody'])) {
171 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
174 if (!empty($opts['timeout'])) {
175 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
177 $curl_time = Config::get('system', 'curl_timeout', 60);
178 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
181 // by default we will allow self-signed certs
182 // but you can override this
184 $check_cert = Config::get('system', 'verifyssl');
185 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
188 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
191 $proxy = Config::get('system', 'proxy');
193 if (strlen($proxy)) {
194 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
195 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
196 $proxyuser = @Config::get('system', 'proxyuser');
198 if (strlen($proxyuser)) {
199 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
203 if (Config::get('system', 'ipv4_resolve', false)) {
204 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
208 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
211 // don't let curl abort the entire application
212 // if it throws any errors.
214 $s = @curl_exec($ch);
215 $curl_info = @curl_getinfo($ch);
217 // Special treatment for HTTP Code 416
218 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
219 if (($curl_info['http_code'] == 416) && ($range > 0)) {
220 @curl_setopt($ch, CURLOPT_RANGE, '');
221 $s = @curl_exec($ch);
222 $curl_info = @curl_getinfo($ch);
225 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
227 if ($curlResponse->isRedirectUrl()) {
229 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
231 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
236 $a->getProfiler()->saveTimestamp($stamp1, 'network', System::callstack());
238 return $curlResponse;
242 * @brief Send POST request to $url
244 * @param string $url URL to post
245 * @param mixed $params array of POST variables
246 * @param array $headers HTTP headers
247 * @param int $redirects Recursion counter for internal use - default = 0
248 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
250 * @return CurlResult The content
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
255 $stamp1 = microtime(true);
257 if (self::isUrlBlocked($url)) {
258 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
259 return CurlResult::createErrorCurl($url);
263 $ch = curl_init($url);
265 if (($redirects > 8) || (!$ch)) {
266 return CurlResult::createErrorCurl($url);
269 Logger::log('post_url: start ' . $url, Logger::DATA);
271 curl_setopt($ch, CURLOPT_HEADER, true);
272 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
273 curl_setopt($ch, CURLOPT_POST, 1);
274 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
275 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
277 if (Config::get('system', 'ipv4_resolve', false)) {
278 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
281 if (intval($timeout)) {
282 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
284 $curl_time = Config::get('system', 'curl_timeout', 60);
285 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
288 if (!empty($headers)) {
289 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
292 $check_cert = Config::get('system', 'verifyssl');
293 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
296 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
299 $proxy = Config::get('system', 'proxy');
301 if (strlen($proxy)) {
302 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
303 curl_setopt($ch, CURLOPT_PROXY, $proxy);
304 $proxyuser = Config::get('system', 'proxyuser');
305 if (strlen($proxyuser)) {
306 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
310 // don't let curl abort the entire application
311 // if it throws any errors.
313 $s = @curl_exec($ch);
315 $curl_info = curl_getinfo($ch);
317 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
319 if ($curlResponse->isRedirectUrl()) {
321 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
323 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
328 $a->getProfiler()->saveTimestamp($stamp1, 'network', System::callstack());
330 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
331 if ($curlResponse->getReturnCode() == 417) {
334 if (empty($headers)) {
335 $headers = ['Expect:'];
337 if (!in_array('Expect:', $headers)) {
338 array_push($headers, 'Expect:');
341 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
342 return self::post($url, $params, $headers, $redirects, $timeout);
345 Logger::log('post_url: end ' . $url, Logger::DATA);
347 return $curlResponse;
351 * Return raw post data from a post request
353 * @return string post data
355 public static function postdata()
357 return file_get_contents('php://input');
361 * @brief Check URL to see if it's real
363 * Take a URL from the wild, prepend http:// if necessary
364 * and check DNS to see if it's real (or check if is a valid IP address)
366 * @param string $url The URL to be validated
367 * @return string|boolean The actual working URL, false else
368 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
370 public static function isUrlValid(string $url)
372 if (Config::get('system', 'disable_url_validation')) {
376 // no naked subdomains (allow localhost for tests)
377 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
381 if (substr($url, 0, 4) != 'http') {
382 $url = 'http://' . $url;
385 /// @TODO Really suppress function outcomes? Why not find them + debug them?
386 $h = @parse_url($url);
388 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
396 * @brief Checks that email is an actual resolvable internet address
398 * @param string $addr The email address
399 * @return boolean True if it's a valid email address, false if it's not
401 public static function isEmailDomainValid(string $addr)
403 if (Config::get('system', 'disable_email_validation')) {
407 if (! strpos($addr, '@')) {
411 $h = substr($addr, strpos($addr, '@') + 1);
413 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
414 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
417 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
424 * @brief Check if URL is allowed
426 * Check $url against our list of allowed sites,
427 * wildcards allowed. If allowed_sites is unset return true;
429 * @param string $url URL which get tested
430 * @return boolean True if url is allowed otherwise return false
432 public static function isUrlAllowed(string $url)
434 $h = @parse_url($url);
440 $str_allowed = Config::get('system', 'allowed_sites');
441 if (! $str_allowed) {
447 $host = strtolower($h['host']);
449 // always allow our own site
450 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
454 $fnmatch = function_exists('fnmatch');
455 $allowed = explode(',', $str_allowed);
457 if (count($allowed)) {
458 foreach ($allowed as $a) {
459 $pat = strtolower(trim($a));
460 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
470 * Checks if the provided url domain is on the domain blocklist.
471 * Returns true if it is or malformed URL, false if not.
473 * @param string $url The url to check the domain from
477 public static function isUrlBlocked(string $url)
479 $host = @parse_url($url, PHP_URL_HOST);
484 $domain_blocklist = Config::get('system', 'blocklist', []);
485 if (!$domain_blocklist) {
489 foreach ($domain_blocklist as $domain_block) {
490 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
499 * @brief Check if email address is allowed to register here.
501 * Compare against our list (wildcards allowed).
503 * @param string $email email address
504 * @return boolean False if not allowed, true if allowed
505 * or if allowed list is not configured
506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508 public static function isEmailDomainAllowed(string $email)
510 $domain = strtolower(substr($email, strpos($email, '@') + 1));
515 $str_allowed = Config::get('system', 'allowed_email', '');
516 if (empty($str_allowed)) {
520 $allowed = explode(',', $str_allowed);
522 return self::isDomainAllowed($domain, $allowed);
526 * Checks for the existence of a domain in a domain list
528 * @brief Checks for the existence of a domain in a domain list
529 * @param string $domain
530 * @param array $domain_list
533 public static function isDomainAllowed(string $domain, array $domain_list)
537 foreach ($domain_list as $item) {
538 $pat = strtolower(trim($item));
539 if (fnmatch($pat, $domain) || ($pat == $domain)) {
548 public static function lookupAvatarByEmail(string $email)
550 $avatar['size'] = 300;
551 $avatar['email'] = $email;
553 $avatar['success'] = false;
555 Hook::callAll('avatar_lookup', $avatar);
557 if (! $avatar['success']) {
558 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
561 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
562 return $avatar['url'];
566 * @brief Remove Google Analytics and other tracking platforms params from URL
568 * @param string $url Any user-submitted URL that may contain tracking params
569 * @return string The same URL stripped of tracking parameters
571 public static function stripTrackingQueryParams(string $url)
573 $urldata = parse_url($url);
574 if (!empty($urldata["query"])) {
575 $query = $urldata["query"];
576 parse_str($query, $querydata);
578 if (is_array($querydata)) {
579 foreach ($querydata as $param => $value) {
583 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
584 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
585 "fb_action_ids", "fb_action_types", "fb_ref",
587 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
590 $pair = $param . "=" . urlencode($value);
591 $url = str_replace($pair, "", $url);
593 // Second try: if the url isn't encoded completely
594 $pair = $param . "=" . str_replace(" ", "+", $value);
595 $url = str_replace($pair, "", $url);
597 // Third try: Maybey the url isn't encoded at all
598 $pair = $param . "=" . $value;
599 $url = str_replace($pair, "", $url);
601 $url = str_replace(["?&", "&&"], ["?", ""], $url);
606 if (substr($url, -1, 1) == "?") {
607 $url = substr($url, 0, -1);
615 * @brief Returns the original URL of the provided URL
617 * This function strips tracking query params and follows redirections, either
618 * through HTTP code or meta refresh tags. Stops after 10 redirections.
620 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
622 * @see ParseUrl::getSiteinfo
624 * @param string $url A user-submitted URL
625 * @param int $depth The current redirection recursion level (internal)
626 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
627 * @return string A canonical URL
628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
630 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
634 $url = self::stripTrackingQueryParams($url);
640 $url = trim($url, "'");
642 $stamp1 = microtime(true);
645 curl_setopt($ch, CURLOPT_URL, $url);
646 curl_setopt($ch, CURLOPT_HEADER, 1);
647 curl_setopt($ch, CURLOPT_NOBODY, 1);
648 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
649 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
650 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
653 $curl_info = @curl_getinfo($ch);
654 $http_code = $curl_info['http_code'];
657 $a->getProfiler()->saveTimestamp($stamp1, "network", System::callstack());
659 if ($http_code == 0) {
663 if (in_array($http_code, ['301', '302'])) {
664 if (!empty($curl_info['redirect_url'])) {
665 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
666 } elseif (!empty($curl_info['location'])) {
667 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
671 // Check for redirects in the meta elements of the body if there are no redirects in the header.
673 return(self::finalUrl($url, ++$depth, true));
676 // if the file is too large then exit
677 if ($curl_info["download_content_length"] > 1000000) {
681 // if it isn't a HTML file then exit
682 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
686 $stamp1 = microtime(true);
689 curl_setopt($ch, CURLOPT_URL, $url);
690 curl_setopt($ch, CURLOPT_HEADER, 0);
691 curl_setopt($ch, CURLOPT_NOBODY, 0);
692 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
693 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
694 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
696 $body = curl_exec($ch);
699 $a->getProfiler()->saveTimestamp($stamp1, "network", System::callstack());
701 if (trim($body) == "") {
705 // Check for redirect in meta elements
706 $doc = new DOMDocument();
707 @$doc->loadHTML($body);
709 $xpath = new DomXPath($doc);
711 $list = $xpath->query("//meta[@content]");
712 foreach ($list as $node) {
714 if ($node->attributes->length) {
715 foreach ($node->attributes as $attribute) {
716 $attr[$attribute->name] = $attribute->value;
720 if (@$attr["http-equiv"] == 'refresh') {
721 $path = $attr["content"];
722 $pathinfo = explode(";", $path);
723 foreach ($pathinfo as $value) {
724 if (substr(strtolower($value), 0, 4) == "url=") {
725 return self::finalUrl(substr($value, 4), ++$depth);
735 * @brief Find the matching part between two url
737 * @param string $url1
738 * @param string $url2
739 * @return string The matching part
741 public static function getUrlMatch(string $url1, string $url2)
743 if (($url1 == "") || ($url2 == "")) {
747 $url1 = Strings::normaliseLink($url1);
748 $url2 = Strings::normaliseLink($url2);
750 $parts1 = parse_url($url1);
751 $parts2 = parse_url($url2);
753 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
757 if (empty($parts1["scheme"])) {
758 $parts1["scheme"] = '';
760 if (empty($parts2["scheme"])) {
761 $parts2["scheme"] = '';
764 if ($parts1["scheme"] != $parts2["scheme"]) {
768 if (empty($parts1["host"])) {
769 $parts1["host"] = '';
771 if (empty($parts2["host"])) {
772 $parts2["host"] = '';
775 if ($parts1["host"] != $parts2["host"]) {
779 if (empty($parts1["port"])) {
780 $parts1["port"] = '';
782 if (empty($parts2["port"])) {
783 $parts2["port"] = '';
786 if ($parts1["port"] != $parts2["port"]) {
790 $match = $parts1["scheme"]."://".$parts1["host"];
792 if ($parts1["port"]) {
793 $match .= ":".$parts1["port"];
796 if (empty($parts1["path"])) {
797 $parts1["path"] = '';
799 if (empty($parts2["path"])) {
800 $parts2["path"] = '';
803 $pathparts1 = explode("/", $parts1["path"]);
804 $pathparts2 = explode("/", $parts2["path"]);
809 $path1 = $pathparts1[$i] ?? '';
810 $path2 = $pathparts2[$i] ?? '';
812 if ($path1 == $path2) {
815 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
819 return Strings::normaliseLink($match);
823 * @brief Glue url parts together
825 * @param array $parsed URL parts
827 * @return string The glued URL
829 public static function unparseURL(array $parsed)
831 $get = function ($key) use ($parsed) {
832 return isset($parsed[$key]) ? $parsed[$key] : null;
835 $pass = $get('pass');
836 $user = $get('user');
837 $userinfo = $pass !== null ? "$user:$pass" : $user;
838 $port = $get('port');
839 $scheme = $get('scheme');
840 $query = $get('query');
841 $fragment = $get('fragment');
842 $authority = ($userinfo !== null ? $userinfo."@" : '') .
844 ($port ? ":$port" : '');
846 return (strlen($scheme) ? $scheme.":" : '') .
847 (strlen($authority) ? "//".$authority : '') .
849 (strlen($query) ? "?".$query : '') .
850 (strlen($fragment) ? "#".$fragment : '');
855 * Switch the scheme of an url between http and https
857 * @param string $url URL
859 * @return string switched URL
861 public static function switchScheme(string $url)
863 $scheme = parse_url($url, PHP_URL_SCHEME);
864 if (empty($scheme)) {
868 if ($scheme === 'http') {
869 $url = str_replace('http://', 'https://', $url);
870 } elseif ($scheme === 'https') {
871 $url = str_replace('https://', 'http://', $url);