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