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;
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.
25 * @param string $url URL to fetch
26 * @param boolean $binary default false
27 * TRUE if asked to return binary results (file download)
28 * @param integer $redirects The recursion counter for internal use - default 0
29 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
30 * @param string $accept_content supply Accept: header with 'accept_content' as the value
31 * @param string $cookiejar Path to cookie jar file
33 * @return string The fetched content
35 public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
37 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
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 * @brief Curl wrapper with array of return values.
49 * @param string $url URL to fetch
50 * @param boolean $binary default false
51 * TRUE if asked to return binary results (file download)
52 * @param integer $redirects The recursion counter for internal use - default 0
53 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
54 * @param string $accept_content supply Accept: header with 'accept_content' as the value
55 * @param string $cookiejar Path to cookie jar file
57 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
59 public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
66 'accept_content'=>$accept_content,
67 'cookiejar'=>$cookiejar
73 * @brief fetches an URL.
75 * @param string $url URL to fetch
76 * @param boolean $binary default false
77 * TRUE if asked to return binary results (file download)
78 * @param int $redirects The recursion counter for internal use - default 0
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
90 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
92 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
94 $stamp1 = microtime(true);
98 $parts = parse_url($url);
99 $path_parts = explode('/', defaults($parts, 'path', ''));
100 foreach ($path_parts as $part) {
101 if (strlen($part) <> mb_strlen($part)) {
102 $parts2[] = rawurlencode($part);
107 $parts['path'] = implode('/', $parts2);
108 $url = self::unparseURL($parts);
110 if (self::isUrlBlocked($url)) {
111 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
112 return CurlResult::createErrorCurl($url);
115 $ch = @curl_init($url);
117 if (($redirects > 8) || (!$ch)) {
118 return CurlResult::createErrorCurl($url);
121 @curl_setopt($ch, CURLOPT_HEADER, true);
123 if (x($opts, "cookiejar")) {
124 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
125 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
128 // These settings aren't needed. We're following the location already.
129 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
130 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
132 if (x($opts, 'accept_content')) {
136 ['Accept: ' . $opts['accept_content']]
140 if (!empty($opts['header'])) {
141 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
144 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
145 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
147 $range = intval(Config::get('system', 'curl_range_bytes', 0));
150 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
153 // Without this setting it seems as if some webservers send compressed content
154 // This seems to confuse curl so that it shows this uncompressed.
155 /// @todo We could possibly set this value to "gzip" or something similar
156 curl_setopt($ch, CURLOPT_ENCODING, '');
158 if (x($opts, 'headers')) {
159 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
162 if (x($opts, 'nobody')) {
163 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
166 if (x($opts, 'timeout')) {
167 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
169 $curl_time = Config::get('system', 'curl_timeout', 60);
170 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
173 // by default we will allow self-signed certs
174 // but you can override this
176 $check_cert = Config::get('system', 'verifyssl');
177 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
180 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
183 $proxy = Config::get('system', 'proxy');
185 if (strlen($proxy)) {
186 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
187 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
188 $proxyuser = @Config::get('system', 'proxyuser');
190 if (strlen($proxyuser)) {
191 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
195 if (Config::get('system', 'ipv4_resolve', false)) {
196 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
200 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
203 // don't let curl abort the entire application
204 // if it throws any errors.
206 $s = @curl_exec($ch);
207 $curl_info = @curl_getinfo($ch);
209 // Special treatment for HTTP Code 416
210 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
211 if (($curl_info['http_code'] == 416) && ($range > 0)) {
212 @curl_setopt($ch, CURLOPT_RANGE, '');
213 $s = @curl_exec($ch);
214 $curl_info = @curl_getinfo($ch);
217 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
219 if ($curlResponse->isRedirectUrl()) {
221 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
223 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
228 $a->saveTimestamp($stamp1, 'network');
230 return $curlResponse;
234 * @brief Send POST request to $url
236 * @param string $url URL to post
237 * @param mixed $params array of POST variables
238 * @param string $headers HTTP headers
239 * @param integer $redirects Recursion counter for internal use - default = 0
240 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
242 * @return CurlResult The content
244 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
246 $stamp1 = microtime(true);
248 if (self::isUrlBlocked($url)) {
249 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
250 return CurlResult::createErrorCurl($url);
254 $ch = curl_init($url);
256 if (($redirects > 8) || (!$ch)) {
257 return CurlResult::createErrorCurl($url);
260 Logger::log('post_url: start ' . $url, Logger::DATA);
262 curl_setopt($ch, CURLOPT_HEADER, true);
263 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
264 curl_setopt($ch, CURLOPT_POST, 1);
265 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
266 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
268 if (Config::get('system', 'ipv4_resolve', false)) {
269 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
272 if (intval($timeout)) {
273 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
275 $curl_time = Config::get('system', 'curl_timeout', 60);
276 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
279 if (defined('LIGHTTPD')) {
280 if (!is_array($headers)) {
281 $headers = ['Expect:'];
283 if (!in_array('Expect:', $headers)) {
284 array_push($headers, 'Expect:');
290 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
293 $check_cert = Config::get('system', 'verifyssl');
294 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
297 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
300 $proxy = Config::get('system', 'proxy');
302 if (strlen($proxy)) {
303 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
304 curl_setopt($ch, CURLOPT_PROXY, $proxy);
305 $proxyuser = Config::get('system', 'proxyuser');
306 if (strlen($proxyuser)) {
307 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
311 // don't let curl abort the entire application
312 // if it throws any errors.
314 $s = @curl_exec($ch);
317 $curl_info = curl_getinfo($ch);
319 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
321 if ($curlResponse->isRedirectUrl()) {
323 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
325 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
330 $a->saveTimestamp($stamp1, 'network');
332 Logger::log('post_url: end ' . $url, Logger::DATA);
334 return $curlResponse;
338 * @brief Check URL to see if it's real
340 * Take a URL from the wild, prepend http:// if necessary
341 * and check DNS to see if it's real (or check if is a valid IP address)
343 * @param string $url The URL to be validated
344 * @return string|boolean The actual working URL, false else
346 public static function isUrlValid($url)
348 if (Config::get('system', 'disable_url_validation')) {
352 // no naked subdomains (allow localhost for tests)
353 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
357 if (substr($url, 0, 4) != 'http') {
358 $url = 'http://' . $url;
361 /// @TODO Really suppress function outcomes? Why not find them + debug them?
362 $h = @parse_url($url);
364 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
372 * @brief Checks that email is an actual resolvable internet address
374 * @param string $addr The email address
375 * @return boolean True if it's a valid email address, false if it's not
377 public static function isEmailDomainValid($addr)
379 if (Config::get('system', 'disable_email_validation')) {
383 if (! strpos($addr, '@')) {
387 $h = substr($addr, strpos($addr, '@') + 1);
389 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
390 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
393 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
400 * @brief Check if URL is allowed
402 * Check $url against our list of allowed sites,
403 * wildcards allowed. If allowed_sites is unset return true;
405 * @param string $url URL which get tested
406 * @return boolean True if url is allowed otherwise return false
408 public static function isUrlAllowed($url)
410 $h = @parse_url($url);
416 $str_allowed = Config::get('system', 'allowed_sites');
417 if (! $str_allowed) {
423 $host = strtolower($h['host']);
425 // always allow our own site
426 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
430 $fnmatch = function_exists('fnmatch');
431 $allowed = explode(',', $str_allowed);
433 if (count($allowed)) {
434 foreach ($allowed as $a) {
435 $pat = strtolower(trim($a));
436 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
446 * Checks if the provided url domain is on the domain blocklist.
447 * Returns true if it is or malformed URL, false if not.
449 * @param string $url The url to check the domain from
453 public static function isUrlBlocked($url)
455 $host = @parse_url($url, PHP_URL_HOST);
460 $domain_blocklist = Config::get('system', 'blocklist', []);
461 if (!$domain_blocklist) {
465 foreach ($domain_blocklist as $domain_block) {
466 if (strcasecmp($domain_block['domain'], $host) === 0) {
475 * @brief Check if email address is allowed to register here.
477 * Compare against our list (wildcards allowed).
479 * @param string $email email address
480 * @return boolean False if not allowed, true if allowed
481 * or if allowed list is not configured
483 public static function isEmailDomainAllowed($email)
485 $domain = strtolower(substr($email, strpos($email, '@') + 1));
490 $str_allowed = Config::get('system', 'allowed_email', '');
491 if (!x($str_allowed)) {
495 $allowed = explode(',', $str_allowed);
497 return self::isDomainAllowed($domain, $allowed);
501 * Checks for the existence of a domain in a domain list
503 * @brief Checks for the existence of a domain in a domain list
504 * @param string $domain
505 * @param array $domain_list
508 public static function isDomainAllowed($domain, array $domain_list)
512 foreach ($domain_list as $item) {
513 $pat = strtolower(trim($item));
514 if (fnmatch($pat, $domain) || ($pat == $domain)) {
523 public static function lookupAvatarByEmail($email)
525 $avatar['size'] = 300;
526 $avatar['email'] = $email;
528 $avatar['success'] = false;
530 Addon::callHooks('avatar_lookup', $avatar);
532 if (! $avatar['success']) {
533 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
536 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
537 return $avatar['url'];
541 * @brief Remove Google Analytics and other tracking platforms params from URL
543 * @param string $url Any user-submitted URL that may contain tracking params
544 * @return string The same URL stripped of tracking parameters
546 public static function stripTrackingQueryParams($url)
548 $urldata = parse_url($url);
549 if (!empty($urldata["query"])) {
550 $query = $urldata["query"];
551 parse_str($query, $querydata);
553 if (is_array($querydata)) {
554 foreach ($querydata as $param => $value) {
558 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
559 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
560 "fb_action_ids", "fb_action_types", "fb_ref",
562 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
565 $pair = $param . "=" . urlencode($value);
566 $url = str_replace($pair, "", $url);
568 // Second try: if the url isn't encoded completely
569 $pair = $param . "=" . str_replace(" ", "+", $value);
570 $url = str_replace($pair, "", $url);
572 // Third try: Maybey the url isn't encoded at all
573 $pair = $param . "=" . $value;
574 $url = str_replace($pair, "", $url);
576 $url = str_replace(["?&", "&&"], ["?", ""], $url);
581 if (substr($url, -1, 1) == "?") {
582 $url = substr($url, 0, -1);
590 * @brief Returns the original URL of the provided URL
592 * This function strips tracking query params and follows redirections, either
593 * through HTTP code or meta refresh tags. Stops after 10 redirections.
595 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
597 * @see ParseUrl::getSiteinfo
599 * @param string $url A user-submitted URL
600 * @param int $depth The current redirection recursion level (internal)
601 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
602 * @return string A canonical URL
604 public static function finalUrl($url, $depth = 1, $fetchbody = false)
608 $url = self::stripTrackingQueryParams($url);
614 $url = trim($url, "'");
616 $stamp1 = microtime(true);
619 curl_setopt($ch, CURLOPT_URL, $url);
620 curl_setopt($ch, CURLOPT_HEADER, 1);
621 curl_setopt($ch, CURLOPT_NOBODY, 1);
622 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
623 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
624 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
627 $curl_info = @curl_getinfo($ch);
628 $http_code = $curl_info['http_code'];
631 $a->saveTimestamp($stamp1, "network");
633 if ($http_code == 0) {
637 if (in_array($http_code, ['301', '302'])) {
638 if (!empty($curl_info['redirect_url'])) {
639 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
640 } elseif (!empty($curl_info['location'])) {
641 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
645 // Check for redirects in the meta elements of the body if there are no redirects in the header.
647 return(self::finalUrl($url, ++$depth, true));
650 // if the file is too large then exit
651 if ($curl_info["download_content_length"] > 1000000) {
655 // if it isn't a HTML file then exit
656 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
660 $stamp1 = microtime(true);
663 curl_setopt($ch, CURLOPT_URL, $url);
664 curl_setopt($ch, CURLOPT_HEADER, 0);
665 curl_setopt($ch, CURLOPT_NOBODY, 0);
666 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
667 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
668 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
670 $body = curl_exec($ch);
673 $a->saveTimestamp($stamp1, "network");
675 if (trim($body) == "") {
679 // Check for redirect in meta elements
680 $doc = new DOMDocument();
681 @$doc->loadHTML($body);
683 $xpath = new DomXPath($doc);
685 $list = $xpath->query("//meta[@content]");
686 foreach ($list as $node) {
688 if ($node->attributes->length) {
689 foreach ($node->attributes as $attribute) {
690 $attr[$attribute->name] = $attribute->value;
694 if (@$attr["http-equiv"] == 'refresh') {
695 $path = $attr["content"];
696 $pathinfo = explode(";", $path);
697 foreach ($pathinfo as $value) {
698 if (substr(strtolower($value), 0, 4) == "url=") {
699 return self::finalUrl(substr($value, 4), ++$depth);
709 * @brief Find the matching part between two url
711 * @param string $url1
712 * @param string $url2
713 * @return string The matching part
715 public static function getUrlMatch($url1, $url2)
717 if (($url1 == "") || ($url2 == "")) {
721 $url1 = normalise_link($url1);
722 $url2 = normalise_link($url2);
724 $parts1 = parse_url($url1);
725 $parts2 = parse_url($url2);
727 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
731 if (empty($parts1["scheme"])) {
732 $parts1["scheme"] = '';
734 if (empty($parts2["scheme"])) {
735 $parts2["scheme"] = '';
738 if ($parts1["scheme"] != $parts2["scheme"]) {
742 if (empty($parts1["host"])) {
743 $parts1["host"] = '';
745 if (empty($parts2["host"])) {
746 $parts2["host"] = '';
749 if ($parts1["host"] != $parts2["host"]) {
753 if (empty($parts1["port"])) {
754 $parts1["port"] = '';
756 if (empty($parts2["port"])) {
757 $parts2["port"] = '';
760 if ($parts1["port"] != $parts2["port"]) {
764 $match = $parts1["scheme"]."://".$parts1["host"];
766 if ($parts1["port"]) {
767 $match .= ":".$parts1["port"];
770 if (empty($parts1["path"])) {
771 $parts1["path"] = '';
773 if (empty($parts2["path"])) {
774 $parts2["path"] = '';
777 $pathparts1 = explode("/", $parts1["path"]);
778 $pathparts2 = explode("/", $parts2["path"]);
783 $path1 = defaults($pathparts1, $i, '');
784 $path2 = defaults($pathparts2, $i, '');
786 if ($path1 == $path2) {
789 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
793 return normalise_link($match);
797 * @brief Glue url parts together
799 * @param array $parsed URL parts
801 * @return string The glued URL
803 public static function unparseURL($parsed)
805 $get = function ($key) use ($parsed) {
806 return isset($parsed[$key]) ? $parsed[$key] : null;
809 $pass = $get('pass');
810 $user = $get('user');
811 $userinfo = $pass !== null ? "$user:$pass" : $user;
812 $port = $get('port');
813 $scheme = $get('scheme');
814 $query = $get('query');
815 $fragment = $get('fragment');
816 $authority = ($userinfo !== null ? $userinfo."@" : '') .
818 ($port ? ":$port" : '');
820 return (strlen($scheme) ? $scheme.":" : '') .
821 (strlen($authority) ? "//".$authority : '') .
823 (strlen($query) ? "?".$query : '') .
824 (strlen($fragment) ? "#".$fragment : '');