3 * @copyright Copyright (C) 2020, Friendica
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 * Check if email address is allowed to register here.
183 * Compare against our list (wildcards allowed).
185 * @param string $email email address
186 * @return boolean False if not allowed, true if allowed
187 * or if allowed list is not configured
188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190 public static function isEmailDomainAllowed(string $email)
192 $domain = strtolower(substr($email, strpos($email, '@') + 1));
197 $str_allowed = DI::config()->get('system', 'allowed_email', '');
198 if (empty($str_allowed)) {
202 $allowed = explode(',', $str_allowed);
204 return self::isDomainAllowed($domain, $allowed);
208 * Checks for the existence of a domain in a domain list
210 * @param string $domain
211 * @param array $domain_list
214 public static function isDomainAllowed(string $domain, array $domain_list)
218 foreach ($domain_list as $item) {
219 $pat = strtolower(trim($item));
220 if (fnmatch($pat, $domain) || ($pat == $domain)) {
229 public static function lookupAvatarByEmail(string $email)
231 $avatar['size'] = 300;
232 $avatar['email'] = $email;
234 $avatar['success'] = false;
236 Hook::callAll('avatar_lookup', $avatar);
238 if (! $avatar['success']) {
239 $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
242 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
243 return $avatar['url'];
247 * Remove Google Analytics and other tracking platforms params from URL
249 * @param string $url Any user-submitted URL that may contain tracking params
250 * @return string The same URL stripped of tracking parameters
252 public static function stripTrackingQueryParams(string $url)
254 $urldata = parse_url($url);
255 if (!empty($urldata["query"])) {
256 $query = $urldata["query"];
257 parse_str($query, $querydata);
259 if (is_array($querydata)) {
260 foreach ($querydata as $param => $value) {
264 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
265 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
266 "fb_action_ids", "fb_action_types", "fb_ref",
268 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
271 $pair = $param . "=" . urlencode($value);
272 $url = str_replace($pair, "", $url);
274 // Second try: if the url isn't encoded completely
275 $pair = $param . "=" . str_replace(" ", "+", $value);
276 $url = str_replace($pair, "", $url);
278 // Third try: Maybey the url isn't encoded at all
279 $pair = $param . "=" . $value;
280 $url = str_replace($pair, "", $url);
282 $url = str_replace(["?&", "&&"], ["?", ""], $url);
287 if (substr($url, -1, 1) == "?") {
288 $url = substr($url, 0, -1);
296 * Add a missing base path (scheme and host) to a given url
299 * @param string $basepath
302 public static function addBasePath(string $url, string $basepath)
304 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
308 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
309 'host' => parse_url($basepath, PHP_URL_HOST)];
311 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
312 return self::unparseURL($parts);
316 * Find the matching part between two url
318 * @param string $url1
319 * @param string $url2
320 * @return string The matching part
322 public static function getUrlMatch(string $url1, string $url2)
324 if (($url1 == "") || ($url2 == "")) {
328 $url1 = Strings::normaliseLink($url1);
329 $url2 = Strings::normaliseLink($url2);
331 $parts1 = parse_url($url1);
332 $parts2 = parse_url($url2);
334 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
338 if (empty($parts1["scheme"])) {
339 $parts1["scheme"] = '';
341 if (empty($parts2["scheme"])) {
342 $parts2["scheme"] = '';
345 if ($parts1["scheme"] != $parts2["scheme"]) {
349 if (empty($parts1["host"])) {
350 $parts1["host"] = '';
352 if (empty($parts2["host"])) {
353 $parts2["host"] = '';
356 if ($parts1["host"] != $parts2["host"]) {
360 if (empty($parts1["port"])) {
361 $parts1["port"] = '';
363 if (empty($parts2["port"])) {
364 $parts2["port"] = '';
367 if ($parts1["port"] != $parts2["port"]) {
371 $match = $parts1["scheme"]."://".$parts1["host"];
373 if ($parts1["port"]) {
374 $match .= ":".$parts1["port"];
377 if (empty($parts1["path"])) {
378 $parts1["path"] = '';
380 if (empty($parts2["path"])) {
381 $parts2["path"] = '';
384 $pathparts1 = explode("/", $parts1["path"]);
385 $pathparts2 = explode("/", $parts2["path"]);
390 $path1 = $pathparts1[$i] ?? '';
391 $path2 = $pathparts2[$i] ?? '';
393 if ($path1 == $path2) {
396 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
400 return Strings::normaliseLink($match);
404 * Glue url parts together
406 * @param array $parsed URL parts
408 * @return string The glued URL
410 public static function unparseURL(array $parsed)
412 $get = function ($key) use ($parsed) {
413 return isset($parsed[$key]) ? $parsed[$key] : null;
416 $pass = $get('pass');
417 $user = $get('user');
418 $userinfo = $pass !== null ? "$user:$pass" : $user;
419 $port = $get('port');
420 $scheme = $get('scheme');
421 $query = $get('query');
422 $fragment = $get('fragment');
423 $authority = ($userinfo !== null ? $userinfo."@" : '') .
425 ($port ? ":$port" : '');
427 return (strlen($scheme) ? $scheme.":" : '') .
428 (strlen($authority) ? "//".$authority : '') .
430 (strlen($query) ? "?".$query : '') .
431 (strlen($fragment) ? "#".$fragment : '');
436 * Switch the scheme of an url between http and https
438 * @param string $url URL
440 * @return string switched URL
442 public static function switchScheme(string $url)
444 $scheme = parse_url($url, PHP_URL_SCHEME);
445 if (empty($scheme)) {
449 if ($scheme === 'http') {
450 $url = str_replace('http://', 'https://', $url);
451 } elseif ($scheme === 'https') {
452 $url = str_replace('https://', 'http://', $url);
459 * Adds query string parameters to the provided URI. Replace the value of existing keys.
461 * @param string $path
462 * @param array $additionalParams Associative array of parameters
465 public static function appendQueryParam(string $path, array $additionalParams)
467 $parsed = parse_url($path);
470 if (!empty($parsed['query'])) {
471 parse_str($parsed['query'], $params);
474 $params = array_merge($params, $additionalParams);
476 $parsed['query'] = http_build_query($params);
478 return self::unparseURL($parsed);
482 * Generates ETag and Last-Modified response headers and checks them against
483 * If-None-Match and If-Modified-Since request headers if present.
485 * Blocking function, sends 304 headers and exits if check passes.
487 * @param string $etag The page etag
488 * @param string $last_modified The page last modification UTC date
491 public static function checkEtagModified(string $etag, string $last_modified)
493 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
496 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
498 $if_none_match = filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH');
499 $if_modified_since = filter_input(INPUT_SERVER, 'HTTP_IF_MODIFIED_SINCE');
500 $flag_not_modified = null;
501 if ($if_none_match) {
503 preg_match('/^(?:W\/")?([^"]+)"?$/i', $etag, $result);
504 $etagTrimmed = $result[1];
505 // Lazy exact ETag match, could check weak/strong ETags
506 $flag_not_modified = $if_none_match == '*' || strpos($if_none_match, $etagTrimmed) !== false;
509 if ($if_modified_since && (!$if_none_match || $flag_not_modified)) {
510 // Lazy exact Last-Modified match, could check If-Modified-Since validity
511 $flag_not_modified = $if_modified_since == $last_modified;
514 header('Etag: ' . $etag);
515 header('Last-Modified: ' . $last_modified);
517 if ($flag_not_modified) {
518 header("HTTP/1.1 304 Not Modified");