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