]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Some more "baseurl" improvements
[friendica.git] / src / Network / Probe.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\Network;
23
24 use DOMDocument;
25 use DomXPath;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Model\Contact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Profile;
35 use Friendica\Protocol\ActivityNamespace;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Email;
38 use Friendica\Protocol\Feed;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\Network;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
43
44 /**
45  * This class contain functions for probing URL
46  */
47 class Probe
48 {
49         private static $baseurl;
50         private static $istimeout;
51
52         /**
53          * Remove stuff from an URI that doesn't belong there
54          *
55          * @param string $URI
56          * @return string Cleaned URI
57          */
58         public static function cleanURI(string $URI)
59         {
60                 // At first remove leading and trailing junk
61                 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
62
63                 $parts = parse_url($URI);
64
65                 if (empty($parts['scheme'])) {
66                         return $URI;
67                 }
68
69                 // Remove the URL fragment, since these shouldn't be part of any profile URL
70                 unset($parts['fragment']);
71
72                 $URI = Network::unparseURL($parts);
73
74                 return $URI;
75         }
76
77         /**
78          * Rearrange the array so that it always has the same order
79          *
80          * @param array $data Unordered data
81          *
82          * @return array Ordered data
83          */
84         private static function rearrangeData($data)
85         {
86                 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
87                                 "community", "keywords", "location", "about", "hide",
88                                 "batch", "notify", "poll", "request", "confirm", "poco",
89                                 "following", "followers", "inbox", "outbox", "sharedinbox",
90                                 "priority", "network", "pubkey", "baseurl", "gsid"];
91
92                 $newdata = [];
93                 foreach ($fields as $field) {
94                         if (isset($data[$field])) {
95                                 $newdata[$field] = $data[$field];
96                         } elseif ($field != "gsid") {
97                                 $newdata[$field] = "";
98                         } else {
99                                 $newdata[$field] = null;
100                         }
101                 }
102
103                 // We don't use the "priority" field anymore and replace it with a dummy.
104                 $newdata["priority"] = 0;
105
106                 return $newdata;
107         }
108
109         /**
110          * Check if the hostname belongs to the own server
111          *
112          * @param string $host The hostname that is to be checked
113          *
114          * @return bool Does the testes hostname belongs to the own server?
115          */
116         private static function ownHost($host)
117         {
118                 $own_host = DI::baseUrl()->getHostname();
119
120                 $parts = parse_url($host);
121
122                 if (!isset($parts['scheme'])) {
123                         $parts = parse_url('http://'.$host);
124                 }
125
126                 if (!isset($parts['host'])) {
127                         return false;
128                 }
129                 return $parts['host'] == $own_host;
130         }
131
132         /**
133          * Probes for webfinger path via "host-meta"
134          *
135          * We have to check if the servers in the future still will offer this.
136          * It seems as if it was dropped from the standard.
137          *
138          * @param string $host The host part of an url
139          *
140          * @return array with template and type of the webfinger template for JSON or XML
141          * @throws HTTPException\InternalServerErrorException
142          */
143         private static function hostMeta($host)
144         {
145                 // Reset the static variable
146                 self::$baseurl = '';
147
148                 // Handles the case when the hostname contains the scheme
149                 if (!parse_url($host, PHP_URL_SCHEME)) {
150                         $ssl_url = "https://" . $host . "/.well-known/host-meta";
151                         $url = "http://" . $host . "/.well-known/host-meta";
152                 } else {
153                         $ssl_url = $host . "/.well-known/host-meta";
154                         $url = '';
155                 }
156
157                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
158
159                 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
160                 $xrd = null;
161
162                 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
163                 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
164                 if ($curlResult->isSuccess()) {
165                         $xml = $curlResult->getBody();
166                         $xrd = XML::parseString($xml, true);
167                         if (!empty($url)) {
168                                 $host_url = 'https://' . $host;
169                         } else {
170                                 $host_url = $host;
171                         }
172                 } elseif ($curlResult->isTimeout()) {
173                         Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
174                         self::$istimeout = true;
175                         return false;
176                 }
177
178                 if (!is_object($xrd) && !empty($url)) {
179                         $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
180                         $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
181                         if ($curlResult->isTimeout()) {
182                                 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
183                                 self::$istimeout = true;
184                                 return false;
185                         } elseif ($connection_error && $ssl_connection_error) {
186                                 self::$istimeout = true;
187                                 return false;
188                         }
189
190                         $xml = $curlResult->getBody();
191                         $xrd = XML::parseString($xml, true);
192                         $host_url = 'http://'.$host;
193                 }
194                 if (!is_object($xrd)) {
195                         Logger::log("No xrd object found for ".$host, Logger::DEBUG);
196                         return [];
197                 }
198
199                 $links = XML::elementToArray($xrd);
200                 if (!isset($links["xrd"]["link"])) {
201                         Logger::log("No xrd data found for ".$host, Logger::DEBUG);
202                         return [];
203                 }
204
205                 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
206
207                 foreach ($links["xrd"]["link"] as $value => $link) {
208                         if (!empty($link["@attributes"])) {
209                                 $attributes = $link["@attributes"];
210                         } elseif ($value == "@attributes") {
211                                 $attributes = $link;
212                         } else {
213                                 continue;
214                         }
215
216                         if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
217                                 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
218
219                                 $lrdd[$type] = $attributes["template"];
220                         }
221                 }
222
223                 self::$baseurl = $host_url;
224
225                 Logger::log("Probing successful for ".$host, Logger::DEBUG);
226
227                 return $lrdd;
228         }
229
230         /**
231          * Perform Webfinger lookup and return DFRN data
232          *
233          * Given an email style address, perform webfinger lookup and
234          * return the resulting DFRN profile URL, or if no DFRN profile URL
235          * is located, returns an OStatus subscription template (prefixed
236          * with the string 'stat:' to identify it as on OStatus template).
237          * If this isn't an email style address just return $webbie.
238          * Return an empty string if email-style addresses but webfinger fails,
239          * or if the resultant personal XRD doesn't contain a supported
240          * subscription/friend-request attribute.
241          *
242          * amended 7/9/2011 to return an hcard which could save potentially loading
243          * a lengthy content page to scrape dfrn attributes
244          *
245          * @param string $webbie    Address that should be probed
246          * @param string $hcard_url Link to the hcard - is returned by reference
247          *
248          * @return string profile link
249          * @throws HTTPException\InternalServerErrorException
250          */
251         public static function webfingerDfrn($webbie, &$hcard_url)
252         {
253                 $profile_link = '';
254
255                 $links = self::lrdd($webbie);
256                 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
257                 if (!empty($links) && is_array($links)) {
258                         foreach ($links as $link) {
259                                 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
260                                         $profile_link = $link['@attributes']['href'];
261                                 }
262                                 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
263                                         $profile_link = 'stat:'.$link['@attributes']['template'];
264                                 }
265                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
266                                         $hcard_url = $link['@attributes']['href'];
267                                 }
268                         }
269                 }
270                 return $profile_link;
271         }
272
273         /**
274          * Get the link for the remote follow page for a given profile link
275          *
276          * @param sting $profile
277          * @return string Remote follow page link
278          */
279         public static function getRemoteFollowLink(string $profile)
280         {
281                 $follow_link = '';
282
283                 $links = self::lrdd($profile);
284
285                 if (!empty($links) && is_array($links)) {
286                         foreach ($links as $link) {
287                                 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
288                                         $follow_link = $link['@attributes']['template'];
289                                 }
290                         }
291                 }
292                 return $follow_link;
293         }
294
295         /**
296          * Check an URI for LRDD data
297          *
298          * @param string $uri Address that should be probed
299          *
300          * @return array uri data
301          * @throws HTTPException\InternalServerErrorException
302          */
303         public static function lrdd($uri)
304         {
305                 $lrdd = self::hostMeta($uri);
306                 $webfinger = null;
307
308                 if (is_bool($lrdd)) {
309                         return [];
310                 }
311
312                 if (!$lrdd) {
313                         $parts = @parse_url($uri);
314                         if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
315                                 return [];
316                         }
317
318                         $host = $parts['scheme'] . '://' . $parts["host"];
319                         if (!empty($parts["port"])) {
320                                 $host .= ':'.$parts["port"];
321                         }
322
323                         $path_parts = explode("/", trim($parts["path"], "/"));
324
325                         $nick = array_pop($path_parts);
326
327                         do {
328                                 $lrdd = self::hostMeta($host);
329                                 $host .= "/".array_shift($path_parts);
330                         } while (!$lrdd && (sizeof($path_parts) > 0));
331                 }
332
333                 if (!$lrdd) {
334                         Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
335                         return [];
336                 }
337
338                 foreach ($lrdd as $type => $template) {
339                         if ($webfinger) {
340                                 continue;
341                         }
342
343                         $path = str_replace('{uri}', urlencode($uri), $template);
344                         $webfinger = self::webfinger($path, $type);
345
346                         if (!$webfinger && (strstr($uri, "@"))) {
347                                 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
348                                 $webfinger = self::webfinger($path, $type);
349                         }
350
351                         // Special treatment for Mastodon
352                         // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
353                         // But the webfinger for this format fails.
354                         if (!$webfinger && !empty($nick)) {
355                                 // Mastodon uses a "@" as prefix for usernames in their url format
356                                 $nick = ltrim($nick, '@');
357
358                                 $addr = $nick."@".$host;
359
360                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
361                                 $webfinger = self::webfinger($path, $type);
362                         }
363                 }
364
365                 if (!is_array($webfinger["links"])) {
366                         Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
367                         return false;
368                 }
369
370                 $data = [];
371
372                 foreach ($webfinger["links"] as $link) {
373                         $data[] = ["@attributes" => $link];
374                 }
375
376                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
377                         foreach ($webfinger["aliases"] as $alias) {
378                                 $data[] = ["@attributes" =>
379                                                         ["rel" => "alias",
380                                                                 "href" => $alias]];
381                         }
382                 }
383
384                 return $data;
385         }
386
387         /**
388          * Fetch information (protocol endpoints and user information) about a given uri
389          *
390          * @param string  $uri     Address that should be probed
391          * @param string  $network Test for this specific network
392          * @param integer $uid     User ID for the probe (only used for mails)
393          * @param boolean $cache   Use cached values?
394          *
395          * @return array uri data
396          * @throws HTTPException\InternalServerErrorException
397          * @throws \ImagickException
398          */
399         public static function uri($uri, $network = '', $uid = -1, $cache = true)
400         {
401                 if ($cache) {
402                         $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
403                         if (!is_null($result)) {
404                                 return $result;
405                         }
406                 }
407
408                 if ($uid == -1) {
409                         $uid = local_user();
410                 }
411
412                 self::$istimeout = false;
413
414                 if ($network != Protocol::ACTIVITYPUB) {
415                         $data = self::detect($uri, $network, $uid);
416                 } else {
417                         $data = null;
418                 }
419
420                 // When the previous detection process had got a time out
421                 // we could falsely detect a Friendica profile as AP profile.
422                 if (!self::$istimeout) {
423                         $ap_profile = ActivityPub::probeProfile($uri);
424
425                         if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
426                                 $data = $ap_profile;
427                         } elseif (!empty($ap_profile)) {
428                                 $ap_profile['batch'] = '';
429                                 $data = array_merge($ap_profile, $data);
430                         }
431                 } else {
432                         Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
433                 }
434
435                 if (!isset($data['url'])) {
436                         $data['url'] = $uri;
437                 }
438
439                 if (empty($data['photo'])) {
440                         $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
441                 }
442
443                 if (empty($data['name'])) {
444                         if (!empty($data['nick'])) {
445                                 $data['name'] = $data['nick'];
446                         }
447
448                         if (empty($data['name'])) {
449                                 $data['name'] = $data['url'];
450                         }
451                 }
452
453                 if (empty($data['nick'])) {
454                         $data['nick'] = strtolower($data['name']);
455
456                         if (strpos($data['nick'], ' ')) {
457                                 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
458                         }
459                 }
460
461                 if (!empty(self::$baseurl)) {
462                         $data['baseurl'] = self::$baseurl;
463                 }
464
465                 if (!empty($data['baseurl']) && empty($data['gsid'])) {
466                         $data['gsid'] = GServer::getID($data['baseurl']);
467                 }
468
469                 if (empty($data['network'])) {
470                         $data['network'] = Protocol::PHANTOM;
471                 }
472
473                 // Ensure that local connections always are DFRN
474                 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
475                         $data['network'] = Protocol::DFRN;
476                 }
477
478                 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
479                         $data['hide'] = self::getHideStatus($data['url']);
480                 }
481
482                 $data = self::rearrangeData($data);
483
484                 // Only store into the cache if the value seems to be valid
485                 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
486                         DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
487                 }
488
489                 return $data;
490         }
491
492
493         /**
494          * Fetches the "hide" status from the profile
495          *
496          * @param string $url URL of the profile
497          *
498          * @return boolean "hide" status
499          */
500         private static function getHideStatus($url)
501         {
502                 $curlResult = Network::curl($url);
503                 if (!$curlResult->isSuccess()) {
504                         return false;
505                 }
506
507                 // If the file is too large then exit
508                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
509                         return false;
510                 }
511
512                 // If it isn't a HTML file then exit
513                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
514                         return false;
515                 }
516
517                 $body = $curlResult->getBody();
518
519                 $doc = new DOMDocument();
520                 @$doc->loadHTML($body);
521
522                 $xpath = new DOMXPath($doc);
523
524                 $list = $xpath->query('//meta[@name]');
525                 foreach ($list as $node) {
526                         $meta_tag = [];
527                         if ($node->attributes->length) {
528                                 foreach ($node->attributes as $attribute) {
529                                         $meta_tag[$attribute->name] = $attribute->value;
530                                 }
531                         }
532
533                         if (empty($meta_tag['content'])) {
534                                 continue;
535                         }
536
537                         $content = strtolower(trim($meta_tag['content']));
538
539                         switch (strtolower(trim($meta_tag['name']))) {
540                                 case 'dfrn-global-visibility':
541                                         if ($content == 'false') {
542                                                 return true;
543                                         }
544                                         break;
545                                 case 'robots':
546                                         if (strpos($content, 'noindex') !== false) {
547                                                 return true;
548                                         }
549                                         break;
550                         }
551                 }
552
553                 return false;
554         }
555
556         /**
557          * Checks if a profile url should be OStatus but only provides partial information
558          *
559          * @param array  $webfinger Webfinger data
560          * @param string $lrdd      Path template for webfinger request
561          * @param string $type      type
562          *
563          * @return array fixed webfinger data
564          * @throws HTTPException\InternalServerErrorException
565          */
566         private static function fixOStatus($webfinger, $lrdd, $type)
567         {
568                 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
569                         return $webfinger;
570                 }
571
572                 $is_ostatus = false;
573                 $has_key = false;
574
575                 foreach ($webfinger['links'] as $link) {
576                         if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
577                                 $is_ostatus = true;
578                         }
579                         if ($link['rel'] == 'magic-public-key') {
580                                 $has_key = true;
581                         }
582                 }
583
584                 if (!$is_ostatus || $has_key) {
585                         return $webfinger;
586                 }
587
588                 $url = Network::switchScheme($webfinger['subject']);
589                 $path = str_replace('{uri}', urlencode($url), $lrdd);
590                 $webfinger2 = self::webfinger($path, $type);
591
592                 // Is the new webfinger detectable as OStatus?
593                 if (self::ostatus($webfinger2, true)) {
594                         $webfinger = $webfinger2;
595                 }
596
597                 return $webfinger;
598         }
599
600         /**
601          * Fetch information (protocol endpoints and user information) about a given uri
602          *
603          * This function is only called by the "uri" function that adds caching and rearranging of data.
604          *
605          * @param string  $uri     Address that should be probed
606          * @param string  $network Test for this specific network
607          * @param integer $uid     User ID for the probe (only used for mails)
608          *
609          * @return array uri data
610          * @throws HTTPException\InternalServerErrorException
611          */
612         private static function detect($uri, $network, $uid)
613         {
614                 $parts = parse_url($uri);
615
616                 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
617                         $host = $parts["host"];
618                         if (!empty($parts["port"])) {
619                                 $host .= ':'.$parts["port"];
620                         }
621
622                         if ($host == 'twitter.com') {
623                                 return self::twitter($uri);
624                         }
625                         $lrdd = self::hostMeta($host);
626
627                         if (is_bool($lrdd)) {
628                                 return [];
629                         }
630
631                         $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
632
633                         while (!$lrdd && (sizeof($path_parts) > 1)) {
634                                 $host .= "/".array_shift($path_parts);
635                                 $lrdd = self::hostMeta($host);
636                         }
637                         if (!$lrdd) {
638                                 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
639                                 return self::feed($uri);
640                         }
641                         $nick = array_pop($path_parts);
642
643                         // Mastodon uses a "@" as prefix for usernames in their url format
644                         $nick = ltrim($nick, '@');
645
646                         $addr = $nick."@".$host;
647                 } elseif (strstr($uri, '@')) {
648                         // If the URI starts with "mailto:" then jump directly to the mail detection
649                         if (strpos($uri, 'mailto:') !== false) {
650                                 $uri = str_replace('mailto:', '', $uri);
651                                 return self::mail($uri, $uid);
652                         }
653
654                         if ($network == Protocol::MAIL) {
655                                 return self::mail($uri, $uid);
656                         }
657                         // Remove "acct:" from the URI
658                         $uri = str_replace('acct:', '', $uri);
659
660                         $host = substr($uri, strpos($uri, '@') + 1);
661                         $nick = substr($uri, 0, strpos($uri, '@'));
662
663                         if (strpos($uri, '@twitter.com')) {
664                                 return self::twitter($uri);
665                         }
666                         $lrdd = self::hostMeta($host);
667
668                         if (is_bool($lrdd)) {
669                                 return [];
670                         }
671
672                         if (!$lrdd) {
673                                 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
674                                 return self::mail($uri, $uid);
675                         }
676                         $addr = $uri;
677                 } else {
678                         Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
679                         return false;
680                 }
681
682                 $webfinger = false;
683
684                 /// @todo Do we need the prefix "acct:" or "acct://"?
685
686                 foreach ($lrdd as $type => $template) {
687                         if ($webfinger) {
688                                 continue;
689                         }
690
691                         // At first try it with the given uri
692                         $path = str_replace('{uri}', urlencode($uri), $template);
693                         $webfinger = self::webfinger($path, $type);
694
695                         // Fix possible problems with GNU Social probing to wrong scheme
696                         $webfinger = self::fixOStatus($webfinger, $template, $type);
697
698                         // We cannot be sure that the detected address was correct, so we don't use the values
699                         if ($webfinger && ($uri != $addr)) {
700                                 $nick = "";
701                                 $addr = "";
702                         }
703
704                         // Try webfinger with the address (user@domain.tld)
705                         if (!$webfinger) {
706                                 $path = str_replace('{uri}', urlencode($addr), $template);
707                                 $webfinger = self::webfinger($path, $type);
708                         }
709
710                         // Mastodon needs to have it with "acct:"
711                         if (!$webfinger) {
712                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
713                                 $webfinger = self::webfinger($path, $type);
714                         }
715                 }
716
717                 if (!$webfinger) {
718                         return self::feed($uri);
719                 }
720
721                 $result = false;
722
723                 Logger::log("Probing ".$uri, Logger::DEBUG);
724
725                 if (in_array($network, ["", Protocol::DFRN])) {
726                         $result = self::dfrn($webfinger);
727                 }
728                 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
729                         $result = self::diaspora($webfinger);
730                 }
731                 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
732                         $result = self::ostatus($webfinger);
733                 }
734                 if (in_array($network, ['', Protocol::ZOT])) {
735                         $result = self::zot($webfinger, $result);
736                 }
737                 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
738                         $result = self::pumpio($webfinger, $addr);
739                 }
740                 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
741                         $result = self::feed($uri);
742                 } else {
743                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
744                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
745                         if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
746                                 $result["nick"] = $nick;
747                         }
748
749                         if (empty($result["addr"]) && ($addr != "")) {
750                                 $result["addr"] = $addr;
751                         }
752                 }
753
754                 if (empty($result["network"])) {
755                         $result["network"] = Protocol::PHANTOM;
756                 }
757
758                 if (empty($result["url"])) {
759                         $result["url"] = $uri;
760                 }
761
762                 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
763
764                 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
765                         $pos = strpos($result["url"], $host);
766                         if ($pos) {
767                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
768                         }
769                 }
770                 return $result;
771         }
772
773         /**
774          * Check for Zot contact
775          *
776          * @param array $webfinger Webfinger data
777          * @param array $data      previously probed data
778          *
779          * @return array Zot data
780          * @throws HTTPException\InternalServerErrorException
781          */
782         private static function zot($webfinger, $data)
783         {
784                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
785                         foreach ($webfinger["aliases"] as $alias) {
786                                 if (substr($alias, 0, 5) == 'acct:') {
787                                         $data["addr"] = substr($alias, 5);
788                                 }
789                         }
790                 }
791
792                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
793                         $data["addr"] = substr($webfinger["subject"], 5);
794                 }
795
796                 $zot_url = '';
797                 foreach ($webfinger['links'] as $link) {
798                         if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
799                                 $zot_url = $link['href'];
800                         }
801                 }
802
803                 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
804                         $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
805                         if (!DBA::exists('gserver', $condition)) {
806                                 return $data;
807                         }
808                         $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
809                 }
810
811                 if (empty($zot_url)) {
812                         return $data;
813                 }
814
815                 $data = self::pollZot($zot_url, $data);
816
817                 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
818                         foreach ($webfinger['aliases'] as $alias) {
819                                 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
820                                         $data['alias'] = $alias;
821                                 }
822                         }
823                 }
824
825                 return $data;
826         }
827
828         public static function pollZot($url, $data)
829         {
830                 $curlResult = Network::curl($url);
831                 if ($curlResult->isTimeout()) {
832                         return $data;
833                 }
834                 $content = $curlResult->getBody();
835                 if (!$content) {
836                         return $data;
837                 }
838
839                 $json = json_decode($content, true);
840                 if (!is_array($json)) {
841                         return $data;
842                 }
843
844                 if (empty($data['network'])) {
845                         if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
846                                 $data['network'] = Protocol::ZOT;
847                         } elseif (!isset($json['protocols'])) {
848                                 $data['network'] = Protocol::ZOT;
849                         }
850                 }
851
852                 if (!empty($json['guid']) && empty($data['guid'])) {
853                         $data['guid'] = $json['guid'];
854                 }
855                 if (!empty($json['key']) && empty($data['pubkey'])) {
856                         $data['pubkey'] = $json['key'];
857                 }
858                 if (!empty($json['name'])) {
859                         $data['name'] = $json['name'];
860                 }
861                 if (!empty($json['photo'])) {
862                         $data['photo'] = $json['photo'];
863                         if (!empty($json['photo_updated'])) {
864                                 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
865                         }
866                 }
867                 if (!empty($json['address'])) {
868                         $data['addr'] = $json['address'];
869                 }
870                 if (!empty($json['url'])) {
871                         $data['url'] = $json['url'];
872                 }
873                 if (!empty($json['connections_url'])) {
874                         $data['poco'] = $json['connections_url'];
875                 }
876                 if (isset($json['searchable'])) {
877                         $data['hide'] = !$json['searchable'];
878                 }
879                 if (!empty($json['public_forum'])) {
880                         $data['community'] = $json['public_forum'];
881                         $data['account-type'] = Contact::PAGE_COMMUNITY;
882                 }
883
884                 if (!empty($json['profile'])) {
885                         $profile = $json['profile'];
886                         if (!empty($profile['description'])) {
887                                 $data['about'] = $profile['description'];
888                         }
889                         if (!empty($profile['keywords'])) {
890                                 $keywords = implode(', ', $profile['keywords']);
891                                 if (!empty($keywords)) {
892                                         $data['keywords'] = $keywords;
893                                 }
894                         }
895
896                         $loc = [];
897                         if (!empty($profile['region'])) {
898                                 $loc['region'] = $profile['region'];
899                         }
900                         if (!empty($profile['country'])) {
901                                 $loc['country-name'] = $profile['country'];
902                         }
903                         $location = Profile::formatLocation($loc);
904                         if (!empty($location)) {
905                                 $data['location'] = $location;
906                         }
907                 }
908
909                 return $data;
910         }
911
912         /**
913          * Perform a webfinger request.
914          *
915          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
916          *
917          * @param string $url  Address that should be probed
918          * @param string $type type
919          *
920          * @return array webfinger data
921          * @throws HTTPException\InternalServerErrorException
922          */
923         private static function webfinger($url, $type)
924         {
925                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
926
927                 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
928                 if ($curlResult->isTimeout()) {
929                         self::$istimeout = true;
930                         return false;
931                 }
932                 $data = $curlResult->getBody();
933
934                 $webfinger = json_decode($data, true);
935                 if (is_array($webfinger)) {
936                         if (!isset($webfinger["links"])) {
937                                 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
938                                 return false;
939                         }
940                         return $webfinger;
941                 }
942
943                 // If it is not JSON, maybe it is XML
944                 $xrd = XML::parseString($data, true);
945                 if (!is_object($xrd)) {
946                         Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
947                         return false;
948                 }
949
950                 $xrd_arr = XML::elementToArray($xrd);
951                 if (!isset($xrd_arr["xrd"]["link"])) {
952                         Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
953                         return false;
954                 }
955
956                 $webfinger = [];
957
958                 if (!empty($xrd_arr["xrd"]["subject"])) {
959                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
960                 }
961
962                 if (!empty($xrd_arr["xrd"]["alias"])) {
963                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
964                 }
965
966                 $webfinger["links"] = [];
967
968                 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
969                         if (!empty($data["@attributes"])) {
970                                 $attributes = $data["@attributes"];
971                         } elseif ($value == "@attributes") {
972                                 $attributes = $data;
973                         } else {
974                                 continue;
975                         }
976
977                         $webfinger["links"][] = $attributes;
978                 }
979                 return $webfinger;
980         }
981
982         /**
983          * Poll the Friendica specific noscrape page.
984          *
985          * "noscrape" is a faster alternative to fetch the data from the hcard.
986          * This functionality was originally created for the directory.
987          *
988          * @param string $noscrape_url Link to the noscrape page
989          * @param array  $data         The already fetched data
990          *
991          * @return array noscrape data
992          * @throws HTTPException\InternalServerErrorException
993          */
994         private static function pollNoscrape($noscrape_url, $data)
995         {
996                 $curlResult = Network::curl($noscrape_url);
997                 if ($curlResult->isTimeout()) {
998                         self::$istimeout = true;
999                         return false;
1000                 }
1001                 $content = $curlResult->getBody();
1002                 if (!$content) {
1003                         Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1004                         return false;
1005                 }
1006
1007                 $json = json_decode($content, true);
1008                 if (!is_array($json)) {
1009                         Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1010                         return false;
1011                 }
1012
1013                 if (!empty($json["fn"])) {
1014                         $data["name"] = $json["fn"];
1015                 }
1016
1017                 if (!empty($json["addr"])) {
1018                         $data["addr"] = $json["addr"];
1019                 }
1020
1021                 if (!empty($json["nick"])) {
1022                         $data["nick"] = $json["nick"];
1023                 }
1024
1025                 if (!empty($json["guid"])) {
1026                         $data["guid"] = $json["guid"];
1027                 }
1028
1029                 if (!empty($json["comm"])) {
1030                         $data["community"] = $json["comm"];
1031                 }
1032
1033                 if (!empty($json["tags"])) {
1034                         $keywords = implode(", ", $json["tags"]);
1035                         if ($keywords != "") {
1036                                 $data["keywords"] = $keywords;
1037                         }
1038                 }
1039
1040                 $location = Profile::formatLocation($json);
1041                 if ($location) {
1042                         $data["location"] = $location;
1043                 }
1044
1045                 if (!empty($json["about"])) {
1046                         $data["about"] = $json["about"];
1047                 }
1048
1049                 if (!empty($json["key"])) {
1050                         $data["pubkey"] = $json["key"];
1051                 }
1052
1053                 if (!empty($json["photo"])) {
1054                         $data["photo"] = $json["photo"];
1055                 }
1056
1057                 if (!empty($json["dfrn-request"])) {
1058                         $data["request"] = $json["dfrn-request"];
1059                 }
1060
1061                 if (!empty($json["dfrn-confirm"])) {
1062                         $data["confirm"] = $json["dfrn-confirm"];
1063                 }
1064
1065                 if (!empty($json["dfrn-notify"])) {
1066                         $data["notify"] = $json["dfrn-notify"];
1067                 }
1068
1069                 if (!empty($json["dfrn-poll"])) {
1070                         $data["poll"] = $json["dfrn-poll"];
1071                 }
1072
1073                 if (isset($json["hide"])) {
1074                         $data["hide"] = (bool)$json["hide"];
1075                 } else {
1076                         $data["hide"] = false;
1077                 }
1078
1079                 return $data;
1080         }
1081
1082         /**
1083          * Check for valid DFRN data
1084          *
1085          * @param array $data DFRN data
1086          *
1087          * @return int Number of errors
1088          */
1089         public static function validDfrn($data)
1090         {
1091                 $errors = 0;
1092                 if (!isset($data['key'])) {
1093                         $errors ++;
1094                 }
1095                 if (!isset($data['dfrn-request'])) {
1096                         $errors ++;
1097                 }
1098                 if (!isset($data['dfrn-confirm'])) {
1099                         $errors ++;
1100                 }
1101                 if (!isset($data['dfrn-notify'])) {
1102                         $errors ++;
1103                 }
1104                 if (!isset($data['dfrn-poll'])) {
1105                         $errors ++;
1106                 }
1107                 return $errors;
1108         }
1109
1110         /**
1111          * Fetch data from a DFRN profile page and via "noscrape"
1112          *
1113          * @param string $profile_link Link to the profile page
1114          *
1115          * @return array profile data
1116          * @throws HTTPException\InternalServerErrorException
1117          * @throws \ImagickException
1118          */
1119         public static function profile($profile_link)
1120         {
1121                 $data = [];
1122
1123                 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1124
1125                 // Fetch data via noscrape - this is faster
1126                 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1127                 $data = self::pollNoscrape($noscrape_url, $data);
1128
1129                 if (!isset($data["notify"])
1130                         || !isset($data["confirm"])
1131                         || !isset($data["request"])
1132                         || !isset($data["poll"])
1133                         || !isset($data["name"])
1134                         || !isset($data["photo"])
1135                 ) {
1136                         $data = self::pollHcard($profile_link, $data, true);
1137                 }
1138
1139                 $prof_data = [];
1140
1141                 if (empty($data["addr"]) || empty($data["nick"])) {
1142                         $probe_data = self::uri($profile_link);
1143                         $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1144                         $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1145                 }
1146
1147                 $prof_data["addr"]         = $data["addr"];
1148                 $prof_data["nick"]         = $data["nick"];
1149                 $prof_data["dfrn-request"] = $data['request'] ?? null;
1150                 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1151                 $prof_data["dfrn-notify"]  = $data['notify']  ?? null;
1152                 $prof_data["dfrn-poll"]    = $data['poll']    ?? null;
1153                 $prof_data["photo"]        = $data['photo']   ?? null;
1154                 $prof_data["fn"]           = $data['name']    ?? null;
1155                 $prof_data["key"]          = $data['pubkey']  ?? null;
1156
1157                 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1158
1159                 return $prof_data;
1160         }
1161
1162         /**
1163          * Check for DFRN contact
1164          *
1165          * @param array $webfinger Webfinger data
1166          *
1167          * @return array DFRN data
1168          * @throws HTTPException\InternalServerErrorException
1169          */
1170         private static function dfrn($webfinger)
1171         {
1172                 $hcard_url = "";
1173                 $data = [];
1174                 // The array is reversed to take into account the order of preference for same-rel links
1175                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1176                 foreach (array_reverse($webfinger["links"]) as $link) {
1177                         if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1178                                 $data["network"] = Protocol::DFRN;
1179                         } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1180                                 $data["poll"] = $link["href"];
1181                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1182                                 $data["url"] = $link["href"];
1183                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1184                                 $hcard_url = $link["href"];
1185                         } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1186                                 $data["poco"] = $link["href"];
1187                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1188                                 $data["photo"] = $link["href"];
1189                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1190                                 $data["baseurl"] = trim($link["href"], '/');
1191                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1192                                 $data["guid"] = $link["href"];
1193                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1194                                 $data["pubkey"] = base64_decode($link["href"]);
1195
1196                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1197                                 if (strstr($data["pubkey"], 'RSA ')) {
1198                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1199                                 }
1200                         }
1201                 }
1202
1203                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1204                         foreach ($webfinger["aliases"] as $alias) {
1205                                 if (empty($data["url"]) && !strstr($alias, "@")) {
1206                                         $data["url"] = $alias;
1207                                 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1208                                         $data["alias"] = $alias;
1209                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1210                                         $data["addr"] = substr($alias, 5);
1211                                 }
1212                         }
1213                 }
1214
1215                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1216                         $data["addr"] = substr($webfinger["subject"], 5);
1217                 }
1218
1219                 if (!isset($data["network"]) || ($hcard_url == "")) {
1220                         return false;
1221                 }
1222
1223                 // Fetch data via noscrape - this is faster
1224                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1225                 $data = self::pollNoscrape($noscrape_url, $data);
1226
1227                 if (isset($data["notify"])
1228                         && isset($data["confirm"])
1229                         && isset($data["request"])
1230                         && isset($data["poll"])
1231                         && isset($data["name"])
1232                         && isset($data["photo"])
1233                 ) {
1234                         return $data;
1235                 }
1236
1237                 $data = self::pollHcard($hcard_url, $data, true);
1238
1239                 return $data;
1240         }
1241
1242         /**
1243          * Poll the hcard page (Diaspora and Friendica specific)
1244          *
1245          * @param string  $hcard_url Link to the hcard page
1246          * @param array   $data      The already fetched data
1247          * @param boolean $dfrn      Poll DFRN specific data
1248          *
1249          * @return array hcard data
1250          * @throws HTTPException\InternalServerErrorException
1251          */
1252         private static function pollHcard($hcard_url, $data, $dfrn = false)
1253         {
1254                 $curlResult = Network::curl($hcard_url);
1255                 if ($curlResult->isTimeout()) {
1256                         self::$istimeout = true;
1257                         return false;
1258                 }
1259                 $content = $curlResult->getBody();
1260                 if (!$content) {
1261                         return false;
1262                 }
1263
1264                 $doc = new DOMDocument();
1265                 if (!@$doc->loadHTML($content)) {
1266                         return false;
1267                 }
1268
1269                 $xpath = new DomXPath($doc);
1270
1271                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1272                 if (!is_object($vcards)) {
1273                         return false;
1274                 }
1275
1276                 if (!isset($data["baseurl"])) {
1277                         $data["baseurl"] = "";
1278                 }
1279
1280                 if ($vcards->length > 0) {
1281                         $vcard = $vcards->item(0);
1282
1283                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1284                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1285                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1286                         if (($search->length > 0) && empty($data["guid"])) {
1287                                 $data["guid"] = $search->item(0)->nodeValue;
1288                         }
1289
1290                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1291                         if ($search->length > 0) {
1292                                 $data["nick"] = $search->item(0)->nodeValue;
1293                         }
1294
1295                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1296                         if ($search->length > 0) {
1297                                 $data["name"] = $search->item(0)->nodeValue;
1298                         }
1299
1300                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1301                         if ($search->length > 0) {
1302                                 $data["searchable"] = $search->item(0)->nodeValue;
1303                         }
1304
1305                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1306                         if ($search->length > 0) {
1307                                 $data["pubkey"] = $search->item(0)->nodeValue;
1308                                 if (strstr($data["pubkey"], 'RSA ')) {
1309                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1310                                 }
1311                         }
1312
1313                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1314                         if ($search->length > 0) {
1315                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1316                         }
1317                 }
1318
1319                 $avatar = [];
1320                 if (!empty($vcard)) {
1321                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1322                         foreach ($photos as $photo) {
1323                                 $attr = [];
1324                                 foreach ($photo->attributes as $attribute) {
1325                                         $attr[$attribute->name] = trim($attribute->value);
1326                                 }
1327
1328                                 if (isset($attr["src"]) && isset($attr["width"])) {
1329                                         $avatar[$attr["width"]] = $attr["src"];
1330                                 }
1331
1332                                 // We don't have a width. So we just take everything that we got.
1333                                 // This is a Hubzilla workaround which doesn't send a width.
1334                                 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1335                                         $avatar[] = $attr["src"];
1336                                 }
1337                         }
1338                 }
1339
1340                 if (sizeof($avatar)) {
1341                         ksort($avatar);
1342                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1343                 }
1344
1345                 if ($dfrn) {
1346                         // Poll DFRN specific data
1347                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1348                         if ($search->length > 0) {
1349                                 foreach ($search as $link) {
1350                                         //$data["request"] = $search->item(0)->nodeValue;
1351                                         $attr = [];
1352                                         foreach ($link->attributes as $attribute) {
1353                                                 $attr[$attribute->name] = trim($attribute->value);
1354                                         }
1355
1356                                         $data[substr($attr["rel"], 5)] = $attr["href"];
1357                                 }
1358                         }
1359
1360                         // Older Friendica versions had used the "uid" field differently than newer versions
1361                         if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1362                                 unset($data["guid"]);
1363                         }
1364                 }
1365
1366
1367                 return $data;
1368         }
1369
1370         /**
1371          * Check for Diaspora contact
1372          *
1373          * @param array $webfinger Webfinger data
1374          *
1375          * @return array Diaspora data
1376          * @throws HTTPException\InternalServerErrorException
1377          */
1378         private static function diaspora($webfinger)
1379         {
1380                 $hcard_url = "";
1381                 $data = [];
1382
1383                 // The array is reversed to take into account the order of preference for same-rel links
1384                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1385                 foreach (array_reverse($webfinger["links"]) as $link) {
1386                         if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1387                                 $hcard_url = $link["href"];
1388                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1389                                 $data["baseurl"] = trim($link["href"], '/');
1390                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1391                                 $data["guid"] = $link["href"];
1392                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1393                                 $data["url"] = $link["href"];
1394                         } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1395                                 $data["poll"] = $link["href"];
1396                         } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1397                                 $data["poco"] = $link["href"];
1398                         } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1399                                 $data["notify"] = $link["href"];
1400                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1401                                 $data["pubkey"] = base64_decode($link["href"]);
1402
1403                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1404                                 if (strstr($data["pubkey"], 'RSA ')) {
1405                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1406                                 }
1407                         }
1408                 }
1409
1410                 if (empty($data["url"]) || empty($hcard_url)) {
1411                         return false;
1412                 }
1413
1414                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1415                         foreach ($webfinger["aliases"] as $alias) {
1416                                 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1417                                         $data["alias"] = $alias;
1418                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1419                                         $data["addr"] = substr($alias, 5);
1420                                 }
1421                         }
1422                 }
1423
1424                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1425                         $data["addr"] = substr($webfinger["subject"], 5);
1426                 }
1427
1428                 // Fetch further information from the hcard
1429                 $data = self::pollHcard($hcard_url, $data);
1430
1431                 if (!$data) {
1432                         return false;
1433                 }
1434
1435                 if (!empty($data["url"])
1436                         && !empty($data["guid"])
1437                         && !empty($data["baseurl"])
1438                         && !empty($data["pubkey"])
1439                         && !empty($hcard_url)
1440                 ) {
1441                         $data["network"] = Protocol::DIASPORA;
1442
1443                         // The Diaspora handle must always be lowercase
1444                         if (!empty($data["addr"])) {
1445                                 $data["addr"] = strtolower($data["addr"]);
1446                         }
1447
1448                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1449                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1450                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1451                 } else {
1452                         return false;
1453                 }
1454
1455                 return $data;
1456         }
1457
1458         /**
1459          * Check for OStatus contact
1460          *
1461          * @param array $webfinger Webfinger data
1462          * @param bool  $short     Short detection mode
1463          *
1464          * @return array|bool OStatus data or "false" on error or "true" on short mode
1465          * @throws HTTPException\InternalServerErrorException
1466          */
1467         private static function ostatus($webfinger, $short = false)
1468         {
1469                 $data = [];
1470
1471                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1472                         foreach ($webfinger["aliases"] as $alias) {
1473                                 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1474                                         $data["addr"] = str_replace('acct:', '', $alias);
1475                                 }
1476                         }
1477                 }
1478
1479                 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1480                         && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1481                 ) {
1482                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1483                 }
1484
1485                 if (is_array($webfinger["links"])) {
1486                         // The array is reversed to take into account the order of preference for same-rel links
1487                         // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1488                         foreach (array_reverse($webfinger["links"]) as $link) {
1489                                 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1490                                         && (($link["type"] ?? "") == "text/html")
1491                                         && ($link["href"] != "")
1492                                 ) {
1493                                         $data["url"] = $link["href"];
1494                                 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1495                                         $data["notify"] = $link["href"];
1496                                 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1497                                         $data["poll"] = $link["href"];
1498                                 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1499                                         $pubkey = $link["href"];
1500
1501                                         if (substr($pubkey, 0, 5) === 'data:') {
1502                                                 if (strstr($pubkey, ',')) {
1503                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1504                                                 } else {
1505                                                         $pubkey = substr($pubkey, 5);
1506                                                 }
1507                                         } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1508                                                 $curlResult = Network::curl($pubkey);
1509                                                 if ($curlResult->isTimeout()) {
1510                                                         self::$istimeout = true;
1511                                                         return false;
1512                                                 }
1513                                                 $pubkey = $curlResult->getBody();
1514                                         }
1515
1516                                         $key = explode(".", $pubkey);
1517
1518                                         if (sizeof($key) >= 3) {
1519                                                 $m = Strings::base64UrlDecode($key[1]);
1520                                                 $e = Strings::base64UrlDecode($key[2]);
1521                                                 $data["pubkey"] = Crypto::meToPem($m, $e);
1522                                         }
1523                                 }
1524                         }
1525                 }
1526
1527                 if (isset($data["notify"]) && isset($data["pubkey"])
1528                         && isset($data["poll"])
1529                         && isset($data["url"])
1530                 ) {
1531                         $data["network"] = Protocol::OSTATUS;
1532                 } else {
1533                         return false;
1534                 }
1535
1536                 if ($short) {
1537                         return true;
1538                 }
1539
1540                 // Fetch all additional data from the feed
1541                 $curlResult = Network::curl($data["poll"]);
1542                 if ($curlResult->isTimeout()) {
1543                         self::$istimeout = true;
1544                         return false;
1545                 }
1546                 $feed = $curlResult->getBody();
1547                 $feed_data = Feed::import($feed);
1548                 if (!$feed_data) {
1549                         return false;
1550                 }
1551
1552                 if (!empty($feed_data["header"]["author-name"])) {
1553                         $data["name"] = $feed_data["header"]["author-name"];
1554                 }
1555                 if (!empty($feed_data["header"]["author-nick"])) {
1556                         $data["nick"] = $feed_data["header"]["author-nick"];
1557                 }
1558                 if (!empty($feed_data["header"]["author-avatar"])) {
1559                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1560                 }
1561                 if (!empty($feed_data["header"]["author-id"])) {
1562                         $data["alias"] = $feed_data["header"]["author-id"];
1563                 }
1564                 if (!empty($feed_data["header"]["author-location"])) {
1565                         $data["location"] = $feed_data["header"]["author-location"];
1566                 }
1567                 if (!empty($feed_data["header"]["author-about"])) {
1568                         $data["about"] = $feed_data["header"]["author-about"];
1569                 }
1570                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1571                 // So we take the value that we just fetched, although the other one worked as well
1572                 if (!empty($feed_data["header"]["author-link"])) {
1573                         $data["url"] = $feed_data["header"]["author-link"];
1574                 }
1575
1576                 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1577                         $data['url'] = $data["alias"];
1578                         $data["alias"] = '';
1579                 }
1580
1581                 /// @todo Fetch location and "about" from the feed as well
1582                 return $data;
1583         }
1584
1585         /**
1586          * Fetch data from a pump.io profile page
1587          *
1588          * @param string $profile_link Link to the profile page
1589          *
1590          * @return array profile data
1591          */
1592         private static function pumpioProfileData($profile_link)
1593         {
1594                 $curlResult = Network::curl($profile_link);
1595                 if (!$curlResult->isSuccess()) {
1596                         return false;
1597                 }
1598
1599                 $doc = new DOMDocument();
1600                 if (!@$doc->loadHTML($curlResult->getBody())) {
1601                         return false;
1602                 }
1603
1604                 $xpath = new DomXPath($doc);
1605
1606                 $data = [];
1607
1608                 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1609
1610                 if ($data["name"] == '') {
1611                         // This is ugly - but pump.io doesn't seem to know a better way for it
1612                         $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1613                         $pos = strpos($data["name"], chr(10));
1614                         if ($pos) {
1615                                 $data["name"] = trim(substr($data["name"], 0, $pos));
1616                         }
1617                 }
1618
1619                 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1620
1621                 if ($data["location"] == '') {
1622                         $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1623                 }
1624
1625                 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1626
1627                 if ($data["about"] == '') {
1628                         $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1629                 }
1630
1631                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1632                 if (!$avatar) {
1633                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1634                 }
1635                 if ($avatar) {
1636                         foreach ($avatar->attributes as $attribute) {
1637                                 if ($attribute->name == "src") {
1638                                         $data["photo"] = trim($attribute->value);
1639                                 }
1640                         }
1641                 }
1642
1643                 return $data;
1644         }
1645
1646         /**
1647          * Check for pump.io contact
1648          *
1649          * @param array  $webfinger Webfinger data
1650          * @param string $addr
1651          * @return array pump.io data
1652          */
1653         private static function pumpio($webfinger, $addr)
1654         {
1655                 $data = [];
1656                 // The array is reversed to take into account the order of preference for same-rel links
1657                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1658                 foreach (array_reverse($webfinger["links"]) as $link) {
1659                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1660                                 && (($link["type"] ?? "") == "text/html")
1661                                 && ($link["href"] != "")
1662                         ) {
1663                                 $data["url"] = $link["href"];
1664                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1665                                 $data["notify"] = $link["href"];
1666                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1667                                 $data["poll"] = $link["href"];
1668                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1669                                 $data["dialback"] = $link["href"];
1670                         }
1671                 }
1672                 if (isset($data["poll"]) && isset($data["notify"])
1673                         && isset($data["dialback"])
1674                         && isset($data["url"])
1675                 ) {
1676                         // by now we use these fields only for the network type detection
1677                         // So we unset all data that isn't used at the moment
1678                         unset($data["dialback"]);
1679
1680                         $data["network"] = Protocol::PUMPIO;
1681                 } else {
1682                         return false;
1683                 }
1684
1685                 $profile_data = self::pumpioProfileData($data["url"]);
1686
1687                 if (!$profile_data) {
1688                         return false;
1689                 }
1690
1691                 $data = array_merge($data, $profile_data);
1692
1693                 if (($addr != '') && ($data['name'] != '')) {
1694                         $name = trim(str_replace($addr, '', $data['name']));
1695                         if ($name != '') {
1696                                 $data['name'] = $name;
1697                         }
1698                 }
1699
1700                 return $data;
1701         }
1702
1703         /**
1704          * Check for twitter contact
1705          *
1706          * @param string $uri
1707          *
1708          * @return array twitter data
1709          */
1710         private static function twitter($uri)
1711         {
1712                 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1713                         $nick = $matches[1];
1714                 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1715                         $nick = $matches[1];
1716                 } else {
1717                         return [];
1718                 }
1719
1720                 $data = [];
1721                 $data['url'] = 'https://twitter.com/' . $nick;
1722                 $data['addr'] = $nick . '@twitter.com';
1723                 $data['nick'] = $data['name'] = $nick;
1724                 $data['network'] = Protocol::TWITTER;
1725                 $data['baseurl'] = 'https://twitter.com';
1726
1727                 $curlResult = Network::curl($data['url'], false);
1728                 if (!$curlResult->isSuccess()) {
1729                         return [];
1730                 }
1731
1732                 $body = $curlResult->getBody();
1733                 $doc = new DOMDocument();
1734                 @$doc->loadHTML($body);
1735                 $xpath = new DOMXPath($doc);
1736
1737                 $list = $xpath->query('//img[@class]');
1738                 foreach ($list as $node) {
1739                         $img_attr = [];
1740                         if ($node->attributes->length) {
1741                                 foreach ($node->attributes as $attribute) {
1742                                         $img_attr[$attribute->name] = $attribute->value;
1743                                 }
1744                         }
1745
1746                         if (empty($img_attr['class'])) {
1747                                 continue;
1748                         }
1749
1750                         if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1751                                 if (!empty($img_attr['src'])) {
1752                                         $data['photo'] = $img_attr['src'];
1753                                 }
1754                                 if (!empty($img_attr['alt'])) {
1755                                         $data['name'] = $img_attr['alt'];
1756                                 }
1757                         }
1758                 }
1759
1760                 return $data;
1761         }
1762
1763         /**
1764          * Checks HTML page for RSS feed link
1765          *
1766          * @param string $url  Page link
1767          * @param string $body Page body string
1768          * @return string|false Feed link or false if body was invalid HTML document
1769          */
1770         public static function getFeedLink(string $url, string $body)
1771         {
1772                 $doc = new DOMDocument();
1773                 if (!@$doc->loadHTML($body)) {
1774                         return false;
1775                 }
1776
1777                 $xpath = new DOMXPath($doc);
1778
1779                 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1780
1781                 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1782
1783                 return $feedUrl;
1784         }
1785
1786         /**
1787          * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1788          *
1789          * Loosely based on RFC 1808
1790          *
1791          * @see https://tools.ietf.org/html/rfc1808
1792          *
1793          * @param string   $href  The potential relative href found in the HTML document
1794          * @param string   $base  The HTML document URL
1795          * @param DOMXPath $xpath The HTML document XPath
1796          * @return string
1797          */
1798         private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1799         {
1800                 if (filter_var($href, FILTER_VALIDATE_URL)) {
1801                         return $href;
1802                 }
1803
1804                 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1805
1806                 $baseParts = parse_url($base);
1807
1808                 // Naked domain case (scheme://basehost)
1809                 $path = $baseParts['path'] ?? '/';
1810
1811                 // Remove the filename part of the path if it exists (/base/path/file)
1812                 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1813
1814                 $hrefParts = parse_url($href);
1815
1816                 // Root path case (/path) including relative scheme case (//host/path)
1817                 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1818                         $path = $hrefParts['path'];
1819                 } else {
1820                         $path = $path . '/' . $hrefParts['path'];
1821
1822                         // Resolve arbitrary relative path
1823                         // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1824                         $parts = array_filter(explode('/', $path), 'strlen');
1825                         $absolutes = array();
1826                         foreach ($parts as $part) {
1827                                 if ('.' == $part) continue;
1828                                 if ('..' == $part) {
1829                                         array_pop($absolutes);
1830                                 } else {
1831                                         $absolutes[] = $part;
1832                                 }
1833                         }
1834
1835                         $path = '/' . implode('/', $absolutes);
1836                 }
1837
1838                 // Relative scheme case (//host/path)
1839                 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1840                 $baseParts['path'] = $path;
1841                 unset($baseParts['query']);
1842                 unset($baseParts['fragment']);
1843
1844                 return Network::unparseURL($baseParts);
1845         }
1846
1847         /**
1848          * Check for feed contact
1849          *
1850          * @param string  $url   Profile link
1851          * @param boolean $probe Do a probe if the page contains a feed link
1852          *
1853          * @return array feed data
1854          * @throws HTTPException\InternalServerErrorException
1855          */
1856         private static function feed($url, $probe = true)
1857         {
1858                 $curlResult = Network::curl($url);
1859                 if ($curlResult->isTimeout()) {
1860                         self::$istimeout = true;
1861                         return false;
1862                 }
1863                 $feed = $curlResult->getBody();
1864                 $feed_data = Feed::import($feed);
1865
1866                 if (!$feed_data) {
1867                         if (!$probe) {
1868                                 return false;
1869                         }
1870
1871                         $feed_url = self::getFeedLink($url, $feed);
1872
1873                         if (!$feed_url) {
1874                                 return false;
1875                         }
1876
1877                         return self::feed($feed_url, false);
1878                 }
1879
1880                 if (!empty($feed_data["header"]["author-name"])) {
1881                         $data["name"] = $feed_data["header"]["author-name"];
1882                 }
1883
1884                 if (!empty($feed_data["header"]["author-nick"])) {
1885                         $data["nick"] = $feed_data["header"]["author-nick"];
1886                 }
1887
1888                 if (!empty($feed_data["header"]["author-avatar"])) {
1889                         $data["photo"] = $feed_data["header"]["author-avatar"];
1890                 }
1891
1892                 if (!empty($feed_data["header"]["author-id"])) {
1893                         $data["alias"] = $feed_data["header"]["author-id"];
1894                 }
1895
1896                 $data["url"] = $url;
1897                 $data["poll"] = $url;
1898
1899                 if (!empty($feed_data["header"]["author-link"])) {
1900                         $data["baseurl"] = $feed_data["header"]["author-link"];
1901                 } else {
1902                         $data["baseurl"] = $data["url"];
1903                 }
1904
1905                 $data["network"] = Protocol::FEED;
1906
1907                 return $data;
1908         }
1909
1910         /**
1911          * Check for mail contact
1912          *
1913          * @param string  $uri Profile link
1914          * @param integer $uid User ID
1915          *
1916          * @return array mail data
1917          * @throws \Exception
1918          */
1919         private static function mail($uri, $uid)
1920         {
1921                 if (!Network::isEmailDomainValid($uri)) {
1922                         return false;
1923                 }
1924
1925                 if ($uid == 0) {
1926                         return false;
1927                 }
1928
1929                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1930
1931                 $condition = ["`uid` = ? AND `server` != ''", $uid];
1932                 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1933                 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1934
1935                 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1936                         return false;
1937                 }
1938
1939                 $mailbox = Email::constructMailboxName($mailacct);
1940                 $password = '';
1941                 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1942                 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1943                 if (!$mbox) {
1944                         return false;
1945                 }
1946
1947                 $msgs = Email::poll($mbox, $uri);
1948                 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1949
1950                 if (!count($msgs)) {
1951                         return false;
1952                 }
1953
1954                 $phost = substr($uri, strpos($uri, '@') + 1);
1955
1956                 $data = [];
1957                 $data["addr"]    = $uri;
1958                 $data["network"] = Protocol::MAIL;
1959                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1960                 $data["nick"]    = $data["name"];
1961                 $data["photo"]   = Network::lookupAvatarByEmail($uri);
1962                 $data["url"]     = 'mailto:'.$uri;
1963                 $data["notify"]  = 'smtp ' . Strings::getRandomHex();
1964                 $data["poll"]    = 'email ' . Strings::getRandomHex();
1965
1966                 $x = Email::messageMeta($mbox, $msgs[0]);
1967                 if (stristr($x[0]->from, $uri)) {
1968                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1969                 } elseif (stristr($x[0]->to, $uri)) {
1970                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1971                 }
1972                 if (isset($adr)) {
1973                         foreach ($adr as $feadr) {
1974                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1975                                         &&(strcasecmp($feadr->host, $phost) == 0)
1976                                         && (strlen($feadr->personal))
1977                                 ) {
1978                                         $personal = imap_mime_header_decode($feadr->personal);
1979                                         $data["name"] = "";
1980                                         foreach ($personal as $perspart) {
1981                                                 if ($perspart->charset != "default") {
1982                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1983                                                 } else {
1984                                                         $data["name"] .= $perspart->text;
1985                                                 }
1986                                         }
1987
1988                                         $data["name"] = Strings::escapeTags($data["name"]);
1989                                 }
1990                         }
1991                 }
1992                 if (!empty($mbox)) {
1993                         imap_close($mbox);
1994                 }
1995                 return $data;
1996         }
1997
1998         /**
1999          * Mix two paths together to possibly fix missing parts
2000          *
2001          * @param string $avatar Path to the avatar
2002          * @param string $base   Another path that is hopefully complete
2003          *
2004          * @return string fixed avatar path
2005          * @throws \Exception
2006          */
2007         public static function fixAvatar($avatar, $base)
2008         {
2009                 $base_parts = parse_url($base);
2010
2011                 // Remove all parts that could create a problem
2012                 unset($base_parts['path']);
2013                 unset($base_parts['query']);
2014                 unset($base_parts['fragment']);
2015
2016                 $avatar_parts = parse_url($avatar);
2017
2018                 // Now we mix them
2019                 $parts = array_merge($base_parts, $avatar_parts);
2020
2021                 // And put them together again
2022                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
2023                 $host     = isset($parts['host'])     ? $parts['host']           : '';
2024                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
2025                 $path     = isset($parts['path'])     ? $parts['path']           : '';
2026                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
2027                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2028
2029                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2030
2031                 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);
2032
2033                 return $fixed;
2034         }
2035 }