3 * @file src/Util/Network.php
5 namespace Friendica\Util;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Logger;
9 use Friendica\Core\System;
10 use Friendica\Core\Config;
11 use Friendica\Network\CurlResult;
12 use Friendica\Util\Strings;
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.
26 * @param string $url URL to fetch
27 * @param boolean $binary default false
28 * TRUE if asked to return binary results (file download)
29 * @param integer $redirects The recursion counter for internal use - default 0
30 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
31 * @param string $accept_content supply Accept: header with 'accept_content' as the value
32 * @param string $cookiejar Path to cookie jar file
34 * @return string The fetched content
36 public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
38 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
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 * @brief Curl wrapper with array of return values.
50 * @param string $url URL to fetch
51 * @param boolean $binary default false
52 * TRUE if asked to return binary results (file download)
53 * @param integer $redirects The recursion counter for internal use - default 0
54 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
55 * @param string $accept_content supply Accept: header with 'accept_content' as the value
56 * @param string $cookiejar Path to cookie jar file
58 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
60 public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
67 'accept_content'=>$accept_content,
68 'cookiejar'=>$cookiejar
74 * @brief fetches an URL.
76 * @param string $url URL to fetch
77 * @param boolean $binary default false
78 * TRUE if asked to return binary results (file download)
79 * @param int $redirects The recursion counter for internal use - default 0
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
91 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
93 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
95 $stamp1 = microtime(true);
99 $parts = parse_url($url);
100 $path_parts = explode('/', defaults($parts, 'path', ''));
101 foreach ($path_parts as $part) {
102 if (strlen($part) <> mb_strlen($part)) {
103 $parts2[] = rawurlencode($part);
108 $parts['path'] = implode('/', $parts2);
109 $url = self::unparseURL($parts);
111 if (self::isUrlBlocked($url)) {
112 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
113 return CurlResult::createErrorCurl($url);
116 $ch = @curl_init($url);
118 if (($redirects > 8) || (!$ch)) {
119 return CurlResult::createErrorCurl($url);
122 @curl_setopt($ch, CURLOPT_HEADER, true);
124 if (x($opts, "cookiejar")) {
125 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
126 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
129 // These settings aren't needed. We're following the location already.
130 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
131 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
133 if (x($opts, 'accept_content')) {
137 ['Accept: ' . $opts['accept_content']]
141 if (!empty($opts['header'])) {
142 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
145 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
146 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
148 $range = intval(Config::get('system', 'curl_range_bytes', 0));
151 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
154 // Without this setting it seems as if some webservers send compressed content
155 // This seems to confuse curl so that it shows this uncompressed.
156 /// @todo We could possibly set this value to "gzip" or something similar
157 curl_setopt($ch, CURLOPT_ENCODING, '');
159 if (x($opts, 'headers')) {
160 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
163 if (x($opts, 'nobody')) {
164 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
167 if (x($opts, 'timeout')) {
168 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
170 $curl_time = Config::get('system', 'curl_timeout', 60);
171 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
174 // by default we will allow self-signed certs
175 // but you can override this
177 $check_cert = Config::get('system', 'verifyssl');
178 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
181 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
184 $proxy = Config::get('system', 'proxy');
186 if (strlen($proxy)) {
187 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
188 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
189 $proxyuser = @Config::get('system', 'proxyuser');
191 if (strlen($proxyuser)) {
192 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
196 if (Config::get('system', 'ipv4_resolve', false)) {
197 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
201 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
204 // don't let curl abort the entire application
205 // if it throws any errors.
207 $s = @curl_exec($ch);
208 $curl_info = @curl_getinfo($ch);
210 // Special treatment for HTTP Code 416
211 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
212 if (($curl_info['http_code'] == 416) && ($range > 0)) {
213 @curl_setopt($ch, CURLOPT_RANGE, '');
214 $s = @curl_exec($ch);
215 $curl_info = @curl_getinfo($ch);
218 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
220 if ($curlResponse->isRedirectUrl()) {
222 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
224 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
229 $a->saveTimestamp($stamp1, 'network');
231 return $curlResponse;
235 * @brief Send POST request to $url
237 * @param string $url URL to post
238 * @param mixed $params array of POST variables
239 * @param string $headers HTTP headers
240 * @param integer $redirects Recursion counter for internal use - default = 0
241 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
243 * @return CurlResult The content
245 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
247 $stamp1 = microtime(true);
249 if (self::isUrlBlocked($url)) {
250 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
251 return CurlResult::createErrorCurl($url);
255 $ch = curl_init($url);
257 if (($redirects > 8) || (!$ch)) {
258 return CurlResult::createErrorCurl($url);
261 Logger::log('post_url: start ' . $url, Logger::DATA);
263 curl_setopt($ch, CURLOPT_HEADER, true);
264 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
265 curl_setopt($ch, CURLOPT_POST, 1);
266 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
267 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
269 if (Config::get('system', 'ipv4_resolve', false)) {
270 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
273 if (intval($timeout)) {
274 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
276 $curl_time = Config::get('system', 'curl_timeout', 60);
277 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
280 if (defined('LIGHTTPD')) {
281 if (!is_array($headers)) {
282 $headers = ['Expect:'];
284 if (!in_array('Expect:', $headers)) {
285 array_push($headers, 'Expect:');
291 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
294 $check_cert = Config::get('system', 'verifyssl');
295 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
298 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
301 $proxy = Config::get('system', 'proxy');
303 if (strlen($proxy)) {
304 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
305 curl_setopt($ch, CURLOPT_PROXY, $proxy);
306 $proxyuser = Config::get('system', 'proxyuser');
307 if (strlen($proxyuser)) {
308 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
312 // don't let curl abort the entire application
313 // if it throws any errors.
315 $s = @curl_exec($ch);
318 $curl_info = curl_getinfo($ch);
320 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
322 if ($curlResponse->isRedirectUrl()) {
324 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
326 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
331 $a->saveTimestamp($stamp1, 'network');
333 Logger::log('post_url: end ' . $url, Logger::DATA);
335 return $curlResponse;
339 * @brief Check URL to see if it's real
341 * Take a URL from the wild, prepend http:// if necessary
342 * and check DNS to see if it's real (or check if is a valid IP address)
344 * @param string $url The URL to be validated
345 * @return string|boolean The actual working URL, false else
347 public static function isUrlValid($url)
349 if (Config::get('system', 'disable_url_validation')) {
353 // no naked subdomains (allow localhost for tests)
354 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
358 if (substr($url, 0, 4) != 'http') {
359 $url = 'http://' . $url;
362 /// @TODO Really suppress function outcomes? Why not find them + debug them?
363 $h = @parse_url($url);
365 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
373 * @brief Checks that email is an actual resolvable internet address
375 * @param string $addr The email address
376 * @return boolean True if it's a valid email address, false if it's not
378 public static function isEmailDomainValid($addr)
380 if (Config::get('system', 'disable_email_validation')) {
384 if (! strpos($addr, '@')) {
388 $h = substr($addr, strpos($addr, '@') + 1);
390 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
391 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
394 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
401 * @brief Check if URL is allowed
403 * Check $url against our list of allowed sites,
404 * wildcards allowed. If allowed_sites is unset return true;
406 * @param string $url URL which get tested
407 * @return boolean True if url is allowed otherwise return false
409 public static function isUrlAllowed($url)
411 $h = @parse_url($url);
417 $str_allowed = Config::get('system', 'allowed_sites');
418 if (! $str_allowed) {
424 $host = strtolower($h['host']);
426 // always allow our own site
427 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
431 $fnmatch = function_exists('fnmatch');
432 $allowed = explode(',', $str_allowed);
434 if (count($allowed)) {
435 foreach ($allowed as $a) {
436 $pat = strtolower(trim($a));
437 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
447 * Checks if the provided url domain is on the domain blocklist.
448 * Returns true if it is or malformed URL, false if not.
450 * @param string $url The url to check the domain from
454 public static function isUrlBlocked($url)
456 $host = @parse_url($url, PHP_URL_HOST);
461 $domain_blocklist = Config::get('system', 'blocklist', []);
462 if (!$domain_blocklist) {
466 foreach ($domain_blocklist as $domain_block) {
467 if (strcasecmp($domain_block['domain'], $host) === 0) {
476 * @brief Check if email address is allowed to register here.
478 * Compare against our list (wildcards allowed).
480 * @param string $email email address
481 * @return boolean False if not allowed, true if allowed
482 * or if allowed list is not configured
484 public static function isEmailDomainAllowed($email)
486 $domain = strtolower(substr($email, strpos($email, '@') + 1));
491 $str_allowed = Config::get('system', 'allowed_email', '');
492 if (!x($str_allowed)) {
496 $allowed = explode(',', $str_allowed);
498 return self::isDomainAllowed($domain, $allowed);
502 * Checks for the existence of a domain in a domain list
504 * @brief Checks for the existence of a domain in a domain list
505 * @param string $domain
506 * @param array $domain_list
509 public static function isDomainAllowed($domain, array $domain_list)
513 foreach ($domain_list as $item) {
514 $pat = strtolower(trim($item));
515 if (fnmatch($pat, $domain) || ($pat == $domain)) {
524 public static function lookupAvatarByEmail($email)
526 $avatar['size'] = 300;
527 $avatar['email'] = $email;
529 $avatar['success'] = false;
531 Addon::callHooks('avatar_lookup', $avatar);
533 if (! $avatar['success']) {
534 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
537 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
538 return $avatar['url'];
542 * @brief Remove Google Analytics and other tracking platforms params from URL
544 * @param string $url Any user-submitted URL that may contain tracking params
545 * @return string The same URL stripped of tracking parameters
547 public static function stripTrackingQueryParams($url)
549 $urldata = parse_url($url);
550 if (!empty($urldata["query"])) {
551 $query = $urldata["query"];
552 parse_str($query, $querydata);
554 if (is_array($querydata)) {
555 foreach ($querydata as $param => $value) {
559 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
560 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
561 "fb_action_ids", "fb_action_types", "fb_ref",
563 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
566 $pair = $param . "=" . urlencode($value);
567 $url = str_replace($pair, "", $url);
569 // Second try: if the url isn't encoded completely
570 $pair = $param . "=" . str_replace(" ", "+", $value);
571 $url = str_replace($pair, "", $url);
573 // Third try: Maybey the url isn't encoded at all
574 $pair = $param . "=" . $value;
575 $url = str_replace($pair, "", $url);
577 $url = str_replace(["?&", "&&"], ["?", ""], $url);
582 if (substr($url, -1, 1) == "?") {
583 $url = substr($url, 0, -1);
591 * @brief Returns the original URL of the provided URL
593 * This function strips tracking query params and follows redirections, either
594 * through HTTP code or meta refresh tags. Stops after 10 redirections.
596 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
598 * @see ParseUrl::getSiteinfo
600 * @param string $url A user-submitted URL
601 * @param int $depth The current redirection recursion level (internal)
602 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
603 * @return string A canonical URL
605 public static function finalUrl($url, $depth = 1, $fetchbody = false)
609 $url = self::stripTrackingQueryParams($url);
615 $url = trim($url, "'");
617 $stamp1 = microtime(true);
620 curl_setopt($ch, CURLOPT_URL, $url);
621 curl_setopt($ch, CURLOPT_HEADER, 1);
622 curl_setopt($ch, CURLOPT_NOBODY, 1);
623 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
624 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
625 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
628 $curl_info = @curl_getinfo($ch);
629 $http_code = $curl_info['http_code'];
632 $a->saveTimestamp($stamp1, "network");
634 if ($http_code == 0) {
638 if (in_array($http_code, ['301', '302'])) {
639 if (!empty($curl_info['redirect_url'])) {
640 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
641 } elseif (!empty($curl_info['location'])) {
642 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
646 // Check for redirects in the meta elements of the body if there are no redirects in the header.
648 return(self::finalUrl($url, ++$depth, true));
651 // if the file is too large then exit
652 if ($curl_info["download_content_length"] > 1000000) {
656 // if it isn't a HTML file then exit
657 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
661 $stamp1 = microtime(true);
664 curl_setopt($ch, CURLOPT_URL, $url);
665 curl_setopt($ch, CURLOPT_HEADER, 0);
666 curl_setopt($ch, CURLOPT_NOBODY, 0);
667 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
668 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
669 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
671 $body = curl_exec($ch);
674 $a->saveTimestamp($stamp1, "network");
676 if (trim($body) == "") {
680 // Check for redirect in meta elements
681 $doc = new DOMDocument();
682 @$doc->loadHTML($body);
684 $xpath = new DomXPath($doc);
686 $list = $xpath->query("//meta[@content]");
687 foreach ($list as $node) {
689 if ($node->attributes->length) {
690 foreach ($node->attributes as $attribute) {
691 $attr[$attribute->name] = $attribute->value;
695 if (@$attr["http-equiv"] == 'refresh') {
696 $path = $attr["content"];
697 $pathinfo = explode(";", $path);
698 foreach ($pathinfo as $value) {
699 if (substr(strtolower($value), 0, 4) == "url=") {
700 return self::finalUrl(substr($value, 4), ++$depth);
710 * @brief Find the matching part between two url
712 * @param string $url1
713 * @param string $url2
714 * @return string The matching part
716 public static function getUrlMatch($url1, $url2)
718 if (($url1 == "") || ($url2 == "")) {
722 $url1 = Strings::normaliseLink($url1);
723 $url2 = Strings::normaliseLink($url2);
725 $parts1 = parse_url($url1);
726 $parts2 = parse_url($url2);
728 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
732 if (empty($parts1["scheme"])) {
733 $parts1["scheme"] = '';
735 if (empty($parts2["scheme"])) {
736 $parts2["scheme"] = '';
739 if ($parts1["scheme"] != $parts2["scheme"]) {
743 if (empty($parts1["host"])) {
744 $parts1["host"] = '';
746 if (empty($parts2["host"])) {
747 $parts2["host"] = '';
750 if ($parts1["host"] != $parts2["host"]) {
754 if (empty($parts1["port"])) {
755 $parts1["port"] = '';
757 if (empty($parts2["port"])) {
758 $parts2["port"] = '';
761 if ($parts1["port"] != $parts2["port"]) {
765 $match = $parts1["scheme"]."://".$parts1["host"];
767 if ($parts1["port"]) {
768 $match .= ":".$parts1["port"];
771 if (empty($parts1["path"])) {
772 $parts1["path"] = '';
774 if (empty($parts2["path"])) {
775 $parts2["path"] = '';
778 $pathparts1 = explode("/", $parts1["path"]);
779 $pathparts2 = explode("/", $parts2["path"]);
784 $path1 = defaults($pathparts1, $i, '');
785 $path2 = defaults($pathparts2, $i, '');
787 if ($path1 == $path2) {
790 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
794 return Strings::normaliseLink($match);
798 * @brief Glue url parts together
800 * @param array $parsed URL parts
802 * @return string The glued URL
804 public static function unparseURL($parsed)
806 $get = function ($key) use ($parsed) {
807 return isset($parsed[$key]) ? $parsed[$key] : null;
810 $pass = $get('pass');
811 $user = $get('user');
812 $userinfo = $pass !== null ? "$user:$pass" : $user;
813 $port = $get('port');
814 $scheme = $get('scheme');
815 $query = $get('query');
816 $fragment = $get('fragment');
817 $authority = ($userinfo !== null ? $userinfo."@" : '') .
819 ($port ? ":$port" : '');
821 return (strlen($scheme) ? $scheme.":" : '') .
822 (strlen($authority) ? "//".$authority : '') .
824 (strlen($query) ? "?".$query : '') .
825 (strlen($fragment) ? "#".$fragment : '');