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 (defined('LIGHTTPD')) {
289 if (empty($headers)) {
290 $headers = ['Expect:'];
292 if (!in_array('Expect:', $headers)) {
293 array_push($headers, 'Expect:');
298 if (!empty($headers)) {
299 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
302 $check_cert = Config::get('system', 'verifyssl');
303 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
306 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
309 $proxy = Config::get('system', 'proxy');
311 if (strlen($proxy)) {
312 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
313 curl_setopt($ch, CURLOPT_PROXY, $proxy);
314 $proxyuser = Config::get('system', 'proxyuser');
315 if (strlen($proxyuser)) {
316 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
320 // don't let curl abort the entire application
321 // if it throws any errors.
323 $s = @curl_exec($ch);
325 $curl_info = curl_getinfo($ch);
327 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
329 if ($curlResponse->isRedirectUrl()) {
331 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
333 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
338 $a->getProfiler()->saveTimestamp($stamp1, 'network', System::callstack());
340 Logger::log('post_url: end ' . $url, Logger::DATA);
342 return $curlResponse;
346 * Return raw post data from a post request
348 * @return string post data
350 public static function postdata()
352 return file_get_contents('php://input');
356 * @brief Check URL to see if it's real
358 * Take a URL from the wild, prepend http:// if necessary
359 * and check DNS to see if it's real (or check if is a valid IP address)
361 * @param string $url The URL to be validated
362 * @return string|boolean The actual working URL, false else
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
365 public static function isUrlValid(string $url)
367 if (Config::get('system', 'disable_url_validation')) {
371 // no naked subdomains (allow localhost for tests)
372 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
376 if (substr($url, 0, 4) != 'http') {
377 $url = 'http://' . $url;
380 /// @TODO Really suppress function outcomes? Why not find them + debug them?
381 $h = @parse_url($url);
383 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
391 * @brief Checks that email is an actual resolvable internet address
393 * @param string $addr The email address
394 * @return boolean True if it's a valid email address, false if it's not
396 public static function isEmailDomainValid(string $addr)
398 if (Config::get('system', 'disable_email_validation')) {
402 if (! strpos($addr, '@')) {
406 $h = substr($addr, strpos($addr, '@') + 1);
408 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
409 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
412 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
419 * @brief Check if URL is allowed
421 * Check $url against our list of allowed sites,
422 * wildcards allowed. If allowed_sites is unset return true;
424 * @param string $url URL which get tested
425 * @return boolean True if url is allowed otherwise return false
427 public static function isUrlAllowed(string $url)
429 $h = @parse_url($url);
435 $str_allowed = Config::get('system', 'allowed_sites');
436 if (! $str_allowed) {
442 $host = strtolower($h['host']);
444 // always allow our own site
445 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
449 $fnmatch = function_exists('fnmatch');
450 $allowed = explode(',', $str_allowed);
452 if (count($allowed)) {
453 foreach ($allowed as $a) {
454 $pat = strtolower(trim($a));
455 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
465 * Checks if the provided url domain is on the domain blocklist.
466 * Returns true if it is or malformed URL, false if not.
468 * @param string $url The url to check the domain from
472 public static function isUrlBlocked(string $url)
474 $host = @parse_url($url, PHP_URL_HOST);
479 $domain_blocklist = Config::get('system', 'blocklist', []);
480 if (!$domain_blocklist) {
484 foreach ($domain_blocklist as $domain_block) {
485 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
494 * @brief Check if email address is allowed to register here.
496 * Compare against our list (wildcards allowed).
498 * @param string $email email address
499 * @return boolean False if not allowed, true if allowed
500 * or if allowed list is not configured
501 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
503 public static function isEmailDomainAllowed(string $email)
505 $domain = strtolower(substr($email, strpos($email, '@') + 1));
510 $str_allowed = Config::get('system', 'allowed_email', '');
511 if (empty($str_allowed)) {
515 $allowed = explode(',', $str_allowed);
517 return self::isDomainAllowed($domain, $allowed);
521 * Checks for the existence of a domain in a domain list
523 * @brief Checks for the existence of a domain in a domain list
524 * @param string $domain
525 * @param array $domain_list
528 public static function isDomainAllowed(string $domain, array $domain_list)
532 foreach ($domain_list as $item) {
533 $pat = strtolower(trim($item));
534 if (fnmatch($pat, $domain) || ($pat == $domain)) {
543 public static function lookupAvatarByEmail(string $email)
545 $avatar['size'] = 300;
546 $avatar['email'] = $email;
548 $avatar['success'] = false;
550 Hook::callAll('avatar_lookup', $avatar);
552 if (! $avatar['success']) {
553 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
556 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
557 return $avatar['url'];
561 * @brief Remove Google Analytics and other tracking platforms params from URL
563 * @param string $url Any user-submitted URL that may contain tracking params
564 * @return string The same URL stripped of tracking parameters
566 public static function stripTrackingQueryParams(string $url)
568 $urldata = parse_url($url);
569 if (!empty($urldata["query"])) {
570 $query = $urldata["query"];
571 parse_str($query, $querydata);
573 if (is_array($querydata)) {
574 foreach ($querydata as $param => $value) {
578 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
579 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
580 "fb_action_ids", "fb_action_types", "fb_ref",
582 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
585 $pair = $param . "=" . urlencode($value);
586 $url = str_replace($pair, "", $url);
588 // Second try: if the url isn't encoded completely
589 $pair = $param . "=" . str_replace(" ", "+", $value);
590 $url = str_replace($pair, "", $url);
592 // Third try: Maybey the url isn't encoded at all
593 $pair = $param . "=" . $value;
594 $url = str_replace($pair, "", $url);
596 $url = str_replace(["?&", "&&"], ["?", ""], $url);
601 if (substr($url, -1, 1) == "?") {
602 $url = substr($url, 0, -1);
610 * @brief Returns the original URL of the provided URL
612 * This function strips tracking query params and follows redirections, either
613 * through HTTP code or meta refresh tags. Stops after 10 redirections.
615 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
617 * @see ParseUrl::getSiteinfo
619 * @param string $url A user-submitted URL
620 * @param int $depth The current redirection recursion level (internal)
621 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
622 * @return string A canonical URL
623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
625 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
629 $url = self::stripTrackingQueryParams($url);
635 $url = trim($url, "'");
637 $stamp1 = microtime(true);
640 curl_setopt($ch, CURLOPT_URL, $url);
641 curl_setopt($ch, CURLOPT_HEADER, 1);
642 curl_setopt($ch, CURLOPT_NOBODY, 1);
643 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
644 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
645 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
648 $curl_info = @curl_getinfo($ch);
649 $http_code = $curl_info['http_code'];
652 $a->getProfiler()->saveTimestamp($stamp1, "network", System::callstack());
654 if ($http_code == 0) {
658 if (in_array($http_code, ['301', '302'])) {
659 if (!empty($curl_info['redirect_url'])) {
660 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
661 } elseif (!empty($curl_info['location'])) {
662 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
666 // Check for redirects in the meta elements of the body if there are no redirects in the header.
668 return(self::finalUrl($url, ++$depth, true));
671 // if the file is too large then exit
672 if ($curl_info["download_content_length"] > 1000000) {
676 // if it isn't a HTML file then exit
677 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
681 $stamp1 = microtime(true);
684 curl_setopt($ch, CURLOPT_URL, $url);
685 curl_setopt($ch, CURLOPT_HEADER, 0);
686 curl_setopt($ch, CURLOPT_NOBODY, 0);
687 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
688 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
689 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
691 $body = curl_exec($ch);
694 $a->getProfiler()->saveTimestamp($stamp1, "network", System::callstack());
696 if (trim($body) == "") {
700 // Check for redirect in meta elements
701 $doc = new DOMDocument();
702 @$doc->loadHTML($body);
704 $xpath = new DomXPath($doc);
706 $list = $xpath->query("//meta[@content]");
707 foreach ($list as $node) {
709 if ($node->attributes->length) {
710 foreach ($node->attributes as $attribute) {
711 $attr[$attribute->name] = $attribute->value;
715 if (@$attr["http-equiv"] == 'refresh') {
716 $path = $attr["content"];
717 $pathinfo = explode(";", $path);
718 foreach ($pathinfo as $value) {
719 if (substr(strtolower($value), 0, 4) == "url=") {
720 return self::finalUrl(substr($value, 4), ++$depth);
730 * @brief Find the matching part between two url
732 * @param string $url1
733 * @param string $url2
734 * @return string The matching part
736 public static function getUrlMatch(string $url1, string $url2)
738 if (($url1 == "") || ($url2 == "")) {
742 $url1 = Strings::normaliseLink($url1);
743 $url2 = Strings::normaliseLink($url2);
745 $parts1 = parse_url($url1);
746 $parts2 = parse_url($url2);
748 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
752 if (empty($parts1["scheme"])) {
753 $parts1["scheme"] = '';
755 if (empty($parts2["scheme"])) {
756 $parts2["scheme"] = '';
759 if ($parts1["scheme"] != $parts2["scheme"]) {
763 if (empty($parts1["host"])) {
764 $parts1["host"] = '';
766 if (empty($parts2["host"])) {
767 $parts2["host"] = '';
770 if ($parts1["host"] != $parts2["host"]) {
774 if (empty($parts1["port"])) {
775 $parts1["port"] = '';
777 if (empty($parts2["port"])) {
778 $parts2["port"] = '';
781 if ($parts1["port"] != $parts2["port"]) {
785 $match = $parts1["scheme"]."://".$parts1["host"];
787 if ($parts1["port"]) {
788 $match .= ":".$parts1["port"];
791 if (empty($parts1["path"])) {
792 $parts1["path"] = '';
794 if (empty($parts2["path"])) {
795 $parts2["path"] = '';
798 $pathparts1 = explode("/", $parts1["path"]);
799 $pathparts2 = explode("/", $parts2["path"]);
804 $path1 = $pathparts1[$i] ?? '';
805 $path2 = $pathparts2[$i] ?? '';
807 if ($path1 == $path2) {
810 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
814 return Strings::normaliseLink($match);
818 * @brief Glue url parts together
820 * @param array $parsed URL parts
822 * @return string The glued URL
824 public static function unparseURL(array $parsed)
826 $get = function ($key) use ($parsed) {
827 return isset($parsed[$key]) ? $parsed[$key] : null;
830 $pass = $get('pass');
831 $user = $get('user');
832 $userinfo = $pass !== null ? "$user:$pass" : $user;
833 $port = $get('port');
834 $scheme = $get('scheme');
835 $query = $get('query');
836 $fragment = $get('fragment');
837 $authority = ($userinfo !== null ? $userinfo."@" : '') .
839 ($port ? ":$port" : '');
841 return (strlen($scheme) ? $scheme.":" : '') .
842 (strlen($authority) ? "//".$authority : '') .
844 (strlen($query) ? "?".$query : '') .
845 (strlen($fragment) ? "#".$fragment : '');
850 * Switch the scheme of an url between http and https
852 * @param string $url URL
854 * @return string switched URL
856 public static function switchScheme(string $url)
858 $scheme = parse_url($url, PHP_URL_SCHEME);
859 if (empty($scheme)) {
863 if ($scheme === 'http') {
864 $url = str_replace('http://', 'https://', $url);
865 } elseif ($scheme === 'https') {
866 $url = str_replace('https://', 'http://', $url);