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 $stamp1 = microtime(true);
99 if (strlen($url) > 1000) {
100 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
101 return CurlResult::createErrorCurl(substr($url, 0, 200));
105 $parts = parse_url($url);
106 $path_parts = explode('/', defaults($parts, 'path', ''));
107 foreach ($path_parts as $part) {
108 if (strlen($part) <> mb_strlen($part)) {
109 $parts2[] = rawurlencode($part);
114 $parts['path'] = implode('/', $parts2);
115 $url = self::unparseURL($parts);
117 if (self::isUrlBlocked($url)) {
118 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
119 return CurlResult::createErrorCurl($url);
122 $ch = @curl_init($url);
124 if (($redirects > 8) || (!$ch)) {
125 return CurlResult::createErrorCurl($url);
128 @curl_setopt($ch, CURLOPT_HEADER, true);
130 if (!empty($opts['cookiejar'])) {
131 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
132 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
135 // These settings aren't needed. We're following the location already.
136 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
137 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
139 if (!empty($opts['accept_content'])) {
143 ['Accept: ' . $opts['accept_content']]
147 if (!empty($opts['header'])) {
148 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
151 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
152 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
154 $range = intval(Config::get('system', 'curl_range_bytes', 0));
157 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
160 // Without this setting it seems as if some webservers send compressed content
161 // This seems to confuse curl so that it shows this uncompressed.
162 /// @todo We could possibly set this value to "gzip" or something similar
163 curl_setopt($ch, CURLOPT_ENCODING, '');
165 if (!empty($opts['headers'])) {
166 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
169 if (!empty($opts['nobody'])) {
170 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
173 if (!empty($opts['timeout'])) {
174 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
176 $curl_time = Config::get('system', 'curl_timeout', 60);
177 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
180 // by default we will allow self-signed certs
181 // but you can override this
183 $check_cert = Config::get('system', 'verifyssl');
184 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
187 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
190 $proxy = Config::get('system', 'proxy');
192 if (strlen($proxy)) {
193 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
194 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
195 $proxyuser = @Config::get('system', 'proxyuser');
197 if (strlen($proxyuser)) {
198 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
202 if (Config::get('system', 'ipv4_resolve', false)) {
203 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
207 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
210 // don't let curl abort the entire application
211 // if it throws any errors.
213 $s = @curl_exec($ch);
214 $curl_info = @curl_getinfo($ch);
216 // Special treatment for HTTP Code 416
217 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
218 if (($curl_info['http_code'] == 416) && ($range > 0)) {
219 @curl_setopt($ch, CURLOPT_RANGE, '');
220 $s = @curl_exec($ch);
221 $curl_info = @curl_getinfo($ch);
224 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
226 if ($curlResponse->isRedirectUrl()) {
228 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
230 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
235 $a->saveTimestamp($stamp1, 'network');
237 return $curlResponse;
241 * @brief Send POST request to $url
243 * @param string $url URL to post
244 * @param mixed $params array of POST variables
245 * @param string $headers HTTP headers
246 * @param integer $redirects Recursion counter for internal use - default = 0
247 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
249 * @return CurlResult The content
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
254 $stamp1 = microtime(true);
256 if (self::isUrlBlocked($url)) {
257 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
258 return CurlResult::createErrorCurl($url);
262 $ch = curl_init($url);
264 if (($redirects > 8) || (!$ch)) {
265 return CurlResult::createErrorCurl($url);
268 Logger::log('post_url: start ' . $url, Logger::DATA);
270 curl_setopt($ch, CURLOPT_HEADER, true);
271 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
272 curl_setopt($ch, CURLOPT_POST, 1);
273 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
274 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
276 if (Config::get('system', 'ipv4_resolve', false)) {
277 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
280 if (intval($timeout)) {
281 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
283 $curl_time = Config::get('system', 'curl_timeout', 60);
284 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
287 if (defined('LIGHTTPD')) {
288 if (!is_array($headers)) {
289 $headers = ['Expect:'];
291 if (!in_array('Expect:', $headers)) {
292 array_push($headers, 'Expect:');
298 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
301 $check_cert = Config::get('system', 'verifyssl');
302 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
305 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
308 $proxy = Config::get('system', 'proxy');
310 if (strlen($proxy)) {
311 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
312 curl_setopt($ch, CURLOPT_PROXY, $proxy);
313 $proxyuser = Config::get('system', 'proxyuser');
314 if (strlen($proxyuser)) {
315 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
319 // don't let curl abort the entire application
320 // if it throws any errors.
322 $s = @curl_exec($ch);
324 $curl_info = curl_getinfo($ch);
326 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
328 if ($curlResponse->isRedirectUrl()) {
330 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
332 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
337 $a->saveTimestamp($stamp1, 'network');
339 Logger::log('post_url: end ' . $url, Logger::DATA);
341 return $curlResponse;
345 * @brief Check URL to see if it's real
347 * Take a URL from the wild, prepend http:// if necessary
348 * and check DNS to see if it's real (or check if is a valid IP address)
350 * @param string $url The URL to be validated
351 * @return string|boolean The actual working URL, false else
352 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
354 public static function isUrlValid($url)
356 if (Config::get('system', 'disable_url_validation')) {
360 // no naked subdomains (allow localhost for tests)
361 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
365 if (substr($url, 0, 4) != 'http') {
366 $url = 'http://' . $url;
369 /// @TODO Really suppress function outcomes? Why not find them + debug them?
370 $h = @parse_url($url);
372 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
380 * @brief Checks that email is an actual resolvable internet address
382 * @param string $addr The email address
383 * @return boolean True if it's a valid email address, false if it's not
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
386 public static function isEmailDomainValid($addr)
388 if (Config::get('system', 'disable_email_validation')) {
392 if (! strpos($addr, '@')) {
396 $h = substr($addr, strpos($addr, '@') + 1);
398 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
399 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
402 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
409 * @brief Check if URL is allowed
411 * Check $url against our list of allowed sites,
412 * wildcards allowed. If allowed_sites is unset return true;
414 * @param string $url URL which get tested
415 * @return boolean True if url is allowed otherwise return false
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 public static function isUrlAllowed($url)
420 $h = @parse_url($url);
426 $str_allowed = Config::get('system', 'allowed_sites');
427 if (! $str_allowed) {
433 $host = strtolower($h['host']);
435 // always allow our own site
436 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
440 $fnmatch = function_exists('fnmatch');
441 $allowed = explode(',', $str_allowed);
443 if (count($allowed)) {
444 foreach ($allowed as $a) {
445 $pat = strtolower(trim($a));
446 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
456 * Checks if the provided url domain is on the domain blocklist.
457 * Returns true if it is or malformed URL, false if not.
459 * @param string $url The url to check the domain from
462 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
464 public static function isUrlBlocked($url)
466 $host = @parse_url($url, PHP_URL_HOST);
471 $domain_blocklist = Config::get('system', 'blocklist', []);
472 if (!$domain_blocklist) {
476 foreach ($domain_blocklist as $domain_block) {
477 if (strcasecmp($domain_block['domain'], $host) === 0) {
486 * @brief Check if email address is allowed to register here.
488 * Compare against our list (wildcards allowed).
490 * @param string $email email address
491 * @return boolean False if not allowed, true if allowed
492 * or if allowed list is not configured
493 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
495 public static function isEmailDomainAllowed($email)
497 $domain = strtolower(substr($email, strpos($email, '@') + 1));
502 $str_allowed = Config::get('system', 'allowed_email', '');
503 if (empty($str_allowed)) {
507 $allowed = explode(',', $str_allowed);
509 return self::isDomainAllowed($domain, $allowed);
513 * Checks for the existence of a domain in a domain list
515 * @brief Checks for the existence of a domain in a domain list
516 * @param string $domain
517 * @param array $domain_list
520 public static function isDomainAllowed($domain, array $domain_list)
524 foreach ($domain_list as $item) {
525 $pat = strtolower(trim($item));
526 if (fnmatch($pat, $domain) || ($pat == $domain)) {
535 public static function lookupAvatarByEmail($email)
537 $avatar['size'] = 300;
538 $avatar['email'] = $email;
540 $avatar['success'] = false;
542 Hook::callAll('avatar_lookup', $avatar);
544 if (! $avatar['success']) {
545 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
548 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
549 return $avatar['url'];
553 * @brief Remove Google Analytics and other tracking platforms params from URL
555 * @param string $url Any user-submitted URL that may contain tracking params
556 * @return string The same URL stripped of tracking parameters
558 public static function stripTrackingQueryParams($url)
560 $urldata = parse_url($url);
561 if (!empty($urldata["query"])) {
562 $query = $urldata["query"];
563 parse_str($query, $querydata);
565 if (is_array($querydata)) {
566 foreach ($querydata as $param => $value) {
570 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
571 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
572 "fb_action_ids", "fb_action_types", "fb_ref",
574 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
577 $pair = $param . "=" . urlencode($value);
578 $url = str_replace($pair, "", $url);
580 // Second try: if the url isn't encoded completely
581 $pair = $param . "=" . str_replace(" ", "+", $value);
582 $url = str_replace($pair, "", $url);
584 // Third try: Maybey the url isn't encoded at all
585 $pair = $param . "=" . $value;
586 $url = str_replace($pair, "", $url);
588 $url = str_replace(["?&", "&&"], ["?", ""], $url);
593 if (substr($url, -1, 1) == "?") {
594 $url = substr($url, 0, -1);
602 * @brief Returns the original URL of the provided URL
604 * This function strips tracking query params and follows redirections, either
605 * through HTTP code or meta refresh tags. Stops after 10 redirections.
607 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
609 * @see ParseUrl::getSiteinfo
611 * @param string $url A user-submitted URL
612 * @param int $depth The current redirection recursion level (internal)
613 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
614 * @return string A canonical URL
615 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
617 public static function finalUrl($url, $depth = 1, $fetchbody = false)
621 $url = self::stripTrackingQueryParams($url);
627 $url = trim($url, "'");
629 $stamp1 = microtime(true);
632 curl_setopt($ch, CURLOPT_URL, $url);
633 curl_setopt($ch, CURLOPT_HEADER, 1);
634 curl_setopt($ch, CURLOPT_NOBODY, 1);
635 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
636 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
637 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
640 $curl_info = @curl_getinfo($ch);
641 $http_code = $curl_info['http_code'];
644 $a->saveTimestamp($stamp1, "network");
646 if ($http_code == 0) {
650 if (in_array($http_code, ['301', '302'])) {
651 if (!empty($curl_info['redirect_url'])) {
652 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
653 } elseif (!empty($curl_info['location'])) {
654 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
658 // Check for redirects in the meta elements of the body if there are no redirects in the header.
660 return(self::finalUrl($url, ++$depth, true));
663 // if the file is too large then exit
664 if ($curl_info["download_content_length"] > 1000000) {
668 // if it isn't a HTML file then exit
669 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
673 $stamp1 = microtime(true);
676 curl_setopt($ch, CURLOPT_URL, $url);
677 curl_setopt($ch, CURLOPT_HEADER, 0);
678 curl_setopt($ch, CURLOPT_NOBODY, 0);
679 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
680 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
681 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
683 $body = curl_exec($ch);
686 $a->saveTimestamp($stamp1, "network");
688 if (trim($body) == "") {
692 // Check for redirect in meta elements
693 $doc = new DOMDocument();
694 @$doc->loadHTML($body);
696 $xpath = new DomXPath($doc);
698 $list = $xpath->query("//meta[@content]");
699 foreach ($list as $node) {
701 if ($node->attributes->length) {
702 foreach ($node->attributes as $attribute) {
703 $attr[$attribute->name] = $attribute->value;
707 if (@$attr["http-equiv"] == 'refresh') {
708 $path = $attr["content"];
709 $pathinfo = explode(";", $path);
710 foreach ($pathinfo as $value) {
711 if (substr(strtolower($value), 0, 4) == "url=") {
712 return self::finalUrl(substr($value, 4), ++$depth);
722 * @brief Find the matching part between two url
724 * @param string $url1
725 * @param string $url2
726 * @return string The matching part
728 public static function getUrlMatch($url1, $url2)
730 if (($url1 == "") || ($url2 == "")) {
734 $url1 = Strings::normaliseLink($url1);
735 $url2 = Strings::normaliseLink($url2);
737 $parts1 = parse_url($url1);
738 $parts2 = parse_url($url2);
740 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
744 if (empty($parts1["scheme"])) {
745 $parts1["scheme"] = '';
747 if (empty($parts2["scheme"])) {
748 $parts2["scheme"] = '';
751 if ($parts1["scheme"] != $parts2["scheme"]) {
755 if (empty($parts1["host"])) {
756 $parts1["host"] = '';
758 if (empty($parts2["host"])) {
759 $parts2["host"] = '';
762 if ($parts1["host"] != $parts2["host"]) {
766 if (empty($parts1["port"])) {
767 $parts1["port"] = '';
769 if (empty($parts2["port"])) {
770 $parts2["port"] = '';
773 if ($parts1["port"] != $parts2["port"]) {
777 $match = $parts1["scheme"]."://".$parts1["host"];
779 if ($parts1["port"]) {
780 $match .= ":".$parts1["port"];
783 if (empty($parts1["path"])) {
784 $parts1["path"] = '';
786 if (empty($parts2["path"])) {
787 $parts2["path"] = '';
790 $pathparts1 = explode("/", $parts1["path"]);
791 $pathparts2 = explode("/", $parts2["path"]);
796 $path1 = defaults($pathparts1, $i, '');
797 $path2 = defaults($pathparts2, $i, '');
799 if ($path1 == $path2) {
802 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
806 return Strings::normaliseLink($match);
810 * @brief Glue url parts together
812 * @param array $parsed URL parts
814 * @return string The glued URL
816 public static function unparseURL($parsed)
818 $get = function ($key) use ($parsed) {
819 return isset($parsed[$key]) ? $parsed[$key] : null;
822 $pass = $get('pass');
823 $user = $get('user');
824 $userinfo = $pass !== null ? "$user:$pass" : $user;
825 $port = $get('port');
826 $scheme = $get('scheme');
827 $query = $get('query');
828 $fragment = $get('fragment');
829 $authority = ($userinfo !== null ? $userinfo."@" : '') .
831 ($port ? ":$port" : '');
833 return (strlen($scheme) ? $scheme.":" : '') .
834 (strlen($authority) ? "//".$authority : '') .
836 (strlen($query) ? "?".$query : '') .
837 (strlen($fragment) ? "#".$fragment : '');