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