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