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 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));
104 $parts = parse_url($url);
105 $path_parts = explode('/', defaults($parts, 'path', ''));
106 foreach ($path_parts as $part) {
107 if (strlen($part) <> mb_strlen($part)) {
108 $parts2[] = rawurlencode($part);
113 $parts['path'] = implode('/', $parts2);
114 $url = self::unparseURL($parts);
116 if (self::isUrlBlocked($url)) {
117 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
118 return CurlResult::createErrorCurl($url);
121 $ch = @curl_init($url);
123 if (($redirects > 8) || (!$ch)) {
124 return CurlResult::createErrorCurl($url);
127 @curl_setopt($ch, CURLOPT_HEADER, true);
129 if (!empty($opts['cookiejar'])) {
130 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
131 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
134 // These settings aren't needed. We're following the location already.
135 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
136 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
138 if (!empty($opts['accept_content'])) {
142 ['Accept: ' . $opts['accept_content']]
146 if (!empty($opts['header'])) {
147 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
150 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
151 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
153 $range = intval(Config::get('system', 'curl_range_bytes', 0));
156 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
159 // Without this setting it seems as if some webservers send compressed content
160 // This seems to confuse curl so that it shows this uncompressed.
161 /// @todo We could possibly set this value to "gzip" or something similar
162 curl_setopt($ch, CURLOPT_ENCODING, '');
164 if (!empty($opts['headers'])) {
165 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
168 if (!empty($opts['nobody'])) {
169 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
172 if (!empty($opts['timeout'])) {
173 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
175 $curl_time = Config::get('system', 'curl_timeout', 60);
176 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
179 // by default we will allow self-signed certs
180 // but you can override this
182 $check_cert = Config::get('system', 'verifyssl');
183 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
186 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
189 $proxy = Config::get('system', 'proxy');
191 if (strlen($proxy)) {
192 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
193 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
194 $proxyuser = @Config::get('system', 'proxyuser');
196 if (strlen($proxyuser)) {
197 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
201 if (Config::get('system', 'ipv4_resolve', false)) {
202 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
206 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
209 // don't let curl abort the entire application
210 // if it throws any errors.
212 $s = @curl_exec($ch);
213 $curl_info = @curl_getinfo($ch);
215 // Special treatment for HTTP Code 416
216 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
217 if (($curl_info['http_code'] == 416) && ($range > 0)) {
218 @curl_setopt($ch, CURLOPT_RANGE, '');
219 $s = @curl_exec($ch);
220 $curl_info = @curl_getinfo($ch);
223 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
225 if ($curlResponse->isRedirectUrl()) {
227 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
229 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
234 $a->saveTimestamp($stamp1, 'network');
236 return $curlResponse;
240 * @brief Send POST request to $url
242 * @param string $url URL to post
243 * @param mixed $params array of POST variables
244 * @param string $headers HTTP headers
245 * @param integer $redirects Recursion counter for internal use - default = 0
246 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
248 * @return CurlResult The content
250 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
252 $stamp1 = microtime(true);
254 if (self::isUrlBlocked($url)) {
255 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
256 return CurlResult::createErrorCurl($url);
260 $ch = curl_init($url);
262 if (($redirects > 8) || (!$ch)) {
263 return CurlResult::createErrorCurl($url);
266 Logger::log('post_url: start ' . $url, Logger::DATA);
268 curl_setopt($ch, CURLOPT_HEADER, true);
269 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
270 curl_setopt($ch, CURLOPT_POST, 1);
271 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
272 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
274 if (Config::get('system', 'ipv4_resolve', false)) {
275 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
278 if (intval($timeout)) {
279 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
281 $curl_time = Config::get('system', 'curl_timeout', 60);
282 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
285 if (defined('LIGHTTPD')) {
286 if (!is_array($headers)) {
287 $headers = ['Expect:'];
289 if (!in_array('Expect:', $headers)) {
290 array_push($headers, 'Expect:');
296 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
299 $check_cert = Config::get('system', 'verifyssl');
300 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
303 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
306 $proxy = Config::get('system', 'proxy');
308 if (strlen($proxy)) {
309 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
310 curl_setopt($ch, CURLOPT_PROXY, $proxy);
311 $proxyuser = Config::get('system', 'proxyuser');
312 if (strlen($proxyuser)) {
313 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
317 // don't let curl abort the entire application
318 // if it throws any errors.
320 $s = @curl_exec($ch);
323 $curl_info = curl_getinfo($ch);
325 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
327 if ($curlResponse->isRedirectUrl()) {
329 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
331 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
336 $a->saveTimestamp($stamp1, 'network');
338 Logger::log('post_url: end ' . $url, Logger::DATA);
340 return $curlResponse;
344 * @brief Check URL to see if it's real
346 * Take a URL from the wild, prepend http:// if necessary
347 * and check DNS to see if it's real (or check if is a valid IP address)
349 * @param string $url The URL to be validated
350 * @return string|boolean The actual working URL, false else
352 public static function isUrlValid($url)
354 if (Config::get('system', 'disable_url_validation')) {
358 // no naked subdomains (allow localhost for tests)
359 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
363 if (substr($url, 0, 4) != 'http') {
364 $url = 'http://' . $url;
367 /// @TODO Really suppress function outcomes? Why not find them + debug them?
368 $h = @parse_url($url);
370 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
378 * @brief Checks that email is an actual resolvable internet address
380 * @param string $addr The email address
381 * @return boolean True if it's a valid email address, false if it's not
383 public static function isEmailDomainValid($addr)
385 if (Config::get('system', 'disable_email_validation')) {
389 if (! strpos($addr, '@')) {
393 $h = substr($addr, strpos($addr, '@') + 1);
395 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
396 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
399 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
406 * @brief Check if URL is allowed
408 * Check $url against our list of allowed sites,
409 * wildcards allowed. If allowed_sites is unset return true;
411 * @param string $url URL which get tested
412 * @return boolean True if url is allowed otherwise return false
414 public static function isUrlAllowed($url)
416 $h = @parse_url($url);
422 $str_allowed = Config::get('system', 'allowed_sites');
423 if (! $str_allowed) {
429 $host = strtolower($h['host']);
431 // always allow our own site
432 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
436 $fnmatch = function_exists('fnmatch');
437 $allowed = explode(',', $str_allowed);
439 if (count($allowed)) {
440 foreach ($allowed as $a) {
441 $pat = strtolower(trim($a));
442 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
452 * Checks if the provided url domain is on the domain blocklist.
453 * Returns true if it is or malformed URL, false if not.
455 * @param string $url The url to check the domain from
459 public static function isUrlBlocked($url)
461 $host = @parse_url($url, PHP_URL_HOST);
466 $domain_blocklist = Config::get('system', 'blocklist', []);
467 if (!$domain_blocklist) {
471 foreach ($domain_blocklist as $domain_block) {
472 if (strcasecmp($domain_block['domain'], $host) === 0) {
481 * @brief Check if email address is allowed to register here.
483 * Compare against our list (wildcards allowed).
485 * @param string $email email address
486 * @return boolean False if not allowed, true if allowed
487 * or if allowed list is not configured
489 public static function isEmailDomainAllowed($email)
491 $domain = strtolower(substr($email, strpos($email, '@') + 1));
496 $str_allowed = Config::get('system', 'allowed_email', '');
497 if (empty($str_allowed)) {
501 $allowed = explode(',', $str_allowed);
503 return self::isDomainAllowed($domain, $allowed);
507 * Checks for the existence of a domain in a domain list
509 * @brief Checks for the existence of a domain in a domain list
510 * @param string $domain
511 * @param array $domain_list
514 public static function isDomainAllowed($domain, array $domain_list)
518 foreach ($domain_list as $item) {
519 $pat = strtolower(trim($item));
520 if (fnmatch($pat, $domain) || ($pat == $domain)) {
529 public static function lookupAvatarByEmail($email)
531 $avatar['size'] = 300;
532 $avatar['email'] = $email;
534 $avatar['success'] = false;
536 Addon::callHooks('avatar_lookup', $avatar);
538 if (! $avatar['success']) {
539 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
542 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
543 return $avatar['url'];
547 * @brief Remove Google Analytics and other tracking platforms params from URL
549 * @param string $url Any user-submitted URL that may contain tracking params
550 * @return string The same URL stripped of tracking parameters
552 public static function stripTrackingQueryParams($url)
554 $urldata = parse_url($url);
555 if (!empty($urldata["query"])) {
556 $query = $urldata["query"];
557 parse_str($query, $querydata);
559 if (is_array($querydata)) {
560 foreach ($querydata as $param => $value) {
564 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
565 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
566 "fb_action_ids", "fb_action_types", "fb_ref",
568 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
571 $pair = $param . "=" . urlencode($value);
572 $url = str_replace($pair, "", $url);
574 // Second try: if the url isn't encoded completely
575 $pair = $param . "=" . str_replace(" ", "+", $value);
576 $url = str_replace($pair, "", $url);
578 // Third try: Maybey the url isn't encoded at all
579 $pair = $param . "=" . $value;
580 $url = str_replace($pair, "", $url);
582 $url = str_replace(["?&", "&&"], ["?", ""], $url);
587 if (substr($url, -1, 1) == "?") {
588 $url = substr($url, 0, -1);
596 * @brief Returns the original URL of the provided URL
598 * This function strips tracking query params and follows redirections, either
599 * through HTTP code or meta refresh tags. Stops after 10 redirections.
601 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
603 * @see ParseUrl::getSiteinfo
605 * @param string $url A user-submitted URL
606 * @param int $depth The current redirection recursion level (internal)
607 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
608 * @return string A canonical URL
610 public static function finalUrl($url, $depth = 1, $fetchbody = false)
614 $url = self::stripTrackingQueryParams($url);
620 $url = trim($url, "'");
622 $stamp1 = microtime(true);
625 curl_setopt($ch, CURLOPT_URL, $url);
626 curl_setopt($ch, CURLOPT_HEADER, 1);
627 curl_setopt($ch, CURLOPT_NOBODY, 1);
628 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
629 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
630 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
633 $curl_info = @curl_getinfo($ch);
634 $http_code = $curl_info['http_code'];
637 $a->saveTimestamp($stamp1, "network");
639 if ($http_code == 0) {
643 if (in_array($http_code, ['301', '302'])) {
644 if (!empty($curl_info['redirect_url'])) {
645 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
646 } elseif (!empty($curl_info['location'])) {
647 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
651 // Check for redirects in the meta elements of the body if there are no redirects in the header.
653 return(self::finalUrl($url, ++$depth, true));
656 // if the file is too large then exit
657 if ($curl_info["download_content_length"] > 1000000) {
661 // if it isn't a HTML file then exit
662 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
666 $stamp1 = microtime(true);
669 curl_setopt($ch, CURLOPT_URL, $url);
670 curl_setopt($ch, CURLOPT_HEADER, 0);
671 curl_setopt($ch, CURLOPT_NOBODY, 0);
672 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
673 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
674 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
676 $body = curl_exec($ch);
679 $a->saveTimestamp($stamp1, "network");
681 if (trim($body) == "") {
685 // Check for redirect in meta elements
686 $doc = new DOMDocument();
687 @$doc->loadHTML($body);
689 $xpath = new DomXPath($doc);
691 $list = $xpath->query("//meta[@content]");
692 foreach ($list as $node) {
694 if ($node->attributes->length) {
695 foreach ($node->attributes as $attribute) {
696 $attr[$attribute->name] = $attribute->value;
700 if (@$attr["http-equiv"] == 'refresh') {
701 $path = $attr["content"];
702 $pathinfo = explode(";", $path);
703 foreach ($pathinfo as $value) {
704 if (substr(strtolower($value), 0, 4) == "url=") {
705 return self::finalUrl(substr($value, 4), ++$depth);
715 * @brief Find the matching part between two url
717 * @param string $url1
718 * @param string $url2
719 * @return string The matching part
721 public static function getUrlMatch($url1, $url2)
723 if (($url1 == "") || ($url2 == "")) {
727 $url1 = Strings::normaliseLink($url1);
728 $url2 = Strings::normaliseLink($url2);
730 $parts1 = parse_url($url1);
731 $parts2 = parse_url($url2);
733 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
737 if (empty($parts1["scheme"])) {
738 $parts1["scheme"] = '';
740 if (empty($parts2["scheme"])) {
741 $parts2["scheme"] = '';
744 if ($parts1["scheme"] != $parts2["scheme"]) {
748 if (empty($parts1["host"])) {
749 $parts1["host"] = '';
751 if (empty($parts2["host"])) {
752 $parts2["host"] = '';
755 if ($parts1["host"] != $parts2["host"]) {
759 if (empty($parts1["port"])) {
760 $parts1["port"] = '';
762 if (empty($parts2["port"])) {
763 $parts2["port"] = '';
766 if ($parts1["port"] != $parts2["port"]) {
770 $match = $parts1["scheme"]."://".$parts1["host"];
772 if ($parts1["port"]) {
773 $match .= ":".$parts1["port"];
776 if (empty($parts1["path"])) {
777 $parts1["path"] = '';
779 if (empty($parts2["path"])) {
780 $parts2["path"] = '';
783 $pathparts1 = explode("/", $parts1["path"]);
784 $pathparts2 = explode("/", $parts2["path"]);
789 $path1 = defaults($pathparts1, $i, '');
790 $path2 = defaults($pathparts2, $i, '');
792 if ($path1 == $path2) {
795 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
799 return Strings::normaliseLink($match);
803 * @brief Glue url parts together
805 * @param array $parsed URL parts
807 * @return string The glued URL
809 public static function unparseURL($parsed)
811 $get = function ($key) use ($parsed) {
812 return isset($parsed[$key]) ? $parsed[$key] : null;
815 $pass = $get('pass');
816 $user = $get('user');
817 $userinfo = $pass !== null ? "$user:$pass" : $user;
818 $port = $get('port');
819 $scheme = $get('scheme');
820 $query = $get('query');
821 $fragment = $get('fragment');
822 $authority = ($userinfo !== null ? $userinfo."@" : '') .
824 ($port ? ":$port" : '');
826 return (strlen($scheme) ? $scheme.":" : '') .
827 (strlen($authority) ? "//".$authority : '') .
829 (strlen($query) ? "?".$query : '') .
830 (strlen($fragment) ? "#".$fragment : '');