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