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