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