3 * @copyright Copyright (C) 2010-2021, 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;
33 * Return raw post data from a post request
35 * @return string post data
37 public static function postdata()
39 return file_get_contents('php://input');
43 * Check URL to see if it's real
45 * Take a URL from the wild, prepend http:// if necessary
46 * and check DNS to see if it's real (or check if is a valid IP address)
48 * @param string $url The URL to be validated
49 * @return string|boolean The actual working URL, false else
50 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52 public static function isUrlValid(string $url)
54 if (DI::config()->get('system', 'disable_url_validation')) {
58 // no naked subdomains (allow localhost for tests)
59 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
63 if (substr($url, 0, 4) != 'http') {
64 $url = 'http://' . $url;
67 /// @TODO Really suppress function outcomes? Why not find them + debug them?
68 $h = @parse_url($url);
70 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
78 * Checks that email is an actual resolvable internet address
80 * @param string $addr The email address
81 * @return boolean True if it's a valid email address, false if it's not
83 public static function isEmailDomainValid(string $addr)
85 if (DI::config()->get('system', 'disable_email_validation')) {
89 if (! strpos($addr, '@')) {
93 $h = substr($addr, strpos($addr, '@') + 1);
95 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
96 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
99 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
106 * Check if URL is allowed
108 * Check $url against our list of allowed sites,
109 * wildcards allowed. If allowed_sites is unset return true;
111 * @param string $url URL which get tested
112 * @return boolean True if url is allowed otherwise return false
114 public static function isUrlAllowed(string $url)
116 $h = @parse_url($url);
122 $str_allowed = DI::config()->get('system', 'allowed_sites');
123 if (! $str_allowed) {
129 $host = strtolower($h['host']);
131 // always allow our own site
132 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
136 $fnmatch = function_exists('fnmatch');
137 $allowed = explode(',', $str_allowed);
139 if (count($allowed)) {
140 foreach ($allowed as $a) {
141 $pat = strtolower(trim($a));
142 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
152 * Checks if the provided url domain is on the domain blocklist.
153 * Returns true if it is or malformed URL, false if not.
155 * @param string $url The url to check the domain from
159 public static function isUrlBlocked(string $url)
161 $host = @parse_url($url, PHP_URL_HOST);
166 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
167 if (!$domain_blocklist) {
171 foreach ($domain_blocklist as $domain_block) {
172 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
181 * Checks if the provided url is on the list of domains where redirects are blocked.
182 * Returns true if it is or malformed URL, false if not.
184 * @param string $url The url to check the domain from
188 public static function isRedirectBlocked(string $url)
190 $host = @parse_url($url, PHP_URL_HOST);
195 $no_redirect_list = DI::config()->get('system', 'no_redirect_list', []);
196 if (!$no_redirect_list) {
200 foreach ($no_redirect_list as $no_redirect) {
201 if (fnmatch(strtolower($no_redirect), strtolower($host))) {
210 * Check if email address is allowed to register here.
212 * Compare against our list (wildcards allowed).
214 * @param string $email email address
215 * @return boolean False if not allowed, true if allowed
216 * or if allowed list is not configured
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
219 public static function isEmailDomainAllowed(string $email)
221 $domain = strtolower(substr($email, strpos($email, '@') + 1));
226 $str_allowed = DI::config()->get('system', 'allowed_email', '');
227 if (empty($str_allowed)) {
231 $allowed = explode(',', $str_allowed);
233 return self::isDomainAllowed($domain, $allowed);
237 * Checks for the existence of a domain in a domain list
239 * @param string $domain
240 * @param array $domain_list
243 public static function isDomainAllowed(string $domain, array $domain_list)
247 foreach ($domain_list as $item) {
248 $pat = strtolower(trim($item));
249 if (fnmatch($pat, $domain) || ($pat == $domain)) {
258 public static function lookupAvatarByEmail(string $email)
260 $avatar['size'] = 300;
261 $avatar['email'] = $email;
263 $avatar['success'] = false;
265 Hook::callAll('avatar_lookup', $avatar);
267 if (! $avatar['success']) {
268 $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
271 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
272 return $avatar['url'];
276 * Remove Google Analytics and other tracking platforms params from URL
278 * @param string $url Any user-submitted URL that may contain tracking params
279 * @return string The same URL stripped of tracking parameters
281 public static function stripTrackingQueryParams(string $url)
283 $urldata = parse_url($url);
284 if (!empty($urldata["query"])) {
285 $query = $urldata["query"];
286 parse_str($query, $querydata);
288 if (is_array($querydata)) {
289 foreach ($querydata as $param => $value) {
293 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
294 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
295 "fb_action_ids", "fb_action_types", "fb_ref",
297 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
300 $pair = $param . "=" . urlencode($value);
301 $url = str_replace($pair, "", $url);
303 // Second try: if the url isn't encoded completely
304 $pair = $param . "=" . str_replace(" ", "+", $value);
305 $url = str_replace($pair, "", $url);
307 // Third try: Maybey the url isn't encoded at all
308 $pair = $param . "=" . $value;
309 $url = str_replace($pair, "", $url);
311 $url = str_replace(["?&", "&&"], ["?", ""], $url);
316 if (substr($url, -1, 1) == "?") {
317 $url = substr($url, 0, -1);
325 * Add a missing base path (scheme and host) to a given url
328 * @param string $basepath
331 public static function addBasePath(string $url, string $basepath)
333 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
337 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
338 'host' => parse_url($basepath, PHP_URL_HOST)];
340 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
341 return self::unparseURL($parts);
345 * Find the matching part between two url
347 * @param string $url1
348 * @param string $url2
349 * @return string The matching part
351 public static function getUrlMatch(string $url1, string $url2)
353 if (($url1 == "") || ($url2 == "")) {
357 $url1 = Strings::normaliseLink($url1);
358 $url2 = Strings::normaliseLink($url2);
360 $parts1 = parse_url($url1);
361 $parts2 = parse_url($url2);
363 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
367 if (empty($parts1["scheme"])) {
368 $parts1["scheme"] = '';
370 if (empty($parts2["scheme"])) {
371 $parts2["scheme"] = '';
374 if ($parts1["scheme"] != $parts2["scheme"]) {
378 if (empty($parts1["host"])) {
379 $parts1["host"] = '';
381 if (empty($parts2["host"])) {
382 $parts2["host"] = '';
385 if ($parts1["host"] != $parts2["host"]) {
389 if (empty($parts1["port"])) {
390 $parts1["port"] = '';
392 if (empty($parts2["port"])) {
393 $parts2["port"] = '';
396 if ($parts1["port"] != $parts2["port"]) {
400 $match = $parts1["scheme"]."://".$parts1["host"];
402 if ($parts1["port"]) {
403 $match .= ":".$parts1["port"];
406 if (empty($parts1["path"])) {
407 $parts1["path"] = '';
409 if (empty($parts2["path"])) {
410 $parts2["path"] = '';
413 $pathparts1 = explode("/", $parts1["path"]);
414 $pathparts2 = explode("/", $parts2["path"]);
419 $path1 = $pathparts1[$i] ?? '';
420 $path2 = $pathparts2[$i] ?? '';
422 if ($path1 == $path2) {
425 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
429 return Strings::normaliseLink($match);
433 * Glue url parts together
435 * @param array $parsed URL parts
437 * @return string The glued URL
439 public static function unparseURL(array $parsed)
441 $get = function ($key) use ($parsed) {
442 return isset($parsed[$key]) ? $parsed[$key] : null;
445 $pass = $get('pass');
446 $user = $get('user');
447 $userinfo = $pass !== null ? "$user:$pass" : $user;
448 $port = $get('port');
449 $scheme = $get('scheme');
450 $query = $get('query');
451 $fragment = $get('fragment');
452 $authority = ($userinfo !== null ? $userinfo."@" : '') .
454 ($port ? ":$port" : '');
456 return (strlen($scheme) ? $scheme.":" : '') .
457 (strlen($authority) ? "//".$authority : '') .
459 (strlen($query) ? "?".$query : '') .
460 (strlen($fragment) ? "#".$fragment : '');
465 * Switch the scheme of an url between http and https
467 * @param string $url URL
469 * @return string switched URL
471 public static function switchScheme(string $url)
473 $scheme = parse_url($url, PHP_URL_SCHEME);
474 if (empty($scheme)) {
478 if ($scheme === 'http') {
479 $url = str_replace('http://', 'https://', $url);
480 } elseif ($scheme === 'https') {
481 $url = str_replace('https://', 'http://', $url);
488 * Adds query string parameters to the provided URI. Replace the value of existing keys.
490 * @param string $path
491 * @param array $additionalParams Associative array of parameters
494 public static function appendQueryParam(string $path, array $additionalParams)
496 $parsed = parse_url($path);
499 if (!empty($parsed['query'])) {
500 parse_str($parsed['query'], $params);
503 $params = array_merge($params, $additionalParams);
505 $parsed['query'] = http_build_query($params);
507 return self::unparseURL($parsed);
511 * Generates ETag and Last-Modified response headers and checks them against
512 * If-None-Match and If-Modified-Since request headers if present.
514 * Blocking function, sends 304 headers and exits if check passes.
516 * @param string $etag The page etag
517 * @param string $last_modified The page last modification UTC date
520 public static function checkEtagModified(string $etag, string $last_modified)
522 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
525 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
527 $if_none_match = filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH');
528 $if_modified_since = filter_input(INPUT_SERVER, 'HTTP_IF_MODIFIED_SINCE');
529 $flag_not_modified = null;
530 if ($if_none_match) {
532 preg_match('/^(?:W\/")?([^"]+)"?$/i', $etag, $result);
533 $etagTrimmed = $result[1];
534 // Lazy exact ETag match, could check weak/strong ETags
535 $flag_not_modified = $if_none_match == '*' || strpos($if_none_match, $etagTrimmed) !== false;
538 if ($if_modified_since && (!$if_none_match || $flag_not_modified)) {
539 // Lazy exact Last-Modified match, could check If-Modified-Since validity
540 $flag_not_modified = $if_modified_since == $last_modified;
543 header('Etag: ' . $etag);
544 header('Last-Modified: ' . $last_modified);
546 if ($flag_not_modified) {
547 header("HTTP/1.1 304 Not Modified");
553 * Check if the given URL is a local link
558 public static function isLocalLink(string $url)
560 return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false);