]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Merge pull request #13660 from annando/issue-13627-a
[friendica.git] / src / Model / GServer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Model;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Exception;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Worker;
30 use Friendica\Database\Database;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Module\Register;
34 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
37 use Friendica\Network\Probe;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Relay;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\JsonLD;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
45 use Friendica\Network\HTTPException;
46 use Friendica\Worker\UpdateGServer;
47 use GuzzleHttp\Psr7\Uri;
48 use Psr\Http\Message\UriInterface;
49
50 /**
51  * This class handles GServer related functions
52  */
53 class GServer
54 {
55         // Directory types
56         const DT_NONE = 0;
57         const DT_POCO = 1;
58         const DT_MASTODON = 2;
59
60         // Methods to detect server types
61
62         // Non endpoint specific methods
63         const DETECT_MANUAL = 0;
64         const DETECT_HEADER = 1;
65         const DETECT_BODY = 2;
66         const DETECT_HOST_META = 3;
67         const DETECT_CONTACTS = 4;
68         const DETECT_AP_ACTOR = 5;
69         const DETECT_AP_COLLECTION = 6;
70
71         const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
72
73         // Implementation specific endpoints
74         // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
75         const DETECT_FRIENDIKA = 10;
76         const DETECT_FRIENDICA = 11;
77         const DETECT_STATUSNET = 12;
78         const DETECT_GNUSOCIAL = 13;
79         const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
80         const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
81         const DETECT_MASTODON_API = 16;
82         const DETECT_STATUS_PHP = 17; // Nextcloud
83         const DETECT_V1_CONFIG = 18;
84         const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
85
86         // Standardized endpoints
87         const DETECT_STATISTICS_JSON = 100;
88         const DETECT_NODEINFO_1 = 101;
89         const DETECT_NODEINFO_2 = 102;
90         const DETECT_NODEINFO_210 = 103;
91
92         /**
93          * Check for the existence of a server and adds it in the background if not existant
94          *
95          * @param string $url
96          * @param boolean $only_nodeinfo
97          *
98          * @return void
99          */
100         public static function add(string $url, bool $only_nodeinfo = false)
101         {
102                 if (self::getID($url)) {
103                         return;
104                 }
105
106                 UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
107         }
108
109         /**
110          * Get the ID for the given server URL
111          *
112          * @param string $url
113          * @param boolean $no_check Don't check if the server hadn't been found
114          *
115          * @return int|null gserver id or NULL on empty URL or failed check
116          */
117         public static function getID(string $url, bool $no_check = false): ?int
118         {
119                 $url = self::cleanURL($url);
120
121                 if (empty($url)) {
122                         return null;
123                 }
124
125                 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
126                 if (DBA::isResult($gserver)) {
127                         Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url]);
128
129                         if (Network::isUrlBlocked($url)) {
130                                 self::setBlockedById($gserver['id']);
131                         } else {
132                                 self::setUnblockedById($gserver['id']);
133                         }
134
135                         return $gserver['id'];
136                 }
137
138                 if ($no_check || !self::check($url)) {
139                         return null;
140                 }
141
142                 return self::getID($url, true);
143         }
144
145         /**
146          * Retrieves all the servers which base domain are matching the provided domain pattern
147          *
148          * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
149          *
150          * @param string $pattern
151          *
152          * @return array
153          *
154          * @throws Exception
155          */
156         public static function listByDomainPattern(string $pattern): array
157         {
158                 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
159
160                 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
161                 // eventual server path and keep only the server domain which we're matching against the pattern.
162                 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
163                         FROM `gserver`
164                         LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
165                         WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
166                         AND NOT `gserver`.`failed`
167                         GROUP BY `gserver`.`id`";
168
169                 $stmt = DI::dba()->p($sql, $likePattern);
170
171                 return DI::dba()->toArray($stmt);
172         }
173
174         /**
175          * Checks if the given server array is unreachable for a long time now
176          *
177          * @param integer $gsid
178          * @return boolean
179          */
180         private static function isDefunct(array $gserver): bool
181         {
182                 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
183                         ($gserver['last_contact'] >= $gserver['created']) &&
184                         ($gserver['last_contact'] < $gserver['last_failure']) &&
185                         ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
186         }
187
188         /**
189          * Checks if the given server id is unreachable for a long time now
190          *
191          * @param integer $gsid
192          * @return boolean
193          */
194         public static function isDefunctById(int $gsid): bool
195         {
196                 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
197                 if (empty($gserver)) {
198                         return false;
199                 } else {
200                         if (strtotime($gserver['next_contact']) < time()) {
201                                 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
202                         }
203
204                         return self::isDefunct($gserver);
205                 }
206         }
207
208         /**
209          * Checks if the given server id is reachable
210          *
211          * @param integer $gsid
212          * @return boolean
213          */
214         public static function isReachableById(int $gsid): bool
215         {
216                 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
217                 if (empty($gserver)) {
218                         return true;
219                 } else {
220                         if (strtotime($gserver['next_contact']) < time()) {
221                                 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
222                         }
223
224                         return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
225                 }
226         }
227
228         /**
229          * Checks if the given server is reachable
230          *
231          * @param array $contact Contact that should be checked
232          *
233          * @return boolean 'true' if server seems vital
234          */
235         public static function reachable(array $contact): bool
236         {
237                 if (!empty($contact['gsid'])) {
238                         $gsid = $contact['gsid'];
239                 } elseif (!empty($contact['baseurl'])) {
240                         $server = $contact['baseurl'];
241                 } elseif ($contact['network'] == Protocol::DIASPORA) {
242                         $parts = (array)parse_url($contact['url']);
243                         unset($parts['path']);
244                         $server = (string)Uri::fromParts($parts);
245                 } else {
246                         return true;
247                 }
248
249                 if (!empty($gsid)) {
250                         $condition = ['id' => $gsid];
251                 } else {
252                         $condition = ['nurl' => Strings::normaliseLink($server)];
253                 }
254
255                 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
256                 if (empty($gserver)) {
257                         $reachable = true;
258                 } else {
259                         $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
260                         $server    = $gserver['url'];
261                 }
262
263                 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
264                         UpdateGServer::add(Worker::PRIORITY_LOW, $server);
265                 }
266
267                 return $reachable;
268         }
269
270         /**
271          * Calculate the next update day
272          *
273          * @param bool $success
274          * @param string $created
275          * @param string $last_contact
276          * @param bool $undetected
277          *
278          * @return string
279          *
280          * @throws Exception
281          */
282         public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
283         {
284                 // On successful contact process check again next week when it is a detected system.
285                 // When we haven't detected the system, it could be a static website or a really old system.
286                 if ($success) {
287                         return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
288                 }
289
290                 $now = strtotime(DateTimeFormat::utcNow());
291
292                 if ($created > $last_contact) {
293                         $contact_time = strtotime($created);
294                 } else {
295                         $contact_time = strtotime($last_contact);
296                 }
297
298                 // If the last contact was less than 6 hours before then try again in 6 hours
299                 if (($now - $contact_time) < (60 * 60 * 6)) {
300                         return DateTimeFormat::utc('now +6 hour');
301                 }
302
303                 // If the last contact was less than 12 hours before then try again in 12 hours
304                 if (($now - $contact_time) < (60 * 60 * 12)) {
305                         return DateTimeFormat::utc('now +12 hour');
306                 }
307
308                 // If the last contact was less than 24 hours before then try tomorrow again
309                 if (($now - $contact_time) < (60 * 60 * 24)) {
310                         return DateTimeFormat::utc('now +1 day');
311                 }
312
313                 // If the last contact was less than a week before then try again in a week
314                 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
315                         return DateTimeFormat::utc('now +1 week');
316                 }
317
318                 // If the last contact was less than two weeks before then try again in two week
319                 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
320                         return DateTimeFormat::utc('now +2 week');
321                 }
322
323                 // If the last contact was less than a month before then try again in a month
324                 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
325                         return DateTimeFormat::utc('now +1 month');
326                 }
327
328                 // The system hadn't been successful contacted for more than a month, so try again in three months
329                 return DateTimeFormat::utc('now +3 month');
330         }
331
332         /**
333          * Checks the state of the given server.
334          *
335          * @param string  $server_url    URL of the given server
336          * @param string  $network       Network value that is used, when detection failed
337          * @param boolean $force         Force an update.
338          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
339          *
340          * @return boolean 'true' if server seems vital
341          */
342         public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
343         {
344                 $server_url = self::cleanURL($server_url);
345                 if ($server_url == '') {
346                         return false;
347                 }
348
349                 if (Network::isUrlBlocked($server_url)) {
350                         Logger::info('Server is blocked', ['url' => $server_url]);
351                         self::setBlockedByUrl($server_url);
352                         return false;
353                 }
354
355                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
356                 if (DBA::isResult($gserver)) {
357                         if ($gserver['created'] <= DBA::NULL_DATETIME) {
358                                 $fields = ['created' => DateTimeFormat::utcNow()];
359                                 $condition = ['nurl' => Strings::normaliseLink($server_url)];
360                                 self::update($fields, $condition);
361                         }
362
363                         if (!$force && (strtotime($gserver['next_contact']) > time())) {
364                                 Logger::info('No update needed', ['server' => $server_url]);
365                                 return (!$gserver['failed']);
366                         }
367                         Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
368                 } else {
369                         Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
370                 }
371
372                 return self::detect($server_url, $network, $only_nodeinfo);
373         }
374
375         /**
376          * Reset failed server status by gserver id
377          *
378          * @param int    $gsid
379          * @param string $network
380          */
381         public static function setReachableById(int $gsid, string $network)
382         {
383                 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
384                 if (!DBA::isResult($gserver)) {
385                         return;
386                 }
387
388                 $blocked = Network::isUrlBlocked($gserver['url']);
389                 if ($gserver['failed']) {
390                         $fields = ['failed' => false, 'blocked' => $blocked, 'last_contact' => DateTimeFormat::utcNow()];
391                         if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
392                                 $fields['network'] = $network;
393                         }
394                         self::update($fields, ['id' => $gsid]);
395                         Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
396
397                         if (strtotime($gserver['next_contact']) < time()) {
398                                 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
399                         }
400                 } elseif ($blocked) {
401                         self::setBlockedById($gsid);
402                 } else {
403                         self::setUnblockedById($gsid);
404                 }
405         }
406
407         /**
408          * Set failed server status by gserver id
409          *
410          * @param int $gsid
411          */
412         public static function setFailureById(int $gsid)
413         {
414                 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
415                 if (DBA::isResult($gserver) && !$gserver['failed']) {
416                         self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
417                         Logger::info('Set failed status for server', ['url' => $gserver['url']]);
418
419                         if (strtotime($gserver['next_contact']) < time()) {
420                                 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
421                         }
422                 }
423         }
424
425         public static function setUnblockedById(int $gsid)
426         {
427                 $gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
428                 if (DBA::isResult($gserver)) {
429                         self::update(['blocked' => false], ['id' => $gsid]);
430                         Logger::info('Set unblocked status for server', ['url' => $gserver['url']]);
431                 }
432         }
433
434         public static function setBlockedById(int $gsid)
435         {
436                 $gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
437                 if (DBA::isResult($gserver)) {
438                         self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
439                         Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
440                 }
441         }
442
443         public static function setBlockedByUrl(string $url)
444         {
445                 $gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
446                 if (DBA::isResult($gserver)) {
447                         self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
448                         Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
449                 }
450         }
451
452         /**
453          * Set failed server status
454          *
455          * @param string $url
456          * @return void
457          */
458         public static function setFailureByUrl(string $url)
459         {
460                 $nurl = Strings::normaliseLink($url);
461
462                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
463                 if (DBA::isResult($gserver)) {
464                         $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
465                         self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
466                         'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
467                         ['nurl' => $nurl]);
468                         Logger::info('Set failed status for existing server', ['url' => $url]);
469                         if (self::isDefunct($gserver)) {
470                                 self::archiveContacts($gserver['id']);
471                         }
472                         return;
473                 }
474
475                 self::insert(['url' => $url, 'nurl' => $nurl,
476                         'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
477                         'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
478                 Logger::info('Set failed status for new server', ['url' => $url]);
479         }
480
481         /**
482          * Archive server related contacts and inboxes
483          *
484          * @param integer $gsid
485          * @return void
486          */
487         private static function archiveContacts(int $gsid)
488         {
489                 Contact::update(['archive' => true], ['gsid' => $gsid]);
490                 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
491         }
492
493         /**
494          * Remove unwanted content from the given URL
495          *
496          * @param string $dirtyUrl
497          *
498          * @return string cleaned URL
499          * @throws Exception
500          * @deprecated since 2023.03 Use cleanUri instead
501          */
502         public static function cleanURL(string $dirtyUrl): string
503         {
504                 try {
505                         return (string)self::cleanUri(new Uri($dirtyUrl));
506                 } catch (\Throwable $e) {
507                         Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
508                         return '';
509                 }
510         }
511
512         /**
513          * Remove unwanted content from the given URI
514          *
515          * @param UriInterface $dirtyUri
516          *
517          * @return UriInterface cleaned URI
518          * @throws Exception
519          */
520         public static function cleanUri(UriInterface $dirtyUri): string
521         {
522                 return $dirtyUri
523                         ->withUserInfo('')
524                         ->withQuery('')
525                         ->withFragment('')
526                         ->withPath(
527                                 preg_replace(
528                                         '#(?:^|/)index\.php#',
529                                         '',
530                                         rtrim($dirtyUri->getPath(), '/')
531                                 )
532                         );
533         }
534
535         /**
536          * Detect server data (type, protocol, version number, ...)
537          * The detected data is then updated or inserted in the gserver table.
538          *
539          * @param string  $url           URL of the given server
540          * @param string  $network       Network value that is used, when detection failed
541          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
542          *
543          * @return boolean 'true' if server could be detected
544          */
545         private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
546         {
547                 Logger::info('Detect server type', ['server' => $url]);
548
549                 $original_url = $url;
550
551                 // Remove URL content that is not supposed to exist for a server url
552                 $url = rtrim(self::cleanURL($url), '/');
553                 if (empty($url)) {
554                         Logger::notice('Empty URL.');
555                         return false;
556                 }
557
558                 // If the URL mismatches, then we mark the old entry as failure
559                 if (!Strings::compareLink($url, $original_url)) {
560                         self::setFailureByUrl($original_url);
561                         if (!self::getID($url, true) && !Network::isUrlBlocked($url)) {
562                                 self::detect($url, $network, $only_nodeinfo);
563                         }
564                         return false;
565                 }
566
567                 $valid_url = Network::isUrlValid($url);
568                 if (!$valid_url) {
569                         self::setFailureByUrl($url);
570                         return false;
571                 } else {
572                         $valid_url = rtrim($valid_url, '/');
573                 }
574
575                 if (!Strings::compareLink($url, $valid_url)) {
576                         // We only follow redirects when the path stays the same or the target url has no path.
577                         // Some systems have got redirects on their landing page to a single account page. This check handles it.
578                         if (((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH))) ||
579                                 (((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) || (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH))) && empty(parse_url($valid_url, PHP_URL_PATH)))) {
580                                 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
581                                 self::setFailureByUrl($url);
582                                 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
583                                         self::detect($valid_url, $network, $only_nodeinfo);
584                                 }
585                                 return false;
586                         }
587
588                         if ((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH)) &&
589                                 (parse_url($url, PHP_URL_PATH) == '')) {
590                                 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
591                                 $parts = (array)parse_url($valid_url);
592                                 unset($parts['path']);
593                                 $valid_url = (string)Uri::fromParts($parts);
594
595                                 self::setFailureByUrl($url);
596                                 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
597                                         self::detect($valid_url, $network, $only_nodeinfo);
598                                 }
599                                 return false;
600                         }
601                         Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
602                 }
603
604                 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
605                         (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
606                         (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
607                         $url = $valid_url;
608                 }
609
610                 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
611
612                 // When a nodeinfo is present, we don't need to dig further
613                 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
614                 if ($curlResult->isTimeout()) {
615                         self::setFailureByUrl($url);
616                         return false;
617                 }
618
619                 if (!empty($network) && !in_array($network, Protocol::NATIVE_SUPPORT)) {
620                         $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => $network, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
621                 } else {
622                         $serverdata = self::parseNodeinfo210($curlResult);
623                         if (empty($serverdata)) {
624                                 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
625                                 $serverdata = self::fetchNodeinfo($url, $curlResult);
626                         }
627                 }
628
629                 if ($only_nodeinfo && empty($serverdata)) {
630                         Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
631                         self::setFailureByUrl($url);
632                         return false;
633                 } elseif (empty($serverdata)) {
634                         $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
635                 }
636
637                 // When there is no Nodeinfo, then use some protocol specific endpoints
638                 if ($serverdata['network'] == Protocol::PHANTOM) {
639                         if ($in_webroot) {
640                                 // Fetch the landing page, possibly it reveals some data
641                                 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
642                                 $curlResult = DI::httpClient()->get($url, $accept);
643                                 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
644                                         $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
645                                         $html_fetched = true;
646                                 } else {
647                                         $html_fetched = false;
648                                 }
649
650                                 if ($curlResult->isSuccess()) {
651                                         $json = json_decode($curlResult->getBody(), true);
652                                         if (!empty($json) && is_array($json)) {
653                                                 $data = self::fetchDataFromSystemActor($json, $serverdata);
654                                                 $serverdata = $data['server'];
655                                                 $systemactor = $data['actor'];
656                                                 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
657                                                         $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
658                                                 }
659                                         } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
660                                                 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
661                                         }
662
663                                         if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
664                                                 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
665                                                 $serverdata = self::analyseRootBody($curlResult, $serverdata);
666                                         }
667                                 }
668
669                                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
670                                         self::setFailureByUrl($url);
671                                         return false;
672                                 }
673
674                                 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
675                                         $serverdata = self::detectMastodonAlikes($url, $serverdata);
676                                 }
677                         }
678
679                         // All following checks are done for systems that always have got a "host-meta" endpoint.
680                         // With this check we don't have to waste time and resources for dead systems.
681                         // Also this hopefully prevents us from receiving abuse messages.
682                         if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
683                                 $validHostMeta = self::validHostMeta($url);
684                         } else {
685                                 $validHostMeta = false;
686                         }
687
688                         if ($validHostMeta) {
689                                 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
690                                         $serverdata['detection-method'] = self::DETECT_HOST_META;
691                                 }
692
693                                 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
694                                         $serverdata = self::detectFriendica($url, $serverdata);
695                                 }
696
697                                 // The following systems have to be installed in the root directory.
698                                 if ($in_webroot) {
699                                         // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
700                                         if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
701                                                 $serverdata = self::fetchSiteinfo($url, $serverdata);
702                                         }
703
704                                         // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
705                                         if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
706                                                 $serverdata = self::detectHubzilla($url, $serverdata);
707                                         }
708
709                                         if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
710                                                 $serverdata = self::detectPeertube($url, $serverdata);
711                                         }
712
713                                         if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
714                                                 $serverdata = self::detectGNUSocial($url, $serverdata);
715                                         }
716                                 }
717                         } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
718                                 $serverdata = self::detectFriendica($url, $serverdata);
719                         }
720
721                         if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
722                                 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
723                         }
724
725                         // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
726                         // Since this endpoint is only rarely used, we query it at a later time
727                         if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
728                                 $serverdata = self::fetchStatistics($url, $serverdata);
729                         }
730                 }
731
732                 // When we hadn't been able to detect the network type, we use the hint from the parameter
733                 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
734                         $serverdata['network'] = $network;
735                 }
736
737                 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
738                 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
739                         self::setFailureByUrl($url);
740                         return false;
741                 }
742
743                 $serverdata['url'] = $url;
744                 $serverdata['nurl'] = Strings::normaliseLink($url);
745
746                 // We have to prevent an endless loop here.
747                 // When a server is new, then there is no gserver entry yet.
748                 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
749                 // and this can call this function here as well.
750                 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
751                         in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
752                         $serverdata = self::detectNetworkViaContacts($url, $serverdata);
753                 }
754
755                 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
756                         self::setFailureByUrl($url);
757                         return false;
758                 }
759
760                 if (empty($serverdata['version']) && in_array($serverdata['platform'], ['osada']) && in_array($serverdata['detection-method'], [self::DETECT_CONTACTS, self::DETECT_BODY])) {
761                         $serverdata['version'] = self::getNomadVersion($url);
762                 }
763
764                 // Detect the directory type
765                 $serverdata['directory-type'] = self::DT_NONE;
766
767                 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
768                         $serverdata = self::checkMastodonDirectory($url, $serverdata);
769
770                         if ($serverdata['directory-type'] == self::DT_NONE) {
771                                 $serverdata = self::checkPoCo($url, $serverdata);
772                         }
773                 }
774
775                 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
776                         $serverdata = self::fetchWeeklyUsage($url, $serverdata);
777                 }
778
779                 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
780
781                 // Numbers above a reasonable value (10 millions) are ignored
782                 if ($serverdata['registered-users'] > 10000000) {
783                         $serverdata['registered-users'] = 0;
784                 }
785
786                 // On an active server there has to be at least a single user
787                 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
788                         $serverdata['registered-users'] = 1;
789                 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
790                         $serverdata['registered-users'] = 0;
791                 }
792
793                 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
794                 $serverdata['last_contact'] = DateTimeFormat::utcNow();
795                 $serverdata['failed']       = false;
796                 $serverdata['blocked']      = false;
797
798                 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
799                 if (!DBA::isResult($gserver)) {
800                         $serverdata['created'] = DateTimeFormat::utcNow();
801                         $ret = self::insert($serverdata);
802                         $id = DBA::lastInsertId();
803                 } else {
804                         $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
805                         $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
806                         if (DBA::isResult($gserver)) {
807                                 $id = $gserver['id'];
808                         }
809                 }
810
811                 // Count the number of known contacts from this server
812                 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
813                         $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
814                         $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
815                         $max_users = max($apcontacts, $contacts);
816                         if ($max_users > $serverdata['registered-users']) {
817                                 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
818                                 self::update(['registered-users' => $max_users], ['id' => $id]);
819                         }
820
821                         if (empty($serverdata['active-month-users'])) {
822                                 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
823                                 if ($contacts > 0) {
824                                         Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
825                                         self::update(['active-month-users' => $contacts], ['id' => $id]);
826                                 }
827                         }
828
829                         if (empty($serverdata['active-halfyear-users'])) {
830                                 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
831                                 if ($contacts > 0) {
832                                         Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
833                                         self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
834                                 }
835                         }
836                 }
837
838                 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
839                         self::discoverRelay($url);
840                 }
841
842                 if (!empty($systemactor)) {
843                         $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
844                         Logger::debug('Fetched system actor',  ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
845                 }
846
847                 return $ret;
848         }
849
850         /**
851          * Fetch relay data from a given server url
852          *
853          * @param string $server_url address of the server
854          *
855          * @return void
856          *
857          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
858          */
859         private static function discoverRelay(string $server_url)
860         {
861                 Logger::info('Discover relay data', ['server' => $server_url]);
862
863                 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
864                 if (!$curlResult->isSuccess()) {
865                         return;
866                 }
867
868                 $data = json_decode($curlResult->getBody(), true);
869                 if (!is_array($data)) {
870                         return;
871                 }
872
873                 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
874                 $data['subscribe'] = (bool)($data['subscribe'] ?? false);
875
876                 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
877                         $data['scope'] = '';
878                         $data['subscribe'] = false;
879                         $data['tags'] = [];
880                 }
881
882                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
883                 if (!DBA::isResult($gserver)) {
884                         return;
885                 }
886
887                 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
888                         $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
889                         self::update($fields, ['id' => $gserver['id']]);
890                 }
891
892                 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
893
894                 if ($data['scope'] == 'tags') {
895                         // Avoid duplicates
896                         $tags = [];
897                         foreach ($data['tags'] as $tag) {
898                                 $tag = mb_strtolower($tag);
899                                 if (strlen($tag) < 100) {
900                                         $tags[$tag] = $tag;
901                                 }
902                         }
903
904                         foreach ($tags as $tag) {
905                                 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
906                         }
907                 }
908
909                 // Create or update the relay contact
910                 $fields = [];
911                 if (isset($data['protocols'])) {
912                         if (isset($data['protocols']['diaspora'])) {
913                                 $fields['network'] = Protocol::DIASPORA;
914
915                                 if (isset($data['protocols']['diaspora']['receive'])) {
916                                         $fields['batch'] = $data['protocols']['diaspora']['receive'];
917                                 } elseif (is_string($data['protocols']['diaspora'])) {
918                                         $fields['batch'] = $data['protocols']['diaspora'];
919                                 }
920                         }
921
922                         if (isset($data['protocols']['dfrn'])) {
923                                 $fields['network'] = Protocol::DFRN;
924
925                                 if (isset($data['protocols']['dfrn']['receive'])) {
926                                         $fields['batch'] = $data['protocols']['dfrn']['receive'];
927                                 } elseif (is_string($data['protocols']['dfrn'])) {
928                                         $fields['batch'] = $data['protocols']['dfrn'];
929                                 }
930                         }
931
932                         if (isset($data['protocols']['activitypub'])) {
933                                 $fields['network'] = Protocol::ACTIVITYPUB;
934
935                                 if (!empty($data['protocols']['activitypub']['actor'])) {
936                                         $fields['url'] = $data['protocols']['activitypub']['actor'];
937                                 }
938                                 if (!empty($data['protocols']['activitypub']['receive'])) {
939                                         $fields['batch'] = $data['protocols']['activitypub']['receive'];
940                                 }
941                         }
942                 }
943
944                 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
945
946                 Relay::updateContact($gserver, $fields);
947         }
948
949         /**
950          * Fetch server data from '/statistics.json' on the given server
951          *
952          * @param string $url URL of the given server
953          *
954          * @return array server data
955          */
956         private static function fetchStatistics(string $url, array $serverdata): array
957         {
958                 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
959                 if (!$curlResult->isSuccess()) {
960                         return $serverdata;
961                 }
962
963                 $data = json_decode($curlResult->getBody(), true);
964                 if (empty($data)) {
965                         return $serverdata;
966                 }
967
968                 // Some AP enabled systems return activity data that we don't expect here.
969                 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
970                         return $serverdata;
971                 }
972
973                 $valid = false;
974                 $old_serverdata = $serverdata;
975
976                 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
977
978                 if (!empty($data['version'])) {
979                         $valid = true;
980                         $serverdata['version'] = $data['version'];
981                         // Version numbers on statistics.json are presented with additional info, e.g.:
982                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
983                         $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
984                 }
985
986                 if (!empty($data['name'])) {
987                         $valid = true;
988                         $serverdata['site_name'] = $data['name'];
989                 }
990
991                 if (!empty($data['network'])) {
992                         $valid = true;
993                         $serverdata['platform'] = strtolower($data['network']);
994
995                         if ($serverdata['platform'] == 'diaspora') {
996                                 $serverdata['network'] = Protocol::DIASPORA;
997                         } elseif ($serverdata['platform'] == 'friendica') {
998                                 $serverdata['network'] = Protocol::DFRN;
999                         } elseif ($serverdata['platform'] == 'hubzilla') {
1000                                 $serverdata['network'] = Protocol::ZOT;
1001                         } elseif ($serverdata['platform'] == 'redmatrix') {
1002                                 $serverdata['network'] = Protocol::ZOT;
1003                         }
1004                 }
1005
1006                 if (!empty($data['total_users'])) {
1007                         $valid = true;
1008                         $serverdata['registered-users'] = max($data['total_users'], 1);
1009                 }
1010
1011                 if (!empty($data['active_users_monthly'])) {
1012                         $valid = true;
1013                         $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
1014                 }
1015
1016                 if (!empty($data['active_users_halfyear'])) {
1017                         $valid = true;
1018                         $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
1019                 }
1020
1021                 if (!empty($data['local_posts'])) {
1022                         $valid = true;
1023                         $serverdata['local-posts'] = max($data['local_posts'], 0);
1024                 }
1025
1026                 if (!empty($data['registrations_open'])) {
1027                         $serverdata['register_policy'] = Register::OPEN;
1028                 } else {
1029                         $serverdata['register_policy'] = Register::CLOSED;
1030                 }
1031
1032                 if (!$valid) {
1033                         return $old_serverdata;
1034                 }
1035
1036                 return $serverdata;
1037         }
1038
1039         /**
1040          * Detect server type by using the nodeinfo data
1041          *
1042          * @param string                  $url        address of the server
1043          * @param ICanHandleHttpResponses $httpResult
1044          *
1045          * @return array Server data
1046          *
1047          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1048          */
1049         private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
1050         {
1051                 if (!$httpResult->isSuccess()) {
1052                         return [];
1053                 }
1054
1055                 $nodeinfo = json_decode($httpResult->getBody(), true);
1056
1057                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
1058                         return [];
1059                 }
1060
1061                 $nodeinfo1_url = '';
1062                 $nodeinfo2_url = '';
1063
1064                 foreach ($nodeinfo['links'] as $link) {
1065                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
1066                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
1067                                 continue;
1068                         }
1069
1070                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
1071                                 $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1072                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
1073                                 $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1074                         }
1075                 }
1076
1077                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1078                         return [];
1079                 }
1080
1081                 $server = [];
1082
1083                 if (!empty($nodeinfo2_url)) {
1084                         $server = self::parseNodeinfo2($nodeinfo2_url);
1085                 }
1086
1087                 if (empty($server) && !empty($nodeinfo1_url)) {
1088                         $server = self::parseNodeinfo1($nodeinfo1_url);
1089                 }
1090
1091                 return $server;
1092         }
1093
1094         /**
1095          * Parses Nodeinfo 1
1096          *
1097          * @param string $nodeinfo_url address of the nodeinfo path
1098          *
1099          * @return array Server data
1100          *
1101          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102          */
1103         private static function parseNodeinfo1(string $nodeinfo_url): array
1104         {
1105                 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1106                 if (!$curlResult->isSuccess()) {
1107                         return [];
1108                 }
1109
1110                 $nodeinfo = json_decode($curlResult->getBody(), true);
1111
1112                 if (!is_array($nodeinfo)) {
1113                         return [];
1114                 }
1115
1116                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1117                         'register_policy' => Register::CLOSED];
1118
1119                 if (!empty($nodeinfo['openRegistrations'])) {
1120                         $server['register_policy'] = Register::OPEN;
1121                 }
1122
1123                 if (is_array($nodeinfo['software'])) {
1124                         if (!empty($nodeinfo['software']['name'])) {
1125                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
1126                         }
1127
1128                         if (!empty($nodeinfo['software']['version'])) {
1129                                 $server['version'] = $nodeinfo['software']['version'];
1130                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1131                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1132                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1133                         }
1134                 }
1135
1136                 if (!empty($nodeinfo['metadata']['nodeName'])) {
1137                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1138                 }
1139
1140                 if (!empty($nodeinfo['usage']['users']['total'])) {
1141                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1142                 }
1143
1144                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1145                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1146                 }
1147
1148                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1149                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1150                 }
1151
1152                 if (!empty($nodeinfo['usage']['localPosts'])) {
1153                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1154                 }
1155
1156                 if (!empty($nodeinfo['usage']['localComments'])) {
1157                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1158                 }
1159
1160                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1161                         $protocols = [];
1162                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1163                                 $protocols[$protocol] = true;
1164                         }
1165
1166                         if (!empty($protocols['friendica'])) {
1167                                 $server['network'] = Protocol::DFRN;
1168                         } elseif (!empty($protocols['activitypub'])) {
1169                                 $server['network'] = Protocol::ACTIVITYPUB;
1170                         } elseif (!empty($protocols['diaspora'])) {
1171                                 $server['network'] = Protocol::DIASPORA;
1172                         } elseif (!empty($protocols['ostatus'])) {
1173                                 $server['network'] = Protocol::OSTATUS;
1174                         } elseif (!empty($protocols['gnusocial'])) {
1175                                 $server['network'] = Protocol::OSTATUS;
1176                         } elseif (!empty($protocols['zot'])) {
1177                                 $server['network'] = Protocol::ZOT;
1178                         }
1179                 }
1180
1181                 if (empty($server)) {
1182                         return [];
1183                 }
1184
1185                 if (empty($server['network'])) {
1186                         $server['network'] = Protocol::PHANTOM;
1187                 }
1188
1189                 return $server;
1190         }
1191
1192         /**
1193          * Parses Nodeinfo 2
1194          *
1195          * @see https://git.feneas.org/jaywink/nodeinfo2
1196          *
1197          * @param string $nodeinfo_url address of the nodeinfo path
1198          *
1199          * @return array Server data
1200          *
1201          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202          */
1203         private static function parseNodeinfo2(string $nodeinfo_url): array
1204         {
1205                 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1206                 if (!$curlResult->isSuccess()) {
1207                         return [];
1208                 }
1209
1210                 $nodeinfo = json_decode($curlResult->getBody(), true);
1211                 if (!is_array($nodeinfo)) {
1212                         return [];
1213                 }
1214
1215                 $server = [
1216                         'detection-method' => self::DETECT_NODEINFO_2,
1217                         'register_policy' => Register::CLOSED,
1218                         'platform' => 'unknown',
1219                 ];
1220
1221                 if (!empty($nodeinfo['openRegistrations'])) {
1222                         $server['register_policy'] = Register::OPEN;
1223                 }
1224
1225                 if (!empty($nodeinfo['software'])) {
1226                         if (isset($nodeinfo['software']['name'])) {
1227                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
1228                         }
1229
1230                         if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1231                                 $server['version'] = $nodeinfo['software']['version'];
1232                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1233                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1234                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1235
1236                                 // qoto advertises itself as Mastodon
1237                                 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1238                                         $server['platform'] = 'qoto';
1239                                 }
1240                         }
1241                 }
1242
1243                 if (!empty($nodeinfo['metadata']['nodeName'])) {
1244                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1245                 }
1246
1247                 if (!empty($nodeinfo['usage']['users']['total'])) {
1248                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1249                 }
1250
1251                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1252                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1253                 }
1254
1255                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1256                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1257                 }
1258
1259                 if (!empty($nodeinfo['usage']['localPosts'])) {
1260                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1261                 }
1262
1263                 if (!empty($nodeinfo['usage']['localComments'])) {
1264                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1265                 }
1266
1267                 if (!empty($nodeinfo['protocols'])) {
1268                         $protocols = [];
1269                         foreach ($nodeinfo['protocols'] as $protocol) {
1270                                 if (is_string($protocol)) {
1271                                         $protocols[$protocol] = true;
1272                                 }
1273                         }
1274
1275                         if (!empty($protocols['dfrn'])) {
1276                                 $server['network'] = Protocol::DFRN;
1277                         } elseif (!empty($protocols['activitypub'])) {
1278                                 $server['network'] = Protocol::ACTIVITYPUB;
1279                         } elseif (!empty($protocols['diaspora'])) {
1280                                 $server['network'] = Protocol::DIASPORA;
1281                         } elseif (!empty($protocols['ostatus'])) {
1282                                 $server['network'] = Protocol::OSTATUS;
1283                         } elseif (!empty($protocols['gnusocial'])) {
1284                                 $server['network'] = Protocol::OSTATUS;
1285                         } elseif (!empty($protocols['zot'])) {
1286                                 $server['network'] = Protocol::ZOT;
1287                         }
1288                 }
1289
1290                 if (empty($server)) {
1291                         return [];
1292                 }
1293
1294                 if (empty($server['network'])) {
1295                         $server['network'] = Protocol::PHANTOM;
1296                 }
1297
1298                 return $server;
1299         }
1300
1301         /**
1302          * Parses NodeInfo2 protocol 1.0
1303          *
1304          * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1305          *
1306          * @param string $nodeinfo_url address of the nodeinfo path
1307          *
1308          * @return array Server data
1309          *
1310          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1311          */
1312         private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1313         {
1314                 if (!$httpResult->isSuccess()) {
1315                         return [];
1316                 }
1317
1318                 $nodeinfo = json_decode($httpResult->getBody(), true);
1319
1320                 if (!is_array($nodeinfo)) {
1321                         return [];
1322                 }
1323
1324                 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1325                         'register_policy' => Register::CLOSED];
1326
1327                 if (!empty($nodeinfo['openRegistrations'])) {
1328                         $server['register_policy'] = Register::OPEN;
1329                 }
1330
1331                 if (!empty($nodeinfo['server'])) {
1332                         if (!empty($nodeinfo['server']['software'])) {
1333                                 $server['platform'] = strtolower($nodeinfo['server']['software']);
1334                         }
1335
1336                         if (!empty($nodeinfo['server']['version'])) {
1337                                 $server['version'] = $nodeinfo['server']['version'];
1338                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1339                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1340                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1341                         }
1342
1343                         if (!empty($nodeinfo['server']['name'])) {
1344                                 $server['site_name'] = $nodeinfo['server']['name'];
1345                         }
1346                 }
1347
1348                 if (!empty($nodeinfo['usage']['users']['total'])) {
1349                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1350                 }
1351
1352                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1353                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1354                 }
1355
1356                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1357                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1358                 }
1359
1360                 if (!empty($nodeinfo['usage']['localPosts'])) {
1361                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1362                 }
1363
1364                 if (!empty($nodeinfo['usage']['localComments'])) {
1365                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1366                 }
1367
1368                 if (!empty($nodeinfo['protocols'])) {
1369                         $protocols = [];
1370                         foreach ($nodeinfo['protocols'] as $protocol) {
1371                                 if (is_string($protocol)) {
1372                                         $protocols[$protocol] = true;
1373                                 }
1374                         }
1375
1376                         if (!empty($protocols['dfrn'])) {
1377                                 $server['network'] = Protocol::DFRN;
1378                         } elseif (!empty($protocols['activitypub'])) {
1379                                 $server['network'] = Protocol::ACTIVITYPUB;
1380                         } elseif (!empty($protocols['diaspora'])) {
1381                                 $server['network'] = Protocol::DIASPORA;
1382                         } elseif (!empty($protocols['ostatus'])) {
1383                                 $server['network'] = Protocol::OSTATUS;
1384                         } elseif (!empty($protocols['gnusocial'])) {
1385                                 $server['network'] = Protocol::OSTATUS;
1386                         } elseif (!empty($protocols['zot'])) {
1387                                 $server['network'] = Protocol::ZOT;
1388                         }
1389                 }
1390
1391                 if (empty($server) || empty($server['platform'])) {
1392                         return [];
1393                 }
1394
1395                 if (empty($server['network'])) {
1396                         $server['network'] = Protocol::PHANTOM;
1397                 }
1398
1399                 return $server;
1400         }
1401
1402         /**
1403          * Fetch server information from a 'siteinfo.json' file on the given server
1404          *
1405          * @param string $url        URL of the given server
1406          * @param array  $serverdata array with server data
1407          *
1408          * @return array server data
1409          */
1410         private static function fetchSiteinfo(string $url, array $serverdata): array
1411         {
1412                 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1413                 if (!$curlResult->isSuccess()) {
1414                         return $serverdata;
1415                 }
1416
1417                 $data = json_decode($curlResult->getBody(), true);
1418                 if (empty($data)) {
1419                         return $serverdata;
1420                 }
1421
1422                 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1423                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1424                 }
1425
1426                 if (!empty($data['platform'])) {
1427                         $serverdata['platform'] = strtolower($data['platform']);
1428                         $serverdata['version'] = $data['version'] ?? 'N/A';
1429                 }
1430
1431                 if (!empty($data['plugins'])) {
1432                         if (in_array('pubcrawl', $data['plugins'])) {
1433                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1434                         } elseif (in_array('diaspora', $data['plugins'])) {
1435                                 $serverdata['network'] = Protocol::DIASPORA;
1436                         } elseif (in_array('gnusoc', $data['plugins'])) {
1437                                 $serverdata['network'] = Protocol::OSTATUS;
1438                         } else {
1439                                 $serverdata['network'] = Protocol::ZOT;
1440                         }
1441                 }
1442
1443                 if (!empty($data['site_name'])) {
1444                         $serverdata['site_name'] = $data['site_name'];
1445                 }
1446
1447                 if (!empty($data['channels_total'])) {
1448                         $serverdata['registered-users'] = max($data['channels_total'], 1);
1449                 }
1450
1451                 if (!empty($data['channels_active_monthly'])) {
1452                         $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1453                 }
1454
1455                 if (!empty($data['channels_active_halfyear'])) {
1456                         $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1457                 }
1458
1459                 if (!empty($data['local_posts'])) {
1460                         $serverdata['local-posts'] = max($data['local_posts'], 0);
1461                 }
1462
1463                 if (!empty($data['local_comments'])) {
1464                         $serverdata['local-comments'] = max($data['local_comments'], 0);
1465                 }
1466
1467                 if (!empty($data['register_policy'])) {
1468                         switch ($data['register_policy']) {
1469                                 case 'REGISTER_OPEN':
1470                                         $serverdata['register_policy'] = Register::OPEN;
1471                                         break;
1472
1473                                 case 'REGISTER_APPROVE':
1474                                         $serverdata['register_policy'] = Register::APPROVE;
1475                                         break;
1476
1477                                 case 'REGISTER_CLOSED':
1478                                 default:
1479                                         $serverdata['register_policy'] = Register::CLOSED;
1480                                         break;
1481                         }
1482                 }
1483
1484                 return $serverdata;
1485         }
1486
1487         /**
1488          * Fetches server data via an ActivityPub account with url of that server
1489          *
1490          * @param string $url        URL of the given server
1491          * @param array  $serverdata array with server data
1492          *
1493          * @return array server data
1494          *
1495          * @throws Exception
1496          */
1497         private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1498         {
1499                 if (empty($data)) {
1500                         return ['server' => $serverdata, 'actor' => ''];
1501                 }
1502
1503                 $actor = JsonLD::compact($data, false);
1504                 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1505                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1506                         $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1507                         $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1508                         if (self::isNomad($actor)) {
1509                                 $serverdata['platform'] = self::getNomadName($actor['@id']);
1510                                 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1511                                 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1512                         } elseif (!empty($actor['as:generator'])) {
1513                                 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1514                                 $serverdata['platform'] = strtolower(array_shift($generator));
1515                                 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1516                                 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1517                         } else {
1518                                 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1519                         }
1520                         return ['server' => $serverdata, 'actor' => $actor['@id']];
1521                 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1522                         // By now only Ktistec seems to provide collections this way
1523                         $serverdata['platform'] = 'ktistec';
1524                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1525                         $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1526
1527                         $actors = JsonLD::fetchElementArray($actor, 'as:items');
1528                         if (!empty($actors) && !empty($actors[0]['@id'])) {
1529                                 $actor_url = $actor['@id'] . $actors[0]['@id'];
1530                         } else {
1531                                 $actor_url = '';
1532                         }
1533
1534                         return ['server' => $serverdata, 'actor' => $actor_url];
1535                 }
1536                 return ['server' => $serverdata, 'actor' => ''];
1537         }
1538
1539         /**
1540          * Detect if the given actor is a nomad account
1541          *
1542          * @param array $actor
1543          * @return boolean
1544          */
1545         private static function isNomad(array $actor): bool
1546         {
1547                 $tags = JsonLD::fetchElementArray($actor, 'as:tag');
1548                 if (empty($tags)) {
1549                         return false;
1550                 }
1551
1552                 foreach ($tags as $tag) {
1553                         if ((($tag['as:name'] ?? '') == 'Protocol') && (($tag['sc:value'] ?? '') == 'nomad')) {
1554                                 return true;
1555                         }
1556                 }
1557                 return false;
1558         }
1559
1560         /**
1561          * Fetch the name of Nomad implementation
1562          *
1563          * @param string $url
1564          * @return string
1565          */
1566         private static function getNomadName(string $url): string
1567         {
1568                 $name = 'nomad';
1569                 $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json');
1570                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1571                         return $name;
1572                 }
1573
1574                 $data = json_decode($curlResult->getBody(), true);
1575                 if (empty($data)) {
1576                         return $name;
1577                 }
1578
1579                 return $data['name'] ?? $name;
1580         }
1581
1582         /**
1583          * Fetch the version of the Nomad installation
1584          *
1585          * @param string $url
1586          * @return string
1587          */
1588         private static function getNomadVersion(string $url): string
1589         {
1590                 $curlResult = DI::httpClient()->get($url . '/api/z/1.0/version', HttpClientAccept::JSON);
1591                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1592                         return '';
1593                 }
1594
1595                 $data = json_decode($curlResult->getBody(), true);
1596                 if (empty($data)) {
1597                         return '';
1598                 }
1599                 return $data ?? '';
1600         }
1601
1602         /**
1603          * Checks if the server contains a valid host meta file
1604          *
1605          * @param string $url URL of the given server
1606          *
1607          * @return boolean 'true' if the server seems to be vital
1608          */
1609         private static function validHostMeta(string $url): bool
1610         {
1611                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1612                 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1613                 if (!$curlResult->isSuccess()) {
1614                         return false;
1615                 }
1616
1617                 $xrd = XML::parseString($curlResult->getBody(), true);
1618                 if (!is_object($xrd)) {
1619                         return false;
1620                 }
1621
1622                 $elements = XML::elementToArray($xrd);
1623                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1624                         return false;
1625                 }
1626
1627                 $valid = false;
1628                 foreach ($elements['xrd']['link'] as $link) {
1629                         // When there is more than a single "link" element, the array looks slightly different
1630                         if (!empty($link['@attributes'])) {
1631                                 $link = $link['@attributes'];
1632                         }
1633
1634                         if (empty($link['rel']) || empty($link['template'])) {
1635                                 continue;
1636                         }
1637
1638                         if ($link['rel'] == 'lrdd') {
1639                                 // When the webfinger host is the same like the system host, it should be ok.
1640                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1641                         }
1642                 }
1643
1644                 return $valid;
1645         }
1646
1647         /**
1648          * Detect the network of the given server via their known contacts
1649          *
1650          * @param string $url        URL of the given server
1651          * @param array  $serverdata array with server data
1652          *
1653          * @return array server data
1654          */
1655         private static function detectNetworkViaContacts(string $url, array $serverdata): array
1656         {
1657                 $contacts = [];
1658
1659                 $nurl = Strings::normaliseLink($url);
1660
1661                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1662                 while ($apcontact = DBA::fetch($apcontacts)) {
1663                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1664                 }
1665                 DBA::close($apcontacts);
1666
1667                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1668                 while ($pcontact = DBA::fetch($pcontacts)) {
1669                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1670                 }
1671                 DBA::close($pcontacts);
1672
1673                 if (empty($contacts)) {
1674                         return $serverdata;
1675                 }
1676
1677                 $time = time();
1678                 foreach ($contacts as $contact) {
1679                         // Endlosschleife verhindern wegen gsid!
1680                         $data = Probe::uri($contact);
1681                         if (in_array($data['network'], Protocol::FEDERATED)) {
1682                                 $serverdata['network'] = $data['network'];
1683
1684                                 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1685                                         $serverdata['detection-method'] = self::DETECT_CONTACTS;
1686                                 }
1687                                 break;
1688                         } elseif ((time() - $time) > 10) {
1689                                 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1690                                 break;
1691                         }
1692                 }
1693
1694                 return $serverdata;
1695         }
1696
1697         /**
1698          * Checks if the given server does have a '/poco' endpoint.
1699          * This is used for the 'PortableContact' functionality,
1700          * which is used by both Friendica and Hubzilla.
1701          *
1702          * @param string $url        URL of the given server
1703          * @param array  $serverdata array with server data
1704          *
1705          * @return array server data
1706          */
1707         private static function checkPoCo(string $url, array $serverdata): array
1708         {
1709                 $serverdata['poco'] = '';
1710
1711                 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1712                 if (!$curlResult->isSuccess()) {
1713                         return $serverdata;
1714                 }
1715
1716                 $data = json_decode($curlResult->getBody(), true);
1717                 if (empty($data)) {
1718                         return $serverdata;
1719                 }
1720
1721                 if (!empty($data['totalResults'])) {
1722                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1723                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1724                         $serverdata['directory-type'] = self::DT_POCO;
1725                         $serverdata['poco'] = $url . '/poco';
1726                 }
1727
1728                 return $serverdata;
1729         }
1730
1731         /**
1732          * Checks if the given server does have a Mastodon style directory endpoint.
1733          *
1734          * @param string $url        URL of the given server
1735          * @param array  $serverdata array with server data
1736          *
1737          * @return array server data
1738          */
1739         public static function checkMastodonDirectory(string $url, array $serverdata): array
1740         {
1741                 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1742                 if (!$curlResult->isSuccess()) {
1743                         return $serverdata;
1744                 }
1745
1746                 $data = json_decode($curlResult->getBody(), true);
1747                 if (empty($data)) {
1748                         return $serverdata;
1749                 }
1750
1751                 if (count($data) == 1) {
1752                         $serverdata['directory-type'] = self::DT_MASTODON;
1753                 }
1754
1755                 return $serverdata;
1756         }
1757
1758         /**
1759          * Detects Peertube via their known endpoint
1760          *
1761          * @param string $url        URL of the given server
1762          * @param array  $serverdata array with server data
1763          *
1764          * @return array server data
1765          */
1766         private static function detectPeertube(string $url, array $serverdata): array
1767         {
1768                 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1769                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1770                         return $serverdata;
1771                 }
1772
1773                 $data = json_decode($curlResult->getBody(), true);
1774                 if (empty($data)) {
1775                         return $serverdata;
1776                 }
1777
1778                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1779                         $serverdata['platform'] = 'peertube';
1780                         $serverdata['version'] = $data['serverVersion'];
1781                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1782
1783                         if (!empty($data['instance']['name'])) {
1784                                 $serverdata['site_name'] = $data['instance']['name'];
1785                         }
1786
1787                         if (!empty($data['instance']['shortDescription'])) {
1788                                 $serverdata['info'] = $data['instance']['shortDescription'];
1789                         }
1790
1791                         if (!empty($data['signup'])) {
1792                                 if (!empty($data['signup']['allowed'])) {
1793                                         $serverdata['register_policy'] = Register::OPEN;
1794                                 }
1795                         }
1796
1797                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1798                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1799                         }
1800                 }
1801
1802                 return $serverdata;
1803         }
1804
1805         /**
1806          * Detects the version number of a given server when it was a NextCloud installation
1807          *
1808          * @param string $url        URL of the given server
1809          * @param array  $serverdata array with server data
1810          * @param bool   $validHostMeta
1811          *
1812          * @return array server data
1813          */
1814         private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1815         {
1816                 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1817                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1818                         return $serverdata;
1819                 }
1820
1821                 $data = json_decode($curlResult->getBody(), true);
1822                 if (empty($data)) {
1823                         return $serverdata;
1824                 }
1825
1826                 if (!empty($data['version'])) {
1827                         $serverdata['platform'] = 'nextcloud';
1828                         $serverdata['version'] = $data['version'];
1829
1830                         if ($validHostMeta) {
1831                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1832                         }
1833
1834                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1835                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1836                         }
1837                 }
1838
1839                 return $serverdata;
1840         }
1841
1842         /**
1843          * Fetches weekly usage data
1844          *
1845          * @param string $url        URL of the given server
1846          * @param array  $serverdata array with server data
1847          *
1848          * @return array server data
1849          */
1850         private static function fetchWeeklyUsage(string $url, array $serverdata): array
1851         {
1852                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1853                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1854                         return $serverdata;
1855                 }
1856
1857                 $data = json_decode($curlResult->getBody(), true);
1858                 if (empty($data)) {
1859                         return $serverdata;
1860                 }
1861
1862                 $current_week = [];
1863                 foreach ($data as $week) {
1864                         // Use only data from a full week
1865                         if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1866                                 continue;
1867                         }
1868
1869                         // Most likely the data is sorted correctly. But we better are safe than sorry
1870                         if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1871                                 $current_week = $week;
1872                         }
1873                 }
1874
1875                 if (!empty($current_week['logins'])) {
1876                         $serverdata['active-week-users'] = max($current_week['logins'], 0);
1877                 }
1878
1879                 return $serverdata;
1880         }
1881
1882         /**
1883          * Detects data from a given server url if it was a mastodon alike system
1884          *
1885          * @param string $url        URL of the given server
1886          * @param array  $serverdata array with server data
1887          *
1888          * @return array server data
1889          */
1890         private static function detectMastodonAlikes(string $url, array $serverdata): array
1891         {
1892                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1893                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1894                         return $serverdata;
1895                 }
1896
1897                 $data = json_decode($curlResult->getBody(), true);
1898                 if (empty($data)) {
1899                         return $serverdata;
1900                 }
1901
1902                 $valid = false;
1903
1904                 if (!empty($data['version'])) {
1905                         $serverdata['platform'] = 'mastodon';
1906                         $serverdata['version'] = $data['version'] ?? '';
1907                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1908                         $valid = true;
1909                 }
1910
1911                 if (!empty($data['title'])) {
1912                         $serverdata['site_name'] = $data['title'];
1913                 }
1914
1915                 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1916                         $serverdata['platform'] = 'mastodon';
1917                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1918                         $valid = true;
1919                 }
1920
1921                 if (!empty($data['description'])) {
1922                         $serverdata['info'] = trim($data['description']);
1923                 }
1924
1925                 if (!empty($data['stats']['user_count'])) {
1926                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1927                 }
1928
1929                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1930                         $serverdata['platform'] = strtolower($matches[1]);
1931                         $serverdata['version'] = $matches[2];
1932                         $valid = true;
1933                 }
1934
1935                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1936                         $serverdata['platform'] = 'pleroma';
1937                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1938                         $valid = true;
1939                 }
1940
1941                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1942                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1943                         $serverdata['platform'] = 'pleroma';
1944                         $valid = true;
1945                 }
1946
1947                 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1948                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1949                 }
1950
1951                 return $serverdata;
1952         }
1953
1954         /**
1955          * Detects data from typical Hubzilla endpoints
1956          *
1957          * @param string $url        URL of the given server
1958          * @param array  $serverdata array with server data
1959          *
1960          * @return array server data
1961          */
1962         private static function detectHubzilla(string $url, array $serverdata): array
1963         {
1964                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1965                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1966                         return $serverdata;
1967                 }
1968
1969                 $data = json_decode($curlResult->getBody(), true);
1970                 if (empty($data) || empty($data['site'])) {
1971                         return $serverdata;
1972                 }
1973
1974                 if (!empty($data['site']['name'])) {
1975                         $serverdata['site_name'] = $data['site']['name'];
1976                 }
1977
1978                 if (!empty($data['site']['platform'])) {
1979                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1980                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1981                         $serverdata['network'] = Protocol::ZOT;
1982                 }
1983
1984                 if (!empty($data['site']['hubzilla'])) {
1985                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1986                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1987                         $serverdata['network'] = Protocol::ZOT;
1988                 }
1989
1990                 if (!empty($data['site']['redmatrix'])) {
1991                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1992                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1993                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1994                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1995                         }
1996
1997                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1998                         $serverdata['network'] = Protocol::ZOT;
1999                 }
2000
2001                 $private = false;
2002                 $inviteonly = false;
2003                 $closed = false;
2004
2005                 if (!empty($data['site']['closed'])) {
2006                         $closed = self::toBoolean($data['site']['closed']);
2007                 }
2008
2009                 if (!empty($data['site']['private'])) {
2010                         $private = self::toBoolean($data['site']['private']);
2011                 }
2012
2013                 if (!empty($data['site']['inviteonly'])) {
2014                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
2015                 }
2016
2017                 if (!$closed && !$private and $inviteonly) {
2018                         $serverdata['register_policy'] = Register::APPROVE;
2019                 } elseif (!$closed && !$private) {
2020                         $serverdata['register_policy'] = Register::OPEN;
2021                 } else {
2022                         $serverdata['register_policy'] = Register::CLOSED;
2023                 }
2024
2025                 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2026                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
2027                 }
2028
2029                 return $serverdata;
2030         }
2031
2032         /**
2033          * Converts input value to a boolean value
2034          *
2035          * @param string|integer $val
2036          *
2037          * @return boolean
2038          */
2039         private static function toBoolean($val): bool
2040         {
2041                 if (($val == 'true') || ($val == 1)) {
2042                         return true;
2043                 } elseif (($val == 'false') || ($val == 0)) {
2044                         return false;
2045                 }
2046
2047                 return $val;
2048         }
2049
2050         /**
2051          * Detect if the URL belongs to a GNU Social server
2052          *
2053          * @param string $url        URL of the given server
2054          * @param array  $serverdata array with server data
2055          *
2056          * @return array server data
2057          */
2058         private static function detectGNUSocial(string $url, array $serverdata): array
2059         {
2060                 // Test for GNU Social
2061                 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
2062                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2063                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2064                         $serverdata['platform'] = 'gnusocial';
2065                         // Remove junk that some GNU Social servers return
2066                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
2067                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2068                         $serverdata['version'] = trim($serverdata['version'], '"');
2069                         $serverdata['network'] = Protocol::OSTATUS;
2070
2071                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2072                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
2073                         }
2074
2075                         return $serverdata;
2076                 }
2077
2078                 // Test for Statusnet
2079                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
2080                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2081                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2082
2083                         // Remove junk that some GNU Social servers return
2084                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
2085                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2086                         $serverdata['version'] = trim($serverdata['version'], '"');
2087
2088                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
2089                                 $serverdata['platform'] = 'pleroma';
2090                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
2091                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
2092                         } else {
2093                                 $serverdata['platform'] = 'statusnet';
2094                                 $serverdata['network'] = Protocol::OSTATUS;
2095                         }
2096
2097                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2098                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
2099                         }
2100                 }
2101
2102                 return $serverdata;
2103         }
2104
2105         /**
2106          * Detect if the URL belongs to a Friendica server
2107          *
2108          * @param string $url        URL of the given server
2109          * @param array  $serverdata array with server data
2110          *
2111          * @return array server data
2112          */
2113         private static function detectFriendica(string $url, array $serverdata): array
2114         {
2115                 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
2116                 // Because of this me must not use ACCEPT_JSON here.
2117                 $curlResult = DI::httpClient()->get($url . '/friendica/json');
2118                 if (!$curlResult->isSuccess()) {
2119                         $curlResult = DI::httpClient()->get($url . '/friendika/json');
2120                         $friendika = true;
2121                         $platform = 'Friendika';
2122                 } else {
2123                         $friendika = false;
2124                         $platform = 'Friendica';
2125                 }
2126
2127                 if (!$curlResult->isSuccess()) {
2128                         return $serverdata;
2129                 }
2130
2131                 $data = json_decode($curlResult->getBody(), true);
2132                 if (empty($data) || empty($data['version'])) {
2133                         return $serverdata;
2134                 }
2135
2136                 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2137                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2138                 }
2139
2140                 $serverdata['network'] = Protocol::DFRN;
2141                 $serverdata['version'] = $data['version'];
2142
2143                 if (!empty($data['no_scrape_url'])) {
2144                         $serverdata['noscrape'] = $data['no_scrape_url'];
2145                 }
2146
2147                 if (!empty($data['site_name'])) {
2148                         $serverdata['site_name'] = $data['site_name'];
2149                 }
2150
2151                 if (!empty($data['info'])) {
2152                         $serverdata['info'] = trim($data['info']);
2153                 }
2154
2155                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2156                 switch ($register_policy) {
2157                         case 'REGISTER_OPEN':
2158                                 $serverdata['register_policy'] = Register::OPEN;
2159                                 break;
2160
2161                         case 'REGISTER_APPROVE':
2162                                 $serverdata['register_policy'] = Register::APPROVE;
2163                                 break;
2164
2165                         case 'REGISTER_CLOSED':
2166                         case 'REGISTER_INVITATION':
2167                                 $serverdata['register_policy'] = Register::CLOSED;
2168                                 break;
2169                         default:
2170                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2171                                 $serverdata['register_policy'] = Register::CLOSED;
2172                                 break;
2173                 }
2174
2175                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2176
2177                 return $serverdata;
2178         }
2179
2180         /**
2181          * Analyses the landing page of a given server for hints about type and system of that server
2182          *
2183          * @param object $curlResult result of curl execution
2184          * @param array  $serverdata array with server data
2185          *
2186          * @return array server data
2187          */
2188         private static function analyseRootBody($curlResult, array $serverdata): array
2189         {
2190                 if (empty($curlResult->getBody())) {
2191                         return $serverdata;
2192                 }
2193
2194                 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2195                         require __DIR__ . '/../../static/platforms.config.php';
2196                 } else {
2197                         throw new HTTPException\InternalServerErrorException('Invalid platform file');
2198                 }
2199
2200                 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2201
2202                 $doc = new DOMDocument();
2203                 @$doc->loadHTML($curlResult->getBody());
2204                 $xpath = new DOMXPath($doc);
2205                 $assigned = false;
2206
2207                 // We can only detect honk via some HTML element on their page
2208                 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2209                         $serverdata['platform'] = 'honk';
2210                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2211                         $assigned = true;
2212                 }
2213
2214                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2215                 if (!empty($title)) {
2216                         $serverdata['site_name'] = $title;
2217                 }
2218
2219                 $list = $xpath->query('//meta[@name]');
2220
2221                 foreach ($list as $node) {
2222                         $attr = [];
2223                         if ($node->attributes->length) {
2224                                 foreach ($node->attributes as $attribute) {
2225                                         $value = trim($attribute->value);
2226                                         if (empty($value)) {
2227                                                 continue;
2228                                         }
2229
2230                                         $attr[$attribute->name] = $value;
2231                                 }
2232
2233                                 if (empty($attr['name']) || empty($attr['content'])) {
2234                                         continue;
2235                                 }
2236                         }
2237
2238                         if ($attr['name'] == 'description') {
2239                                 $serverdata['info'] = $attr['content'];
2240                         }
2241
2242                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2243                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2244                                 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2245                                 $platform = str_replace('/', ' ', $platform);
2246                                 $platform_parts = explode(' ', $platform);
2247                                 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2248                                         $platform = $platform_parts[0];
2249                                         $serverdata['version'] = $platform_parts[1];
2250                                 }
2251                                 if (in_array($platform, array_values($dfrn_platforms))) {
2252                                         $serverdata['network'] = Protocol::DFRN;
2253                                 } elseif (in_array($platform, array_values($ap_platforms))) {
2254                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2255                                 } elseif (in_array($platform, array_values($zap_platforms))) {
2256                                         $serverdata['network'] = Protocol::ZOT;
2257                                 }
2258                                 if (in_array($platform, array_values($platforms))) {
2259                                         $serverdata['platform'] = $platform;
2260                                         $assigned = true;
2261                                 }
2262                         }
2263                 }
2264
2265                 $list = $xpath->query('//meta[@property]');
2266
2267                 foreach ($list as $node) {
2268                         $attr = [];
2269                         if ($node->attributes->length) {
2270                                 foreach ($node->attributes as $attribute) {
2271                                         $value = trim($attribute->value);
2272                                         if (empty($value)) {
2273                                                 continue;
2274                                         }
2275
2276                                         $attr[$attribute->name] = $value;
2277                                 }
2278
2279                                 if (empty($attr['property']) || empty($attr['content'])) {
2280                                         continue;
2281                                 }
2282                         }
2283
2284                         if ($attr['property'] == 'og:site_name') {
2285                                 $serverdata['site_name'] = $attr['content'];
2286                         }
2287
2288                         if ($attr['property'] == 'og:description') {
2289                                 $serverdata['info'] = $attr['content'];
2290                         }
2291
2292                         if (in_array($attr['property'], ['og:platform', 'generator'])) {
2293                                 if (in_array($attr['content'], array_keys($platforms))) {
2294                                         $serverdata['platform'] = $platforms[$attr['content']];
2295                                         $assigned = true;
2296                                 }
2297
2298                                 if (in_array($attr['content'], array_keys($ap_platforms))) {
2299                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2300                                 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2301                                         $serverdata['network'] = Protocol::ZOT;
2302                                 }
2303                         }
2304                 }
2305
2306                 $list = $xpath->query('//link[@rel="me"]');
2307                 foreach ($list as $node) {
2308                         foreach ($node->attributes as $attribute) {
2309                                 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2310                                         $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2311                                         $serverdata['platform'] = 'microblog';
2312                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2313                                         $assigned = true;
2314                                 }
2315                         }
2316                 }
2317
2318                 if ($serverdata['platform'] != 'microblog') {
2319                         $list = $xpath->query('//link[@rel="micropub"]');
2320                         foreach ($list as $node) {
2321                                 foreach ($node->attributes as $attribute) {
2322                                         if (trim($attribute->value) == 'https://micro.blog/micropub') {
2323                                                 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2324                                                 $serverdata['platform'] = 'microblog';
2325                                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
2326                                                 $assigned = true;
2327                                         }
2328                                 }
2329                         }
2330                 }
2331
2332                 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2333                         $serverdata['detection-method'] = self::DETECT_BODY;
2334                 }
2335
2336                 return $serverdata;
2337         }
2338
2339         /**
2340          * Analyses the header data of a given server for hints about type and system of that server
2341          *
2342          * @param object $curlResult result of curl execution
2343          * @param array  $serverdata array with server data
2344          *
2345          * @return array server data
2346          */
2347         private static function analyseRootHeader($curlResult, array $serverdata): array
2348         {
2349                 if ($curlResult->getHeader('server') == 'Mastodon') {
2350                         $serverdata['platform'] = 'mastodon';
2351                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2352                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2353                         $serverdata['platform'] = 'diaspora';
2354                         $serverdata['network'] = Protocol::DIASPORA;
2355                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2356                 } elseif ($curlResult->inHeader('x-friendica-version')) {
2357                         $serverdata['platform'] = 'friendica';
2358                         $serverdata['network'] = Protocol::DFRN;
2359                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2360                 } else {
2361                         return $serverdata;
2362                 }
2363
2364                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2365                         $serverdata['detection-method'] = self::DETECT_HEADER;
2366                 }
2367
2368                 return $serverdata;
2369         }
2370
2371         /**
2372          * Update GServer entries
2373          */
2374         public static function discover()
2375         {
2376                 // Update the server list
2377                 self::discoverFederation();
2378
2379                 $no_of_queries = 5;
2380
2381                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2382
2383                 if ($requery_days == 0) {
2384                         $requery_days = 7;
2385                 }
2386
2387                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2388
2389                 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2390                         ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2391                         ['order' => ['RAND()']]);
2392
2393                 while ($gserver = DBA::fetch($gservers)) {
2394                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2395                         Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2396
2397                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2398                         Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2399
2400                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2401                         self::update($fields, ['nurl' => $gserver['nurl']]);
2402
2403                         if (--$no_of_queries == 0) {
2404                                 break;
2405                         }
2406                 }
2407
2408                 DBA::close($gservers);
2409         }
2410
2411         /**
2412          * Discover federated servers
2413          */
2414         private static function discoverFederation()
2415         {
2416                 $last = DI::keyValue()->get('poco_last_federation_discovery');
2417
2418                 if ($last) {
2419                         $next = $last + (24 * 60 * 60);
2420
2421                         if ($next > time()) {
2422                                 return;
2423                         }
2424                 }
2425
2426                 // Discover federated servers
2427                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2428                 foreach ($protocols as $protocol) {
2429                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2430                         $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2431                         if (!empty($curlResult)) {
2432                                 $data = json_decode($curlResult, true);
2433                                 if (!empty($data['data']['nodes'])) {
2434                                         foreach ($data['data']['nodes'] as $server) {
2435                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2436                                                 self::add('https://' . $server['host'], true);
2437                                         }
2438                                 }
2439                         }
2440                 }
2441
2442                 // Discover Mastodon servers
2443                 $accesstoken = DI::config()->get('system', 'instances_social_key');
2444
2445                 if (!empty($accesstoken)) {
2446                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
2447                         $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2448                         if ($curlResult->isSuccess()) {
2449                                 $servers = json_decode($curlResult->getBody(), true);
2450
2451                                 if (!empty($servers['instances'])) {
2452                                         foreach ($servers['instances'] as $server) {
2453                                                 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2454                                                 self::add($url);
2455                                         }
2456                                 }
2457                         }
2458                 }
2459
2460                 DI::keyValue()->set('poco_last_federation_discovery', time());
2461         }
2462
2463         /**
2464          * Set the protocol for the given server
2465          *
2466          * @param int $gsid     Server id
2467          * @param int $protocol Protocol id
2468          *
2469          * @throws Exception
2470          */
2471         public static function setProtocol(int $gsid, int $protocol)
2472         {
2473                 if (empty($gsid)) {
2474                         return;
2475                 }
2476
2477                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2478                 if (!DBA::isResult($gserver)) {
2479                         return;
2480                 }
2481
2482                 $old = $gserver['protocol'];
2483
2484                 if (!is_null($old)) {
2485                         /*
2486                         The priority for the protocols is:
2487                                 1. ActivityPub
2488                                 2. DFRN via Diaspora
2489                                 3. Legacy DFRN
2490                                 4. Diaspora
2491                                 5. OStatus
2492                         */
2493
2494                         // We don't need to change it when nothing is to be changed
2495                         if ($old == $protocol) {
2496                                 return;
2497                         }
2498
2499                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2500                         if ($protocol == Post\DeliveryData::OSTATUS) {
2501                                 return;
2502                         }
2503
2504                         // If the server is marked as ActivityPub then we won't change it to anything different
2505                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
2506                                 return;
2507                         }
2508
2509                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2510                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2511                                 return;
2512                         }
2513
2514                         // Don't change it to Diaspora when it is a legacy DFRN server
2515                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2516                                 return;
2517                         }
2518                 }
2519
2520                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]);
2521                 self::update(['protocol' => $protocol], ['id' => $gsid]);
2522         }
2523
2524         /**
2525          * Fetch the protocol of the given server
2526          *
2527          * @param int $gsid Server id
2528          *
2529          * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2530          *
2531          * @throws Exception
2532          */
2533         public static function getProtocol(int $gsid): ?int
2534         {
2535                 if (empty($gsid)) {
2536                         return null;
2537                 }
2538
2539                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2540                 if (DBA::isResult($gserver)) {
2541                         return $gserver['protocol'];
2542                 }
2543
2544                 return null;
2545         }
2546
2547         /**
2548          * Update rows in the gserver table.
2549          * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2550          *
2551          * @param array $fields
2552          * @param array $condition
2553          *
2554          * @return bool
2555          *
2556          * @throws Exception
2557          */
2558         public static function update(array $fields, array $condition): bool
2559         {
2560                 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2561
2562                 return DBA::update('gserver', $fields, $condition);
2563         }
2564
2565         /**
2566          * Insert a row into the gserver table.
2567          * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2568          *
2569          * @param array $fields
2570          * @param int   $duplicate_mode What to do on a duplicated entry
2571          *
2572          * @return bool
2573          *
2574          * @throws Exception
2575          */
2576         public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2577         {
2578                 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2579
2580                 return DBA::insert('gserver', $fields, $duplicate_mode);
2581         }
2582 }