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.
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 * @param string $url URL to fetch
50 * @param bool $binary default false
51 * TRUE if asked to return binary results (file download)
52 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
53 * @param string $accept_content supply Accept: header with 'accept_content' as the value
54 * @param string $cookiejar Path to cookie jar file
55 * @param int $redirects The recursion counter for internal use - default 0
57 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
66 'timeout' => $timeout,
67 'accept_content' => $accept_content,
68 'cookiejar' => $cookiejar
77 * @param string $url URL to fetch
78 * @param bool $binary default false
79 * TRUE if asked to return binary results (file download)
80 * @param array $opts (optional parameters) assoziative array with:
81 * 'accept_content' => supply Accept: header with 'accept_content' as the value
82 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
83 * 'http_auth' => username:password
84 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
85 * 'nobody' => only return the header
86 * 'cookiejar' => path to cookie jar file
87 * 'header' => header array
88 * @param int $redirects The recursion counter for internal use - default 0
91 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
93 public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
95 $stamp1 = microtime(true);
99 if (strlen($url) > 1000) {
100 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
101 return CurlResult::createErrorCurl(substr($url, 0, 200));
105 $parts = parse_url($url);
106 $path_parts = explode('/', $parts['path'] ?? '');
107 foreach ($path_parts as $part) {
108 if (strlen($part) <> mb_strlen($part)) {
109 $parts2[] = rawurlencode($part);
114 $parts['path'] = implode('/', $parts2);
115 $url = self::unparseURL($parts);
117 if (self::isUrlBlocked($url)) {
118 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
119 return CurlResult::createErrorCurl($url);
122 $ch = @curl_init($url);
124 if (($redirects > 8) || (!$ch)) {
125 return CurlResult::createErrorCurl($url);
128 @curl_setopt($ch, CURLOPT_HEADER, true);
130 if (!empty($opts['cookiejar'])) {
131 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
132 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
135 // These settings aren't needed. We're following the location already.
136 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
137 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
139 if (!empty($opts['accept_content'])) {
143 ['Accept: ' . $opts['accept_content']]
147 if (!empty($opts['header'])) {
148 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
151 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
152 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
154 $range = intval(DI::config()->get('system', 'curl_range_bytes', 0));
157 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
160 // Without this setting it seems as if some webservers send compressed content
161 // This seems to confuse curl so that it shows this uncompressed.
162 /// @todo We could possibly set this value to "gzip" or something similar
163 curl_setopt($ch, CURLOPT_ENCODING, '');
165 if (!empty($opts['headers'])) {
166 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
169 if (!empty($opts['nobody'])) {
170 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
173 if (!empty($opts['timeout'])) {
174 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
176 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
177 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
180 // by default we will allow self-signed certs
181 // but you can override this
183 $check_cert = DI::config()->get('system', 'verifyssl');
184 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
187 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
190 $proxy = DI::config()->get('system', 'proxy');
192 if (strlen($proxy)) {
193 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
194 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
195 $proxyuser = @DI::config()->get('system', 'proxyuser');
197 if (strlen($proxyuser)) {
198 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
202 if (DI::config()->get('system', 'ipv4_resolve', false)) {
203 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
207 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
210 // don't let curl abort the entire application
211 // if it throws any errors.
213 $s = @curl_exec($ch);
214 $curl_info = @curl_getinfo($ch);
216 // Special treatment for HTTP Code 416
217 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
218 if (($curl_info['http_code'] == 416) && ($range > 0)) {
219 @curl_setopt($ch, CURLOPT_RANGE, '');
220 $s = @curl_exec($ch);
221 $curl_info = @curl_getinfo($ch);
224 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
226 if ($curlResponse->isRedirectUrl()) {
228 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
230 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
235 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
237 return $curlResponse;
241 * Send POST request to $url
243 * @param string $url URL to post
244 * @param mixed $params array of POST variables
245 * @param array $headers HTTP headers
246 * @param int $redirects Recursion counter for internal use - default = 0
247 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
249 * @return CurlResult The content
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
254 $stamp1 = microtime(true);
256 if (self::isUrlBlocked($url)) {
257 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
258 return CurlResult::createErrorCurl($url);
262 $ch = curl_init($url);
264 if (($redirects > 8) || (!$ch)) {
265 return CurlResult::createErrorCurl($url);
268 Logger::log('post_url: start ' . $url, Logger::DATA);
270 curl_setopt($ch, CURLOPT_HEADER, true);
271 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
272 curl_setopt($ch, CURLOPT_POST, 1);
273 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
274 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
276 if (DI::config()->get('system', 'ipv4_resolve', false)) {
277 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
280 if (intval($timeout)) {
281 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
283 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
284 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
287 if (!empty($headers)) {
288 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
291 $check_cert = DI::config()->get('system', 'verifyssl');
292 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
295 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
298 $proxy = DI::config()->get('system', 'proxy');
300 if (strlen($proxy)) {
301 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
302 curl_setopt($ch, CURLOPT_PROXY, $proxy);
303 $proxyuser = DI::config()->get('system', 'proxyuser');
304 if (strlen($proxyuser)) {
305 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
309 // don't let curl abort the entire application
310 // if it throws any errors.
312 $s = @curl_exec($ch);
314 $curl_info = curl_getinfo($ch);
316 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
318 if ($curlResponse->isRedirectUrl()) {
320 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
322 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
327 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
329 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
330 if ($curlResponse->getReturnCode() == 417) {
333 if (empty($headers)) {
334 $headers = ['Expect:'];
336 if (!in_array('Expect:', $headers)) {
337 array_push($headers, 'Expect:');
340 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
341 return self::post($url, $params, $headers, $redirects, $timeout);
344 Logger::log('post_url: end ' . $url, Logger::DATA);
346 return $curlResponse;
350 * Return raw post data from a post request
352 * @return string post data
354 public static function postdata()
356 return file_get_contents('php://input');
360 * Check URL to see if it's real
362 * Take a URL from the wild, prepend http:// if necessary
363 * and check DNS to see if it's real (or check if is a valid IP address)
365 * @param string $url The URL to be validated
366 * @return string|boolean The actual working URL, false else
367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
369 public static function isUrlValid(string $url)
371 if (DI::config()->get('system', 'disable_url_validation')) {
375 // no naked subdomains (allow localhost for tests)
376 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
380 if (substr($url, 0, 4) != 'http') {
381 $url = 'http://' . $url;
384 /// @TODO Really suppress function outcomes? Why not find them + debug them?
385 $h = @parse_url($url);
387 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
395 * Checks that email is an actual resolvable internet address
397 * @param string $addr The email address
398 * @return boolean True if it's a valid email address, false if it's not
400 public static function isEmailDomainValid(string $addr)
402 if (DI::config()->get('system', 'disable_email_validation')) {
406 if (! strpos($addr, '@')) {
410 $h = substr($addr, strpos($addr, '@') + 1);
412 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
413 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
416 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
423 * Check if URL is allowed
425 * Check $url against our list of allowed sites,
426 * wildcards allowed. If allowed_sites is unset return true;
428 * @param string $url URL which get tested
429 * @return boolean True if url is allowed otherwise return false
431 public static function isUrlAllowed(string $url)
433 $h = @parse_url($url);
439 $str_allowed = DI::config()->get('system', 'allowed_sites');
440 if (! $str_allowed) {
446 $host = strtolower($h['host']);
448 // always allow our own site
449 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
453 $fnmatch = function_exists('fnmatch');
454 $allowed = explode(',', $str_allowed);
456 if (count($allowed)) {
457 foreach ($allowed as $a) {
458 $pat = strtolower(trim($a));
459 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
469 * Checks if the provided url domain is on the domain blocklist.
470 * Returns true if it is or malformed URL, false if not.
472 * @param string $url The url to check the domain from
476 public static function isUrlBlocked(string $url)
478 $host = @parse_url($url, PHP_URL_HOST);
483 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
484 if (!$domain_blocklist) {
488 foreach ($domain_blocklist as $domain_block) {
489 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
498 * Check if email address is allowed to register here.
500 * Compare against our list (wildcards allowed).
502 * @param string $email email address
503 * @return boolean False if not allowed, true if allowed
504 * or if allowed list is not configured
505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
507 public static function isEmailDomainAllowed(string $email)
509 $domain = strtolower(substr($email, strpos($email, '@') + 1));
514 $str_allowed = DI::config()->get('system', 'allowed_email', '');
515 if (empty($str_allowed)) {
519 $allowed = explode(',', $str_allowed);
521 return self::isDomainAllowed($domain, $allowed);
525 * Checks for the existence of a domain in a domain list
527 * @param string $domain
528 * @param array $domain_list
531 public static function isDomainAllowed(string $domain, array $domain_list)
535 foreach ($domain_list as $item) {
536 $pat = strtolower(trim($item));
537 if (fnmatch($pat, $domain) || ($pat == $domain)) {
546 public static function lookupAvatarByEmail(string $email)
548 $avatar['size'] = 300;
549 $avatar['email'] = $email;
551 $avatar['success'] = false;
553 Hook::callAll('avatar_lookup', $avatar);
555 if (! $avatar['success']) {
556 $avatar['url'] = DI::baseUrl() . '/images/person-300.jpg';
559 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
560 return $avatar['url'];
564 * Remove Google Analytics and other tracking platforms params from URL
566 * @param string $url Any user-submitted URL that may contain tracking params
567 * @return string The same URL stripped of tracking parameters
569 public static function stripTrackingQueryParams(string $url)
571 $urldata = parse_url($url);
572 if (!empty($urldata["query"])) {
573 $query = $urldata["query"];
574 parse_str($query, $querydata);
576 if (is_array($querydata)) {
577 foreach ($querydata as $param => $value) {
581 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
582 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
583 "fb_action_ids", "fb_action_types", "fb_ref",
585 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
588 $pair = $param . "=" . urlencode($value);
589 $url = str_replace($pair, "", $url);
591 // Second try: if the url isn't encoded completely
592 $pair = $param . "=" . str_replace(" ", "+", $value);
593 $url = str_replace($pair, "", $url);
595 // Third try: Maybey the url isn't encoded at all
596 $pair = $param . "=" . $value;
597 $url = str_replace($pair, "", $url);
599 $url = str_replace(["?&", "&&"], ["?", ""], $url);
604 if (substr($url, -1, 1) == "?") {
605 $url = substr($url, 0, -1);
613 * Returns the original URL of the provided URL
615 * This function strips tracking query params and follows redirections, either
616 * through HTTP code or meta refresh tags. Stops after 10 redirections.
618 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
620 * @see ParseUrl::getSiteinfo
622 * @param string $url A user-submitted URL
623 * @param int $depth The current redirection recursion level (internal)
624 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
625 * @return string A canonical URL
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
628 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
632 $url = self::stripTrackingQueryParams($url);
638 $url = trim($url, "'");
640 $stamp1 = microtime(true);
643 curl_setopt($ch, CURLOPT_URL, $url);
644 curl_setopt($ch, CURLOPT_HEADER, 1);
645 curl_setopt($ch, CURLOPT_NOBODY, 1);
646 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
647 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
648 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
651 $curl_info = @curl_getinfo($ch);
652 $http_code = $curl_info['http_code'];
655 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
657 if ($http_code == 0) {
661 if (in_array($http_code, ['301', '302'])) {
662 if (!empty($curl_info['redirect_url'])) {
663 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
664 } elseif (!empty($curl_info['location'])) {
665 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
669 // Check for redirects in the meta elements of the body if there are no redirects in the header.
671 return(self::finalUrl($url, ++$depth, true));
674 // if the file is too large then exit
675 if ($curl_info["download_content_length"] > 1000000) {
679 // if it isn't a HTML file then exit
680 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
684 $stamp1 = microtime(true);
687 curl_setopt($ch, CURLOPT_URL, $url);
688 curl_setopt($ch, CURLOPT_HEADER, 0);
689 curl_setopt($ch, CURLOPT_NOBODY, 0);
690 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
691 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
692 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
694 $body = curl_exec($ch);
697 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
699 if (trim($body) == "") {
703 // Check for redirect in meta elements
704 $doc = new DOMDocument();
705 @$doc->loadHTML($body);
707 $xpath = new DomXPath($doc);
709 $list = $xpath->query("//meta[@content]");
710 foreach ($list as $node) {
712 if ($node->attributes->length) {
713 foreach ($node->attributes as $attribute) {
714 $attr[$attribute->name] = $attribute->value;
718 if (@$attr["http-equiv"] == 'refresh') {
719 $path = $attr["content"];
720 $pathinfo = explode(";", $path);
721 foreach ($pathinfo as $value) {
722 if (substr(strtolower($value), 0, 4) == "url=") {
723 return self::finalUrl(substr($value, 4), ++$depth);
733 * Find the matching part between two url
735 * @param string $url1
736 * @param string $url2
737 * @return string The matching part
739 public static function getUrlMatch(string $url1, string $url2)
741 if (($url1 == "") || ($url2 == "")) {
745 $url1 = Strings::normaliseLink($url1);
746 $url2 = Strings::normaliseLink($url2);
748 $parts1 = parse_url($url1);
749 $parts2 = parse_url($url2);
751 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
755 if (empty($parts1["scheme"])) {
756 $parts1["scheme"] = '';
758 if (empty($parts2["scheme"])) {
759 $parts2["scheme"] = '';
762 if ($parts1["scheme"] != $parts2["scheme"]) {
766 if (empty($parts1["host"])) {
767 $parts1["host"] = '';
769 if (empty($parts2["host"])) {
770 $parts2["host"] = '';
773 if ($parts1["host"] != $parts2["host"]) {
777 if (empty($parts1["port"])) {
778 $parts1["port"] = '';
780 if (empty($parts2["port"])) {
781 $parts2["port"] = '';
784 if ($parts1["port"] != $parts2["port"]) {
788 $match = $parts1["scheme"]."://".$parts1["host"];
790 if ($parts1["port"]) {
791 $match .= ":".$parts1["port"];
794 if (empty($parts1["path"])) {
795 $parts1["path"] = '';
797 if (empty($parts2["path"])) {
798 $parts2["path"] = '';
801 $pathparts1 = explode("/", $parts1["path"]);
802 $pathparts2 = explode("/", $parts2["path"]);
807 $path1 = $pathparts1[$i] ?? '';
808 $path2 = $pathparts2[$i] ?? '';
810 if ($path1 == $path2) {
813 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
817 return Strings::normaliseLink($match);
821 * Glue url parts together
823 * @param array $parsed URL parts
825 * @return string The glued URL
827 public static function unparseURL(array $parsed)
829 $get = function ($key) use ($parsed) {
830 return isset($parsed[$key]) ? $parsed[$key] : null;
833 $pass = $get('pass');
834 $user = $get('user');
835 $userinfo = $pass !== null ? "$user:$pass" : $user;
836 $port = $get('port');
837 $scheme = $get('scheme');
838 $query = $get('query');
839 $fragment = $get('fragment');
840 $authority = ($userinfo !== null ? $userinfo."@" : '') .
842 ($port ? ":$port" : '');
844 return (strlen($scheme) ? $scheme.":" : '') .
845 (strlen($authority) ? "//".$authority : '') .
847 (strlen($query) ? "?".$query : '') .
848 (strlen($fragment) ? "#".$fragment : '');
853 * Switch the scheme of an url between http and https
855 * @param string $url URL
857 * @return string switched URL
859 public static function switchScheme(string $url)
861 $scheme = parse_url($url, PHP_URL_SCHEME);
862 if (empty($scheme)) {
866 if ($scheme === 'http') {
867 $url = str_replace('http://', 'https://', $url);
868 } elseif ($scheme === 'https') {
869 $url = str_replace('https://', 'http://', $url);