3 * @file src/Util/Network.php
5 namespace Friendica\Util;
8 use Friendica\Core\Addon;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Network\Probe;
13 use Friendica\Object\Image;
14 use Friendica\Util\XML;
23 * If binary flag is true, return binary results.
24 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
25 * to preserve cookies from one request to the next.
27 * @param string $url URL to fetch
28 * @param boolean $binary default false
29 * TRUE if asked to return binary results (file download)
30 * @param integer $redirects The recursion counter for internal use - default 0
31 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
32 * @param string $accept_content supply Accept: header with 'accept_content' as the value
33 * @param string $cookiejar Path to cookie jar file
35 * @return string The fetched content
37 public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
44 'accept_content'=>$accept_content,
45 'cookiejar'=>$cookiejar
53 * @brief fetches an URL.
55 * @param string $url URL to fetch
56 * @param boolean $binary default false
57 * TRUE if asked to return binary results (file download)
58 * @param int $redirects The recursion counter for internal use - default 0
59 * @param array $opts (optional parameters) assoziative array with:
60 * 'accept_content' => supply Accept: header with 'accept_content' as the value
61 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
62 * 'http_auth' => username:password
63 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
64 * 'nobody' => only return the header
65 * 'cookiejar' => path to cookie jar file
67 * @return array an assoziative array with:
68 * int 'return_code' => HTTP return code or 0 if timeout or failure
69 * boolean 'success' => boolean true (if HTTP 2xx result) or false
70 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
71 * string 'header' => HTTP headers
72 * string 'body' => fetched content
74 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
76 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
78 $stamp1 = microtime(true);
82 if (self::isUrlBlocked($url)) {
83 logger('domain of ' . $url . ' is blocked', LOGGER_DATA);
87 $ch = @curl_init($url);
89 if (($redirects > 8) || (!$ch)) {
93 @curl_setopt($ch, CURLOPT_HEADER, true);
95 if (x($opts, "cookiejar")) {
96 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
97 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
100 // These settings aren't needed. We're following the location already.
101 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
102 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
104 if (x($opts, 'accept_content')) {
108 ['Accept: ' . $opts['accept_content']]
112 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
113 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
115 $range = intval(Config::get('system', 'curl_range_bytes', 0));
118 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
121 // Without this setting it seems as if some webservers send compressed content
122 // This seems to confuse curl so that it shows this uncompressed.
123 /// @todo We could possibly set this value to "gzip" or something similar
124 curl_setopt($ch, CURLOPT_ENCODING, '');
126 if (x($opts, 'headers')) {
127 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
130 if (x($opts, 'nobody')) {
131 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
134 if (x($opts, 'timeout')) {
135 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
137 $curl_time = Config::get('system', 'curl_timeout', 60);
138 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
141 // by default we will allow self-signed certs
142 // but you can override this
144 $check_cert = Config::get('system', 'verifyssl');
145 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
148 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
151 $proxy = Config::get('system', 'proxy');
153 if (strlen($proxy)) {
154 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
155 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
156 $proxyuser = @Config::get('system', 'proxyuser');
158 if (strlen($proxyuser)) {
159 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
163 if (Config::get('system', 'ipv4_resolve', false)) {
164 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
168 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
171 $a->set_curl_code(0);
173 // don't let curl abort the entire application
174 // if it throws any errors.
176 $s = @curl_exec($ch);
177 $curl_info = @curl_getinfo($ch);
179 // Special treatment for HTTP Code 416
180 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
181 if (($curl_info['http_code'] == 416) && ($range > 0)) {
182 @curl_setopt($ch, CURLOPT_RANGE, '');
183 $s = @curl_exec($ch);
184 $curl_info = @curl_getinfo($ch);
187 if (curl_errno($ch) !== CURLE_OK) {
188 logger('error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
191 $ret['errno'] = curl_errno($ch);
194 $ret['info'] = $curl_info;
196 $http_code = $curl_info['http_code'];
198 logger($url . ': ' . $http_code . " " . $s, LOGGER_DATA);
201 // Pull out multiple headers, e.g. proxy and continuation headers
202 // allow for HTTP/2.x without fixing code
204 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
205 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
207 $base = substr($base, strlen($chunk));
210 $a->set_curl_code($http_code);
211 $a->set_curl_content_type($curl_info['content_type']);
212 $a->set_curl_headers($header);
214 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
215 $new_location_info = @parse_url($curl_info['redirect_url']);
216 $old_location_info = @parse_url($curl_info['url']);
218 $newurl = $curl_info['redirect_url'];
220 if (($new_location_info['path'] == '') && ($new_location_info['host'] != '')) {
221 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
226 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
227 $newurl = trim(array_pop($matches));
229 if (strpos($newurl, '/') === 0) {
230 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
232 $old_location_query = @parse_url($url, PHP_URL_QUERY);
234 if ($old_location_query != '') {
235 $newurl .= '?' . $old_location_query;
238 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
241 return self::curl($newurl, $binary, $redirects, $opts);
245 $a->set_curl_code($http_code);
246 $a->set_curl_content_type($curl_info['content_type']);
248 $rc = intval($http_code);
249 $ret['return_code'] = $rc;
250 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
251 $ret['redirect_url'] = $url;
253 if (!$ret['success']) {
254 $ret['error'] = curl_error($ch);
255 $ret['debug'] = $curl_info;
256 logger('error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
257 logger('debug: '.print_r($curl_info, true), LOGGER_DATA);
260 $ret['body'] = substr($s, strlen($header));
261 $ret['header'] = $header;
263 if (x($opts, 'debug')) {
264 $ret['debug'] = $curl_info;
269 $a->save_timestamp($stamp1, 'network');
275 * @brief Send POST request to $url
277 * @param string $url URL to post
278 * @param mixed $params array of POST variables
279 * @param string $headers HTTP headers
280 * @param integer $redirects Recursion counter for internal use - default = 0
281 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
283 * @return string The content
285 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
287 $stamp1 = microtime(true);
289 if (self::isUrlBlocked($url)) {
290 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
295 $ch = curl_init($url);
297 if (($redirects > 8) || (!$ch)) {
301 logger('post_url: start ' . $url, LOGGER_DATA);
303 curl_setopt($ch, CURLOPT_HEADER, true);
304 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
305 curl_setopt($ch, CURLOPT_POST, 1);
306 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
307 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
309 if (Config::get('system', 'ipv4_resolve', false)) {
310 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
313 if (intval($timeout)) {
314 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
316 $curl_time = Config::get('system', 'curl_timeout', 60);
317 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
320 if (defined('LIGHTTPD')) {
321 if (!is_array($headers)) {
322 $headers = ['Expect:'];
324 if (!in_array('Expect:', $headers)) {
325 array_push($headers, 'Expect:');
331 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
334 $check_cert = Config::get('system', 'verifyssl');
335 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
338 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
341 $proxy = Config::get('system', 'proxy');
343 if (strlen($proxy)) {
344 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
345 curl_setopt($ch, CURLOPT_PROXY, $proxy);
346 $proxyuser = Config::get('system', 'proxyuser');
347 if (strlen($proxyuser)) {
348 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
352 $a->set_curl_code(0);
354 // don't let curl abort the entire application
355 // if it throws any errors.
357 $s = @curl_exec($ch);
360 $curl_info = curl_getinfo($ch);
361 $http_code = $curl_info['http_code'];
363 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
367 // Pull out multiple headers, e.g. proxy and continuation headers
368 // allow for HTTP/2.x without fixing code
370 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
371 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
373 $base = substr($base, strlen($chunk));
376 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
378 $new_location_info = @parse_url($curl_info['redirect_url']);
379 $old_location_info = @parse_url($curl_info['url']);
381 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
382 $newurl = trim(array_pop($matches));
384 if (strpos($newurl, '/') === 0) {
385 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
388 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
390 logger('post_url: redirect ' . $url . ' to ' . $newurl);
391 return self::post($newurl, $params, $headers, $redirects, $timeout);
395 $a->set_curl_code($http_code);
397 $body = substr($s, strlen($header));
399 $a->set_curl_headers($header);
403 $a->save_timestamp($stamp1, 'network');
405 logger('post_url: end ' . $url, LOGGER_DATA);
411 * @brief Check URL to see if it's real
413 * Take a URL from the wild, prepend http:// if necessary
414 * and check DNS to see if it's real (or check if is a valid IP address)
416 * @param string $url The URL to be validated
417 * @return string|boolean The actual working URL, false else
419 public static function isUrlValid($url)
421 if (Config::get('system', 'disable_url_validation')) {
425 // no naked subdomains (allow localhost for tests)
426 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
430 if (substr($url, 0, 4) != 'http') {
431 $url = 'http://' . $url;
434 /// @TODO Really suppress function outcomes? Why not find them + debug them?
435 $h = @parse_url($url);
437 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
445 * @brief Checks that email is an actual resolvable internet address
447 * @param string $addr The email address
448 * @return boolean True if it's a valid email address, false if it's not
450 public static function isEmailDomainValid($addr)
452 if (Config::get('system', 'disable_email_validation')) {
456 if (! strpos($addr, '@')) {
460 $h = substr($addr, strpos($addr, '@') + 1);
462 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
469 * @brief Check if URL is allowed
471 * Check $url against our list of allowed sites,
472 * wildcards allowed. If allowed_sites is unset return true;
474 * @param string $url URL which get tested
475 * @return boolean True if url is allowed otherwise return false
477 public static function isUrlAllowed($url)
479 $h = @parse_url($url);
485 $str_allowed = Config::get('system', 'allowed_sites');
486 if (! $str_allowed) {
492 $host = strtolower($h['host']);
494 // always allow our own site
495 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
499 $fnmatch = function_exists('fnmatch');
500 $allowed = explode(',', $str_allowed);
502 if (count($allowed)) {
503 foreach ($allowed as $a) {
504 $pat = strtolower(trim($a));
505 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
515 * Checks if the provided url domain is on the domain blocklist.
516 * Returns true if it is or malformed URL, false if not.
518 * @param string $url The url to check the domain from
522 public static function isUrlBlocked($url)
524 $h = @parse_url($url);
530 $domain_blocklist = Config::get('system', 'blocklist', []);
531 if (! $domain_blocklist) {
535 $host = strtolower($h['host']);
537 foreach ($domain_blocklist as $domain_block) {
538 if (strtolower($domain_block['domain']) == $host) {
547 * @brief Check if email address is allowed to register here.
549 * Compare against our list (wildcards allowed).
551 * @param string $email email address
552 * @return boolean False if not allowed, true if allowed
553 * or if allowed list is not configured
555 public static function isEmailDomainAllowed($email)
557 $domain = strtolower(substr($email, strpos($email, '@') + 1));
562 $str_allowed = Config::get('system', 'allowed_email', '');
563 if (!x($str_allowed)) {
567 $allowed = explode(',', $str_allowed);
569 return self::isDomainAllowed($domain, $allowed);
573 * Checks for the existence of a domain in a domain list
575 * @brief Checks for the existence of a domain in a domain list
576 * @param string $domain
577 * @param array $domain_list
580 public static function isDomainAllowed($domain, array $domain_list)
584 foreach ($domain_list as $item) {
585 $pat = strtolower(trim($item));
586 if (fnmatch($pat, $domain) || ($pat == $domain)) {
595 public static function lookupAvatarByEmail($email)
597 $avatar['size'] = 175;
598 $avatar['email'] = $email;
600 $avatar['success'] = false;
602 Addon::callHooks('avatar_lookup', $avatar);
604 if (! $avatar['success']) {
605 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
608 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
609 return $avatar['url'];
613 * @brief Remove Google Analytics and other tracking platforms params from URL
615 * @param string $url Any user-submitted URL that may contain tracking params
616 * @return string The same URL stripped of tracking parameters
618 public static function stripTrackingQueryParams($url)
620 $urldata = parse_url($url);
621 if (is_string($urldata["query"])) {
622 $query = $urldata["query"];
623 parse_str($query, $querydata);
625 if (is_array($querydata)) {
626 foreach ($querydata as $param => $value) {
630 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
631 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
632 "fb_action_ids", "fb_action_types", "fb_ref",
634 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
637 $pair = $param . "=" . urlencode($value);
638 $url = str_replace($pair, "", $url);
640 // Second try: if the url isn't encoded completely
641 $pair = $param . "=" . str_replace(" ", "+", $value);
642 $url = str_replace($pair, "", $url);
644 // Third try: Maybey the url isn't encoded at all
645 $pair = $param . "=" . $value;
646 $url = str_replace($pair, "", $url);
648 $url = str_replace(["?&", "&&"], ["?", ""], $url);
653 if (substr($url, -1, 1) == "?") {
654 $url = substr($url, 0, -1);
662 * @brief Returns the original URL of the provided URL
664 * This function strips tracking query params and follows redirections, either
665 * through HTTP code or meta refresh tags. Stops after 10 redirections.
667 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
669 * @see ParseUrl::getSiteinfo
671 * @param string $url A user-submitted URL
672 * @param int $depth The current redirection recursion level (internal)
673 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
674 * @return string A canonical URL
676 public static function finalUrl($url, $depth = 1, $fetchbody = false)
680 $url = self::stripTrackingQueryParams($url);
686 $url = trim($url, "'");
688 $stamp1 = microtime(true);
691 curl_setopt($ch, CURLOPT_URL, $url);
692 curl_setopt($ch, CURLOPT_HEADER, 1);
693 curl_setopt($ch, CURLOPT_NOBODY, 1);
694 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
695 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
696 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
699 $curl_info = @curl_getinfo($ch);
700 $http_code = $curl_info['http_code'];
703 $a->save_timestamp($stamp1, "network");
705 if ($http_code == 0) {
709 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
710 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
712 if ($curl_info['redirect_url'] != "") {
713 return(self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody));
715 return(self::finalUrl($curl_info['location'], ++$depth, $fetchbody));
719 // Check for redirects in the meta elements of the body if there are no redirects in the header.
721 return(self::finalUrl($url, ++$depth, true));
724 // if the file is too large then exit
725 if ($curl_info["download_content_length"] > 1000000) {
729 // if it isn't a HTML file then exit
730 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
734 $stamp1 = microtime(true);
737 curl_setopt($ch, CURLOPT_URL, $url);
738 curl_setopt($ch, CURLOPT_HEADER, 0);
739 curl_setopt($ch, CURLOPT_NOBODY, 0);
740 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
741 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
742 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
744 $body = curl_exec($ch);
747 $a->save_timestamp($stamp1, "network");
749 if (trim($body) == "") {
753 // Check for redirect in meta elements
754 $doc = new DOMDocument();
755 @$doc->loadHTML($body);
757 $xpath = new DomXPath($doc);
759 $list = $xpath->query("//meta[@content]");
760 foreach ($list as $node) {
762 if ($node->attributes->length) {
763 foreach ($node->attributes as $attribute) {
764 $attr[$attribute->name] = $attribute->value;
768 if (@$attr["http-equiv"] == 'refresh') {
769 $path = $attr["content"];
770 $pathinfo = explode(";", $path);
771 foreach ($pathinfo as $value) {
772 if (substr(strtolower($value), 0, 4) == "url=") {
773 return(self::finalUrl(substr($value, 4), ++$depth));
783 * @brief Find the matching part between two url
785 * @param string $url1
786 * @param string $url2
787 * @return string The matching part
789 public static function getUrlMatch($url1, $url2)
791 if (($url1 == "") || ($url2 == "")) {
795 $url1 = normalise_link($url1);
796 $url2 = normalise_link($url2);
798 $parts1 = parse_url($url1);
799 $parts2 = parse_url($url2);
801 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
805 if ($parts1["scheme"] != $parts2["scheme"]) {
809 if ($parts1["host"] != $parts2["host"]) {
813 if ($parts1["port"] != $parts2["port"]) {
817 $match = $parts1["scheme"]."://".$parts1["host"];
819 if ($parts1["port"]) {
820 $match .= ":".$parts1["port"];
823 $pathparts1 = explode("/", $parts1["path"]);
824 $pathparts2 = explode("/", $parts2["path"]);
829 $path1 = $pathparts1[$i];
830 $path2 = $pathparts2[$i];
832 if ($path1 == $path2) {
835 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
839 return normalise_link($match);
843 * @brief Glue url parts together
845 * @param array $parsed URL parts
847 * @return string The glued URL
849 public static function unparseURL($parsed)
851 $get = function ($key) use ($parsed) {
852 return isset($parsed[$key]) ? $parsed[$key] : null;
855 $pass = $get('pass');
856 $user = $get('user');
857 $userinfo = $pass !== null ? "$user:$pass" : $user;
858 $port = $get('port');
859 $scheme = $get('scheme');
860 $query = $get('query');
861 $fragment = $get('fragment');
862 $authority = ($userinfo !== null ? $userinfo."@" : '') .
864 ($port ? ":$port" : '');
866 return (strlen($scheme) ? $scheme.":" : '') .
867 (strlen($authority) ? "//".$authority : '') .
869 (strlen($query) ? "?".$query : '') .
870 (strlen($fragment) ? "#".$fragment : '');