]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
2cc603e501c3c65609b421d6e4533b6df2eba370
[friendica.git] / src / Util / Network.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\DI;
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;
32
33 class Network
34 {
35
36         /**
37          * Return raw post data from a post request
38          *
39          * @return string post data
40          */
41         public static function postdata()
42         {
43                 return file_get_contents('php://input');
44         }
45
46         /**
47          * Check URL to see if it's real
48          *
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)
51          *
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
55          */
56         public static function isUrlValid(string $url)
57         {
58                 if (DI::config()->get('system', 'disable_url_validation')) {
59                         return $url;
60                 }
61
62                 // no naked subdomains (allow localhost for tests)
63                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
64                         return false;
65                 }
66
67                 if (substr($url, 0, 4) != 'http') {
68                         $url = 'http://' . $url;
69                 }
70
71                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
72                 $host = parse_url($url, PHP_URL_HOST);
73
74                 if (empty($host) || !(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
75                         return false;
76                 }
77
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);
81         
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);
85                         }
86         
87                         if (!$curlResult->isSuccess()) {
88                                 Logger::notice('Url not reachable', ['host' => $host, 'url' => $url]);
89                                 return false;
90                         } elseif ($curlResult->isRedirectUrl()) {
91                                 $url = $curlResult->getRedirectUrl();
92                         }
93                 }
94
95                 return $url;
96         }
97
98         /**
99          * Checks that email is an actual resolvable internet address
100          *
101          * @param string $addr The email address
102          * @return boolean True if it's a valid email address, false if it's not
103          */
104         public static function isEmailDomainValid(string $addr)
105         {
106                 if (DI::config()->get('system', 'disable_email_validation')) {
107                         return true;
108                 }
109
110                 if (! strpos($addr, '@')) {
111                         return false;
112                 }
113
114                 $h = substr($addr, strpos($addr, '@') + 1);
115
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))) {
118                         return true;
119                 }
120                 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
121                         return true;
122                 }
123                 return false;
124         }
125
126         /**
127          * Check if URL is allowed
128          *
129          * Check $url against our list of allowed sites,
130          * wildcards allowed. If allowed_sites is unset return true;
131          *
132          * @param string $url URL which get tested
133          * @return boolean True if url is allowed otherwise return false
134          */
135         public static function isUrlAllowed(string $url)
136         {
137                 $h = @parse_url($url);
138
139                 if (! $h) {
140                         return false;
141                 }
142
143                 $str_allowed = DI::config()->get('system', 'allowed_sites');
144                 if (! $str_allowed) {
145                         return true;
146                 }
147
148                 $found = false;
149
150                 $host = strtolower($h['host']);
151
152                 // always allow our own site
153                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
154                         return true;
155                 }
156
157                 $fnmatch = function_exists('fnmatch');
158                 $allowed = explode(',', $str_allowed);
159
160                 if (count($allowed)) {
161                         foreach ($allowed as $a) {
162                                 $pat = strtolower(trim($a));
163                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
164                                         $found = true;
165                                         break;
166                                 }
167                         }
168                 }
169                 return $found;
170         }
171
172         /**
173          * Checks if the provided url domain is on the domain blocklist.
174          * Returns true if it is or malformed URL, false if not.
175          *
176          * @param string $url The url to check the domain from
177          *
178          * @return boolean
179          */
180         public static function isUrlBlocked(string $url)
181         {
182                 $host = @parse_url($url, PHP_URL_HOST);
183                 if (!$host) {
184                         return false;
185                 }
186
187                 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
188                 if (!$domain_blocklist) {
189                         return false;
190                 }
191
192                 foreach ($domain_blocklist as $domain_block) {
193                         if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
194                                 return true;
195                         }
196                 }
197
198                 return false;
199         }
200
201         /**
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.
204          *
205          * @param string $url The url to check the domain from
206          *
207          * @return boolean
208          */
209         public static function isRedirectBlocked(string $url)
210         {
211                 $host = @parse_url($url, PHP_URL_HOST);
212                 if (!$host) {
213                         return false;
214                 }
215
216                 $no_redirect_list = DI::config()->get('system', 'no_redirect_list', []);
217                 if (!$no_redirect_list) {
218                         return false;
219                 }
220
221                 foreach ($no_redirect_list as $no_redirect) {
222                         if (fnmatch(strtolower($no_redirect), strtolower($host))) {
223                                 return true;
224                         }
225                 }
226
227                 return false;
228         }
229
230         /**
231          * Check if email address is allowed to register here.
232          *
233          * Compare against our list (wildcards allowed).
234          *
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
239          */
240         public static function isEmailDomainAllowed(string $email)
241         {
242                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
243                 if (!$domain) {
244                         return false;
245                 }
246
247                 $str_allowed = DI::config()->get('system', 'allowed_email', '');
248                 if (empty($str_allowed)) {
249                         return true;
250                 }
251
252                 $allowed = explode(',', $str_allowed);
253
254                 return self::isDomainAllowed($domain, $allowed);
255         }
256
257         /**
258          * Checks for the existence of a domain in a domain list
259          *
260          * @param string $domain
261          * @param array  $domain_list
262          * @return boolean
263          */
264         public static function isDomainAllowed(string $domain, array $domain_list)
265         {
266                 $found = false;
267
268                 foreach ($domain_list as $item) {
269                         $pat = strtolower(trim($item));
270                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
271                                 $found = true;
272                                 break;
273                         }
274                 }
275
276                 return $found;
277         }
278
279         public static function lookupAvatarByEmail(string $email)
280         {
281                 $avatar['size'] = 300;
282                 $avatar['email'] = $email;
283                 $avatar['url'] = '';
284                 $avatar['success'] = false;
285
286                 Hook::callAll('avatar_lookup', $avatar);
287
288                 if (! $avatar['success']) {
289                         $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
290                 }
291
292                 Logger::info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']);
293                 return $avatar['url'];
294         }
295
296         /**
297          * Remove Google Analytics and other tracking platforms params from URL
298          *
299          * @param string $url Any user-submitted URL that may contain tracking params
300          * @return string The same URL stripped of tracking parameters
301          */
302         public static function stripTrackingQueryParams(string $url)
303         {
304                 $urldata = parse_url($url);
305                 if (!empty($urldata["query"])) {
306                         $query = $urldata["query"];
307                         parse_str($query, $querydata);
308
309                         if (is_array($querydata)) {
310                                 foreach ($querydata as $param => $value) {
311                                         if (in_array(
312                                                 $param,
313                                                 [
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",
317                                                         "awesm", "wtrid",
318                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
319                                                 )
320                                         ) {
321                                                 $pair = $param . "=" . urlencode($value);
322                                                 $url = str_replace($pair, "", $url);
323
324                                                 // Second try: if the url isn't encoded completely
325                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
326                                                 $url = str_replace($pair, "", $url);
327
328                                                 // Third try: Maybey the url isn't encoded at all
329                                                 $pair = $param . "=" . $value;
330                                                 $url = str_replace($pair, "", $url);
331
332                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
333                                         }
334                                 }
335                         }
336
337                         if (substr($url, -1, 1) == "?") {
338                                 $url = substr($url, 0, -1);
339                         }
340                 }
341
342                 return $url;
343         }
344
345         /**
346          * Add a missing base path (scheme and host) to a given url
347          *
348          * @param string $url
349          * @param string $basepath
350          * @return string url
351          */
352         public static function addBasePath(string $url, string $basepath)
353         {
354                 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
355                         return $url;
356                 }
357
358                 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
359                         'host' => parse_url($basepath, PHP_URL_HOST)];
360
361                 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
362                 return self::unparseURL($parts);
363         }
364
365         /**
366          * Find the matching part between two url
367          *
368          * @param string $url1
369          * @param string $url2
370          * @return string The matching part
371          */
372         public static function getUrlMatch(string $url1, string $url2)
373         {
374                 if (($url1 == "") || ($url2 == "")) {
375                         return "";
376                 }
377
378                 $url1 = Strings::normaliseLink($url1);
379                 $url2 = Strings::normaliseLink($url2);
380
381                 $parts1 = parse_url($url1);
382                 $parts2 = parse_url($url2);
383
384                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
385                         return "";
386                 }
387
388                 if (empty($parts1["scheme"])) {
389                         $parts1["scheme"] = '';
390                 }
391                 if (empty($parts2["scheme"])) {
392                         $parts2["scheme"] = '';
393                 }
394
395                 if ($parts1["scheme"] != $parts2["scheme"]) {
396                         return "";
397                 }
398
399                 if (empty($parts1["host"])) {
400                         $parts1["host"] = '';
401                 }
402                 if (empty($parts2["host"])) {
403                         $parts2["host"] = '';
404                 }
405
406                 if ($parts1["host"] != $parts2["host"]) {
407                         return "";
408                 }
409
410                 if (empty($parts1["port"])) {
411                         $parts1["port"] = '';
412                 }
413                 if (empty($parts2["port"])) {
414                         $parts2["port"] = '';
415                 }
416
417                 if ($parts1["port"] != $parts2["port"]) {
418                         return "";
419                 }
420
421                 $match = $parts1["scheme"]."://".$parts1["host"];
422
423                 if ($parts1["port"]) {
424                         $match .= ":".$parts1["port"];
425                 }
426
427                 if (empty($parts1["path"])) {
428                         $parts1["path"] = '';
429                 }
430                 if (empty($parts2["path"])) {
431                         $parts2["path"] = '';
432                 }
433
434                 $pathparts1 = explode("/", $parts1["path"]);
435                 $pathparts2 = explode("/", $parts2["path"]);
436
437                 $i = 0;
438                 $path = "";
439                 do {
440                         $path1 = $pathparts1[$i] ?? '';
441                         $path2 = $pathparts2[$i] ?? '';
442
443                         if ($path1 == $path2) {
444                                 $path .= $path1."/";
445                         }
446                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
447
448                 $match .= $path;
449
450                 return Strings::normaliseLink($match);
451         }
452
453         /**
454          * Glue url parts together
455          *
456          * @param array $parsed URL parts
457          *
458          * @return string The glued URL.
459          * @deprecated since version 2021.12, use GuzzleHttp\Psr7\Uri::fromParts($parts) instead
460          */
461         public static function unparseURL(array $parsed)
462         {
463                 $get = function ($key) use ($parsed) {
464                         return isset($parsed[$key]) ? $parsed[$key] : null;
465                 };
466
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."@" : '') .
475                                                 $get('host') .
476                                                 ($port ? ":$port" : '');
477
478                 return  (strlen($scheme) ? $scheme.":" : '') .
479                         (strlen($authority) ? "//".$authority : '') .
480                         $get('path') .
481                         (strlen($query) ? "?".$query : '') .
482                         (strlen($fragment) ? "#".$fragment : '');
483         }
484
485         /**
486          * Convert an URI to an IDN compatible URI
487          *
488          * @param string $uri
489          * @return string
490          */
491         public static function convertToIdn(string $uri): string
492         {
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);
497                 } else {
498                         $parts = explode('@', $uri);
499                         if (count($parts) == 2) {
500                                 $uri = $parts[0] . '@' . idn_to_ascii($parts[1]);
501                         } else {
502                                 $uri = idn_to_ascii($uri);
503                         }
504                 }
505
506                 return $uri;
507         }
508
509         /**
510          * Switch the scheme of an url between http and https
511          *
512          * @param string $url URL
513          *
514          * @return string switched URL
515          */
516         public static function switchScheme(string $url)
517         {
518                 $scheme = parse_url($url, PHP_URL_SCHEME);
519                 if (empty($scheme)) {
520                         return $url;
521                 }
522
523                 if ($scheme === 'http') {
524                         $url = str_replace('http://', 'https://', $url);
525                 } elseif ($scheme === 'https') {
526                         $url = str_replace('https://', 'http://', $url);
527                 }
528
529                 return $url;
530         }
531
532         /**
533          * Adds query string parameters to the provided URI. Replace the value of existing keys.
534          *
535          * @param string $path
536          * @param array  $additionalParams Associative array of parameters
537          * @return string
538          */
539         public static function appendQueryParam(string $path, array $additionalParams)
540         {
541                 $parsed = parse_url($path);
542
543                 $params = [];
544                 if (!empty($parsed['query'])) {
545                         parse_str($parsed['query'], $params);
546                 }
547
548                 $params = array_merge($params, $additionalParams);
549
550                 $parsed['query'] = http_build_query($params);
551
552                 return self::unparseURL($parsed);
553         }
554
555         /**
556          * Generates ETag and Last-Modified response headers and checks them against
557          * If-None-Match and If-Modified-Since request headers if present.
558          *
559          * Blocking function, sends 304 headers and exits if check passes.
560          *
561          * @param string $etag          The page etag
562          * @param string $last_modified The page last modification UTC date
563          * @throws \Exception
564          */
565         public static function checkEtagModified(string $etag, string $last_modified)
566         {
567                 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
568
569                 /**
570                  * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
571                  */
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) {
576                         $result = [];
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;
581                 }
582
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;
586                 }
587
588                 header('Etag: ' . $etag);
589                 header('Last-Modified: ' . $last_modified);
590
591                 if ($flag_not_modified) {
592                         throw new NotModifiedException();
593                 }
594         }
595
596         /**
597          * Check if the given URL is a local link
598          *
599          * @param string $url
600          * @return bool
601          */
602         public static function isLocalLink(string $url)
603         {
604                 return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false);
605         }
606
607         /**
608          * Check if the given URL is a valid HTTP/HTTPS URL
609          *
610          * @param string $url
611          * @return bool
612          */
613         public static function isValidHttpUrl(string $url)
614         {
615                 $scheme = parse_url($url, PHP_URL_SCHEME);
616                 return !empty($scheme) && in_array($scheme, ['http', 'https']) && parse_url($url, PHP_URL_HOST);
617         }
618 }