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;
18 require_once 'library/slinky.php';
25 * If binary flag is true, return binary results.
26 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
27 * to preserve cookies from one request to the next.
29 * @param string $url URL to fetch
30 * @param boolean $binary default false
31 * TRUE if asked to return binary results (file download)
32 * @param integer $redirects The recursion counter for internal use - default 0
33 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
34 * @param string $accept_content supply Accept: header with 'accept_content' as the value
35 * @param string $cookiejar Path to cookie jar file
37 * @return string The fetched content
39 public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
46 'accept_content'=>$accept_content,
47 'cookiejar'=>$cookiejar
55 * @brief fetches an URL.
57 * @param string $url URL to fetch
58 * @param boolean $binary default false
59 * TRUE if asked to return binary results (file download)
60 * @param int $redirects The recursion counter for internal use - default 0
61 * @param array $opts (optional parameters) assoziative array with:
62 * 'accept_content' => supply Accept: header with 'accept_content' as the value
63 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
64 * 'http_auth' => username:password
65 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
66 * 'nobody' => only return the header
67 * 'cookiejar' => path to cookie jar file
69 * @return array an assoziative array with:
70 * int 'return_code' => HTTP return code or 0 if timeout or failure
71 * boolean 'success' => boolean true (if HTTP 2xx result) or false
72 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
73 * string 'header' => HTTP headers
74 * string 'body' => fetched content
76 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
78 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
80 $stamp1 = microtime(true);
84 if (self::isUrlBlocked($url)) {
85 logger('domain of ' . $url . ' is blocked', LOGGER_DATA);
89 $ch = @curl_init($url);
91 if (($redirects > 8) || (!$ch)) {
95 @curl_setopt($ch, CURLOPT_HEADER, true);
97 if (x($opts, "cookiejar")) {
98 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
99 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
102 // These settings aren't needed. We're following the location already.
103 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
104 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
106 if (x($opts, 'accept_content')) {
110 ['Accept: ' . $opts['accept_content']]
114 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
115 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
117 $range = intval(Config::get('system', 'curl_range_bytes', 0));
120 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
123 // Without this setting it seems as if some webservers send compressed content
124 // This seems to confuse curl so that it shows this uncompressed.
125 /// @todo We could possibly set this value to "gzip" or something similar
126 curl_setopt($ch, CURLOPT_ENCODING, '');
128 if (x($opts, 'headers')) {
129 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
132 if (x($opts, 'nobody')) {
133 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
136 if (x($opts, 'timeout')) {
137 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
139 $curl_time = Config::get('system', 'curl_timeout', 60);
140 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
143 // by default we will allow self-signed certs
144 // but you can override this
146 $check_cert = Config::get('system', 'verifyssl');
147 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
150 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
153 $proxy = Config::get('system', 'proxy');
155 if (strlen($proxy)) {
156 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
157 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
158 $proxyuser = @Config::get('system', 'proxyuser');
160 if (strlen($proxyuser)) {
161 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
165 if (Config::get('system', 'ipv4_resolve', false)) {
166 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
170 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
173 $a->set_curl_code(0);
175 // don't let curl abort the entire application
176 // if it throws any errors.
178 $s = @curl_exec($ch);
179 $curl_info = @curl_getinfo($ch);
181 // Special treatment for HTTP Code 416
182 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
183 if (($curl_info['http_code'] == 416) && ($range > 0)) {
184 @curl_setopt($ch, CURLOPT_RANGE, '');
185 $s = @curl_exec($ch);
186 $curl_info = @curl_getinfo($ch);
189 if (curl_errno($ch) !== CURLE_OK) {
190 logger('error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
193 $ret['errno'] = curl_errno($ch);
196 $ret['info'] = $curl_info;
198 $http_code = $curl_info['http_code'];
200 logger($url . ': ' . $http_code . " " . $s, LOGGER_DATA);
203 // Pull out multiple headers, e.g. proxy and continuation headers
204 // allow for HTTP/2.x without fixing code
206 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
207 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
209 $base = substr($base, strlen($chunk));
212 $a->set_curl_code($http_code);
213 $a->set_curl_content_type($curl_info['content_type']);
214 $a->set_curl_headers($header);
216 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
217 $new_location_info = @parse_url($curl_info['redirect_url']);
218 $old_location_info = @parse_url($curl_info['url']);
220 $newurl = $curl_info['redirect_url'];
222 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
223 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
228 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
229 $newurl = trim(array_pop($matches));
231 if (strpos($newurl, '/') === 0) {
232 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
235 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
238 return self::curl($newurl, $binary, $redirects, $opts);
242 $a->set_curl_code($http_code);
243 $a->set_curl_content_type($curl_info['content_type']);
245 $rc = intval($http_code);
246 $ret['return_code'] = $rc;
247 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
248 $ret['redirect_url'] = $url;
250 if (!$ret['success']) {
251 $ret['error'] = curl_error($ch);
252 $ret['debug'] = $curl_info;
253 logger('error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
254 logger('debug: '.print_r($curl_info, true), LOGGER_DATA);
257 $ret['body'] = substr($s, strlen($header));
258 $ret['header'] = $header;
260 if (x($opts, 'debug')) {
261 $ret['debug'] = $curl_info;
266 $a->save_timestamp($stamp1, 'network');
272 * @brief Send POST request to $url
274 * @param string $url URL to post
275 * @param mixed $params array of POST variables
276 * @param string $headers HTTP headers
277 * @param integer $redirects Recursion counter for internal use - default = 0
278 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
280 * @return string The content
282 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
284 $stamp1 = microtime(true);
286 if (self::isUrlBlocked($url)) {
287 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
292 $ch = curl_init($url);
294 if (($redirects > 8) || (!$ch)) {
298 logger('post_url: start ' . $url, LOGGER_DATA);
300 curl_setopt($ch, CURLOPT_HEADER, true);
301 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
302 curl_setopt($ch, CURLOPT_POST, 1);
303 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
304 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
306 if (Config::get('system', 'ipv4_resolve', false)) {
307 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
310 if (intval($timeout)) {
311 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
313 $curl_time = Config::get('system', 'curl_timeout', 60);
314 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
317 if (defined('LIGHTTPD')) {
318 if (!is_array($headers)) {
319 $headers = ['Expect:'];
321 if (!in_array('Expect:', $headers)) {
322 array_push($headers, 'Expect:');
328 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
331 $check_cert = Config::get('system', 'verifyssl');
332 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
335 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
338 $proxy = Config::get('system', 'proxy');
340 if (strlen($proxy)) {
341 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
342 curl_setopt($ch, CURLOPT_PROXY, $proxy);
343 $proxyuser = Config::get('system', 'proxyuser');
344 if (strlen($proxyuser)) {
345 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
349 $a->set_curl_code(0);
351 // don't let curl abort the entire application
352 // if it throws any errors.
354 $s = @curl_exec($ch);
357 $curl_info = curl_getinfo($ch);
358 $http_code = $curl_info['http_code'];
360 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
364 // Pull out multiple headers, e.g. proxy and continuation headers
365 // allow for HTTP/2.x without fixing code
367 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
368 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
370 $base = substr($base, strlen($chunk));
373 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
375 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
376 $newurl = trim(array_pop($matches));
378 if (strpos($newurl, '/') === 0) {
379 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
382 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
384 logger('post_url: redirect ' . $url . ' to ' . $newurl);
385 return self::post($newurl, $params, $headers, $redirects, $timeout);
389 $a->set_curl_code($http_code);
391 $body = substr($s, strlen($header));
393 $a->set_curl_headers($header);
397 $a->save_timestamp($stamp1, 'network');
399 logger('post_url: end ' . $url, LOGGER_DATA);
405 * @brief Check URL to see if it's real
407 * Take a URL from the wild, prepend http:// if necessary
408 * and check DNS to see if it's real (or check if is a valid IP address)
410 * @param string $url The URL to be validated
411 * @return string|boolean The actual working URL, false else
413 public static function isUrlValid($url)
415 if (Config::get('system', 'disable_url_validation')) {
419 // no naked subdomains (allow localhost for tests)
420 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
424 if (substr($url, 0, 4) != 'http') {
425 $url = 'http://' . $url;
428 /// @TODO Really suppress function outcomes? Why not find them + debug them?
429 $h = @parse_url($url);
431 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
439 * @brief Checks that email is an actual resolvable internet address
441 * @param string $addr The email address
442 * @return boolean True if it's a valid email address, false if it's not
444 public static function isEmailDomainValid($addr)
446 if (Config::get('system', 'disable_email_validation')) {
450 if (! strpos($addr, '@')) {
454 $h = substr($addr, strpos($addr, '@') + 1);
456 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
463 * @brief Check if URL is allowed
465 * Check $url against our list of allowed sites,
466 * wildcards allowed. If allowed_sites is unset return true;
468 * @param string $url URL which get tested
469 * @return boolean True if url is allowed otherwise return false
471 public static function isUrlAllowed($url)
473 $h = @parse_url($url);
479 $str_allowed = Config::get('system', 'allowed_sites');
480 if (! $str_allowed) {
486 $host = strtolower($h['host']);
488 // always allow our own site
489 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
493 $fnmatch = function_exists('fnmatch');
494 $allowed = explode(',', $str_allowed);
496 if (count($allowed)) {
497 foreach ($allowed as $a) {
498 $pat = strtolower(trim($a));
499 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
509 * Checks if the provided url domain is on the domain blocklist.
510 * Returns true if it is or malformed URL, false if not.
512 * @param string $url The url to check the domain from
516 public static function isUrlBlocked($url)
518 $h = @parse_url($url);
524 $domain_blocklist = Config::get('system', 'blocklist', []);
525 if (! $domain_blocklist) {
529 $host = strtolower($h['host']);
531 foreach ($domain_blocklist as $domain_block) {
532 if (strtolower($domain_block['domain']) == $host) {
541 * @brief Check if email address is allowed to register here.
543 * Compare against our list (wildcards allowed).
545 * @param string $email email address
546 * @return boolean False if not allowed, true if allowed
547 * or if allowed list is not configured
549 public static function isEmailDomainAllowed($email)
551 $domain = strtolower(substr($email, strpos($email, '@') + 1));
556 $str_allowed = Config::get('system', 'allowed_email', '');
557 if (!x($str_allowed)) {
561 $allowed = explode(',', $str_allowed);
563 return self::isDomainAllowed($domain, $allowed);
567 * Checks for the existence of a domain in a domain list
569 * @brief Checks for the existence of a domain in a domain list
570 * @param string $domain
571 * @param array $domain_list
574 public static function isDomainAllowed($domain, array $domain_list)
578 foreach ($domain_list as $item) {
579 $pat = strtolower(trim($item));
580 if (fnmatch($pat, $domain) || ($pat == $domain)) {
589 public static function lookupAvatarByEmail($email)
591 $avatar['size'] = 175;
592 $avatar['email'] = $email;
594 $avatar['success'] = false;
596 Addon::callHooks('avatar_lookup', $avatar);
598 if (! $avatar['success']) {
599 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
602 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
603 return $avatar['url'];
607 * @brief Remove Google Analytics and other tracking platforms params from URL
609 * @param string $url Any user-submitted URL that may contain tracking params
610 * @return string The same URL stripped of tracking parameters
612 public static function stripTrackingQueryParams($url)
614 $urldata = parse_url($url);
615 if (is_string($urldata["query"])) {
616 $query = $urldata["query"];
617 parse_str($query, $querydata);
619 if (is_array($querydata)) {
620 foreach ($querydata as $param => $value) {
624 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
625 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
626 "fb_action_ids", "fb_action_types", "fb_ref",
628 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
631 $pair = $param . "=" . urlencode($value);
632 $url = str_replace($pair, "", $url);
634 // Second try: if the url isn't encoded completely
635 $pair = $param . "=" . str_replace(" ", "+", $value);
636 $url = str_replace($pair, "", $url);
638 // Third try: Maybey the url isn't encoded at all
639 $pair = $param . "=" . $value;
640 $url = str_replace($pair, "", $url);
642 $url = str_replace(["?&", "&&"], ["?", ""], $url);
647 if (substr($url, -1, 1) == "?") {
648 $url = substr($url, 0, -1);
656 * @brief Returns the original URL of the provided URL
658 * This function strips tracking query params and follows redirections, either
659 * through HTTP code or meta refresh tags. Stops after 10 redirections.
661 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
663 * @see ParseUrl::getSiteinfo
665 * @param string $url A user-submitted URL
666 * @param int $depth The current redirection recursion level (internal)
667 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
668 * @return string A canonical URL
670 public static function finalUrl($url, $depth = 1, $fetchbody = false)
674 $url = self::stripTrackingQueryParams($url);
680 $url = trim($url, "'");
682 $stamp1 = microtime(true);
685 curl_setopt($ch, CURLOPT_URL, $url);
686 curl_setopt($ch, CURLOPT_HEADER, 1);
687 curl_setopt($ch, CURLOPT_NOBODY, 1);
688 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
689 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
690 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
693 $curl_info = @curl_getinfo($ch);
694 $http_code = $curl_info['http_code'];
697 $a->save_timestamp($stamp1, "network");
699 if ($http_code == 0) {
703 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
704 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
706 if ($curl_info['redirect_url'] != "") {
707 return(self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody));
709 return(self::finalUrl($curl_info['location'], ++$depth, $fetchbody));
713 // Check for redirects in the meta elements of the body if there are no redirects in the header.
715 return(self::finalUrl($url, ++$depth, true));
718 // if the file is too large then exit
719 if ($curl_info["download_content_length"] > 1000000) {
723 // if it isn't a HTML file then exit
724 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
728 $stamp1 = microtime(true);
731 curl_setopt($ch, CURLOPT_URL, $url);
732 curl_setopt($ch, CURLOPT_HEADER, 0);
733 curl_setopt($ch, CURLOPT_NOBODY, 0);
734 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
735 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
736 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
738 $body = curl_exec($ch);
741 $a->save_timestamp($stamp1, "network");
743 if (trim($body) == "") {
747 // Check for redirect in meta elements
748 $doc = new DOMDocument();
749 @$doc->loadHTML($body);
751 $xpath = new DomXPath($doc);
753 $list = $xpath->query("//meta[@content]");
754 foreach ($list as $node) {
756 if ($node->attributes->length) {
757 foreach ($node->attributes as $attribute) {
758 $attr[$attribute->name] = $attribute->value;
762 if (@$attr["http-equiv"] == 'refresh') {
763 $path = $attr["content"];
764 $pathinfo = explode(";", $path);
765 foreach ($pathinfo as $value) {
766 if (substr(strtolower($value), 0, 4) == "url=") {
767 return(self::finalUrl(substr($value, 4), ++$depth));
776 public static function shortenUrl($url)
778 $slinky = new Slinky($url);
779 $yourls_url = Config::get('yourls', 'url1');
781 $yourls_username = Config::get('yourls', 'username1');
782 $yourls_password = Config::get('yourls', 'password1');
783 $yourls_ssl = Config::get('yourls', 'ssl1');
784 $yourls = new Slinky_YourLS();
785 $yourls->set('username', $yourls_username);
786 $yourls->set('password', $yourls_password);
787 $yourls->set('ssl', $yourls_ssl);
788 $yourls->set('yourls-url', $yourls_url);
789 $slinky->set_cascade([$yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()]);
791 // setup a cascade of shortening services
792 // try to get a short link from these services
793 // in the order ur1.ca, tinyurl
794 $slinky->set_cascade([new Slinky_Ur1ca(), new Slinky_TinyURL()]);
796 return $slinky->short();
800 * @brief Find the matching part between two url
802 * @param string $url1
803 * @param string $url2
804 * @return string The matching part
806 public static function getUrlMatch($url1, $url2)
808 if (($url1 == "") || ($url2 == "")) {
812 $url1 = normalise_link($url1);
813 $url2 = normalise_link($url2);
815 $parts1 = parse_url($url1);
816 $parts2 = parse_url($url2);
818 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
822 if ($parts1["scheme"] != $parts2["scheme"]) {
826 if ($parts1["host"] != $parts2["host"]) {
830 if ($parts1["port"] != $parts2["port"]) {
834 $match = $parts1["scheme"]."://".$parts1["host"];
836 if ($parts1["port"]) {
837 $match .= ":".$parts1["port"];
840 $pathparts1 = explode("/", $parts1["path"]);
841 $pathparts2 = explode("/", $parts2["path"]);
846 $path1 = $pathparts1[$i];
847 $path2 = $pathparts2[$i];
849 if ($path1 == $path2) {
852 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
856 return normalise_link($match);
860 * @brief Glue url parts together
862 * @param array $parsed URL parts
864 * @return string The glued URL
866 public static function unparseURL($parsed)
868 $get = function ($key) use ($parsed) {
869 return isset($parsed[$key]) ? $parsed[$key] : null;
872 $pass = $get('pass');
873 $user = $get('user');
874 $userinfo = $pass !== null ? "$user:$pass" : $user;
875 $port = $get('port');
876 $scheme = $get('scheme');
877 $query = $get('query');
878 $fragment = $get('fragment');
879 $authority = ($userinfo !== null ? $userinfo."@" : '') .
881 ($port ? ":$port" : '');
883 return (strlen($scheme) ? $scheme.":" : '') .
884 (strlen($authority) ? "//".$authority : '') .
886 (strlen($query) ? "?".$query : '') .
887 (strlen($fragment) ? "#".$fragment : '');