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
54 * @return string|boolean The actual working URL, false else
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 public static function isUrlValid(string $url)
59 if (DI::config()->get('system', 'disable_url_validation')) {
63 // no naked subdomains (allow localhost for tests)
64 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
68 if (substr($url, 0, 4) != 'http') {
69 $url = 'http://' . $url;
72 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
73 $host = parse_url($url, PHP_URL_HOST);
75 if (empty($host) || !(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
79 if (in_array(parse_url($url, PHP_URL_SCHEME), ['https', 'http'])) {
80 $options = [HttpClientOptions::VERIFY => true, HttpClientOptions::TIMEOUT => $xrd_timeout];
81 $curlResult = DI::httpClient()->head($url, $options);
83 // Workaround for systems that can't handle a HEAD request. Don't retry on timeouts.
84 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() >= 400) && !in_array($curlResult->getReturnCode(), [408, 504])) {
85 $curlResult = DI::httpClient()->get($url, HttpClientAccept::DEFAULT, $options);
88 if (!$curlResult->isSuccess()) {
89 Logger::notice('Url not reachable', ['host' => $host, 'url' => $url]);
91 } elseif ($curlResult->isRedirectUrl()) {
92 $url = $curlResult->getRedirectUrl();
100 * Checks that email is an actual resolvable internet address
102 * @param string $addr The email address
103 * @return boolean True if it's a valid email address, false if it's not
105 public static function isEmailDomainValid(string $addr): bool
107 if (DI::config()->get('system', 'disable_email_validation')) {
111 if (! strpos($addr, '@')) {
115 $h = substr($addr, strpos($addr, '@') + 1);
117 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
118 if ($h && (@dns_get_record($h, DNS_A + DNS_AAAA + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
121 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
128 * Check if URL is allowed
130 * Check $url against our list of allowed sites,
131 * wildcards allowed. If allowed_sites is unset return true;
133 * @param string $url URL which get tested
134 * @return boolean True if url is allowed otherwise return false
136 public static function isUrlAllowed(string $url): bool
138 $h = @parse_url($url);
144 $str_allowed = DI::config()->get('system', 'allowed_sites');
145 if (! $str_allowed) {
151 $host = strtolower($h['host']);
153 // always allow our own site
154 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
158 $fnmatch = function_exists('fnmatch');
159 $allowed = explode(',', $str_allowed);
161 if (count($allowed)) {
162 foreach ($allowed as $a) {
163 $pat = strtolower(trim($a));
164 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
174 * Checks if the provided url domain is on the domain blocklist.
175 * Returns true if it is or malformed URL, false if not.
177 * @param string $url The url to check the domain from
181 public static function isUrlBlocked(string $url): bool
183 $host = @parse_url($url, PHP_URL_HOST);
188 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
189 if (!$domain_blocklist) {
193 foreach ($domain_blocklist as $domain_block) {
194 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
203 * Checks if the provided url is on the list of domains where redirects are blocked.
204 * Returns true if it is or malformed URL, false if not.
206 * @param string $url The url to check the domain from
210 public static function isRedirectBlocked(string $url): bool
212 $host = @parse_url($url, PHP_URL_HOST);
217 $no_redirect_list = DI::config()->get('system', 'no_redirect_list', []);
218 if (!$no_redirect_list) {
222 foreach ($no_redirect_list as $no_redirect) {
223 if (fnmatch(strtolower($no_redirect), strtolower($host))) {
232 * Check if email address is allowed to register here.
234 * Compare against our list (wildcards allowed).
236 * @param string $email email address
237 * @return boolean False if not allowed, true if allowed
238 * or if allowed list is not configured
239 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
241 public static function isEmailDomainAllowed(string $email): bool
243 $domain = strtolower(substr($email, strpos($email, '@') + 1));
248 $str_allowed = DI::config()->get('system', 'allowed_email', '');
249 if (empty($str_allowed)) {
253 $allowed = explode(',', $str_allowed);
255 return self::isDomainAllowed($domain, $allowed);
259 * Checks for the existence of a domain in a domain list
261 * @param string $domain
262 * @param array $domain_list
266 public static function isDomainAllowed(string $domain, array $domain_list): bool
270 foreach ($domain_list as $item) {
271 $pat = strtolower(trim($item));
272 if (fnmatch($pat, $domain) || ($pat == $domain)) {
281 public static function lookupAvatarByEmail(string $email): string
283 $avatar['size'] = 300;
284 $avatar['email'] = $email;
286 $avatar['success'] = false;
288 Hook::callAll('avatar_lookup', $avatar);
290 if (! $avatar['success']) {
291 $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
294 Logger::info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']);
295 return $avatar['url'];
299 * Remove Google Analytics and other tracking platforms params from URL
301 * @param string $url Any user-submitted URL that may contain tracking params
303 * @return string The same URL stripped of tracking parameters
305 public static function stripTrackingQueryParams(string $url): string
307 $urldata = parse_url($url);
309 if (!empty($urldata['query'])) {
310 $query = $urldata['query'];
311 parse_str($query, $querydata);
313 if (is_array($querydata)) {
314 foreach ($querydata as $param => $value) {
318 'utm_source', 'utm_medium', 'utm_term', 'utm_content', 'utm_campaign',
319 // As seen from Purism
320 'mtm_source', 'mtm_medium', 'mtm_term', 'mtm_content', 'mtm_campaign',
321 'wt_mc', 'pk_campaign', 'pk_kwd', 'mc_cid', 'mc_eid',
322 'fb_action_ids', 'fb_action_types', 'fb_ref',
324 'woo_campaign', 'woo_source', 'woo_medium', 'woo_content', 'woo_term']
327 $pair = $param . '=' . urlencode($value);
328 $url = str_replace($pair, '', $url);
330 // Second try: if the url isn't encoded completely
331 $pair = $param . '=' . str_replace(' ', '+', $value);
332 $url = str_replace($pair, '', $url);
334 // Third try: Maybey the url isn't encoded at all
335 $pair = $param . '=' . $value;
336 $url = str_replace($pair, '', $url);
338 $url = str_replace(['?&', '&&'], ['?', ''], $url);
343 if (substr($url, -1, 1) == '?') {
344 $url = substr($url, 0, -1);
352 * Add a missing base path (scheme and host) to a given url
355 * @param string $basepath
359 public static function addBasePath(string $url, string $basepath): string
361 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
366 'scheme' => parse_url($basepath, PHP_URL_SCHEME),
367 'host' => parse_url($basepath, PHP_URL_HOST),
370 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
371 return self::unparseURL($parts);
375 * Find the matching part between two url
377 * @param string $url1
378 * @param string $url2
380 * @return string The matching part or empty string on error
382 public static function getUrlMatch(string $url1, string $url2): string
384 if (($url1 == '') || ($url2 == '')) {
388 $url1 = Strings::normaliseLink($url1);
389 $url2 = Strings::normaliseLink($url2);
391 $parts1 = parse_url($url1);
392 $parts2 = parse_url($url2);
394 if (!isset($parts1['host']) || !isset($parts2['host'])) {
398 if (empty($parts1['scheme'])) {
399 $parts1['scheme'] = '';
401 if (empty($parts2['scheme'])) {
402 $parts2['scheme'] = '';
405 if ($parts1['scheme'] != $parts2['scheme']) {
409 if (empty($parts1['host'])) {
410 $parts1['host'] = '';
412 if (empty($parts2['host'])) {
413 $parts2['host'] = '';
416 if ($parts1['host'] != $parts2['host']) {
420 if (empty($parts1['port'])) {
421 $parts1['port'] = '';
423 if (empty($parts2['port'])) {
424 $parts2['port'] = '';
427 if ($parts1['port'] != $parts2['port']) {
431 $match = $parts1['scheme'] . '://' . $parts1['host'];
433 if ($parts1['port']) {
434 $match .= ':' . $parts1['port'];
437 if (empty($parts1['path'])) {
438 $parts1['path'] = '';
440 if (empty($parts2['path'])) {
441 $parts2['path'] = '';
444 $pathparts1 = explode('/', $parts1['path']);
445 $pathparts2 = explode('/', $parts2['path']);
450 $path1 = $pathparts1[$i] ?? '';
451 $path2 = $pathparts2[$i] ?? '';
453 if ($path1 == $path2) {
454 $path .= $path1 . '/';
456 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
460 return Strings::normaliseLink($match);
464 * Glue url parts together
466 * @param array $parsed URL parts
468 * @return string|null The glued URL or null on error
469 * @deprecated since version 2021.12, use GuzzleHttp\Psr7\Uri::fromParts($parts) instead
471 public static function unparseURL(array $parsed): string
473 $get = function ($key) use ($parsed) {
474 return isset($parsed[$key]) ? $parsed[$key] : null;
477 $pass = $get('pass');
478 $user = $get('user');
479 $userinfo = $pass !== null ? "$user:$pass" : $user;
480 $port = $get('port');
481 $scheme = $get('scheme');
482 $query = $get('query');
483 $fragment = $get('fragment');
484 $authority = ($userinfo !== null ? $userinfo . '@' : '') .
486 ($port ? ":$port" : '');
488 return (!empty($scheme) ? $scheme . ':' : '') .
489 (!empty($authority) ? '//' . $authority : '') .
491 (!empty($query) ? '?' . $query : '') .
492 (!empty($fragment) ? '#' . $fragment : '');
496 * Convert an URI to an IDN compatible URI
502 public static function convertToIdn(string $uri): string
504 $parts = parse_url($uri);
505 if (!empty($parts['scheme']) && !empty($parts['host'])) {
506 $parts['host'] = idn_to_ascii($parts['host']);
507 $uri = (string)Uri::fromParts($parts);
509 $parts = explode('@', $uri);
510 if (count($parts) == 2) {
511 $uri = $parts[0] . '@' . idn_to_ascii($parts[1]);
513 $uri = idn_to_ascii($uri);
521 * Switch the scheme of an url between http and https
525 * @return string Switched URL
527 public static function switchScheme(string $url): string
529 $scheme = parse_url($url, PHP_URL_SCHEME);
530 if (empty($scheme)) {
534 if ($scheme === 'http') {
535 $url = str_replace('http://', 'https://', $url);
536 } elseif ($scheme === 'https') {
537 $url = str_replace('https://', 'http://', $url);
544 * Adds query string parameters to the provided URI. Replace the value of existing keys.
546 * @param string $path
547 * @param array $additionalParams Associative array of parameters
551 public static function appendQueryParam(string $path, array $additionalParams): string
553 $parsed = parse_url($path);
556 if (!empty($parsed['query'])) {
557 parse_str($parsed['query'], $params);
560 $params = array_merge($params, $additionalParams);
562 $parsed['query'] = http_build_query($params);
564 return self::unparseURL($parsed);
568 * Generates ETag and Last-Modified response headers and checks them against
569 * If-None-Match and If-Modified-Since request headers if present.
571 * Blocking function, sends 304 headers and exits if check passes.
573 * @param string $etag The page etag
574 * @param string $last_modified The page last modification UTC date
579 public static function checkEtagModified(string $etag, string $last_modified)
581 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
584 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
586 $if_none_match = filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH');
587 $if_modified_since = filter_input(INPUT_SERVER, 'HTTP_IF_MODIFIED_SINCE');
588 $flag_not_modified = null;
589 if ($if_none_match) {
591 preg_match('/^(?:W\/")?([^"]+)"?$/i', $etag, $result);
592 $etagTrimmed = $result[1];
593 // Lazy exact ETag match, could check weak/strong ETags
594 $flag_not_modified = $if_none_match == '*' || strpos($if_none_match, $etagTrimmed) !== false;
597 if ($if_modified_since && (!$if_none_match || $flag_not_modified)) {
598 // Lazy exact Last-Modified match, could check If-Modified-Since validity
599 $flag_not_modified = $if_modified_since == $last_modified;
602 header('Etag: ' . $etag);
603 header('Last-Modified: ' . $last_modified);
605 if ($flag_not_modified) {
606 throw new NotModifiedException();
611 * Check if the given URL is a local link
617 public static function isLocalLink(string $url): bool
619 return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false);
623 * Check if the given URL is a valid HTTP/HTTPS URL
628 public static function isValidHttpUrl(string $url): bool
630 $scheme = parse_url($url, PHP_URL_SCHEME);
631 return !empty($scheme) && in_array($scheme, ['http', 'https']) && parse_url($url, PHP_URL_HOST);