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
89 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
91 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
93 $stamp1 = microtime(true);
97 $parts = parse_url($url);
98 $path_parts = explode('/', defaults($parts, 'path', ''));
99 foreach ($path_parts as $part) {
100 if (strlen($part) <> mb_strlen($part)) {
101 $parts2[] = rawurlencode($part);
106 $parts['path'] = implode('/', $parts2);
107 $url = self::unparseURL($parts);
109 if (self::isUrlBlocked($url)) {
110 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
111 return CurlResult::createErrorCurl($url);
114 $ch = @curl_init($url);
116 if (($redirects > 8) || (!$ch)) {
117 return CurlResult::createErrorCurl($url);
120 @curl_setopt($ch, CURLOPT_HEADER, true);
122 if (x($opts, "cookiejar")) {
123 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
124 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
127 // These settings aren't needed. We're following the location already.
128 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
129 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
131 if (x($opts, 'accept_content')) {
135 ['Accept: ' . $opts['accept_content']]
139 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
140 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
142 $range = intval(Config::get('system', 'curl_range_bytes', 0));
145 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
148 // Without this setting it seems as if some webservers send compressed content
149 // This seems to confuse curl so that it shows this uncompressed.
150 /// @todo We could possibly set this value to "gzip" or something similar
151 curl_setopt($ch, CURLOPT_ENCODING, '');
153 if (x($opts, 'headers')) {
154 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
157 if (x($opts, 'nobody')) {
158 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
161 if (x($opts, 'timeout')) {
162 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
164 $curl_time = Config::get('system', 'curl_timeout', 60);
165 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
168 // by default we will allow self-signed certs
169 // but you can override this
171 $check_cert = Config::get('system', 'verifyssl');
172 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
175 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
178 $proxy = Config::get('system', 'proxy');
180 if (strlen($proxy)) {
181 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
182 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
183 $proxyuser = @Config::get('system', 'proxyuser');
185 if (strlen($proxyuser)) {
186 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
190 if (Config::get('system', 'ipv4_resolve', false)) {
191 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
195 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
198 // don't let curl abort the entire application
199 // if it throws any errors.
201 $s = @curl_exec($ch);
202 $curl_info = @curl_getinfo($ch);
204 // Special treatment for HTTP Code 416
205 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
206 if (($curl_info['http_code'] == 416) && ($range > 0)) {
207 @curl_setopt($ch, CURLOPT_RANGE, '');
208 $s = @curl_exec($ch);
209 $curl_info = @curl_getinfo($ch);
212 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
214 if ($curlResponse->isRedirectUrl()) {
216 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
218 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
223 $a->saveTimestamp($stamp1, 'network');
225 return $curlResponse;
229 * @brief Send POST request to $url
231 * @param string $url URL to post
232 * @param mixed $params array of POST variables
233 * @param string $headers HTTP headers
234 * @param integer $redirects Recursion counter for internal use - default = 0
235 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
237 * @return CurlResult The content
239 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
241 $stamp1 = microtime(true);
243 if (self::isUrlBlocked($url)) {
244 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
245 return CurlResult::createErrorCurl($url);
249 $ch = curl_init($url);
251 if (($redirects > 8) || (!$ch)) {
252 return CurlResult::createErrorCurl($url);
255 Logger::log('post_url: start ' . $url, Logger::DATA);
257 curl_setopt($ch, CURLOPT_HEADER, true);
258 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
259 curl_setopt($ch, CURLOPT_POST, 1);
260 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
261 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
263 if (Config::get('system', 'ipv4_resolve', false)) {
264 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
267 if (intval($timeout)) {
268 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
270 $curl_time = Config::get('system', 'curl_timeout', 60);
271 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
274 if (defined('LIGHTTPD')) {
275 if (!is_array($headers)) {
276 $headers = ['Expect:'];
278 if (!in_array('Expect:', $headers)) {
279 array_push($headers, 'Expect:');
285 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
288 $check_cert = Config::get('system', 'verifyssl');
289 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
292 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
295 $proxy = Config::get('system', 'proxy');
297 if (strlen($proxy)) {
298 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
299 curl_setopt($ch, CURLOPT_PROXY, $proxy);
300 $proxyuser = Config::get('system', 'proxyuser');
301 if (strlen($proxyuser)) {
302 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
306 // don't let curl abort the entire application
307 // if it throws any errors.
309 $s = @curl_exec($ch);
312 $curl_info = curl_getinfo($ch);
314 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
316 if ($curlResponse->isRedirectUrl()) {
318 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
320 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
325 $a->saveTimestamp($stamp1, 'network');
327 Logger::log('post_url: end ' . $url, Logger::DATA);
329 return $curlResponse;
333 * @brief Check URL to see if it's real
335 * Take a URL from the wild, prepend http:// if necessary
336 * and check DNS to see if it's real (or check if is a valid IP address)
338 * @param string $url The URL to be validated
339 * @return string|boolean The actual working URL, false else
341 public static function isUrlValid($url)
343 if (Config::get('system', 'disable_url_validation')) {
347 // no naked subdomains (allow localhost for tests)
348 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
352 if (substr($url, 0, 4) != 'http') {
353 $url = 'http://' . $url;
356 /// @TODO Really suppress function outcomes? Why not find them + debug them?
357 $h = @parse_url($url);
359 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
367 * @brief Checks that email is an actual resolvable internet address
369 * @param string $addr The email address
370 * @return boolean True if it's a valid email address, false if it's not
372 public static function isEmailDomainValid($addr)
374 if (Config::get('system', 'disable_email_validation')) {
378 if (! strpos($addr, '@')) {
382 $h = substr($addr, strpos($addr, '@') + 1);
384 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
385 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
388 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
395 * @brief Check if URL is allowed
397 * Check $url against our list of allowed sites,
398 * wildcards allowed. If allowed_sites is unset return true;
400 * @param string $url URL which get tested
401 * @return boolean True if url is allowed otherwise return false
403 public static function isUrlAllowed($url)
405 $h = @parse_url($url);
411 $str_allowed = Config::get('system', 'allowed_sites');
412 if (! $str_allowed) {
418 $host = strtolower($h['host']);
420 // always allow our own site
421 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
425 $fnmatch = function_exists('fnmatch');
426 $allowed = explode(',', $str_allowed);
428 if (count($allowed)) {
429 foreach ($allowed as $a) {
430 $pat = strtolower(trim($a));
431 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
441 * Checks if the provided url domain is on the domain blocklist.
442 * Returns true if it is or malformed URL, false if not.
444 * @param string $url The url to check the domain from
448 public static function isUrlBlocked($url)
450 $host = @parse_url($url, PHP_URL_HOST);
455 $domain_blocklist = Config::get('system', 'blocklist', []);
456 if (!$domain_blocklist) {
460 foreach ($domain_blocklist as $domain_block) {
461 if (strcasecmp($domain_block['domain'], $host) === 0) {
470 * @brief Check if email address is allowed to register here.
472 * Compare against our list (wildcards allowed).
474 * @param string $email email address
475 * @return boolean False if not allowed, true if allowed
476 * or if allowed list is not configured
478 public static function isEmailDomainAllowed($email)
480 $domain = strtolower(substr($email, strpos($email, '@') + 1));
485 $str_allowed = Config::get('system', 'allowed_email', '');
486 if (!x($str_allowed)) {
490 $allowed = explode(',', $str_allowed);
492 return self::isDomainAllowed($domain, $allowed);
496 * Checks for the existence of a domain in a domain list
498 * @brief Checks for the existence of a domain in a domain list
499 * @param string $domain
500 * @param array $domain_list
503 public static function isDomainAllowed($domain, array $domain_list)
507 foreach ($domain_list as $item) {
508 $pat = strtolower(trim($item));
509 if (fnmatch($pat, $domain) || ($pat == $domain)) {
518 public static function lookupAvatarByEmail($email)
520 $avatar['size'] = 300;
521 $avatar['email'] = $email;
523 $avatar['success'] = false;
525 Addon::callHooks('avatar_lookup', $avatar);
527 if (! $avatar['success']) {
528 $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
531 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
532 return $avatar['url'];
536 * @brief Remove Google Analytics and other tracking platforms params from URL
538 * @param string $url Any user-submitted URL that may contain tracking params
539 * @return string The same URL stripped of tracking parameters
541 public static function stripTrackingQueryParams($url)
543 $urldata = parse_url($url);
544 if (!empty($urldata["query"])) {
545 $query = $urldata["query"];
546 parse_str($query, $querydata);
548 if (is_array($querydata)) {
549 foreach ($querydata as $param => $value) {
553 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
554 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
555 "fb_action_ids", "fb_action_types", "fb_ref",
557 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
560 $pair = $param . "=" . urlencode($value);
561 $url = str_replace($pair, "", $url);
563 // Second try: if the url isn't encoded completely
564 $pair = $param . "=" . str_replace(" ", "+", $value);
565 $url = str_replace($pair, "", $url);
567 // Third try: Maybey the url isn't encoded at all
568 $pair = $param . "=" . $value;
569 $url = str_replace($pair, "", $url);
571 $url = str_replace(["?&", "&&"], ["?", ""], $url);
576 if (substr($url, -1, 1) == "?") {
577 $url = substr($url, 0, -1);
585 * @brief Returns the original URL of the provided URL
587 * This function strips tracking query params and follows redirections, either
588 * through HTTP code or meta refresh tags. Stops after 10 redirections.
590 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
592 * @see ParseUrl::getSiteinfo
594 * @param string $url A user-submitted URL
595 * @param int $depth The current redirection recursion level (internal)
596 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
597 * @return string A canonical URL
599 public static function finalUrl($url, $depth = 1, $fetchbody = false)
603 $url = self::stripTrackingQueryParams($url);
609 $url = trim($url, "'");
611 $stamp1 = microtime(true);
614 curl_setopt($ch, CURLOPT_URL, $url);
615 curl_setopt($ch, CURLOPT_HEADER, 1);
616 curl_setopt($ch, CURLOPT_NOBODY, 1);
617 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
618 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
619 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
622 $curl_info = @curl_getinfo($ch);
623 $http_code = $curl_info['http_code'];
626 $a->saveTimestamp($stamp1, "network");
628 if ($http_code == 0) {
632 if (in_array($http_code, ['301', '302'])) {
633 if (!empty($curl_info['redirect_url'])) {
634 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
635 } elseif (!empty($curl_info['location'])) {
636 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
640 // Check for redirects in the meta elements of the body if there are no redirects in the header.
642 return(self::finalUrl($url, ++$depth, true));
645 // if the file is too large then exit
646 if ($curl_info["download_content_length"] > 1000000) {
650 // if it isn't a HTML file then exit
651 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
655 $stamp1 = microtime(true);
658 curl_setopt($ch, CURLOPT_URL, $url);
659 curl_setopt($ch, CURLOPT_HEADER, 0);
660 curl_setopt($ch, CURLOPT_NOBODY, 0);
661 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
662 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
663 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
665 $body = curl_exec($ch);
668 $a->saveTimestamp($stamp1, "network");
670 if (trim($body) == "") {
674 // Check for redirect in meta elements
675 $doc = new DOMDocument();
676 @$doc->loadHTML($body);
678 $xpath = new DomXPath($doc);
680 $list = $xpath->query("//meta[@content]");
681 foreach ($list as $node) {
683 if ($node->attributes->length) {
684 foreach ($node->attributes as $attribute) {
685 $attr[$attribute->name] = $attribute->value;
689 if (@$attr["http-equiv"] == 'refresh') {
690 $path = $attr["content"];
691 $pathinfo = explode(";", $path);
692 foreach ($pathinfo as $value) {
693 if (substr(strtolower($value), 0, 4) == "url=") {
694 return self::finalUrl(substr($value, 4), ++$depth);
704 * @brief Find the matching part between two url
706 * @param string $url1
707 * @param string $url2
708 * @return string The matching part
710 public static function getUrlMatch($url1, $url2)
712 if (($url1 == "") || ($url2 == "")) {
716 $url1 = normalise_link($url1);
717 $url2 = normalise_link($url2);
719 $parts1 = parse_url($url1);
720 $parts2 = parse_url($url2);
722 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
726 if (empty($parts1["scheme"])) {
727 $parts1["scheme"] = '';
729 if (empty($parts2["scheme"])) {
730 $parts2["scheme"] = '';
733 if ($parts1["scheme"] != $parts2["scheme"]) {
737 if (empty($parts1["host"])) {
738 $parts1["host"] = '';
740 if (empty($parts2["host"])) {
741 $parts2["host"] = '';
744 if ($parts1["host"] != $parts2["host"]) {
748 if (empty($parts1["port"])) {
749 $parts1["port"] = '';
751 if (empty($parts2["port"])) {
752 $parts2["port"] = '';
755 if ($parts1["port"] != $parts2["port"]) {
759 $match = $parts1["scheme"]."://".$parts1["host"];
761 if ($parts1["port"]) {
762 $match .= ":".$parts1["port"];
765 if (empty($parts1["path"])) {
766 $parts1["path"] = '';
768 if (empty($parts2["path"])) {
769 $parts2["path"] = '';
772 $pathparts1 = explode("/", $parts1["path"]);
773 $pathparts2 = explode("/", $parts2["path"]);
778 $path1 = defaults($pathparts1, $i, '');
779 $path2 = defaults($pathparts2, $i, '');
781 if ($path1 == $path2) {
784 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
788 return normalise_link($match);
792 * @brief Glue url parts together
794 * @param array $parsed URL parts
796 * @return string The glued URL
798 public static function unparseURL($parsed)
800 $get = function ($key) use ($parsed) {
801 return isset($parsed[$key]) ? $parsed[$key] : null;
804 $pass = $get('pass');
805 $user = $get('user');
806 $userinfo = $pass !== null ? "$user:$pass" : $user;
807 $port = $get('port');
808 $scheme = $get('scheme');
809 $query = $get('query');
810 $fragment = $get('fragment');
811 $authority = ($userinfo !== null ? $userinfo."@" : '') .
813 ($port ? ":$port" : '');
815 return (strlen($scheme) ? $scheme.":" : '') .
816 (strlen($authority) ? "//".$authority : '') .
818 (strlen($query) ? "?".$query : '') .
819 (strlen($fragment) ? "#".$fragment : '');