3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
27 use Friendica\Model\Contact;
28 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
29 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
30 use Friendica\Network\HTTPException\NotModifiedException;
31 use GuzzleHttp\Psr7\Uri;
37 * Return raw post data from a post request
39 * @return string post data
41 public static function postdata()
43 return file_get_contents('php://input');
47 * Check URL to see if it's real
49 * Take a URL from the wild, prepend http:// if necessary
50 * and check DNS to see if it's real (or check if is a valid IP address)
52 * @param string $url The URL to be validated
53 * @return string|boolean The actual working URL, false else
54 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 public static function isUrlValid(string $url)
58 if (DI::config()->get('system', 'disable_url_validation')) {
62 // no naked subdomains (allow localhost for tests)
63 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
67 if (substr($url, 0, 4) != 'http') {
68 $url = 'http://' . $url;
71 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
72 $host = parse_url($url, PHP_URL_HOST);
74 if (empty($host) || !(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
78 if (in_array(parse_url($url, PHP_URL_SCHEME), ['https', 'http'])) {
79 $options = [HttpClientOptions::VERIFY => true, HttpClientOptions::TIMEOUT => $xrd_timeout];
80 $curlResult = DI::httpClient()->head($url, $options);
82 // Workaround for systems that can't handle a HEAD request. Don't retry on timeouts.
83 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() >= 400) && !in_array($curlResult->getReturnCode(), [408, 504])) {
84 $curlResult = DI::httpClient()->get($url, HttpClientAccept::DEFAULT, $options);
87 if (!$curlResult->isSuccess()) {
88 Logger::notice('Url not reachable', ['host' => $host, 'url' => $url]);
90 } elseif ($curlResult->isRedirectUrl()) {
91 $url = $curlResult->getRedirectUrl();
99 * Checks that email is an actual resolvable internet address
101 * @param string $addr The email address
102 * @return boolean True if it's a valid email address, false if it's not
104 public static function isEmailDomainValid(string $addr)
106 if (DI::config()->get('system', 'disable_email_validation')) {
110 if (! strpos($addr, '@')) {
114 $h = substr($addr, strpos($addr, '@') + 1);
116 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
117 if ($h && (@dns_get_record($h, DNS_A + DNS_AAAA + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
120 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
127 * Check if URL is allowed
129 * Check $url against our list of allowed sites,
130 * wildcards allowed. If allowed_sites is unset return true;
132 * @param string $url URL which get tested
133 * @return boolean True if url is allowed otherwise return false
135 public static function isUrlAllowed(string $url)
137 $h = @parse_url($url);
143 $str_allowed = DI::config()->get('system', 'allowed_sites');
144 if (! $str_allowed) {
150 $host = strtolower($h['host']);
152 // always allow our own site
153 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
157 $fnmatch = function_exists('fnmatch');
158 $allowed = explode(',', $str_allowed);
160 if (count($allowed)) {
161 foreach ($allowed as $a) {
162 $pat = strtolower(trim($a));
163 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
173 * Checks if the provided url domain is on the domain blocklist.
174 * Returns true if it is or malformed URL, false if not.
176 * @param string $url The url to check the domain from
180 public static function isUrlBlocked(string $url)
182 $host = @parse_url($url, PHP_URL_HOST);
187 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
188 if (!$domain_blocklist) {
192 foreach ($domain_blocklist as $domain_block) {
193 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
202 * Checks if the provided url is on the list of domains where redirects are blocked.
203 * Returns true if it is or malformed URL, false if not.
205 * @param string $url The url to check the domain from
209 public static function isRedirectBlocked(string $url)
211 $host = @parse_url($url, PHP_URL_HOST);
216 $no_redirect_list = DI::config()->get('system', 'no_redirect_list', []);
217 if (!$no_redirect_list) {
221 foreach ($no_redirect_list as $no_redirect) {
222 if (fnmatch(strtolower($no_redirect), strtolower($host))) {
231 * Check if email address is allowed to register here.
233 * Compare against our list (wildcards allowed).
235 * @param string $email email address
236 * @return boolean False if not allowed, true if allowed
237 * or if allowed list is not configured
238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
240 public static function isEmailDomainAllowed(string $email)
242 $domain = strtolower(substr($email, strpos($email, '@') + 1));
247 $str_allowed = DI::config()->get('system', 'allowed_email', '');
248 if (empty($str_allowed)) {
252 $allowed = explode(',', $str_allowed);
254 return self::isDomainAllowed($domain, $allowed);
258 * Checks for the existence of a domain in a domain list
260 * @param string $domain
261 * @param array $domain_list
264 public static function isDomainAllowed(string $domain, array $domain_list)
268 foreach ($domain_list as $item) {
269 $pat = strtolower(trim($item));
270 if (fnmatch($pat, $domain) || ($pat == $domain)) {
279 public static function lookupAvatarByEmail(string $email)
281 $avatar['size'] = 300;
282 $avatar['email'] = $email;
284 $avatar['success'] = false;
286 Hook::callAll('avatar_lookup', $avatar);
288 if (! $avatar['success']) {
289 $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
292 Logger::info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']);
293 return $avatar['url'];
297 * Remove Google Analytics and other tracking platforms params from URL
299 * @param string $url Any user-submitted URL that may contain tracking params
300 * @return string The same URL stripped of tracking parameters
302 public static function stripTrackingQueryParams(string $url)
304 $urldata = parse_url($url);
305 if (!empty($urldata["query"])) {
306 $query = $urldata["query"];
307 parse_str($query, $querydata);
309 if (is_array($querydata)) {
310 foreach ($querydata as $param => $value) {
314 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
315 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
316 "fb_action_ids", "fb_action_types", "fb_ref",
318 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
321 $pair = $param . "=" . urlencode($value);
322 $url = str_replace($pair, "", $url);
324 // Second try: if the url isn't encoded completely
325 $pair = $param . "=" . str_replace(" ", "+", $value);
326 $url = str_replace($pair, "", $url);
328 // Third try: Maybey the url isn't encoded at all
329 $pair = $param . "=" . $value;
330 $url = str_replace($pair, "", $url);
332 $url = str_replace(["?&", "&&"], ["?", ""], $url);
337 if (substr($url, -1, 1) == "?") {
338 $url = substr($url, 0, -1);
346 * Add a missing base path (scheme and host) to a given url
349 * @param string $basepath
352 public static function addBasePath(string $url, string $basepath)
354 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
358 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
359 'host' => parse_url($basepath, PHP_URL_HOST)];
361 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
362 return self::unparseURL($parts);
366 * Find the matching part between two url
368 * @param string $url1
369 * @param string $url2
370 * @return string The matching part
372 public static function getUrlMatch(string $url1, string $url2)
374 if (($url1 == "") || ($url2 == "")) {
378 $url1 = Strings::normaliseLink($url1);
379 $url2 = Strings::normaliseLink($url2);
381 $parts1 = parse_url($url1);
382 $parts2 = parse_url($url2);
384 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
388 if (empty($parts1["scheme"])) {
389 $parts1["scheme"] = '';
391 if (empty($parts2["scheme"])) {
392 $parts2["scheme"] = '';
395 if ($parts1["scheme"] != $parts2["scheme"]) {
399 if (empty($parts1["host"])) {
400 $parts1["host"] = '';
402 if (empty($parts2["host"])) {
403 $parts2["host"] = '';
406 if ($parts1["host"] != $parts2["host"]) {
410 if (empty($parts1["port"])) {
411 $parts1["port"] = '';
413 if (empty($parts2["port"])) {
414 $parts2["port"] = '';
417 if ($parts1["port"] != $parts2["port"]) {
421 $match = $parts1["scheme"]."://".$parts1["host"];
423 if ($parts1["port"]) {
424 $match .= ":".$parts1["port"];
427 if (empty($parts1["path"])) {
428 $parts1["path"] = '';
430 if (empty($parts2["path"])) {
431 $parts2["path"] = '';
434 $pathparts1 = explode("/", $parts1["path"]);
435 $pathparts2 = explode("/", $parts2["path"]);
440 $path1 = $pathparts1[$i] ?? '';
441 $path2 = $pathparts2[$i] ?? '';
443 if ($path1 == $path2) {
446 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
450 return Strings::normaliseLink($match);
454 * Glue url parts together
456 * @param array $parsed URL parts
458 * @return string The glued URL.
459 * @deprecated since version 2021.12, use GuzzleHttp\Psr7\Uri::fromParts($parts) instead
461 public static function unparseURL(array $parsed)
463 $get = function ($key) use ($parsed) {
464 return isset($parsed[$key]) ? $parsed[$key] : null;
467 $pass = $get('pass');
468 $user = $get('user');
469 $userinfo = $pass !== null ? "$user:$pass" : $user;
470 $port = $get('port');
471 $scheme = $get('scheme');
472 $query = $get('query');
473 $fragment = $get('fragment');
474 $authority = ($userinfo !== null ? $userinfo."@" : '') .
476 ($port ? ":$port" : '');
478 return (strlen($scheme) ? $scheme.":" : '') .
479 (strlen($authority) ? "//".$authority : '') .
481 (strlen($query) ? "?".$query : '') .
482 (strlen($fragment) ? "#".$fragment : '');
486 * Convert an URI to an IDN compatible URI
491 public static function convertToIdn(string $uri): string
493 $parts = parse_url($uri);
494 if (!empty($parts['scheme']) && !empty($parts['host'])) {
495 $parts['host'] = idn_to_ascii($parts['host']);
496 $uri = Uri::fromParts($parts);
498 $parts = explode('@', $uri);
499 if (count($parts) == 2) {
500 $uri = $parts[0] . '@' . idn_to_ascii($parts[1]);
502 $uri = idn_to_ascii($uri);
510 * Switch the scheme of an url between http and https
512 * @param string $url URL
514 * @return string switched URL
516 public static function switchScheme(string $url)
518 $scheme = parse_url($url, PHP_URL_SCHEME);
519 if (empty($scheme)) {
523 if ($scheme === 'http') {
524 $url = str_replace('http://', 'https://', $url);
525 } elseif ($scheme === 'https') {
526 $url = str_replace('https://', 'http://', $url);
533 * Adds query string parameters to the provided URI. Replace the value of existing keys.
535 * @param string $path
536 * @param array $additionalParams Associative array of parameters
539 public static function appendQueryParam(string $path, array $additionalParams)
541 $parsed = parse_url($path);
544 if (!empty($parsed['query'])) {
545 parse_str($parsed['query'], $params);
548 $params = array_merge($params, $additionalParams);
550 $parsed['query'] = http_build_query($params);
552 return self::unparseURL($parsed);
556 * Generates ETag and Last-Modified response headers and checks them against
557 * If-None-Match and If-Modified-Since request headers if present.
559 * Blocking function, sends 304 headers and exits if check passes.
561 * @param string $etag The page etag
562 * @param string $last_modified The page last modification UTC date
565 public static function checkEtagModified(string $etag, string $last_modified)
567 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
570 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
572 $if_none_match = filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH');
573 $if_modified_since = filter_input(INPUT_SERVER, 'HTTP_IF_MODIFIED_SINCE');
574 $flag_not_modified = null;
575 if ($if_none_match) {
577 preg_match('/^(?:W\/")?([^"]+)"?$/i', $etag, $result);
578 $etagTrimmed = $result[1];
579 // Lazy exact ETag match, could check weak/strong ETags
580 $flag_not_modified = $if_none_match == '*' || strpos($if_none_match, $etagTrimmed) !== false;
583 if ($if_modified_since && (!$if_none_match || $flag_not_modified)) {
584 // Lazy exact Last-Modified match, could check If-Modified-Since validity
585 $flag_not_modified = $if_modified_since == $last_modified;
588 header('Etag: ' . $etag);
589 header('Last-Modified: ' . $last_modified);
591 if ($flag_not_modified) {
592 throw new NotModifiedException();
597 * Check if the given URL is a local link
602 public static function isLocalLink(string $url)
604 return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false);
608 * Check if the given URL is a valid HTTP/HTTPS URL
613 public static function isValidHttpUrl(string $url)
615 $scheme = parse_url($url, PHP_URL_SCHEME);
616 return !empty($scheme) && in_array($scheme, ['http', 'https']) && parse_url($url, PHP_URL_HOST);