3 * @file src/Util/Network.php
5 namespace Friendica\Util;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 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.
24 * @param string $url URL to fetch
25 * @param bool $binary default false
26 * TRUE if asked to return binary results (file download)
27 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
28 * @param string $accept_content supply Accept: header with 'accept_content' as the value
29 * @param string $cookiejar Path to cookie jar file
30 * @param int $redirects The recursion counter for internal use - default 0
32 * @return string The fetched content
33 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
35 public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
37 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
39 return $ret->getBody();
43 * Curl wrapper with array of return values.
45 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
46 * all the information collected during the fetch.
48 * @param string $url URL to fetch
49 * @param bool $binary default false
50 * TRUE if asked to return binary results (file download)
51 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
52 * @param string $accept_content supply Accept: header with 'accept_content' as the value
53 * @param string $cookiejar Path to cookie jar file
54 * @param int $redirects The recursion counter for internal use - default 0
56 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
57 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
65 'timeout' => $timeout,
66 'accept_content' => $accept_content,
67 'cookiejar' => $cookiejar
76 * @param string $url URL to fetch
77 * @param bool $binary default false
78 * TRUE if asked to return binary results (file download)
79 * @param array $opts (optional parameters) assoziative array with:
80 * 'accept_content' => supply Accept: header with 'accept_content' as the value
81 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
82 * 'http_auth' => username:password
83 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
84 * 'nobody' => only return the header
85 * 'cookiejar' => path to cookie jar file
86 * 'header' => header array
87 * @param int $redirects The recursion counter for internal use - default 0
90 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
92 public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
94 $stamp1 = microtime(true);
98 if (strlen($url) > 1000) {
99 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
100 return CurlResult::createErrorCurl(substr($url, 0, 200));
104 $parts = parse_url($url);
105 $path_parts = explode('/', $parts['path'] ?? '');
106 foreach ($path_parts as $part) {
107 if (strlen($part) <> mb_strlen($part)) {
108 $parts2[] = rawurlencode($part);
113 $parts['path'] = implode('/', $parts2);
114 $url = self::unparseURL($parts);
116 if (self::isUrlBlocked($url)) {
117 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
118 return CurlResult::createErrorCurl($url);
121 $ch = @curl_init($url);
123 if (($redirects > 8) || (!$ch)) {
124 return CurlResult::createErrorCurl($url);
127 @curl_setopt($ch, CURLOPT_HEADER, true);
129 if (!empty($opts['cookiejar'])) {
130 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
131 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
134 // These settings aren't needed. We're following the location already.
135 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
136 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
138 if (!empty($opts['accept_content'])) {
142 ['Accept: ' . $opts['accept_content']]
146 if (!empty($opts['header'])) {
147 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
150 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
151 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
153 $range = intval(DI::config()->get('system', 'curl_range_bytes', 0));
156 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
159 // Without this setting it seems as if some webservers send compressed content
160 // This seems to confuse curl so that it shows this uncompressed.
161 /// @todo We could possibly set this value to "gzip" or something similar
162 curl_setopt($ch, CURLOPT_ENCODING, '');
164 if (!empty($opts['headers'])) {
165 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
168 if (!empty($opts['nobody'])) {
169 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
172 if (!empty($opts['timeout'])) {
173 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
175 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
176 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
179 // by default we will allow self-signed certs
180 // but you can override this
182 $check_cert = DI::config()->get('system', 'verifyssl');
183 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
186 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
189 $proxy = DI::config()->get('system', 'proxy');
191 if (strlen($proxy)) {
192 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
193 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
194 $proxyuser = @DI::config()->get('system', 'proxyuser');
196 if (strlen($proxyuser)) {
197 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
201 if (DI::config()->get('system', 'ipv4_resolve', false)) {
202 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
206 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
209 // don't let curl abort the entire application
210 // if it throws any errors.
212 $s = @curl_exec($ch);
213 $curl_info = @curl_getinfo($ch);
215 // Special treatment for HTTP Code 416
216 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
217 if (($curl_info['http_code'] == 416) && ($range > 0)) {
218 @curl_setopt($ch, CURLOPT_RANGE, '');
219 $s = @curl_exec($ch);
220 $curl_info = @curl_getinfo($ch);
223 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
225 if ($curlResponse->isRedirectUrl()) {
227 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
229 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
234 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
236 return $curlResponse;
240 * Send POST request to $url
242 * @param string $url URL to post
243 * @param mixed $params array of POST variables
244 * @param array $headers HTTP headers
245 * @param int $redirects Recursion counter for internal use - default = 0
246 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
248 * @return CurlResult The content
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
253 $stamp1 = microtime(true);
255 if (self::isUrlBlocked($url)) {
256 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
257 return CurlResult::createErrorCurl($url);
261 $ch = curl_init($url);
263 if (($redirects > 8) || (!$ch)) {
264 return CurlResult::createErrorCurl($url);
267 Logger::log('post_url: start ' . $url, Logger::DATA);
269 curl_setopt($ch, CURLOPT_HEADER, true);
270 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
271 curl_setopt($ch, CURLOPT_POST, 1);
272 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
273 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
275 if (DI::config()->get('system', 'ipv4_resolve', false)) {
276 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
279 if (intval($timeout)) {
280 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
282 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
283 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
286 if (!empty($headers)) {
287 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
290 $check_cert = DI::config()->get('system', 'verifyssl');
291 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
294 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
297 $proxy = DI::config()->get('system', 'proxy');
299 if (strlen($proxy)) {
300 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
301 curl_setopt($ch, CURLOPT_PROXY, $proxy);
302 $proxyuser = DI::config()->get('system', 'proxyuser');
303 if (strlen($proxyuser)) {
304 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
308 // don't let curl abort the entire application
309 // if it throws any errors.
311 $s = @curl_exec($ch);
313 $curl_info = curl_getinfo($ch);
315 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
317 if ($curlResponse->isRedirectUrl()) {
319 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
321 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
326 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
328 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
329 if ($curlResponse->getReturnCode() == 417) {
332 if (empty($headers)) {
333 $headers = ['Expect:'];
335 if (!in_array('Expect:', $headers)) {
336 array_push($headers, 'Expect:');
339 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
340 return self::post($url, $params, $headers, $redirects, $timeout);
343 Logger::log('post_url: end ' . $url, Logger::DATA);
345 return $curlResponse;
349 * Return raw post data from a post request
351 * @return string post data
353 public static function postdata()
355 return file_get_contents('php://input');
359 * Check URL to see if it's real
361 * Take a URL from the wild, prepend http:// if necessary
362 * and check DNS to see if it's real (or check if is a valid IP address)
364 * @param string $url The URL to be validated
365 * @return string|boolean The actual working URL, false else
366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
368 public static function isUrlValid(string $url)
370 if (DI::config()->get('system', 'disable_url_validation')) {
374 // no naked subdomains (allow localhost for tests)
375 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
379 if (substr($url, 0, 4) != 'http') {
380 $url = 'http://' . $url;
383 /// @TODO Really suppress function outcomes? Why not find them + debug them?
384 $h = @parse_url($url);
386 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
394 * Checks that email is an actual resolvable internet address
396 * @param string $addr The email address
397 * @return boolean True if it's a valid email address, false if it's not
399 public static function isEmailDomainValid(string $addr)
401 if (DI::config()->get('system', 'disable_email_validation')) {
405 if (! strpos($addr, '@')) {
409 $h = substr($addr, strpos($addr, '@') + 1);
411 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
412 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
415 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
422 * Check if URL is allowed
424 * Check $url against our list of allowed sites,
425 * wildcards allowed. If allowed_sites is unset return true;
427 * @param string $url URL which get tested
428 * @return boolean True if url is allowed otherwise return false
430 public static function isUrlAllowed(string $url)
432 $h = @parse_url($url);
438 $str_allowed = DI::config()->get('system', 'allowed_sites');
439 if (! $str_allowed) {
445 $host = strtolower($h['host']);
447 // always allow our own site
448 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
452 $fnmatch = function_exists('fnmatch');
453 $allowed = explode(',', $str_allowed);
455 if (count($allowed)) {
456 foreach ($allowed as $a) {
457 $pat = strtolower(trim($a));
458 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
468 * Checks if the provided url domain is on the domain blocklist.
469 * Returns true if it is or malformed URL, false if not.
471 * @param string $url The url to check the domain from
475 public static function isUrlBlocked(string $url)
477 $host = @parse_url($url, PHP_URL_HOST);
482 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
483 if (!$domain_blocklist) {
487 foreach ($domain_blocklist as $domain_block) {
488 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
497 * Check if email address is allowed to register here.
499 * Compare against our list (wildcards allowed).
501 * @param string $email email address
502 * @return boolean False if not allowed, true if allowed
503 * or if allowed list is not configured
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 public static function isEmailDomainAllowed(string $email)
508 $domain = strtolower(substr($email, strpos($email, '@') + 1));
513 $str_allowed = DI::config()->get('system', 'allowed_email', '');
514 if (empty($str_allowed)) {
518 $allowed = explode(',', $str_allowed);
520 return self::isDomainAllowed($domain, $allowed);
524 * Checks for the existence of a domain in a domain list
526 * @param string $domain
527 * @param array $domain_list
530 public static function isDomainAllowed(string $domain, array $domain_list)
534 foreach ($domain_list as $item) {
535 $pat = strtolower(trim($item));
536 if (fnmatch($pat, $domain) || ($pat == $domain)) {
545 public static function lookupAvatarByEmail(string $email)
547 $avatar['size'] = 300;
548 $avatar['email'] = $email;
550 $avatar['success'] = false;
552 Hook::callAll('avatar_lookup', $avatar);
554 if (! $avatar['success']) {
555 $avatar['url'] = DI::baseUrl() . '/images/person-300.jpg';
558 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
559 return $avatar['url'];
563 * Remove Google Analytics and other tracking platforms params from URL
565 * @param string $url Any user-submitted URL that may contain tracking params
566 * @return string The same URL stripped of tracking parameters
568 public static function stripTrackingQueryParams(string $url)
570 $urldata = parse_url($url);
571 if (!empty($urldata["query"])) {
572 $query = $urldata["query"];
573 parse_str($query, $querydata);
575 if (is_array($querydata)) {
576 foreach ($querydata as $param => $value) {
580 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
581 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
582 "fb_action_ids", "fb_action_types", "fb_ref",
584 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
587 $pair = $param . "=" . urlencode($value);
588 $url = str_replace($pair, "", $url);
590 // Second try: if the url isn't encoded completely
591 $pair = $param . "=" . str_replace(" ", "+", $value);
592 $url = str_replace($pair, "", $url);
594 // Third try: Maybey the url isn't encoded at all
595 $pair = $param . "=" . $value;
596 $url = str_replace($pair, "", $url);
598 $url = str_replace(["?&", "&&"], ["?", ""], $url);
603 if (substr($url, -1, 1) == "?") {
604 $url = substr($url, 0, -1);
612 * Returns the original URL of the provided URL
614 * This function strips tracking query params and follows redirections, either
615 * through HTTP code or meta refresh tags. Stops after 10 redirections.
617 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
619 * @see ParseUrl::getSiteinfo
621 * @param string $url A user-submitted URL
622 * @param int $depth The current redirection recursion level (internal)
623 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
624 * @return string A canonical URL
625 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
631 $url = self::stripTrackingQueryParams($url);
637 $url = trim($url, "'");
639 $stamp1 = microtime(true);
642 curl_setopt($ch, CURLOPT_URL, $url);
643 curl_setopt($ch, CURLOPT_HEADER, 1);
644 curl_setopt($ch, CURLOPT_NOBODY, 1);
645 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
646 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
647 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
650 $curl_info = @curl_getinfo($ch);
651 $http_code = $curl_info['http_code'];
654 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
656 if ($http_code == 0) {
660 if (in_array($http_code, ['301', '302'])) {
661 if (!empty($curl_info['redirect_url'])) {
662 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
663 } elseif (!empty($curl_info['location'])) {
664 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
668 // Check for redirects in the meta elements of the body if there are no redirects in the header.
670 return(self::finalUrl($url, ++$depth, true));
673 // if the file is too large then exit
674 if ($curl_info["download_content_length"] > 1000000) {
678 // if it isn't a HTML file then exit
679 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
683 $stamp1 = microtime(true);
686 curl_setopt($ch, CURLOPT_URL, $url);
687 curl_setopt($ch, CURLOPT_HEADER, 0);
688 curl_setopt($ch, CURLOPT_NOBODY, 0);
689 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
690 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
691 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
693 $body = curl_exec($ch);
696 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
698 if (trim($body) == "") {
702 // Check for redirect in meta elements
703 $doc = new DOMDocument();
704 @$doc->loadHTML($body);
706 $xpath = new DomXPath($doc);
708 $list = $xpath->query("//meta[@content]");
709 foreach ($list as $node) {
711 if ($node->attributes->length) {
712 foreach ($node->attributes as $attribute) {
713 $attr[$attribute->name] = $attribute->value;
717 if (@$attr["http-equiv"] == 'refresh') {
718 $path = $attr["content"];
719 $pathinfo = explode(";", $path);
720 foreach ($pathinfo as $value) {
721 if (substr(strtolower($value), 0, 4) == "url=") {
722 return self::finalUrl(substr($value, 4), ++$depth);
732 * Find the matching part between two url
734 * @param string $url1
735 * @param string $url2
736 * @return string The matching part
738 public static function getUrlMatch(string $url1, string $url2)
740 if (($url1 == "") || ($url2 == "")) {
744 $url1 = Strings::normaliseLink($url1);
745 $url2 = Strings::normaliseLink($url2);
747 $parts1 = parse_url($url1);
748 $parts2 = parse_url($url2);
750 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
754 if (empty($parts1["scheme"])) {
755 $parts1["scheme"] = '';
757 if (empty($parts2["scheme"])) {
758 $parts2["scheme"] = '';
761 if ($parts1["scheme"] != $parts2["scheme"]) {
765 if (empty($parts1["host"])) {
766 $parts1["host"] = '';
768 if (empty($parts2["host"])) {
769 $parts2["host"] = '';
772 if ($parts1["host"] != $parts2["host"]) {
776 if (empty($parts1["port"])) {
777 $parts1["port"] = '';
779 if (empty($parts2["port"])) {
780 $parts2["port"] = '';
783 if ($parts1["port"] != $parts2["port"]) {
787 $match = $parts1["scheme"]."://".$parts1["host"];
789 if ($parts1["port"]) {
790 $match .= ":".$parts1["port"];
793 if (empty($parts1["path"])) {
794 $parts1["path"] = '';
796 if (empty($parts2["path"])) {
797 $parts2["path"] = '';
800 $pathparts1 = explode("/", $parts1["path"]);
801 $pathparts2 = explode("/", $parts2["path"]);
806 $path1 = $pathparts1[$i] ?? '';
807 $path2 = $pathparts2[$i] ?? '';
809 if ($path1 == $path2) {
812 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
816 return Strings::normaliseLink($match);
820 * Glue url parts together
822 * @param array $parsed URL parts
824 * @return string The glued URL
826 public static function unparseURL(array $parsed)
828 $get = function ($key) use ($parsed) {
829 return isset($parsed[$key]) ? $parsed[$key] : null;
832 $pass = $get('pass');
833 $user = $get('user');
834 $userinfo = $pass !== null ? "$user:$pass" : $user;
835 $port = $get('port');
836 $scheme = $get('scheme');
837 $query = $get('query');
838 $fragment = $get('fragment');
839 $authority = ($userinfo !== null ? $userinfo."@" : '') .
841 ($port ? ":$port" : '');
843 return (strlen($scheme) ? $scheme.":" : '') .
844 (strlen($authority) ? "//".$authority : '') .
846 (strlen($query) ? "?".$query : '') .
847 (strlen($fragment) ? "#".$fragment : '');
852 * Switch the scheme of an url between http and https
854 * @param string $url URL
856 * @return string switched URL
858 public static function switchScheme(string $url)
860 $scheme = parse_url($url, PHP_URL_SCHEME);
861 if (empty($scheme)) {
865 if ($scheme === 'http') {
866 $url = str_replace('http://', 'https://', $url);
867 } elseif ($scheme === 'https') {
868 $url = str_replace('https://', 'http://', $url);