]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
Merge pull request #8909 from MrPetovan/task/ex_auth
[friendica.git] / src / Util / Network.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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
29 class Network
30 {
31
32         /**
33          * Return raw post data from a post request
34          *
35          * @return string post data
36          */
37         public static function postdata()
38         {
39                 return file_get_contents('php://input');
40         }
41
42         /**
43          * Check URL to see if it's real
44          *
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)
47          *
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
51          */
52         public static function isUrlValid(string $url)
53         {
54                 if (DI::config()->get('system', 'disable_url_validation')) {
55                         return $url;
56                 }
57
58                 // no naked subdomains (allow localhost for tests)
59                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
60                         return false;
61                 }
62
63                 if (substr($url, 0, 4) != 'http') {
64                         $url = 'http://' . $url;
65                 }
66
67                 /// @TODO Really suppress function outcomes? Why not find them + debug them?
68                 $h = @parse_url($url);
69
70                 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
71                         return $url;
72                 }
73
74                 return false;
75         }
76
77         /**
78          * Checks that email is an actual resolvable internet address
79          *
80          * @param string $addr The email address
81          * @return boolean True if it's a valid email address, false if it's not
82          */
83         public static function isEmailDomainValid(string $addr)
84         {
85                 if (DI::config()->get('system', 'disable_email_validation')) {
86                         return true;
87                 }
88
89                 if (! strpos($addr, '@')) {
90                         return false;
91                 }
92
93                 $h = substr($addr, strpos($addr, '@') + 1);
94
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))) {
97                         return true;
98                 }
99                 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
100                         return true;
101                 }
102                 return false;
103         }
104
105         /**
106          * Check if URL is allowed
107          *
108          * Check $url against our list of allowed sites,
109          * wildcards allowed. If allowed_sites is unset return true;
110          *
111          * @param string $url URL which get tested
112          * @return boolean True if url is allowed otherwise return false
113          */
114         public static function isUrlAllowed(string $url)
115         {
116                 $h = @parse_url($url);
117
118                 if (! $h) {
119                         return false;
120                 }
121
122                 $str_allowed = DI::config()->get('system', 'allowed_sites');
123                 if (! $str_allowed) {
124                         return true;
125                 }
126
127                 $found = false;
128
129                 $host = strtolower($h['host']);
130
131                 // always allow our own site
132                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
133                         return true;
134                 }
135
136                 $fnmatch = function_exists('fnmatch');
137                 $allowed = explode(',', $str_allowed);
138
139                 if (count($allowed)) {
140                         foreach ($allowed as $a) {
141                                 $pat = strtolower(trim($a));
142                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
143                                         $found = true;
144                                         break;
145                                 }
146                         }
147                 }
148                 return $found;
149         }
150
151         /**
152          * Checks if the provided url domain is on the domain blocklist.
153          * Returns true if it is or malformed URL, false if not.
154          *
155          * @param string $url The url to check the domain from
156          *
157          * @return boolean
158          */
159         public static function isUrlBlocked(string $url)
160         {
161                 $host = @parse_url($url, PHP_URL_HOST);
162                 if (!$host) {
163                         return false;
164                 }
165
166                 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
167                 if (!$domain_blocklist) {
168                         return false;
169                 }
170
171                 foreach ($domain_blocklist as $domain_block) {
172                         if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
173                                 return true;
174                         }
175                 }
176
177                 return false;
178         }
179
180         /**
181          * Check if email address is allowed to register here.
182          *
183          * Compare against our list (wildcards allowed).
184          *
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
189          */
190         public static function isEmailDomainAllowed(string $email)
191         {
192                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
193                 if (!$domain) {
194                         return false;
195                 }
196
197                 $str_allowed = DI::config()->get('system', 'allowed_email', '');
198                 if (empty($str_allowed)) {
199                         return true;
200                 }
201
202                 $allowed = explode(',', $str_allowed);
203
204                 return self::isDomainAllowed($domain, $allowed);
205         }
206
207         /**
208          * Checks for the existence of a domain in a domain list
209          *
210          * @param string $domain
211          * @param array  $domain_list
212          * @return boolean
213          */
214         public static function isDomainAllowed(string $domain, array $domain_list)
215         {
216                 $found = false;
217
218                 foreach ($domain_list as $item) {
219                         $pat = strtolower(trim($item));
220                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
221                                 $found = true;
222                                 break;
223                         }
224                 }
225
226                 return $found;
227         }
228
229         public static function lookupAvatarByEmail(string $email)
230         {
231                 $avatar['size'] = 300;
232                 $avatar['email'] = $email;
233                 $avatar['url'] = '';
234                 $avatar['success'] = false;
235
236                 Hook::callAll('avatar_lookup', $avatar);
237
238                 if (! $avatar['success']) {
239                         $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
240                 }
241
242                 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
243                 return $avatar['url'];
244         }
245
246         /**
247          * Remove Google Analytics and other tracking platforms params from URL
248          *
249          * @param string $url Any user-submitted URL that may contain tracking params
250          * @return string The same URL stripped of tracking parameters
251          */
252         public static function stripTrackingQueryParams(string $url)
253         {
254                 $urldata = parse_url($url);
255                 if (!empty($urldata["query"])) {
256                         $query = $urldata["query"];
257                         parse_str($query, $querydata);
258
259                         if (is_array($querydata)) {
260                                 foreach ($querydata as $param => $value) {
261                                         if (in_array(
262                                                 $param,
263                                                 [
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",
267                                                         "awesm", "wtrid",
268                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
269                                                 )
270                                         ) {
271                                                 $pair = $param . "=" . urlencode($value);
272                                                 $url = str_replace($pair, "", $url);
273
274                                                 // Second try: if the url isn't encoded completely
275                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
276                                                 $url = str_replace($pair, "", $url);
277
278                                                 // Third try: Maybey the url isn't encoded at all
279                                                 $pair = $param . "=" . $value;
280                                                 $url = str_replace($pair, "", $url);
281
282                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
283                                         }
284                                 }
285                         }
286
287                         if (substr($url, -1, 1) == "?") {
288                                 $url = substr($url, 0, -1);
289                         }
290                 }
291
292                 return $url;
293         }
294
295         /**
296          * Add a missing base path (scheme and host) to a given url
297          *
298          * @param string $url
299          * @param string $basepath
300          * @return string url
301          */
302         public static function addBasePath(string $url, string $basepath)
303         {
304                 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
305                         return $url;
306                 }
307
308                 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
309                         'host' => parse_url($basepath, PHP_URL_HOST)];
310
311                 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
312                 return self::unparseURL($parts);
313         }
314
315         /**
316          * Find the matching part between two url
317          *
318          * @param string $url1
319          * @param string $url2
320          * @return string The matching part
321          */
322         public static function getUrlMatch(string $url1, string $url2)
323         {
324                 if (($url1 == "") || ($url2 == "")) {
325                         return "";
326                 }
327
328                 $url1 = Strings::normaliseLink($url1);
329                 $url2 = Strings::normaliseLink($url2);
330
331                 $parts1 = parse_url($url1);
332                 $parts2 = parse_url($url2);
333
334                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
335                         return "";
336                 }
337
338                 if (empty($parts1["scheme"])) {
339                         $parts1["scheme"] = '';
340                 }
341                 if (empty($parts2["scheme"])) {
342                         $parts2["scheme"] = '';
343                 }
344
345                 if ($parts1["scheme"] != $parts2["scheme"]) {
346                         return "";
347                 }
348
349                 if (empty($parts1["host"])) {
350                         $parts1["host"] = '';
351                 }
352                 if (empty($parts2["host"])) {
353                         $parts2["host"] = '';
354                 }
355
356                 if ($parts1["host"] != $parts2["host"]) {
357                         return "";
358                 }
359
360                 if (empty($parts1["port"])) {
361                         $parts1["port"] = '';
362                 }
363                 if (empty($parts2["port"])) {
364                         $parts2["port"] = '';
365                 }
366
367                 if ($parts1["port"] != $parts2["port"]) {
368                         return "";
369                 }
370
371                 $match = $parts1["scheme"]."://".$parts1["host"];
372
373                 if ($parts1["port"]) {
374                         $match .= ":".$parts1["port"];
375                 }
376
377                 if (empty($parts1["path"])) {
378                         $parts1["path"] = '';
379                 }
380                 if (empty($parts2["path"])) {
381                         $parts2["path"] = '';
382                 }
383
384                 $pathparts1 = explode("/", $parts1["path"]);
385                 $pathparts2 = explode("/", $parts2["path"]);
386
387                 $i = 0;
388                 $path = "";
389                 do {
390                         $path1 = $pathparts1[$i] ?? '';
391                         $path2 = $pathparts2[$i] ?? '';
392
393                         if ($path1 == $path2) {
394                                 $path .= $path1."/";
395                         }
396                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
397
398                 $match .= $path;
399
400                 return Strings::normaliseLink($match);
401         }
402
403         /**
404          * Glue url parts together
405          *
406          * @param array $parsed URL parts
407          *
408          * @return string The glued URL
409          */
410         public static function unparseURL(array $parsed)
411         {
412                 $get = function ($key) use ($parsed) {
413                         return isset($parsed[$key]) ? $parsed[$key] : null;
414                 };
415
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."@" : '') .
424                                                 $get('host') .
425                                                 ($port ? ":$port" : '');
426
427                 return  (strlen($scheme) ? $scheme.":" : '') .
428                         (strlen($authority) ? "//".$authority : '') .
429                         $get('path') .
430                         (strlen($query) ? "?".$query : '') .
431                         (strlen($fragment) ? "#".$fragment : '');
432         }
433
434
435         /**
436          * Switch the scheme of an url between http and https
437          *
438          * @param string $url URL
439          *
440          * @return string switched URL
441          */
442         public static function switchScheme(string $url)
443         {
444                 $scheme = parse_url($url, PHP_URL_SCHEME);
445                 if (empty($scheme)) {
446                         return $url;
447                 }
448
449                 if ($scheme === 'http') {
450                         $url = str_replace('http://', 'https://', $url);
451                 } elseif ($scheme === 'https') {
452                         $url = str_replace('https://', 'http://', $url);
453                 }
454
455                 return $url;
456         }
457
458         /**
459          * Adds query string parameters to the provided URI. Replace the value of existing keys.
460          *
461          * @param string $path
462          * @param array  $additionalParams Associative array of parameters
463          * @return string
464          */
465         public static function appendQueryParam(string $path, array $additionalParams)
466         {
467                 $parsed = parse_url($path);
468
469                 $params = [];
470                 if (!empty($parsed['query'])) {
471                         parse_str($parsed['query'], $params);
472                 }
473
474                 $params = array_merge($params, $additionalParams);
475
476                 $parsed['query'] = http_build_query($params);
477
478                 return self::unparseURL($parsed);
479         }
480
481         /**
482          * Generates ETag and Last-Modified response headers and checks them against
483          * If-None-Match and If-Modified-Since request headers if present.
484          *
485          * Blocking function, sends 304 headers and exits if check passes.
486          *
487          * @param string $etag          The page etag
488          * @param string $last_modified The page last modification UTC date
489          * @throws \Exception
490          */
491         public static function checkEtagModified(string $etag, string $last_modified)
492         {
493                 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
494
495                 /**
496                  * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
497                  */
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) {
502                         $result = [];
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;
507                 }
508
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;
512                 }
513
514                 header('Etag: ' . $etag);
515                 header('Last-Modified: ' . $last_modified);
516
517                 if ($flag_not_modified) {
518                         header("HTTP/1.1 304 Not Modified");
519                         exit;
520                 }
521         }
522 }