3 * @file src/Util/Network.php
5 namespace Friendica\Util;
7 use Friendica\Core\Hook;
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
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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.
59 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61 public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
68 'accept_content'=>$accept_content,
69 'cookiejar'=>$cookiejar
75 * @brief fetches an URL.
77 * @param string $url URL to fetch
78 * @param boolean $binary default false
79 * TRUE if asked to return binary results (file download)
80 * @param int $redirects The recursion counter for internal use - default 0
81 * @param array $opts (optional parameters) assoziative array with:
82 * 'accept_content' => supply Accept: header with 'accept_content' as the value
83 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
84 * 'http_auth' => username:password
85 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
86 * 'nobody' => only return the header
87 * 'cookiejar' => path to cookie jar file
88 * 'header' => header array
91 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
93 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
95 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
97 $stamp1 = microtime(true);
101 if (strlen($url) > 1000) {
102 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
103 return CurlResult::createErrorCurl(substr($url, 0, 200));
106 $parts = parse_url($url);
107 $path_parts = explode('/', defaults($parts, 'path', ''));
108 foreach ($path_parts as $part) {
109 if (strlen($part) <> mb_strlen($part)) {
110 $parts2[] = rawurlencode($part);
115 $parts['path'] = implode('/', $parts2);
116 $url = self::unparseURL($parts);
118 if (self::isUrlBlocked($url)) {
119 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
120 return CurlResult::createErrorCurl($url);
123 $ch = @curl_init($url);
125 if (($redirects > 8) || (!$ch)) {
126 return CurlResult::createErrorCurl($url);
129 @curl_setopt($ch, CURLOPT_HEADER, true);
131 if (!empty($opts['cookiejar'])) {
132 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
133 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
136 // These settings aren't needed. We're following the location already.
137 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
138 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
140 if (!empty($opts['accept_content'])) {
144 ['Accept: ' . $opts['accept_content']]
148 if (!empty($opts['header'])) {
149 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
152 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
153 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
155 $range = intval(Config::get('system', 'curl_range_bytes', 0));
158 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
161 // Without this setting it seems as if some webservers send compressed content
162 // This seems to confuse curl so that it shows this uncompressed.
163 /// @todo We could possibly set this value to "gzip" or something similar
164 curl_setopt($ch, CURLOPT_ENCODING, '');
166 if (!empty($opts['headers'])) {
167 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
170 if (!empty($opts['nobody'])) {
171 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
174 if (!empty($opts['timeout'])) {
175 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
177 $curl_time = Config::get('system', 'curl_timeout', 60);
178 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
181 // by default we will allow self-signed certs
182 // but you can override this
184 $check_cert = Config::get('system', 'verifyssl');
185 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
188 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
191 $proxy = Config::get('system', 'proxy');
193 if (strlen($proxy)) {
194 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
195 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
196 $proxyuser = @Config::get('system', 'proxyuser');
198 if (strlen($proxyuser)) {
199 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
203 if (Config::get('system', 'ipv4_resolve', false)) {
204 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
208 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
211 // don't let curl abort the entire application
212 // if it throws any errors.
214 $s = @curl_exec($ch);
215 $curl_info = @curl_getinfo($ch);
217 // Special treatment for HTTP Code 416
218 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
219 if (($curl_info['http_code'] == 416) && ($range > 0)) {
220 @curl_setopt($ch, CURLOPT_RANGE, '');
221 $s = @curl_exec($ch);
222 $curl_info = @curl_getinfo($ch);
225 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
227 if ($curlResponse->isRedirectUrl()) {
229 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
231 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
236 $a->saveTimestamp($stamp1, 'network');
238 return $curlResponse;
242 * @brief Send POST request to $url
244 * @param string $url URL to post
245 * @param mixed $params array of POST variables
246 * @param string $headers HTTP headers
247 * @param integer $redirects Recursion counter for internal use - default = 0
248 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
250 * @return CurlResult The content
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
255 $stamp1 = microtime(true);
257 if (self::isUrlBlocked($url)) {
258 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
259 return CurlResult::createErrorCurl($url);
263 $ch = curl_init($url);
265 if (($redirects > 8) || (!$ch)) {
266 return CurlResult::createErrorCurl($url);
269 Logger::log('post_url: start ' . $url, Logger::DATA);
271 curl_setopt($ch, CURLOPT_HEADER, true);
272 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
273 curl_setopt($ch, CURLOPT_POST, 1);
274 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
275 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
277 if (Config::get('system', 'ipv4_resolve', false)) {
278 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
281 if (intval($timeout)) {
282 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
284 $curl_time = Config::get('system', 'curl_timeout', 60);
285 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
288 if (defined('LIGHTTPD')) {
289 if (!is_array($headers)) {
290 $headers = ['Expect:'];
292 if (!in_array('Expect:', $headers)) {
293 array_push($headers, 'Expect:');
299 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
302 $check_cert = Config::get('system', 'verifyssl');
303 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
306 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
309 $proxy = Config::get('system', 'proxy');
311 if (strlen($proxy)) {
312 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
313 curl_setopt($ch, CURLOPT_PROXY, $proxy);
314 $proxyuser = Config::get('system', 'proxyuser');
315 if (strlen($proxyuser)) {
316 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
320 // don't let curl abort the entire application
321 // if it throws any errors.
323 $s = @curl_exec($ch);
326 $curl_info = curl_getinfo($ch);
328 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
330 if ($curlResponse->isRedirectUrl()) {
332 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
334 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
339 $a->saveTimestamp($stamp1, 'network');
341 Logger::log('post_url: end ' . $url, Logger::DATA);
343 return $curlResponse;
347 * @brief Check URL to see if it's real
349 * Take a URL from the wild, prepend http:// if necessary
350 * and check DNS to see if it's real (or check if is a valid IP address)
352 * @param string $url The URL to be validated
353 * @return string|boolean The actual working URL, false else
354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
356 public static function isUrlValid($url)
358 if (Config::get('system', 'disable_url_validation')) {
362 // no naked subdomains (allow localhost for tests)
363 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
367 if (substr($url, 0, 4) != 'http') {
368 $url = 'http://' . $url;
371 /// @TODO Really suppress function outcomes? Why not find them + debug them?
372 $h = @parse_url($url);
374 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
382 * @brief Checks that email is an actual resolvable internet address
384 * @param string $addr The email address
385 * @return boolean True if it's a valid email address, false if it's not
386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
388 public static function isEmailDomainValid($addr)
390 if (Config::get('system', 'disable_email_validation')) {
394 if (! strpos($addr, '@')) {
398 $h = substr($addr, strpos($addr, '@') + 1);
400 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
401 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
404 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
411 * @brief Check if URL is allowed
413 * Check $url against our list of allowed sites,
414 * wildcards allowed. If allowed_sites is unset return true;
416 * @param string $url URL which get tested
417 * @return boolean True if url is allowed otherwise return false
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 public static function isUrlAllowed($url)
422 $h = @parse_url($url);
428 $str_allowed = Config::get('system', 'allowed_sites');
429 if (! $str_allowed) {
435 $host = strtolower($h['host']);
437 // always allow our own site
438 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
442 $fnmatch = function_exists('fnmatch');
443 $allowed = explode(',', $str_allowed);
445 if (count($allowed)) {
446 foreach ($allowed as $a) {
447 $pat = strtolower(trim($a));
448 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
458 * Checks if the provided url domain is on the domain blocklist.
459 * Returns true if it is or malformed URL, false if not.
461 * @param string $url The url to check the domain from
464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
466 public static function isUrlBlocked($url)
468 $host = @parse_url($url, PHP_URL_HOST);
473 $domain_blocklist = Config::get('system', 'blocklist', []);
474 if (!$domain_blocklist) {
478 foreach ($domain_blocklist as $domain_block) {
479 if (strcasecmp($domain_block['domain'], $host) === 0) {
488 * @brief Check if email address is allowed to register here.
490 * Compare against our list (wildcards allowed).
492 * @param string $email email address
493 * @return boolean False if not allowed, true if allowed
494 * or if allowed list is not configured
495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
497 public static function isEmailDomainAllowed($email)
499 $domain = strtolower(substr($email, strpos($email, '@') + 1));
504 $str_allowed = Config::get('system', 'allowed_email', '');
505 if (empty($str_allowed)) {
509 $allowed = explode(',', $str_allowed);
511 return self::isDomainAllowed($domain, $allowed);
515 * Checks for the existence of a domain in a domain list
517 * @brief Checks for the existence of a domain in a domain list
518 * @param string $domain
519 * @param array $domain_list
522 public static function isDomainAllowed($domain, array $domain_list)
526 foreach ($domain_list as $item) {
527 $pat = strtolower(trim($item));
528 if (fnmatch($pat, $domain) || ($pat == $domain)) {
537 public static function lookupAvatarByEmail($email)
539 $avatar['size'] = 300;
540 $avatar['email'] = $email;
542 $avatar['success'] = false;
544 Hook::callAll('avatar_lookup', $avatar);
546 if (! $avatar['success']) {
547 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
550 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
551 return $avatar['url'];
555 * @brief Remove Google Analytics and other tracking platforms params from URL
557 * @param string $url Any user-submitted URL that may contain tracking params
558 * @return string The same URL stripped of tracking parameters
560 public static function stripTrackingQueryParams($url)
562 $urldata = parse_url($url);
563 if (!empty($urldata["query"])) {
564 $query = $urldata["query"];
565 parse_str($query, $querydata);
567 if (is_array($querydata)) {
568 foreach ($querydata as $param => $value) {
572 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
573 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
574 "fb_action_ids", "fb_action_types", "fb_ref",
576 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
579 $pair = $param . "=" . urlencode($value);
580 $url = str_replace($pair, "", $url);
582 // Second try: if the url isn't encoded completely
583 $pair = $param . "=" . str_replace(" ", "+", $value);
584 $url = str_replace($pair, "", $url);
586 // Third try: Maybey the url isn't encoded at all
587 $pair = $param . "=" . $value;
588 $url = str_replace($pair, "", $url);
590 $url = str_replace(["?&", "&&"], ["?", ""], $url);
595 if (substr($url, -1, 1) == "?") {
596 $url = substr($url, 0, -1);
604 * @brief Returns the original URL of the provided URL
606 * This function strips tracking query params and follows redirections, either
607 * through HTTP code or meta refresh tags. Stops after 10 redirections.
609 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
611 * @see ParseUrl::getSiteinfo
613 * @param string $url A user-submitted URL
614 * @param int $depth The current redirection recursion level (internal)
615 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
616 * @return string A canonical URL
617 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
619 public static function finalUrl($url, $depth = 1, $fetchbody = false)
623 $url = self::stripTrackingQueryParams($url);
629 $url = trim($url, "'");
631 $stamp1 = microtime(true);
634 curl_setopt($ch, CURLOPT_URL, $url);
635 curl_setopt($ch, CURLOPT_HEADER, 1);
636 curl_setopt($ch, CURLOPT_NOBODY, 1);
637 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
638 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
639 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
642 $curl_info = @curl_getinfo($ch);
643 $http_code = $curl_info['http_code'];
646 $a->saveTimestamp($stamp1, "network");
648 if ($http_code == 0) {
652 if (in_array($http_code, ['301', '302'])) {
653 if (!empty($curl_info['redirect_url'])) {
654 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
655 } elseif (!empty($curl_info['location'])) {
656 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
660 // Check for redirects in the meta elements of the body if there are no redirects in the header.
662 return(self::finalUrl($url, ++$depth, true));
665 // if the file is too large then exit
666 if ($curl_info["download_content_length"] > 1000000) {
670 // if it isn't a HTML file then exit
671 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
675 $stamp1 = microtime(true);
678 curl_setopt($ch, CURLOPT_URL, $url);
679 curl_setopt($ch, CURLOPT_HEADER, 0);
680 curl_setopt($ch, CURLOPT_NOBODY, 0);
681 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
682 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
683 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
685 $body = curl_exec($ch);
688 $a->saveTimestamp($stamp1, "network");
690 if (trim($body) == "") {
694 // Check for redirect in meta elements
695 $doc = new DOMDocument();
696 @$doc->loadHTML($body);
698 $xpath = new DomXPath($doc);
700 $list = $xpath->query("//meta[@content]");
701 foreach ($list as $node) {
703 if ($node->attributes->length) {
704 foreach ($node->attributes as $attribute) {
705 $attr[$attribute->name] = $attribute->value;
709 if (@$attr["http-equiv"] == 'refresh') {
710 $path = $attr["content"];
711 $pathinfo = explode(";", $path);
712 foreach ($pathinfo as $value) {
713 if (substr(strtolower($value), 0, 4) == "url=") {
714 return self::finalUrl(substr($value, 4), ++$depth);
724 * @brief Find the matching part between two url
726 * @param string $url1
727 * @param string $url2
728 * @return string The matching part
730 public static function getUrlMatch($url1, $url2)
732 if (($url1 == "") || ($url2 == "")) {
736 $url1 = Strings::normaliseLink($url1);
737 $url2 = Strings::normaliseLink($url2);
739 $parts1 = parse_url($url1);
740 $parts2 = parse_url($url2);
742 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
746 if (empty($parts1["scheme"])) {
747 $parts1["scheme"] = '';
749 if (empty($parts2["scheme"])) {
750 $parts2["scheme"] = '';
753 if ($parts1["scheme"] != $parts2["scheme"]) {
757 if (empty($parts1["host"])) {
758 $parts1["host"] = '';
760 if (empty($parts2["host"])) {
761 $parts2["host"] = '';
764 if ($parts1["host"] != $parts2["host"]) {
768 if (empty($parts1["port"])) {
769 $parts1["port"] = '';
771 if (empty($parts2["port"])) {
772 $parts2["port"] = '';
775 if ($parts1["port"] != $parts2["port"]) {
779 $match = $parts1["scheme"]."://".$parts1["host"];
781 if ($parts1["port"]) {
782 $match .= ":".$parts1["port"];
785 if (empty($parts1["path"])) {
786 $parts1["path"] = '';
788 if (empty($parts2["path"])) {
789 $parts2["path"] = '';
792 $pathparts1 = explode("/", $parts1["path"]);
793 $pathparts2 = explode("/", $parts2["path"]);
798 $path1 = defaults($pathparts1, $i, '');
799 $path2 = defaults($pathparts2, $i, '');
801 if ($path1 == $path2) {
804 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
808 return Strings::normaliseLink($match);
812 * @brief Glue url parts together
814 * @param array $parsed URL parts
816 * @return string The glued URL
818 public static function unparseURL($parsed)
820 $get = function ($key) use ($parsed) {
821 return isset($parsed[$key]) ? $parsed[$key] : null;
824 $pass = $get('pass');
825 $user = $get('user');
826 $userinfo = $pass !== null ? "$user:$pass" : $user;
827 $port = $get('port');
828 $scheme = $get('scheme');
829 $query = $get('query');
830 $fragment = $get('fragment');
831 $authority = ($userinfo !== null ? $userinfo."@" : '') .
833 ($port ? ":$port" : '');
835 return (strlen($scheme) ? $scheme.":" : '') .
836 (strlen($authority) ? "//".$authority : '') .
838 (strlen($query) ? "?".$query : '') .
839 (strlen($fragment) ? "#".$fragment : '');