3 * @file src/Util/Network.php
5 namespace Friendica\Util;
7 use Friendica\Core\Addon;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Network\CurlResult;
19 * If binary flag is true, return binary results.
20 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
21 * to preserve cookies from one request to the next.
24 * @param string $url URL to fetch
25 * @param boolean $binary default false
26 * TRUE if asked to return binary results (file download)
27 * @param integer $redirects The recursion counter for internal use - default 0
28 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
29 * @param string $accept_content supply Accept: header with 'accept_content' as the value
30 * @param string $cookiejar Path to cookie jar file
32 * @return string The fetched content
34 public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
36 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
38 return $ret->getBody();
42 * Curl wrapper with array of return values.
44 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
45 * all the information collected during the fetch.
47 * @brief Curl wrapper with array of return values.
48 * @param string $url URL to fetch
49 * @param boolean $binary default false
50 * TRUE if asked to return binary results (file download)
51 * @param integer $redirects The recursion counter for internal use - default 0
52 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
53 * @param string $accept_content supply Accept: header with 'accept_content' as the value
54 * @param string $cookiejar Path to cookie jar file
56 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
58 public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
65 'accept_content'=>$accept_content,
66 'cookiejar'=>$cookiejar
72 * @brief fetches an URL.
74 * @param string $url URL to fetch
75 * @param boolean $binary default false
76 * TRUE if asked to return binary results (file download)
77 * @param int $redirects The recursion counter for internal use - default 0
78 * @param array $opts (optional parameters) assoziative array with:
79 * 'accept_content' => supply Accept: header with 'accept_content' as the value
80 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
81 * 'http_auth' => username:password
82 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
83 * 'nobody' => only return the header
84 * 'cookiejar' => path to cookie jar file
88 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
90 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
92 $stamp1 = microtime(true);
96 $parts = parse_url($url);
97 $path_parts = explode('/', defaults($parts, 'path', ''));
98 foreach ($path_parts as $part) {
99 if (strlen($part) <> mb_strlen($part)) {
100 $parts2[] = rawurlencode($part);
105 $parts['path'] = implode('/', $parts2);
106 $url = self::unparseURL($parts);
108 if (self::isUrlBlocked($url)) {
109 logger('domain of ' . $url . ' is blocked', LOGGER_DATA);
110 return CurlResult::createErrorCurl($url);
113 $ch = @curl_init($url);
115 if (($redirects > 8) || (!$ch)) {
116 return CurlResult::createErrorCurl($url);
119 @curl_setopt($ch, CURLOPT_HEADER, true);
121 if (x($opts, "cookiejar")) {
122 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
123 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
126 // These settings aren't needed. We're following the location already.
127 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
128 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
130 if (x($opts, 'accept_content')) {
134 ['Accept: ' . $opts['accept_content']]
138 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
139 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
141 $range = intval(Config::get('system', 'curl_range_bytes', 0));
144 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
147 // Without this setting it seems as if some webservers send compressed content
148 // This seems to confuse curl so that it shows this uncompressed.
149 /// @todo We could possibly set this value to "gzip" or something similar
150 curl_setopt($ch, CURLOPT_ENCODING, '');
152 if (x($opts, 'headers')) {
153 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
156 if (x($opts, 'nobody')) {
157 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
160 if (x($opts, 'timeout')) {
161 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
163 $curl_time = Config::get('system', 'curl_timeout', 60);
164 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
167 // by default we will allow self-signed certs
168 // but you can override this
170 $check_cert = Config::get('system', 'verifyssl');
171 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
174 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
177 $proxy = Config::get('system', 'proxy');
179 if (strlen($proxy)) {
180 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
181 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
182 $proxyuser = @Config::get('system', 'proxyuser');
184 if (strlen($proxyuser)) {
185 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
189 if (Config::get('system', 'ipv4_resolve', false)) {
190 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
194 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
197 // don't let curl abort the entire application
198 // if it throws any errors.
200 $s = @curl_exec($ch);
201 $curl_info = @curl_getinfo($ch);
203 // Special treatment for HTTP Code 416
204 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
205 if (($curl_info['http_code'] == 416) && ($range > 0)) {
206 @curl_setopt($ch, CURLOPT_RANGE, '');
207 $s = @curl_exec($ch);
208 $curl_info = @curl_getinfo($ch);
211 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
213 if ($curlResponse->isRedirectUrl()) {
215 logger('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
217 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
222 $a->saveTimestamp($stamp1, 'network');
224 return $curlResponse;
228 * @brief Send POST request to $url
230 * @param string $url URL to post
231 * @param mixed $params array of POST variables
232 * @param string $headers HTTP headers
233 * @param integer $redirects Recursion counter for internal use - default = 0
234 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
236 * @return CurlResult The content
238 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
240 $stamp1 = microtime(true);
242 if (self::isUrlBlocked($url)) {
243 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
244 return CurlResult::createErrorCurl($url);
248 $ch = curl_init($url);
250 if (($redirects > 8) || (!$ch)) {
251 return CurlResult::createErrorCurl($url);
254 logger('post_url: start ' . $url, LOGGER_DATA);
256 curl_setopt($ch, CURLOPT_HEADER, true);
257 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
258 curl_setopt($ch, CURLOPT_POST, 1);
259 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
260 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
262 if (Config::get('system', 'ipv4_resolve', false)) {
263 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
266 if (intval($timeout)) {
267 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
269 $curl_time = Config::get('system', 'curl_timeout', 60);
270 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
273 if (defined('LIGHTTPD')) {
274 if (!is_array($headers)) {
275 $headers = ['Expect:'];
277 if (!in_array('Expect:', $headers)) {
278 array_push($headers, 'Expect:');
284 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
287 $check_cert = Config::get('system', 'verifyssl');
288 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
291 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
294 $proxy = Config::get('system', 'proxy');
296 if (strlen($proxy)) {
297 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
298 curl_setopt($ch, CURLOPT_PROXY, $proxy);
299 $proxyuser = Config::get('system', 'proxyuser');
300 if (strlen($proxyuser)) {
301 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
305 // don't let curl abort the entire application
306 // if it throws any errors.
308 $s = @curl_exec($ch);
311 $curl_info = curl_getinfo($ch);
313 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
315 if ($curlResponse->isRedirectUrl()) {
317 logger('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
319 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
324 $a->saveTimestamp($stamp1, 'network');
326 logger('post_url: end ' . $url, LOGGER_DATA);
328 return $curlResponse;
332 * @brief Check URL to see if it's real
334 * Take a URL from the wild, prepend http:// if necessary
335 * and check DNS to see if it's real (or check if is a valid IP address)
337 * @param string $url The URL to be validated
338 * @return string|boolean The actual working URL, false else
340 public static function isUrlValid($url)
342 if (Config::get('system', 'disable_url_validation')) {
346 // no naked subdomains (allow localhost for tests)
347 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
351 if (substr($url, 0, 4) != 'http') {
352 $url = 'http://' . $url;
355 /// @TODO Really suppress function outcomes? Why not find them + debug them?
356 $h = @parse_url($url);
358 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
366 * @brief Checks that email is an actual resolvable internet address
368 * @param string $addr The email address
369 * @return boolean True if it's a valid email address, false if it's not
371 public static function isEmailDomainValid($addr)
373 if (Config::get('system', 'disable_email_validation')) {
377 if (! strpos($addr, '@')) {
381 $h = substr($addr, strpos($addr, '@') + 1);
383 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
384 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
387 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
394 * @brief Check if URL is allowed
396 * Check $url against our list of allowed sites,
397 * wildcards allowed. If allowed_sites is unset return true;
399 * @param string $url URL which get tested
400 * @return boolean True if url is allowed otherwise return false
402 public static function isUrlAllowed($url)
404 $h = @parse_url($url);
410 $str_allowed = Config::get('system', 'allowed_sites');
411 if (! $str_allowed) {
417 $host = strtolower($h['host']);
419 // always allow our own site
420 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
424 $fnmatch = function_exists('fnmatch');
425 $allowed = explode(',', $str_allowed);
427 if (count($allowed)) {
428 foreach ($allowed as $a) {
429 $pat = strtolower(trim($a));
430 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
440 * Checks if the provided url domain is on the domain blocklist.
441 * Returns true if it is or malformed URL, false if not.
443 * @param string $url The url to check the domain from
447 public static function isUrlBlocked($url)
449 $host = @parse_url($url, PHP_URL_HOST);
454 $domain_blocklist = Config::get('system', 'blocklist', []);
455 if (!$domain_blocklist) {
459 foreach ($domain_blocklist as $domain_block) {
460 if (strcasecmp($domain_block['domain'], $host) === 0) {
469 * @brief Check if email address is allowed to register here.
471 * Compare against our list (wildcards allowed).
473 * @param string $email email address
474 * @return boolean False if not allowed, true if allowed
475 * or if allowed list is not configured
477 public static function isEmailDomainAllowed($email)
479 $domain = strtolower(substr($email, strpos($email, '@') + 1));
484 $str_allowed = Config::get('system', 'allowed_email', '');
485 if (!x($str_allowed)) {
489 $allowed = explode(',', $str_allowed);
491 return self::isDomainAllowed($domain, $allowed);
495 * Checks for the existence of a domain in a domain list
497 * @brief Checks for the existence of a domain in a domain list
498 * @param string $domain
499 * @param array $domain_list
502 public static function isDomainAllowed($domain, array $domain_list)
506 foreach ($domain_list as $item) {
507 $pat = strtolower(trim($item));
508 if (fnmatch($pat, $domain) || ($pat == $domain)) {
517 public static function lookupAvatarByEmail($email)
519 $avatar['size'] = 175;
520 $avatar['email'] = $email;
522 $avatar['success'] = false;
524 Addon::callHooks('avatar_lookup', $avatar);
526 if (! $avatar['success']) {
527 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
530 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
531 return $avatar['url'];
535 * @brief Remove Google Analytics and other tracking platforms params from URL
537 * @param string $url Any user-submitted URL that may contain tracking params
538 * @return string The same URL stripped of tracking parameters
540 public static function stripTrackingQueryParams($url)
542 $urldata = parse_url($url);
543 if (!empty($urldata["query"])) {
544 $query = $urldata["query"];
545 parse_str($query, $querydata);
547 if (is_array($querydata)) {
548 foreach ($querydata as $param => $value) {
552 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
553 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
554 "fb_action_ids", "fb_action_types", "fb_ref",
556 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
559 $pair = $param . "=" . urlencode($value);
560 $url = str_replace($pair, "", $url);
562 // Second try: if the url isn't encoded completely
563 $pair = $param . "=" . str_replace(" ", "+", $value);
564 $url = str_replace($pair, "", $url);
566 // Third try: Maybey the url isn't encoded at all
567 $pair = $param . "=" . $value;
568 $url = str_replace($pair, "", $url);
570 $url = str_replace(["?&", "&&"], ["?", ""], $url);
575 if (substr($url, -1, 1) == "?") {
576 $url = substr($url, 0, -1);
584 * @brief Returns the original URL of the provided URL
586 * This function strips tracking query params and follows redirections, either
587 * through HTTP code or meta refresh tags. Stops after 10 redirections.
589 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
591 * @see ParseUrl::getSiteinfo
593 * @param string $url A user-submitted URL
594 * @param int $depth The current redirection recursion level (internal)
595 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
596 * @return string A canonical URL
598 public static function finalUrl($url, $depth = 1, $fetchbody = false)
602 $url = self::stripTrackingQueryParams($url);
608 $url = trim($url, "'");
610 $stamp1 = microtime(true);
613 curl_setopt($ch, CURLOPT_URL, $url);
614 curl_setopt($ch, CURLOPT_HEADER, 1);
615 curl_setopt($ch, CURLOPT_NOBODY, 1);
616 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
617 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
618 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
621 $curl_info = @curl_getinfo($ch);
622 $http_code = $curl_info['http_code'];
625 $a->saveTimestamp($stamp1, "network");
627 if ($http_code == 0) {
631 if (in_array($http_code, ['301', '302'])) {
632 if (!empty($curl_info['redirect_url'])) {
633 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
634 } elseif (!empty($curl_info['location'])) {
635 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
639 // Check for redirects in the meta elements of the body if there are no redirects in the header.
641 return(self::finalUrl($url, ++$depth, true));
644 // if the file is too large then exit
645 if ($curl_info["download_content_length"] > 1000000) {
649 // if it isn't a HTML file then exit
650 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
654 $stamp1 = microtime(true);
657 curl_setopt($ch, CURLOPT_URL, $url);
658 curl_setopt($ch, CURLOPT_HEADER, 0);
659 curl_setopt($ch, CURLOPT_NOBODY, 0);
660 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
661 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
662 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
664 $body = curl_exec($ch);
667 $a->saveTimestamp($stamp1, "network");
669 if (trim($body) == "") {
673 // Check for redirect in meta elements
674 $doc = new DOMDocument();
675 @$doc->loadHTML($body);
677 $xpath = new DomXPath($doc);
679 $list = $xpath->query("//meta[@content]");
680 foreach ($list as $node) {
682 if ($node->attributes->length) {
683 foreach ($node->attributes as $attribute) {
684 $attr[$attribute->name] = $attribute->value;
688 if (@$attr["http-equiv"] == 'refresh') {
689 $path = $attr["content"];
690 $pathinfo = explode(";", $path);
691 foreach ($pathinfo as $value) {
692 if (substr(strtolower($value), 0, 4) == "url=") {
693 return self::finalUrl(substr($value, 4), ++$depth);
703 * @brief Find the matching part between two url
705 * @param string $url1
706 * @param string $url2
707 * @return string The matching part
709 public static function getUrlMatch($url1, $url2)
711 if (($url1 == "") || ($url2 == "")) {
715 $url1 = normalise_link($url1);
716 $url2 = normalise_link($url2);
718 $parts1 = parse_url($url1);
719 $parts2 = parse_url($url2);
721 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
725 if (empty($parts1["scheme"])) {
726 $parts1["scheme"] = '';
728 if (empty($parts2["scheme"])) {
729 $parts2["scheme"] = '';
732 if ($parts1["scheme"] != $parts2["scheme"]) {
736 if (empty($parts1["host"])) {
737 $parts1["host"] = '';
739 if (empty($parts2["host"])) {
740 $parts2["host"] = '';
743 if ($parts1["host"] != $parts2["host"]) {
747 if (empty($parts1["port"])) {
748 $parts1["port"] = '';
750 if (empty($parts2["port"])) {
751 $parts2["port"] = '';
754 if ($parts1["port"] != $parts2["port"]) {
758 $match = $parts1["scheme"]."://".$parts1["host"];
760 if ($parts1["port"]) {
761 $match .= ":".$parts1["port"];
764 if (empty($parts1["path"])) {
765 $parts1["path"] = '';
767 if (empty($parts2["path"])) {
768 $parts2["path"] = '';
771 $pathparts1 = explode("/", $parts1["path"]);
772 $pathparts2 = explode("/", $parts2["path"]);
777 $path1 = defaults($pathparts1, $i, '');
778 $path2 = defaults($pathparts2, $i, '');
780 if ($path1 == $path2) {
783 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
787 return normalise_link($match);
791 * @brief Glue url parts together
793 * @param array $parsed URL parts
795 * @return string The glued URL
797 public static function unparseURL($parsed)
799 $get = function ($key) use ($parsed) {
800 return isset($parsed[$key]) ? $parsed[$key] : null;
803 $pass = $get('pass');
804 $user = $get('user');
805 $userinfo = $pass !== null ? "$user:$pass" : $user;
806 $port = $get('port');
807 $scheme = $get('scheme');
808 $query = $get('query');
809 $fragment = $get('fragment');
810 $authority = ($userinfo !== null ? $userinfo."@" : '') .
812 ($port ? ":$port" : '');
814 return (strlen($scheme) ? $scheme.":" : '') .
815 (strlen($authority) ? "//".$authority : '') .
817 (strlen($query) ? "?".$query : '') .
818 (strlen($fragment) ? "#".$fragment : '');