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