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