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\HTTPException\NotModifiedException;
29 use GuzzleHttp\Psr7\Uri;
35 * Return raw post data from a post request
37 * @return string post data
39 public static function postdata()
41 return file_get_contents('php://input');
45 * Check URL to see if it's real
47 * Take a URL from the wild, prepend http:// if necessary
48 * and check DNS to see if it's real (or check if is a valid IP address)
50 * @param string $url The URL to be validated
51 * @return string|boolean The actual working URL, false else
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 public static function isUrlValid(string $url)
56 if (DI::config()->get('system', 'disable_url_validation')) {
60 // no naked subdomains (allow localhost for tests)
61 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
65 if (substr($url, 0, 4) != 'http') {
66 $url = 'http://' . $url;
69 /// @TODO Really suppress function outcomes? Why not find them + debug them?
70 $h = @parse_url($url);
72 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
80 * Checks that email is an actual resolvable internet address
82 * @param string $addr The email address
83 * @return boolean True if it's a valid email address, false if it's not
85 public static function isEmailDomainValid(string $addr)
87 if (DI::config()->get('system', 'disable_email_validation')) {
91 if (! strpos($addr, '@')) {
95 $h = substr($addr, strpos($addr, '@') + 1);
97 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
98 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
101 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
108 * Check if URL is allowed
110 * Check $url against our list of allowed sites,
111 * wildcards allowed. If allowed_sites is unset return true;
113 * @param string $url URL which get tested
114 * @return boolean True if url is allowed otherwise return false
116 public static function isUrlAllowed(string $url)
118 $h = @parse_url($url);
124 $str_allowed = DI::config()->get('system', 'allowed_sites');
125 if (! $str_allowed) {
131 $host = strtolower($h['host']);
133 // always allow our own site
134 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
138 $fnmatch = function_exists('fnmatch');
139 $allowed = explode(',', $str_allowed);
141 if (count($allowed)) {
142 foreach ($allowed as $a) {
143 $pat = strtolower(trim($a));
144 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
154 * Checks if the provided url domain is on the domain blocklist.
155 * Returns true if it is or malformed URL, false if not.
157 * @param string $url The url to check the domain from
161 public static function isUrlBlocked(string $url)
163 $host = @parse_url($url, PHP_URL_HOST);
168 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
169 if (!$domain_blocklist) {
173 foreach ($domain_blocklist as $domain_block) {
174 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
183 * Checks if the provided url is on the list of domains where redirects are blocked.
184 * Returns true if it is or malformed URL, false if not.
186 * @param string $url The url to check the domain from
190 public static function isRedirectBlocked(string $url)
192 $host = @parse_url($url, PHP_URL_HOST);
197 $no_redirect_list = DI::config()->get('system', 'no_redirect_list', []);
198 if (!$no_redirect_list) {
202 foreach ($no_redirect_list as $no_redirect) {
203 if (fnmatch(strtolower($no_redirect), strtolower($host))) {
212 * Check if email address is allowed to register here.
214 * Compare against our list (wildcards allowed).
216 * @param string $email email address
217 * @return boolean False if not allowed, true if allowed
218 * or if allowed list is not configured
219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
221 public static function isEmailDomainAllowed(string $email)
223 $domain = strtolower(substr($email, strpos($email, '@') + 1));
228 $str_allowed = DI::config()->get('system', 'allowed_email', '');
229 if (empty($str_allowed)) {
233 $allowed = explode(',', $str_allowed);
235 return self::isDomainAllowed($domain, $allowed);
239 * Checks for the existence of a domain in a domain list
241 * @param string $domain
242 * @param array $domain_list
245 public static function isDomainAllowed(string $domain, array $domain_list)
249 foreach ($domain_list as $item) {
250 $pat = strtolower(trim($item));
251 if (fnmatch($pat, $domain) || ($pat == $domain)) {
260 public static function lookupAvatarByEmail(string $email)
262 $avatar['size'] = 300;
263 $avatar['email'] = $email;
265 $avatar['success'] = false;
267 Hook::callAll('avatar_lookup', $avatar);
269 if (! $avatar['success']) {
270 $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
273 Logger::info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']);
274 return $avatar['url'];
278 * Remove Google Analytics and other tracking platforms params from URL
280 * @param string $url Any user-submitted URL that may contain tracking params
281 * @return string The same URL stripped of tracking parameters
283 public static function stripTrackingQueryParams(string $url)
285 $urldata = parse_url($url);
286 if (!empty($urldata["query"])) {
287 $query = $urldata["query"];
288 parse_str($query, $querydata);
290 if (is_array($querydata)) {
291 foreach ($querydata as $param => $value) {
295 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
296 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
297 "fb_action_ids", "fb_action_types", "fb_ref",
299 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
302 $pair = $param . "=" . urlencode($value);
303 $url = str_replace($pair, "", $url);
305 // Second try: if the url isn't encoded completely
306 $pair = $param . "=" . str_replace(" ", "+", $value);
307 $url = str_replace($pair, "", $url);
309 // Third try: Maybey the url isn't encoded at all
310 $pair = $param . "=" . $value;
311 $url = str_replace($pair, "", $url);
313 $url = str_replace(["?&", "&&"], ["?", ""], $url);
318 if (substr($url, -1, 1) == "?") {
319 $url = substr($url, 0, -1);
327 * Add a missing base path (scheme and host) to a given url
330 * @param string $basepath
333 public static function addBasePath(string $url, string $basepath)
335 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
339 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
340 'host' => parse_url($basepath, PHP_URL_HOST)];
342 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
343 return self::unparseURL($parts);
347 * Find the matching part between two url
349 * @param string $url1
350 * @param string $url2
351 * @return string The matching part
353 public static function getUrlMatch(string $url1, string $url2)
355 if (($url1 == "") || ($url2 == "")) {
359 $url1 = Strings::normaliseLink($url1);
360 $url2 = Strings::normaliseLink($url2);
362 $parts1 = parse_url($url1);
363 $parts2 = parse_url($url2);
365 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
369 if (empty($parts1["scheme"])) {
370 $parts1["scheme"] = '';
372 if (empty($parts2["scheme"])) {
373 $parts2["scheme"] = '';
376 if ($parts1["scheme"] != $parts2["scheme"]) {
380 if (empty($parts1["host"])) {
381 $parts1["host"] = '';
383 if (empty($parts2["host"])) {
384 $parts2["host"] = '';
387 if ($parts1["host"] != $parts2["host"]) {
391 if (empty($parts1["port"])) {
392 $parts1["port"] = '';
394 if (empty($parts2["port"])) {
395 $parts2["port"] = '';
398 if ($parts1["port"] != $parts2["port"]) {
402 $match = $parts1["scheme"]."://".$parts1["host"];
404 if ($parts1["port"]) {
405 $match .= ":".$parts1["port"];
408 if (empty($parts1["path"])) {
409 $parts1["path"] = '';
411 if (empty($parts2["path"])) {
412 $parts2["path"] = '';
415 $pathparts1 = explode("/", $parts1["path"]);
416 $pathparts2 = explode("/", $parts2["path"]);
421 $path1 = $pathparts1[$i] ?? '';
422 $path2 = $pathparts2[$i] ?? '';
424 if ($path1 == $path2) {
427 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
431 return Strings::normaliseLink($match);
435 * Glue url parts together
437 * @param array $parsed URL parts
439 * @return string The glued URL.
440 * @deprecated since version 2021.12, use GuzzleHttp\Psr7\Uri::fromParts($parts) instead
442 public static function unparseURL(array $parsed)
444 $get = function ($key) use ($parsed) {
445 return isset($parsed[$key]) ? $parsed[$key] : null;
448 $pass = $get('pass');
449 $user = $get('user');
450 $userinfo = $pass !== null ? "$user:$pass" : $user;
451 $port = $get('port');
452 $scheme = $get('scheme');
453 $query = $get('query');
454 $fragment = $get('fragment');
455 $authority = ($userinfo !== null ? $userinfo."@" : '') .
457 ($port ? ":$port" : '');
459 return (strlen($scheme) ? $scheme.":" : '') .
460 (strlen($authority) ? "//".$authority : '') .
462 (strlen($query) ? "?".$query : '') .
463 (strlen($fragment) ? "#".$fragment : '');
467 * Convert an URI to an IDN compatible URI
472 public static function convertToIdn(string $uri): string
474 $parts = parse_url($uri);
475 if (!empty($parts['scheme']) && !empty($parts['host'])) {
476 $parts['host'] = idn_to_ascii($parts['host']);
477 $uri = Uri::fromParts($parts);
479 $parts = explode('@', $uri);
480 if (count($parts) == 2) {
481 $uri = $parts[0] . '@' . idn_to_ascii($parts[1]);
483 $uri = idn_to_ascii($uri);
491 * Switch the scheme of an url between http and https
493 * @param string $url URL
495 * @return string switched URL
497 public static function switchScheme(string $url)
499 $scheme = parse_url($url, PHP_URL_SCHEME);
500 if (empty($scheme)) {
504 if ($scheme === 'http') {
505 $url = str_replace('http://', 'https://', $url);
506 } elseif ($scheme === 'https') {
507 $url = str_replace('https://', 'http://', $url);
514 * Adds query string parameters to the provided URI. Replace the value of existing keys.
516 * @param string $path
517 * @param array $additionalParams Associative array of parameters
520 public static function appendQueryParam(string $path, array $additionalParams)
522 $parsed = parse_url($path);
525 if (!empty($parsed['query'])) {
526 parse_str($parsed['query'], $params);
529 $params = array_merge($params, $additionalParams);
531 $parsed['query'] = http_build_query($params);
533 return self::unparseURL($parsed);
537 * Generates ETag and Last-Modified response headers and checks them against
538 * If-None-Match and If-Modified-Since request headers if present.
540 * Blocking function, sends 304 headers and exits if check passes.
542 * @param string $etag The page etag
543 * @param string $last_modified The page last modification UTC date
546 public static function checkEtagModified(string $etag, string $last_modified)
548 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
551 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
553 $if_none_match = filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH');
554 $if_modified_since = filter_input(INPUT_SERVER, 'HTTP_IF_MODIFIED_SINCE');
555 $flag_not_modified = null;
556 if ($if_none_match) {
558 preg_match('/^(?:W\/")?([^"]+)"?$/i', $etag, $result);
559 $etagTrimmed = $result[1];
560 // Lazy exact ETag match, could check weak/strong ETags
561 $flag_not_modified = $if_none_match == '*' || strpos($if_none_match, $etagTrimmed) !== false;
564 if ($if_modified_since && (!$if_none_match || $flag_not_modified)) {
565 // Lazy exact Last-Modified match, could check If-Modified-Since validity
566 $flag_not_modified = $if_modified_since == $last_modified;
569 header('Etag: ' . $etag);
570 header('Last-Modified: ' . $last_modified);
572 if ($flag_not_modified) {
573 throw new NotModifiedException();
578 * Check if the given URL is a local link
583 public static function isLocalLink(string $url)
585 return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false);
589 * Check if the given URL is a valid HTTP/HTTPS URL
594 public static function isValidHttpUrl(string $url)
596 $scheme = parse_url($url, PHP_URL_SCHEME);
597 return !empty($scheme) && in_array($scheme, ['http', 'https']) && parse_url($url, PHP_URL_HOST);