]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Do not remove trailing slash from URIs
[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(string $url, array $data): array
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 ')) {
1164                                         $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1165                                 }
1166                         }
1167                 }
1168
1169                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1170                         foreach ($webfinger['aliases'] as $alias) {
1171                                 if (empty($data['url']) && !strstr($alias, '@')) {
1172                                         $data['url'] = $alias;
1173                                 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1174                                         $data['alias'] = $alias;
1175                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1176                                         $data['addr'] = substr($alias, 5);
1177                                 }
1178                         }
1179                 }
1180
1181                 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1182                         $data['addr'] = substr($webfinger['subject'], 5);
1183                 }
1184
1185                 if (!isset($data['network']) || ($hcard_url == '')) {
1186                         return [];
1187                 }
1188
1189                 // Fetch data via noscrape - this is faster
1190                 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1191                 $data = self::pollNoscrape($noscrape_url, $data);
1192
1193                 if (isset($data['notify'])
1194                         && isset($data['confirm'])
1195                         && isset($data['request'])
1196                         && isset($data['poll'])
1197                         && isset($data['name'])
1198                         && isset($data['photo'])
1199                 ) {
1200                         return $data;
1201                 }
1202
1203                 $data = self::pollHcard($hcard_url, $data, true);
1204
1205                 return $data;
1206         }
1207
1208         /**
1209          * Poll the hcard page (Diaspora and Friendica specific)
1210          *
1211          * @param string  $hcard_url Link to the hcard page
1212          * @param array   $data      The already fetched data
1213          * @param boolean $dfrn      Poll DFRN specific data
1214          * @return array hcard data
1215          * @throws HTTPException\InternalServerErrorException
1216          */
1217         private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1218         {
1219                 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1220                 if ($curlResult->isTimeout()) {
1221                         self::$istimeout = true;
1222                         return [];
1223                 }
1224                 $content = $curlResult->getBody();
1225                 if (empty($content)) {
1226                         return [];
1227                 }
1228
1229                 $doc = new DOMDocument();
1230                 if (!@$doc->loadHTML($content)) {
1231                         return [];
1232                 }
1233
1234                 $xpath = new DomXPath($doc);
1235
1236                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1237                 if (!is_object($vcards)) {
1238                         return [];
1239                 }
1240
1241                 if (!isset($data['baseurl'])) {
1242                         $data['baseurl'] = '';
1243                 }
1244
1245                 if ($vcards->length > 0) {
1246                         $vcard = $vcards->item(0);
1247
1248                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1249                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1250                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1251                         if (($search->length > 0) && empty($data['guid'])) {
1252                                 $data['guid'] = $search->item(0)->nodeValue;
1253                         }
1254
1255                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1256                         if ($search->length > 0) {
1257                                 $data['nick'] = $search->item(0)->nodeValue;
1258                         }
1259
1260                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1261                         if ($search->length > 0) {
1262                                 $data['name'] = $search->item(0)->nodeValue;
1263                         }
1264
1265                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1266                         if ($search->length > 0) {
1267                                 $data['searchable'] = $search->item(0)->nodeValue;
1268                         }
1269
1270                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1271                         if ($search->length > 0) {
1272                                 $data['pubkey'] = $search->item(0)->nodeValue;
1273                                 if (strstr($data['pubkey'], 'RSA ')) {
1274                                         $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1275                                 }
1276                         }
1277
1278                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1279                         if ($search->length > 0) {
1280                                 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1281                         }
1282                 }
1283
1284                 $avatar = [];
1285                 if (!empty($vcard)) {
1286                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1287                         foreach ($photos as $photo) {
1288                                 $attr = [];
1289                                 foreach ($photo->attributes as $attribute) {
1290                                         $attr[$attribute->name] = trim($attribute->value);
1291                                 }
1292
1293                                 if (isset($attr['src']) && isset($attr['width'])) {
1294                                         $avatar[$attr['width']] = $attr['src'];
1295                                 }
1296
1297                                 // We don't have a width. So we just take everything that we got.
1298                                 // This is a Hubzilla workaround which doesn't send a width.
1299                                 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1300                                         $avatar[] = $attr['src'];
1301                                 }
1302                         }
1303                 }
1304
1305                 if (sizeof($avatar)) {
1306                         ksort($avatar);
1307                         $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1308                 }
1309
1310                 if ($dfrn) {
1311                         // Poll DFRN specific data
1312                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1313                         if ($search->length > 0) {
1314                                 foreach ($search as $link) {
1315                                         //$data['request'] = $search->item(0)->nodeValue;
1316                                         $attr = [];
1317                                         foreach ($link->attributes as $attribute) {
1318                                                 $attr[$attribute->name] = trim($attribute->value);
1319                                         }
1320
1321                                         $data[substr($attr['rel'], 5)] = $attr['href'];
1322                                 }
1323                         }
1324
1325                         // Older Friendica versions had used the "uid" field differently than newer versions
1326                         if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1327                                 unset($data['guid']);
1328                         }
1329                 }
1330
1331
1332                 return $data;
1333         }
1334
1335         /**
1336          * Check for Diaspora contact
1337          *
1338          * @param array $webfinger Webfinger data
1339          * @return array Diaspora data
1340          * @throws HTTPException\InternalServerErrorException
1341          */
1342         private static function diaspora(array $webfinger): array
1343         {
1344                 $hcard_url = '';
1345                 $data = [];
1346
1347                 // The array is reversed to take into account the order of preference for same-rel links
1348                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1349                 foreach (array_reverse($webfinger['links']) as $link) {
1350                         if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1351                                 $hcard_url = $link['href'];
1352                         } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1353                                 $data['baseurl'] = trim($link['href'], '/');
1354                         } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1355                                 $data['guid'] = $link['href'];
1356                         } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1357                                 $data['url'] = $link['href'];
1358                         } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1359                                 $profile_url = $link['href'];
1360                         } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1361                                 $data['poll'] = $link['href'];
1362                         } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1363                                 $data['poco'] = $link['href'];
1364                         } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1365                                 $data['notify'] = $link['href'];
1366                         } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1367                                 $data['pubkey'] = base64_decode($link['href']);
1368
1369                                 if (strstr($data['pubkey'], 'RSA ')) {
1370                                         $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1371                                 }
1372                         }
1373                 }
1374
1375                 if (empty($data['url']) && !empty($profile_url)) {
1376                         $data['url'] = $profile_url;
1377                 }
1378
1379                 if (empty($data['url']) || empty($hcard_url)) {
1380                         return [];
1381                 }
1382
1383                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1384                         foreach ($webfinger['aliases'] as $alias) {
1385                                 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1386                                         $data['alias'] = $alias;
1387                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1388                                         $data['addr'] = substr($alias, 5);
1389                                 }
1390                         }
1391                 }
1392
1393                 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1394                         $data['addr'] = substr($webfinger['subject'], 5);
1395                 }
1396
1397                 // Fetch further information from the hcard
1398                 $data = self::pollHcard($hcard_url, $data);
1399
1400                 if (!$data) {
1401                         return [];
1402                 }
1403
1404                 if (!empty($data['url'])
1405                         && !empty($data['guid'])
1406                         && !empty($data['baseurl'])
1407                         && !empty($data['pubkey'])
1408                         && !empty($hcard_url)
1409                 ) {
1410                         $data['network'] = Protocol::DIASPORA;
1411                         $data['manually-approve'] = false;
1412
1413                         // The Diaspora handle must always be lowercase
1414                         if (!empty($data['addr'])) {
1415                                 $data['addr'] = strtolower($data['addr']);
1416                         }
1417
1418                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1419                         $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1420                         $data['batch']  = $data['baseurl'] . '/receive/public';
1421                 } else {
1422                         return [];
1423                 }
1424
1425                 return $data;
1426         }
1427
1428         /**
1429          * Check for OStatus contact
1430          *
1431          * @param array $webfinger Webfinger data
1432          * @param bool  $short     Short detection mode
1433          * @return array|bool OStatus data or "false" on error or "true" on short mode
1434          * @throws HTTPException\InternalServerErrorException
1435          */
1436         private static function ostatus(array $webfinger, bool $short = false)
1437         {
1438                 $data = [];
1439
1440                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1441                         foreach ($webfinger['aliases'] as $alias) {
1442                                 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1443                                         $data['addr'] = str_replace('acct:', '', $alias);
1444                                 }
1445                         }
1446                 }
1447
1448                 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1449                         && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1450                 ) {
1451                         $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1452                 }
1453
1454                 if (!empty($webfinger['links'])) {
1455                         // The array is reversed to take into account the order of preference for same-rel links
1456                         // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1457                         foreach (array_reverse($webfinger['links']) as $link) {
1458                                 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1459                                         && (($link['type'] ?? '') == 'text/html')
1460                                         && ($link['href'] != '')
1461                                 ) {
1462                                         $data['url'] = $data['alias'] = $link['href'];
1463                                 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1464                                         $data['notify'] = $link['href'];
1465                                 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1466                                         $data['poll'] = $link['href'];
1467                                 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1468                                         $pubkey = $link['href'];
1469
1470                                         if (substr($pubkey, 0, 5) === 'data:') {
1471                                                 if (strstr($pubkey, ',')) {
1472                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1473                                                 } else {
1474                                                         $pubkey = substr($pubkey, 5);
1475                                                 }
1476                                         } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1477                                                 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1478                                                 if ($curlResult->isTimeout()) {
1479                                                         self::$istimeout = true;
1480                                                         return $short ? false : [];
1481                                                 }
1482                                                 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1483                                                 $pubkey = $curlResult->getBody();
1484                                         }
1485
1486                                         $key = explode('.', $pubkey);
1487
1488                                         if (sizeof($key) >= 3) {
1489                                                 $m = Strings::base64UrlDecode($key[1]);
1490                                                 $e = Strings::base64UrlDecode($key[2]);
1491                                                 $data['pubkey'] = Crypto::meToPem($m, $e);
1492                                         }
1493                                 }
1494                         }
1495                 }
1496
1497                 if (isset($data['notify']) && isset($data['pubkey'])
1498                         && isset($data['poll'])
1499                         && isset($data['url'])
1500                 ) {
1501                         $data['network'] = Protocol::OSTATUS;
1502                         $data['manually-approve'] = false;
1503                 } else {
1504                         return $short ? false : [];
1505                 }
1506
1507                 if ($short) {
1508                         return true;
1509                 }
1510
1511                 // Fetch all additional data from the feed
1512                 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1513                 if ($curlResult->isTimeout()) {
1514                         self::$istimeout = true;
1515                         return [];
1516                 }
1517                 $feed = $curlResult->getBody();
1518                 $feed_data = Feed::import($feed);
1519                 if (!$feed_data) {
1520                         return [];
1521                 }
1522
1523                 if (!empty($feed_data['header']['author-name'])) {
1524                         $data['name'] = $feed_data['header']['author-name'];
1525                 }
1526                 if (!empty($feed_data['header']['author-nick'])) {
1527                         $data['nick'] = $feed_data['header']['author-nick'];
1528                 }
1529                 if (!empty($feed_data['header']['author-avatar'])) {
1530                         $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1531                 }
1532                 if (!empty($feed_data['header']['author-id'])) {
1533                         $data['alias'] = $feed_data['header']['author-id'];
1534                 }
1535                 if (!empty($feed_data['header']['author-location'])) {
1536                         $data['location'] = $feed_data['header']['author-location'];
1537                 }
1538                 if (!empty($feed_data['header']['author-about'])) {
1539                         $data['about'] = $feed_data['header']['author-about'];
1540                 }
1541                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1542                 // So we take the value that we just fetched, although the other one worked as well
1543                 if (!empty($feed_data['header']['author-link'])) {
1544                         $data['url'] = $feed_data['header']['author-link'];
1545                 }
1546
1547                 if ($data['url'] == $data['alias']) {
1548                         $data['alias'] = '';
1549                 }
1550
1551                 /// @todo Fetch location and "about" from the feed as well
1552                 return $data;
1553         }
1554
1555         /**
1556          * Fetch data from a pump.io profile page
1557          *
1558          * @param string $profile_link Link to the profile page
1559          * @return array Profile data
1560          */
1561         private static function pumpioProfileData(string $profile_link): array
1562         {
1563                 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1564                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1565                         return [];
1566                 }
1567
1568                 $doc = new DOMDocument();
1569                 if (!@$doc->loadHTML($curlResult->getBody())) {
1570                         return [];
1571                 }
1572
1573                 $xpath = new DomXPath($doc);
1574
1575                 $data = [];
1576                 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1577
1578                 if ($data['name'] == '') {
1579                         // This is ugly - but pump.io doesn't seem to know a better way for it
1580                         $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1581                         $pos = strpos($data['name'], chr(10));
1582                         if ($pos) {
1583                                 $data['name'] = trim(substr($data['name'], 0, $pos));
1584                         }
1585                 }
1586
1587                 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1588
1589                 if ($data['location'] == '') {
1590                         $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1591                 }
1592
1593                 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1594
1595                 if ($data['about'] == '') {
1596                         $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1597                 }
1598
1599                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1600                 if (!$avatar) {
1601                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1602                 }
1603                 if ($avatar) {
1604                         foreach ($avatar->attributes as $attribute) {
1605                                 if ($attribute->name == 'src') {
1606                                         $data['photo'] = trim($attribute->value);
1607                                 }
1608                         }
1609                 }
1610
1611                 return $data;
1612         }
1613
1614         /**
1615          * Check for pump.io contact
1616          *
1617          * @param array  $webfinger Webfinger data
1618          * @param string $addr
1619          * @return array pump.io data
1620          */
1621         private static function pumpio(array $webfinger, string $addr): array
1622         {
1623                 $data = [];
1624                 // The array is reversed to take into account the order of preference for same-rel links
1625                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1626                 foreach (array_reverse($webfinger['links']) as $link) {
1627                         if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1628                                 && (($link['type'] ?? '') == 'text/html')
1629                                 && ($link['href'] != '')
1630                         ) {
1631                                 $data['url'] = $link['href'];
1632                         } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1633                                 $data['notify'] = $link['href'];
1634                         } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1635                                 $data['poll'] = $link['href'];
1636                         } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1637                                 $data['dialback'] = $link['href'];
1638                         }
1639                 }
1640                 if (isset($data['poll']) && isset($data['notify'])
1641                         && isset($data['dialback'])
1642                         && isset($data['url'])
1643                 ) {
1644                         // by now we use these fields only for the network type detection
1645                         // So we unset all data that isn't used at the moment
1646                         unset($data['dialback']);
1647
1648                         $data['network'] = Protocol::PUMPIO;
1649                 } else {
1650                         return [];
1651                 }
1652
1653                 $profile_data = self::pumpioProfileData($data['url']);
1654
1655                 if (!$profile_data) {
1656                         return [];
1657                 }
1658
1659                 $data = array_merge($data, $profile_data);
1660
1661                 if (($addr != '') && ($data['name'] != '')) {
1662                         $name = trim(str_replace($addr, '', $data['name']));
1663                         if ($name != '') {
1664                                 $data['name'] = $name;
1665                         }
1666                 }
1667
1668                 return $data;
1669         }
1670
1671         /**
1672          * Checks HTML page for RSS feed link
1673          *
1674          * @param string $url  Page link
1675          * @param string $body Page body string
1676          * @return string|false Feed link or false if body was invalid HTML document
1677          */
1678         public static function getFeedLink(string $url, string $body)
1679         {
1680                 if (empty($body)) {
1681                         return '';
1682                 }
1683
1684                 $doc = new DOMDocument();
1685                 if (!@$doc->loadHTML($body)) {
1686                         return false;
1687                 }
1688
1689                 $xpath = new DOMXPath($doc);
1690
1691                 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1692
1693                 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1694
1695                 return $feedUrl;
1696         }
1697
1698         /**
1699          * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1700          *
1701          * Loosely based on RFC 1808
1702          *
1703          * @see https://tools.ietf.org/html/rfc1808
1704          *
1705          * @param string   $href  The potential relative href found in the HTML document
1706          * @param string   $base  The HTML document URL
1707          * @param DOMXPath $xpath The HTML document XPath
1708          * @return string Absolute URL
1709          */
1710         private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1711         {
1712                 if (filter_var($href, FILTER_VALIDATE_URL)) {
1713                         return $href;
1714                 }
1715
1716                 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1717
1718                 $baseParts = parse_url($base);
1719                 if (empty($baseParts['host'])) {
1720                         return $href;
1721                 }
1722
1723                 // Naked domain case (scheme://basehost)
1724                 $path = $baseParts['path'] ?? '/';
1725
1726                 // Remove the filename part of the path if it exists (/base/path/file)
1727                 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1728
1729                 $hrefParts = parse_url($href);
1730
1731                 if (!empty($hrefParts['path'])) {
1732                         // Root path case (/path) including relative scheme case (//host/path)
1733                         if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1734                                 $path = $hrefParts['path'];
1735                         } else {
1736                                 $path = $path . '/' . $hrefParts['path'];
1737
1738                                 // Resolve arbitrary relative path
1739                                 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1740                                 $parts = array_filter(explode('/', $path), 'strlen');
1741                                 $absolutes = [];
1742                                 foreach ($parts as $part) {
1743                                         if ('.' == $part) continue;
1744                                         if ('..' == $part) {
1745                                                 array_pop($absolutes);
1746                                         } else {
1747                                                 $absolutes[] = $part;
1748                                         }
1749                                 }
1750
1751                                 $path = '/' . implode('/', $absolutes);
1752                         }
1753                 }
1754
1755                 // Relative scheme case (//host/path)
1756                 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1757                 $baseParts['path'] = $path;
1758                 unset($baseParts['query']);
1759                 unset($baseParts['fragment']);
1760
1761                 return Network::unparseURL($baseParts);
1762         }
1763
1764         /**
1765          * Check for feed contact
1766          *
1767          * @param string  $url   Profile link
1768          * @param boolean $probe Do a probe if the page contains a feed link
1769          * @return array feed data
1770          * @throws HTTPException\InternalServerErrorException
1771          */
1772         private static function feed(string $url, bool $probe = true): array
1773         {
1774                 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1775                 if ($curlResult->isTimeout()) {
1776                         self::$istimeout = true;
1777                         return [];
1778                 }
1779                 $feed = $curlResult->getBody();
1780                 $feed_data = Feed::import($feed);
1781
1782                 if (!$feed_data) {
1783                         if (!$probe) {
1784                                 return [];
1785                         }
1786
1787                         $feed_url = self::getFeedLink($url, $feed);
1788
1789                         if (!$feed_url) {
1790                                 return [];
1791                         }
1792
1793                         return self::feed($feed_url, false);
1794                 }
1795
1796                 if (!empty($feed_data['header']['author-name'])) {
1797                         $data['name'] = $feed_data['header']['author-name'];
1798                 }
1799
1800                 if (!empty($feed_data['header']['author-nick'])) {
1801                         $data['nick'] = $feed_data['header']['author-nick'];
1802                 }
1803
1804                 if (!empty($feed_data['header']['author-avatar'])) {
1805                         $data['photo'] = $feed_data['header']['author-avatar'];
1806                 }
1807
1808                 if (!empty($feed_data['header']['author-id'])) {
1809                         $data['alias'] = $feed_data['header']['author-id'];
1810                 }
1811
1812                 $data['url'] = $url;
1813                 $data['poll'] = $url;
1814
1815                 $data['network'] = Protocol::FEED;
1816
1817                 return $data;
1818         }
1819
1820         /**
1821          * Check for mail contact
1822          *
1823          * @param string  $uri Profile link
1824          * @param integer $uid User ID
1825          * @return array mail data
1826          * @throws \Exception
1827          */
1828         private static function mail(string $uri, int $uid): array
1829         {
1830                 if (!Network::isEmailDomainValid($uri)) {
1831                         return [];
1832                 }
1833
1834                 if ($uid == 0) {
1835                         return [];
1836                 }
1837
1838                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1839
1840                 $condition = ["`uid` = ? AND `server` != ''", $uid];
1841                 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1842                 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1843
1844                 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1845                         return [];
1846                 }
1847
1848                 $mailbox = Email::constructMailboxName($mailacct);
1849                 $password = '';
1850                 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1851                 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1852                 if (!$mbox) {
1853                         return [];
1854                 }
1855
1856                 $msgs = Email::poll($mbox, $uri);
1857                 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1858
1859                 if (!count($msgs)) {
1860                         return [];
1861                 }
1862
1863                 $phost = substr($uri, strpos($uri, '@') + 1);
1864
1865                 $data = [];
1866                 $data['addr']    = $uri;
1867                 $data['network'] = Protocol::MAIL;
1868                 $data['name']    = substr($uri, 0, strpos($uri, '@'));
1869                 $data['nick']    = $data['name'];
1870                 $data['photo']   = Network::lookupAvatarByEmail($uri);
1871                 $data['url']     = 'mailto:'.$uri;
1872                 $data['notify']  = 'smtp ' . Strings::getRandomHex();
1873                 $data['poll']    = 'email ' . Strings::getRandomHex();
1874
1875                 $x = Email::messageMeta($mbox, $msgs[0]);
1876                 if (stristr($x[0]->from, $uri)) {
1877                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1878                 } elseif (stristr($x[0]->to, $uri)) {
1879                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1880                 }
1881                 if (isset($adr)) {
1882                         foreach ($adr as $feadr) {
1883                                 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1884                                         &&(strcasecmp($feadr->host, $phost) == 0)
1885                                         && (strlen($feadr->personal))
1886                                 ) {
1887                                         $personal = imap_mime_header_decode($feadr->personal);
1888                                         $data['name'] = '';
1889                                         foreach ($personal as $perspart) {
1890                                                 if ($perspart->charset != 'default') {
1891                                                         $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1892                                                 } else {
1893                                                         $data['name'] .= $perspart->text;
1894                                                 }
1895                                         }
1896                                 }
1897                         }
1898                 }
1899                 if (!empty($mbox)) {
1900                         imap_close($mbox);
1901                 }
1902                 return $data;
1903         }
1904
1905         /**
1906          * Mix two paths together to possibly fix missing parts
1907          *
1908          * @param string $avatar Path to the avatar
1909          * @param string $base   Another path that is hopefully complete
1910          * @return string fixed avatar path
1911          * @throws \Exception
1912          */
1913         public static function fixAvatar(string $avatar, string $base): string
1914         {
1915                 $base_parts = parse_url($base);
1916
1917                 // Remove all parts that could create a problem
1918                 unset($base_parts['path']);
1919                 unset($base_parts['query']);
1920                 unset($base_parts['fragment']);
1921
1922                 $avatar_parts = parse_url($avatar);
1923
1924                 // Now we mix them
1925                 $parts = array_merge($base_parts, $avatar_parts);
1926
1927                 // And put them together again
1928                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1929                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1930                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1931                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1932                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
1933                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1934
1935                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1936
1937                 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1938
1939                 return $fixed;
1940         }
1941
1942         /**
1943          * Fetch the last date that the contact had posted something (publically)
1944          *
1945          * @param array $data  probing result
1946          * @return string last activity
1947          */
1948         public static function getLastUpdate(array $data): string
1949         {
1950                 $uid = User::getIdForURL($data['url']);
1951                 if (!empty($uid)) {
1952                         $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1953                         if (!empty($contact['last-item'])) {
1954                                 return $contact['last-item'];
1955                         }
1956                 }
1957
1958                 if ($lastUpdate = self::updateFromNoScrape($data)) {
1959                         return $lastUpdate;
1960                 }
1961
1962                 if (!empty($data['outbox'])) {
1963                         return self::updateFromOutbox($data['outbox'], $data);
1964                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
1965                         return self::updateFromOutbox($data['poll'], $data);
1966                 } elseif (!empty($data['poll'])) {
1967                         return self::updateFromFeed($data);
1968                 }
1969
1970                 return '';
1971         }
1972
1973         /**
1974          * Fetch the last activity date from the "noscrape" endpoint
1975          *
1976          * @param array $data Probing result
1977          * @return string last activity or true if update was successful or the server was unreachable
1978          */
1979         private static function updateFromNoScrape(array $data): string
1980         {
1981                 if (empty($data['baseurl'])) {
1982                         return '';
1983                 }
1984
1985                 // Check the 'noscrape' endpoint when it is a Friendica server
1986                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
1987                         Strings::normaliseLink($data['baseurl'])]);
1988                 if (!DBA::isResult($gserver)) {
1989                         return '';
1990                 }
1991
1992                 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
1993
1994                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1995                         $noscrape = json_decode($curlResult->getBody(), true);
1996                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
1997                                 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
1998                         }
1999                 }
2000
2001                 return '';
2002         }
2003
2004         /**
2005          * Fetch the last activity date from an ActivityPub Outbox
2006          *
2007          * @param string $feed
2008          * @param array  $data Probing result
2009          * @return string last activity
2010          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2011          */
2012         private static function updateFromOutbox(string $feed, array $data): string
2013         {
2014                 $outbox = ActivityPub::fetchContent($feed);
2015                 if (empty($outbox)) {
2016                         return '';
2017                 }
2018
2019                 if (!empty($outbox['orderedItems'])) {
2020                         $items = $outbox['orderedItems'];
2021                 } elseif (!empty($outbox['first']['orderedItems'])) {
2022                         $items = $outbox['first']['orderedItems'];
2023                 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2024                         return self::updateFromOutbox($outbox['first']['href'], $data);
2025                 } elseif (!empty($outbox['first'])) {
2026                         if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2027                                 return self::updateFromOutbox($outbox['first'], $data);
2028                         } else {
2029                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2030                         }
2031                         return '';
2032                 } else {
2033                         $items = [];
2034                 }
2035
2036                 $last_updated = '';
2037                 foreach ($items as $activity) {
2038                         if (!empty($activity['published'])) {
2039                                 $published =  DateTimeFormat::utc($activity['published']);
2040                         } elseif (!empty($activity['object']['published'])) {
2041                                 $published =  DateTimeFormat::utc($activity['object']['published']);
2042                         } else {
2043                                 continue;
2044                         }
2045
2046                         if ($last_updated < $published) {
2047                                 $last_updated = $published;
2048                         }
2049                 }
2050
2051                 if (!empty($last_updated)) {
2052                         return $last_updated;
2053                 }
2054
2055                 return '';
2056         }
2057
2058         /**
2059          * Fetch the last activity date from an XML feed
2060          *
2061          * @param array $data Probing result
2062          * @return string last activity
2063          */
2064         private static function updateFromFeed(array $data): string
2065         {
2066                 // Search for the newest entry in the feed
2067                 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2068                 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2069                         return '';
2070                 }
2071
2072                 $doc = new DOMDocument();
2073                 @$doc->loadXML($curlResult->getBody());
2074
2075                 $xpath = new DOMXPath($doc);
2076                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2077
2078                 $entries = $xpath->query('/atom:feed/atom:entry');
2079
2080                 $last_updated = '';
2081
2082                 foreach ($entries as $entry) {
2083                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2084                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
2085                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2086                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2087
2088                         if (empty($published) || empty($updated)) {
2089                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2090                                 continue;
2091                         }
2092
2093                         if ($last_updated < $published) {
2094                                 $last_updated = $published;
2095                         }
2096
2097                         if ($last_updated < $updated) {
2098                                 $last_updated = $updated;
2099                         }
2100                 }
2101
2102                 if (!empty($last_updated)) {
2103                         return $last_updated;
2104                 }
2105
2106                 return '';
2107         }
2108
2109         /**
2110          * Probe data from local profiles without network traffic
2111          *
2112          * @param string $url
2113          * @return array probed data
2114          * @throws HTTPException\InternalServerErrorException
2115          * @throws HTTPException\NotFoundException
2116          */
2117         private static function localProbe(string $url): array
2118         {
2119                 try {
2120                         $uid = User::getIdForURL($url);
2121                         if (!$uid) {
2122                                 throw new HTTPException\NotFoundException('User not found.');
2123                         }
2124
2125                         $owner     = User::getOwnerDataById($uid);
2126                         $approfile = ActivityPub\Transmitter::getProfile($uid);
2127
2128                         if (empty($owner['gsid'])) {
2129                                 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2130                         }
2131
2132                         $data = [
2133                                 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2134                                 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2135                                 'photo' => User::getAvatarUrl($owner),
2136                                 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2137                                 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2138                                 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2139                                 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2140                                 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2141                                 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2142                                 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2143                                 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2144                                 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2145                                 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2146                                 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2147                                 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2148                         ];
2149                 } catch (Exception $e) {
2150                         // Default values for non existing targets
2151                         $data = [
2152                                 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2153                                 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2154                         ];
2155                 }
2156
2157                 return self::rearrangeData($data);
2158         }
2159 }