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\Curl;
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 Curl 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 Curl::createErrorCurl($url);
113 $ch = @curl_init($url);
115 if (($redirects > 8) || (!$ch)) {
116 return Curl::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 if (curl_errno($ch) !== CURLE_OK) {
212 logger('error fetching ' . $url . ': ' . curl_error($ch), LOGGER_INFO);
215 $curlResponse = new Curl($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
217 if ($curlResponse->isRedirectUrl()) {
219 logger('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
221 return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
226 $a->saveTimestamp($stamp1, 'network');
228 return $curlResponse;
232 * @brief Send POST request to $url
234 * @param string $url URL to post
235 * @param mixed $params array of POST variables
236 * @param string $headers HTTP headers
237 * @param integer $redirects Recursion counter for internal use - default = 0
238 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
240 * @return Curl The content
242 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
244 $stamp1 = microtime(true);
246 if (self::isUrlBlocked($url)) {
247 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
248 return Curl::createErrorCurl($url);
252 $ch = curl_init($url);
254 if (($redirects > 8) || (!$ch)) {
255 return Curl::createErrorCurl($url);
258 logger('post_url: start ' . $url, LOGGER_DATA);
260 curl_setopt($ch, CURLOPT_HEADER, true);
261 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
262 curl_setopt($ch, CURLOPT_POST, 1);
263 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
264 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
266 if (Config::get('system', 'ipv4_resolve', false)) {
267 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
270 if (intval($timeout)) {
271 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
273 $curl_time = Config::get('system', 'curl_timeout', 60);
274 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
277 if (defined('LIGHTTPD')) {
278 if (!is_array($headers)) {
279 $headers = ['Expect:'];
281 if (!in_array('Expect:', $headers)) {
282 array_push($headers, 'Expect:');
288 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
291 $check_cert = Config::get('system', 'verifyssl');
292 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
295 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
298 $proxy = Config::get('system', 'proxy');
300 if (strlen($proxy)) {
301 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
302 curl_setopt($ch, CURLOPT_PROXY, $proxy);
303 $proxyuser = Config::get('system', 'proxyuser');
304 if (strlen($proxyuser)) {
305 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
309 // don't let curl abort the entire application
310 // if it throws any errors.
312 $s = @curl_exec($ch);
315 $curl_info = curl_getinfo($ch);
317 $curlResponse = new Curl($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
319 if ($curlResponse->isRedirectUrl()) {
321 logger('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
323 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
328 $a->saveTimestamp($stamp1, 'network');
330 logger('post_url: end ' . $url, LOGGER_DATA);
332 return $curlResponse;
336 * @brief Check URL to see if it's real
338 * Take a URL from the wild, prepend http:// if necessary
339 * and check DNS to see if it's real (or check if is a valid IP address)
341 * @param string $url The URL to be validated
342 * @return string|boolean The actual working URL, false else
344 public static function isUrlValid($url)
346 if (Config::get('system', 'disable_url_validation')) {
350 // no naked subdomains (allow localhost for tests)
351 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
355 if (substr($url, 0, 4) != 'http') {
356 $url = 'http://' . $url;
359 /// @TODO Really suppress function outcomes? Why not find them + debug them?
360 $h = @parse_url($url);
362 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
370 * @brief Checks that email is an actual resolvable internet address
372 * @param string $addr The email address
373 * @return boolean True if it's a valid email address, false if it's not
375 public static function isEmailDomainValid($addr)
377 if (Config::get('system', 'disable_email_validation')) {
381 if (! strpos($addr, '@')) {
385 $h = substr($addr, strpos($addr, '@') + 1);
387 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
388 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
391 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
398 * @brief Check if URL is allowed
400 * Check $url against our list of allowed sites,
401 * wildcards allowed. If allowed_sites is unset return true;
403 * @param string $url URL which get tested
404 * @return boolean True if url is allowed otherwise return false
406 public static function isUrlAllowed($url)
408 $h = @parse_url($url);
414 $str_allowed = Config::get('system', 'allowed_sites');
415 if (! $str_allowed) {
421 $host = strtolower($h['host']);
423 // always allow our own site
424 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
428 $fnmatch = function_exists('fnmatch');
429 $allowed = explode(',', $str_allowed);
431 if (count($allowed)) {
432 foreach ($allowed as $a) {
433 $pat = strtolower(trim($a));
434 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
444 * Checks if the provided url domain is on the domain blocklist.
445 * Returns true if it is or malformed URL, false if not.
447 * @param string $url The url to check the domain from
451 public static function isUrlBlocked($url)
453 $host = @parse_url($url, PHP_URL_HOST);
458 $domain_blocklist = Config::get('system', 'blocklist', []);
459 if (!$domain_blocklist) {
463 foreach ($domain_blocklist as $domain_block) {
464 if (strcasecmp($domain_block['domain'], $host) === 0) {
473 * @brief Check if email address is allowed to register here.
475 * Compare against our list (wildcards allowed).
477 * @param string $email email address
478 * @return boolean False if not allowed, true if allowed
479 * or if allowed list is not configured
481 public static function isEmailDomainAllowed($email)
483 $domain = strtolower(substr($email, strpos($email, '@') + 1));
488 $str_allowed = Config::get('system', 'allowed_email', '');
489 if (!x($str_allowed)) {
493 $allowed = explode(',', $str_allowed);
495 return self::isDomainAllowed($domain, $allowed);
499 * Checks for the existence of a domain in a domain list
501 * @brief Checks for the existence of a domain in a domain list
502 * @param string $domain
503 * @param array $domain_list
506 public static function isDomainAllowed($domain, array $domain_list)
510 foreach ($domain_list as $item) {
511 $pat = strtolower(trim($item));
512 if (fnmatch($pat, $domain) || ($pat == $domain)) {
521 public static function lookupAvatarByEmail($email)
523 $avatar['size'] = 175;
524 $avatar['email'] = $email;
526 $avatar['success'] = false;
528 Addon::callHooks('avatar_lookup', $avatar);
530 if (! $avatar['success']) {
531 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
534 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
535 return $avatar['url'];
539 * @brief Remove Google Analytics and other tracking platforms params from URL
541 * @param string $url Any user-submitted URL that may contain tracking params
542 * @return string The same URL stripped of tracking parameters
544 public static function stripTrackingQueryParams($url)
546 $urldata = parse_url($url);
547 if (!empty($urldata["query"])) {
548 $query = $urldata["query"];
549 parse_str($query, $querydata);
551 if (is_array($querydata)) {
552 foreach ($querydata as $param => $value) {
556 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
557 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
558 "fb_action_ids", "fb_action_types", "fb_ref",
560 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
563 $pair = $param . "=" . urlencode($value);
564 $url = str_replace($pair, "", $url);
566 // Second try: if the url isn't encoded completely
567 $pair = $param . "=" . str_replace(" ", "+", $value);
568 $url = str_replace($pair, "", $url);
570 // Third try: Maybey the url isn't encoded at all
571 $pair = $param . "=" . $value;
572 $url = str_replace($pair, "", $url);
574 $url = str_replace(["?&", "&&"], ["?", ""], $url);
579 if (substr($url, -1, 1) == "?") {
580 $url = substr($url, 0, -1);
588 * @brief Returns the original URL of the provided URL
590 * This function strips tracking query params and follows redirections, either
591 * through HTTP code or meta refresh tags. Stops after 10 redirections.
593 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
595 * @see ParseUrl::getSiteinfo
597 * @param string $url A user-submitted URL
598 * @param int $depth The current redirection recursion level (internal)
599 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
600 * @return string A canonical URL
602 public static function finalUrl($url, $depth = 1, $fetchbody = false)
606 $url = self::stripTrackingQueryParams($url);
612 $url = trim($url, "'");
614 $stamp1 = microtime(true);
617 curl_setopt($ch, CURLOPT_URL, $url);
618 curl_setopt($ch, CURLOPT_HEADER, 1);
619 curl_setopt($ch, CURLOPT_NOBODY, 1);
620 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
621 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
622 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
625 $curl_info = @curl_getinfo($ch);
626 $http_code = $curl_info['http_code'];
629 $a->saveTimestamp($stamp1, "network");
631 if ($http_code == 0) {
635 if (in_array($http_code, ['301', '302'])) {
636 if (!empty($curl_info['redirect_url'])) {
637 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
638 } elseif (!empty($curl_info['location'])) {
639 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
643 // Check for redirects in the meta elements of the body if there are no redirects in the header.
645 return(self::finalUrl($url, ++$depth, true));
648 // if the file is too large then exit
649 if ($curl_info["download_content_length"] > 1000000) {
653 // if it isn't a HTML file then exit
654 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
658 $stamp1 = microtime(true);
661 curl_setopt($ch, CURLOPT_URL, $url);
662 curl_setopt($ch, CURLOPT_HEADER, 0);
663 curl_setopt($ch, CURLOPT_NOBODY, 0);
664 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
665 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
666 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
668 $body = curl_exec($ch);
671 $a->saveTimestamp($stamp1, "network");
673 if (trim($body) == "") {
677 // Check for redirect in meta elements
678 $doc = new DOMDocument();
679 @$doc->loadHTML($body);
681 $xpath = new DomXPath($doc);
683 $list = $xpath->query("//meta[@content]");
684 foreach ($list as $node) {
686 if ($node->attributes->length) {
687 foreach ($node->attributes as $attribute) {
688 $attr[$attribute->name] = $attribute->value;
692 if (@$attr["http-equiv"] == 'refresh') {
693 $path = $attr["content"];
694 $pathinfo = explode(";", $path);
695 foreach ($pathinfo as $value) {
696 if (substr(strtolower($value), 0, 4) == "url=") {
697 return self::finalUrl(substr($value, 4), ++$depth);
707 * @brief Find the matching part between two url
709 * @param string $url1
710 * @param string $url2
711 * @return string The matching part
713 public static function getUrlMatch($url1, $url2)
715 if (($url1 == "") || ($url2 == "")) {
719 $url1 = normalise_link($url1);
720 $url2 = normalise_link($url2);
722 $parts1 = parse_url($url1);
723 $parts2 = parse_url($url2);
725 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
729 if (empty($parts1["scheme"])) {
730 $parts1["scheme"] = '';
732 if (empty($parts2["scheme"])) {
733 $parts2["scheme"] = '';
736 if ($parts1["scheme"] != $parts2["scheme"]) {
740 if (empty($parts1["host"])) {
741 $parts1["host"] = '';
743 if (empty($parts2["host"])) {
744 $parts2["host"] = '';
747 if ($parts1["host"] != $parts2["host"]) {
751 if (empty($parts1["port"])) {
752 $parts1["port"] = '';
754 if (empty($parts2["port"])) {
755 $parts2["port"] = '';
758 if ($parts1["port"] != $parts2["port"]) {
762 $match = $parts1["scheme"]."://".$parts1["host"];
764 if ($parts1["port"]) {
765 $match .= ":".$parts1["port"];
768 if (empty($parts1["path"])) {
769 $parts1["path"] = '';
771 if (empty($parts2["path"])) {
772 $parts2["path"] = '';
775 $pathparts1 = explode("/", $parts1["path"]);
776 $pathparts2 = explode("/", $parts2["path"]);
781 $path1 = defaults($pathparts1, $i, '');
782 $path2 = defaults($pathparts2, $i, '');
784 if ($path1 == $path2) {
787 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
791 return normalise_link($match);
795 * @brief Glue url parts together
797 * @param array $parsed URL parts
799 * @return string The glued URL
801 public static function unparseURL($parsed)
803 $get = function ($key) use ($parsed) {
804 return isset($parsed[$key]) ? $parsed[$key] : null;
807 $pass = $get('pass');
808 $user = $get('user');
809 $userinfo = $pass !== null ? "$user:$pass" : $user;
810 $port = $get('port');
811 $scheme = $get('scheme');
812 $query = $get('query');
813 $fragment = $get('fragment');
814 $authority = ($userinfo !== null ? $userinfo."@" : '') .
816 ($port ? ":$port" : '');
818 return (strlen($scheme) ? $scheme.":" : '') .
819 (strlen($authority) ? "//".$authority : '') .
821 (strlen($query) ? "?".$query : '') .
822 (strlen($fragment) ? "#".$fragment : '');