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