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 $parts = parse_url($url);
83 $path_parts = explode('/', $parts['path']);
84 foreach ($path_parts as $part) {
85 if (strlen($part) <> mb_strlen($part)) {
86 $parts2[] = rawurlencode($part);
91 $parts['path'] = implode('/', $parts2);
92 $url = self::unparseURL($parts);
94 if (self::isUrlBlocked($url)) {
95 logger('domain of ' . $url . ' is blocked', LOGGER_DATA);
99 $ch = @curl_init($url);
101 if (($redirects > 8) || (!$ch)) {
105 @curl_setopt($ch, CURLOPT_HEADER, true);
107 if (x($opts, "cookiejar")) {
108 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
109 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
112 // These settings aren't needed. We're following the location already.
113 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
114 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
116 if (x($opts, 'accept_content')) {
120 ['Accept: ' . $opts['accept_content']]
124 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
125 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
127 $range = intval(Config::get('system', 'curl_range_bytes', 0));
130 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
133 // Without this setting it seems as if some webservers send compressed content
134 // This seems to confuse curl so that it shows this uncompressed.
135 /// @todo We could possibly set this value to "gzip" or something similar
136 curl_setopt($ch, CURLOPT_ENCODING, '');
138 if (x($opts, 'headers')) {
139 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
142 if (x($opts, 'nobody')) {
143 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
146 if (x($opts, 'timeout')) {
147 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
149 $curl_time = Config::get('system', 'curl_timeout', 60);
150 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
153 // by default we will allow self-signed certs
154 // but you can override this
156 $check_cert = Config::get('system', 'verifyssl');
157 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
160 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
163 $proxy = Config::get('system', 'proxy');
165 if (strlen($proxy)) {
166 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
167 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
168 $proxyuser = @Config::get('system', 'proxyuser');
170 if (strlen($proxyuser)) {
171 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
175 if (Config::get('system', 'ipv4_resolve', false)) {
176 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
180 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
183 $a->set_curl_code(0);
185 // don't let curl abort the entire application
186 // if it throws any errors.
188 $s = @curl_exec($ch);
189 $curl_info = @curl_getinfo($ch);
191 // Special treatment for HTTP Code 416
192 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
193 if (($curl_info['http_code'] == 416) && ($range > 0)) {
194 @curl_setopt($ch, CURLOPT_RANGE, '');
195 $s = @curl_exec($ch);
196 $curl_info = @curl_getinfo($ch);
199 if (curl_errno($ch) !== CURLE_OK) {
200 logger('error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
203 $ret['errno'] = curl_errno($ch);
206 $ret['info'] = $curl_info;
208 $http_code = $curl_info['http_code'];
210 logger($url . ': ' . $http_code . " " . $s, LOGGER_DATA);
213 // Pull out multiple headers, e.g. proxy and continuation headers
214 // allow for HTTP/2.x without fixing code
216 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
217 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
219 $base = substr($base, strlen($chunk));
222 $a->set_curl_code($http_code);
223 $a->set_curl_content_type($curl_info['content_type']);
224 $a->set_curl_headers($header);
226 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
227 $new_location_info = @parse_url($curl_info['redirect_url']);
228 $old_location_info = @parse_url($curl_info['url']);
230 $newurl = $curl_info['redirect_url'];
232 if (($new_location_info['path'] == '') && ($new_location_info['host'] != '')) {
233 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
238 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
239 $newurl = trim(array_pop($matches));
241 if (strpos($newurl, '/') === 0) {
242 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
244 $old_location_query = @parse_url($url, PHP_URL_QUERY);
246 if ($old_location_query != '') {
247 $newurl .= '?' . $old_location_query;
250 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
253 return self::curl($newurl, $binary, $redirects, $opts);
257 $a->set_curl_code($http_code);
258 $a->set_curl_content_type($curl_info['content_type']);
260 $rc = intval($http_code);
261 $ret['return_code'] = $rc;
262 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
263 $ret['redirect_url'] = $url;
265 if (!$ret['success']) {
266 $ret['error'] = curl_error($ch);
267 $ret['debug'] = $curl_info;
268 logger('error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
269 logger('debug: '.print_r($curl_info, true), LOGGER_DATA);
272 $ret['body'] = substr($s, strlen($header));
273 $ret['header'] = $header;
275 if (x($opts, 'debug')) {
276 $ret['debug'] = $curl_info;
281 $a->save_timestamp($stamp1, 'network');
287 * @brief Send POST request to $url
289 * @param string $url URL to post
290 * @param mixed $params array of POST variables
291 * @param string $headers HTTP headers
292 * @param integer $redirects Recursion counter for internal use - default = 0
293 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
295 * @return string The content
297 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
299 $stamp1 = microtime(true);
301 if (self::isUrlBlocked($url)) {
302 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
307 $ch = curl_init($url);
309 if (($redirects > 8) || (!$ch)) {
313 logger('post_url: start ' . $url, LOGGER_DATA);
315 curl_setopt($ch, CURLOPT_HEADER, true);
316 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
317 curl_setopt($ch, CURLOPT_POST, 1);
318 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
319 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
321 if (Config::get('system', 'ipv4_resolve', false)) {
322 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
325 if (intval($timeout)) {
326 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
328 $curl_time = Config::get('system', 'curl_timeout', 60);
329 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
332 if (defined('LIGHTTPD')) {
333 if (!is_array($headers)) {
334 $headers = ['Expect:'];
336 if (!in_array('Expect:', $headers)) {
337 array_push($headers, 'Expect:');
343 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
346 $check_cert = Config::get('system', 'verifyssl');
347 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
350 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
353 $proxy = Config::get('system', 'proxy');
355 if (strlen($proxy)) {
356 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
357 curl_setopt($ch, CURLOPT_PROXY, $proxy);
358 $proxyuser = Config::get('system', 'proxyuser');
359 if (strlen($proxyuser)) {
360 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
364 $a->set_curl_code(0);
366 // don't let curl abort the entire application
367 // if it throws any errors.
369 $s = @curl_exec($ch);
372 $curl_info = curl_getinfo($ch);
373 $http_code = $curl_info['http_code'];
375 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
379 // Pull out multiple headers, e.g. proxy and continuation headers
380 // allow for HTTP/2.x without fixing code
382 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
383 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
385 $base = substr($base, strlen($chunk));
388 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
390 $new_location_info = @parse_url($curl_info['redirect_url']);
391 $old_location_info = @parse_url($curl_info['url']);
393 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
394 $newurl = trim(array_pop($matches));
396 if (strpos($newurl, '/') === 0) {
397 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
400 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
402 logger('post_url: redirect ' . $url . ' to ' . $newurl);
403 return self::post($newurl, $params, $headers, $redirects, $timeout);
407 $a->set_curl_code($http_code);
409 $body = substr($s, strlen($header));
411 $a->set_curl_headers($header);
415 $a->save_timestamp($stamp1, 'network');
417 logger('post_url: end ' . $url, LOGGER_DATA);
423 * @brief Check URL to see if it's real
425 * Take a URL from the wild, prepend http:// if necessary
426 * and check DNS to see if it's real (or check if is a valid IP address)
428 * @param string $url The URL to be validated
429 * @return string|boolean The actual working URL, false else
431 public static function isUrlValid($url)
433 if (Config::get('system', 'disable_url_validation')) {
437 // no naked subdomains (allow localhost for tests)
438 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
442 if (substr($url, 0, 4) != 'http') {
443 $url = 'http://' . $url;
446 /// @TODO Really suppress function outcomes? Why not find them + debug them?
447 $h = @parse_url($url);
449 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
457 * @brief Checks that email is an actual resolvable internet address
459 * @param string $addr The email address
460 * @return boolean True if it's a valid email address, false if it's not
462 public static function isEmailDomainValid($addr)
464 if (Config::get('system', 'disable_email_validation')) {
468 if (! strpos($addr, '@')) {
472 $h = substr($addr, strpos($addr, '@') + 1);
474 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
481 * @brief Check if URL is allowed
483 * Check $url against our list of allowed sites,
484 * wildcards allowed. If allowed_sites is unset return true;
486 * @param string $url URL which get tested
487 * @return boolean True if url is allowed otherwise return false
489 public static function isUrlAllowed($url)
491 $h = @parse_url($url);
497 $str_allowed = Config::get('system', 'allowed_sites');
498 if (! $str_allowed) {
504 $host = strtolower($h['host']);
506 // always allow our own site
507 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
511 $fnmatch = function_exists('fnmatch');
512 $allowed = explode(',', $str_allowed);
514 if (count($allowed)) {
515 foreach ($allowed as $a) {
516 $pat = strtolower(trim($a));
517 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
527 * Checks if the provided url domain is on the domain blocklist.
528 * Returns true if it is or malformed URL, false if not.
530 * @param string $url The url to check the domain from
534 public static function isUrlBlocked($url)
536 $h = @parse_url($url);
542 $domain_blocklist = Config::get('system', 'blocklist', []);
543 if (! $domain_blocklist) {
547 $host = strtolower($h['host']);
549 foreach ($domain_blocklist as $domain_block) {
550 if (strtolower($domain_block['domain']) == $host) {
559 * @brief Check if email address is allowed to register here.
561 * Compare against our list (wildcards allowed).
563 * @param string $email email address
564 * @return boolean False if not allowed, true if allowed
565 * or if allowed list is not configured
567 public static function isEmailDomainAllowed($email)
569 $domain = strtolower(substr($email, strpos($email, '@') + 1));
574 $str_allowed = Config::get('system', 'allowed_email', '');
575 if (!x($str_allowed)) {
579 $allowed = explode(',', $str_allowed);
581 return self::isDomainAllowed($domain, $allowed);
585 * Checks for the existence of a domain in a domain list
587 * @brief Checks for the existence of a domain in a domain list
588 * @param string $domain
589 * @param array $domain_list
592 public static function isDomainAllowed($domain, array $domain_list)
596 foreach ($domain_list as $item) {
597 $pat = strtolower(trim($item));
598 if (fnmatch($pat, $domain) || ($pat == $domain)) {
607 public static function lookupAvatarByEmail($email)
609 $avatar['size'] = 175;
610 $avatar['email'] = $email;
612 $avatar['success'] = false;
614 Addon::callHooks('avatar_lookup', $avatar);
616 if (! $avatar['success']) {
617 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
620 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
621 return $avatar['url'];
625 * @brief Remove Google Analytics and other tracking platforms params from URL
627 * @param string $url Any user-submitted URL that may contain tracking params
628 * @return string The same URL stripped of tracking parameters
630 public static function stripTrackingQueryParams($url)
632 $urldata = parse_url($url);
633 if (is_string($urldata["query"])) {
634 $query = $urldata["query"];
635 parse_str($query, $querydata);
637 if (is_array($querydata)) {
638 foreach ($querydata as $param => $value) {
642 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
643 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
644 "fb_action_ids", "fb_action_types", "fb_ref",
646 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
649 $pair = $param . "=" . urlencode($value);
650 $url = str_replace($pair, "", $url);
652 // Second try: if the url isn't encoded completely
653 $pair = $param . "=" . str_replace(" ", "+", $value);
654 $url = str_replace($pair, "", $url);
656 // Third try: Maybey the url isn't encoded at all
657 $pair = $param . "=" . $value;
658 $url = str_replace($pair, "", $url);
660 $url = str_replace(["?&", "&&"], ["?", ""], $url);
665 if (substr($url, -1, 1) == "?") {
666 $url = substr($url, 0, -1);
674 * @brief Returns the original URL of the provided URL
676 * This function strips tracking query params and follows redirections, either
677 * through HTTP code or meta refresh tags. Stops after 10 redirections.
679 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
681 * @see ParseUrl::getSiteinfo
683 * @param string $url A user-submitted URL
684 * @param int $depth The current redirection recursion level (internal)
685 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
686 * @return string A canonical URL
688 public static function finalUrl($url, $depth = 1, $fetchbody = false)
692 $url = self::stripTrackingQueryParams($url);
698 $url = trim($url, "'");
700 $stamp1 = microtime(true);
703 curl_setopt($ch, CURLOPT_URL, $url);
704 curl_setopt($ch, CURLOPT_HEADER, 1);
705 curl_setopt($ch, CURLOPT_NOBODY, 1);
706 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
707 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
708 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
711 $curl_info = @curl_getinfo($ch);
712 $http_code = $curl_info['http_code'];
715 $a->save_timestamp($stamp1, "network");
717 if ($http_code == 0) {
721 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
722 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
724 if ($curl_info['redirect_url'] != "") {
725 return(self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody));
727 return(self::finalUrl($curl_info['location'], ++$depth, $fetchbody));
731 // Check for redirects in the meta elements of the body if there are no redirects in the header.
733 return(self::finalUrl($url, ++$depth, true));
736 // if the file is too large then exit
737 if ($curl_info["download_content_length"] > 1000000) {
741 // if it isn't a HTML file then exit
742 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
746 $stamp1 = microtime(true);
749 curl_setopt($ch, CURLOPT_URL, $url);
750 curl_setopt($ch, CURLOPT_HEADER, 0);
751 curl_setopt($ch, CURLOPT_NOBODY, 0);
752 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
753 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
754 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
756 $body = curl_exec($ch);
759 $a->save_timestamp($stamp1, "network");
761 if (trim($body) == "") {
765 // Check for redirect in meta elements
766 $doc = new DOMDocument();
767 @$doc->loadHTML($body);
769 $xpath = new DomXPath($doc);
771 $list = $xpath->query("//meta[@content]");
772 foreach ($list as $node) {
774 if ($node->attributes->length) {
775 foreach ($node->attributes as $attribute) {
776 $attr[$attribute->name] = $attribute->value;
780 if (@$attr["http-equiv"] == 'refresh') {
781 $path = $attr["content"];
782 $pathinfo = explode(";", $path);
783 foreach ($pathinfo as $value) {
784 if (substr(strtolower($value), 0, 4) == "url=") {
785 return(self::finalUrl(substr($value, 4), ++$depth));
795 * @brief Find the matching part between two url
797 * @param string $url1
798 * @param string $url2
799 * @return string The matching part
801 public static function getUrlMatch($url1, $url2)
803 if (($url1 == "") || ($url2 == "")) {
807 $url1 = normalise_link($url1);
808 $url2 = normalise_link($url2);
810 $parts1 = parse_url($url1);
811 $parts2 = parse_url($url2);
813 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
817 if ($parts1["scheme"] != $parts2["scheme"]) {
821 if ($parts1["host"] != $parts2["host"]) {
825 if ($parts1["port"] != $parts2["port"]) {
829 $match = $parts1["scheme"]."://".$parts1["host"];
831 if ($parts1["port"]) {
832 $match .= ":".$parts1["port"];
835 $pathparts1 = explode("/", $parts1["path"]);
836 $pathparts2 = explode("/", $parts2["path"]);
841 $path1 = $pathparts1[$i];
842 $path2 = $pathparts2[$i];
844 if ($path1 == $path2) {
847 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
851 return normalise_link($match);
855 * @brief Glue url parts together
857 * @param array $parsed URL parts
859 * @return string The glued URL
861 public static function unparseURL($parsed)
863 $get = function ($key) use ($parsed) {
864 return isset($parsed[$key]) ? $parsed[$key] : null;
867 $pass = $get('pass');
868 $user = $get('user');
869 $userinfo = $pass !== null ? "$user:$pass" : $user;
870 $port = $get('port');
871 $scheme = $get('scheme');
872 $query = $get('query');
873 $fragment = $get('fragment');
874 $authority = ($userinfo !== null ? $userinfo."@" : '') .
876 ($port ? ":$port" : '');
878 return (strlen($scheme) ? $scheme.":" : '') .
879 (strlen($authority) ? "//".$authority : '') .
881 (strlen($query) ? "?".$query : '') .
882 (strlen($fragment) ? "#".$fragment : '');