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