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