]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Merge pull request #13708 from MrPetovan/bug/deprecated
[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                         if (is_string($nodeinfo['protocols'])) {
1270                                 $protocols[$nodeinfo['protocols']] = true;
1271                         } else {
1272                                 foreach ($nodeinfo['protocols'] as $protocol) {
1273                                         if (is_string($protocol)) {
1274                                                 $protocols[$protocol] = true;
1275                                         }
1276                                 }
1277                         }
1278
1279                         if (!empty($protocols['dfrn'])) {
1280                                 $server['network'] = Protocol::DFRN;
1281                         } elseif (!empty($protocols['activitypub'])) {
1282                                 $server['network'] = Protocol::ACTIVITYPUB;
1283                         } elseif (!empty($protocols['diaspora'])) {
1284                                 $server['network'] = Protocol::DIASPORA;
1285                         } elseif (!empty($protocols['ostatus'])) {
1286                                 $server['network'] = Protocol::OSTATUS;
1287                         } elseif (!empty($protocols['gnusocial'])) {
1288                                 $server['network'] = Protocol::OSTATUS;
1289                         } elseif (!empty($protocols['zot'])) {
1290                                 $server['network'] = Protocol::ZOT;
1291                         }
1292                 }
1293
1294                 if (empty($server)) {
1295                         return [];
1296                 }
1297
1298                 if (empty($server['network'])) {
1299                         $server['network'] = Protocol::PHANTOM;
1300                 }
1301
1302                 return $server;
1303         }
1304
1305         /**
1306          * Parses NodeInfo2 protocol 1.0
1307          *
1308          * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1309          *
1310          * @param string $nodeinfo_url address of the nodeinfo path
1311          *
1312          * @return array Server data
1313          *
1314          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1315          */
1316         private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1317         {
1318                 if (!$httpResult->isSuccess()) {
1319                         return [];
1320                 }
1321
1322                 $nodeinfo = json_decode($httpResult->getBody(), true);
1323
1324                 if (!is_array($nodeinfo)) {
1325                         return [];
1326                 }
1327
1328                 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1329                         'register_policy' => Register::CLOSED];
1330
1331                 if (!empty($nodeinfo['openRegistrations'])) {
1332                         $server['register_policy'] = Register::OPEN;
1333                 }
1334
1335                 if (!empty($nodeinfo['server'])) {
1336                         if (!empty($nodeinfo['server']['software'])) {
1337                                 $server['platform'] = strtolower($nodeinfo['server']['software']);
1338                         }
1339
1340                         if (!empty($nodeinfo['server']['version'])) {
1341                                 $server['version'] = $nodeinfo['server']['version'];
1342                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1343                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1344                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1345                         }
1346
1347                         if (!empty($nodeinfo['server']['name'])) {
1348                                 $server['site_name'] = $nodeinfo['server']['name'];
1349                         }
1350                 }
1351
1352                 if (!empty($nodeinfo['usage']['users']['total'])) {
1353                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1354                 }
1355
1356                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1357                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1358                 }
1359
1360                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1361                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1362                 }
1363
1364                 if (!empty($nodeinfo['usage']['localPosts'])) {
1365                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1366                 }
1367
1368                 if (!empty($nodeinfo['usage']['localComments'])) {
1369                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1370                 }
1371
1372                 if (!empty($nodeinfo['protocols'])) {
1373                         $protocols = [];
1374                         if (is_string($nodeinfo['protocols'])) {
1375                                 $protocols[$nodeinfo['protocols']] = true;
1376                         } else {
1377                                 foreach ($nodeinfo['protocols'] as $protocol) {
1378                                         if (is_string($protocol)) {
1379                                                 $protocols[$protocol] = true;
1380                                         }
1381                                 }
1382                         }
1383
1384                         if (!empty($protocols['dfrn'])) {
1385                                 $server['network'] = Protocol::DFRN;
1386                         } elseif (!empty($protocols['activitypub'])) {
1387                                 $server['network'] = Protocol::ACTIVITYPUB;
1388                         } elseif (!empty($protocols['diaspora'])) {
1389                                 $server['network'] = Protocol::DIASPORA;
1390                         } elseif (!empty($protocols['ostatus'])) {
1391                                 $server['network'] = Protocol::OSTATUS;
1392                         } elseif (!empty($protocols['gnusocial'])) {
1393                                 $server['network'] = Protocol::OSTATUS;
1394                         } elseif (!empty($protocols['zot'])) {
1395                                 $server['network'] = Protocol::ZOT;
1396                         }
1397                 }
1398
1399                 if (empty($server) || empty($server['platform'])) {
1400                         return [];
1401                 }
1402
1403                 if (empty($server['network'])) {
1404                         $server['network'] = Protocol::PHANTOM;
1405                 }
1406
1407                 return $server;
1408         }
1409
1410         /**
1411          * Fetch server information from a 'siteinfo.json' file on the given server
1412          *
1413          * @param string $url        URL of the given server
1414          * @param array  $serverdata array with server data
1415          *
1416          * @return array server data
1417          */
1418         private static function fetchSiteinfo(string $url, array $serverdata): array
1419         {
1420                 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1421                 if (!$curlResult->isSuccess()) {
1422                         return $serverdata;
1423                 }
1424
1425                 $data = json_decode($curlResult->getBody(), true);
1426                 if (empty($data)) {
1427                         return $serverdata;
1428                 }
1429
1430                 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1431                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1432                 }
1433
1434                 if (!empty($data['platform'])) {
1435                         $serverdata['platform'] = strtolower($data['platform']);
1436                         $serverdata['version'] = $data['version'] ?? 'N/A';
1437                 }
1438
1439                 if (!empty($data['plugins'])) {
1440                         if (in_array('pubcrawl', $data['plugins'])) {
1441                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1442                         } elseif (in_array('diaspora', $data['plugins'])) {
1443                                 $serverdata['network'] = Protocol::DIASPORA;
1444                         } elseif (in_array('gnusoc', $data['plugins'])) {
1445                                 $serverdata['network'] = Protocol::OSTATUS;
1446                         } else {
1447                                 $serverdata['network'] = Protocol::ZOT;
1448                         }
1449                 }
1450
1451                 if (!empty($data['site_name'])) {
1452                         $serverdata['site_name'] = $data['site_name'];
1453                 }
1454
1455                 if (!empty($data['channels_total'])) {
1456                         $serverdata['registered-users'] = max($data['channels_total'], 1);
1457                 }
1458
1459                 if (!empty($data['channels_active_monthly'])) {
1460                         $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1461                 }
1462
1463                 if (!empty($data['channels_active_halfyear'])) {
1464                         $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1465                 }
1466
1467                 if (!empty($data['local_posts'])) {
1468                         $serverdata['local-posts'] = max($data['local_posts'], 0);
1469                 }
1470
1471                 if (!empty($data['local_comments'])) {
1472                         $serverdata['local-comments'] = max($data['local_comments'], 0);
1473                 }
1474
1475                 if (!empty($data['register_policy'])) {
1476                         switch ($data['register_policy']) {
1477                                 case 'REGISTER_OPEN':
1478                                         $serverdata['register_policy'] = Register::OPEN;
1479                                         break;
1480
1481                                 case 'REGISTER_APPROVE':
1482                                         $serverdata['register_policy'] = Register::APPROVE;
1483                                         break;
1484
1485                                 case 'REGISTER_CLOSED':
1486                                 default:
1487                                         $serverdata['register_policy'] = Register::CLOSED;
1488                                         break;
1489                         }
1490                 }
1491
1492                 return $serverdata;
1493         }
1494
1495         /**
1496          * Fetches server data via an ActivityPub account with url of that server
1497          *
1498          * @param string $url        URL of the given server
1499          * @param array  $serverdata array with server data
1500          *
1501          * @return array server data
1502          *
1503          * @throws Exception
1504          */
1505         private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1506         {
1507                 if (empty($data)) {
1508                         return ['server' => $serverdata, 'actor' => ''];
1509                 }
1510
1511                 $actor = JsonLD::compact($data, false);
1512                 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1513                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1514                         $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1515                         $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1516                         if (self::isNomad($actor)) {
1517                                 $serverdata['platform'] = self::getNomadName($actor['@id']);
1518                                 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1519                                 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1520                         } elseif (!empty($actor['as:generator'])) {
1521                                 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1522                                 $serverdata['platform'] = strtolower(array_shift($generator));
1523                                 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1524                                 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1525                         } else {
1526                                 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1527                         }
1528                         return ['server' => $serverdata, 'actor' => $actor['@id']];
1529                 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1530                         // By now only Ktistec seems to provide collections this way
1531                         $serverdata['platform'] = 'ktistec';
1532                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1533                         $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1534
1535                         $actors = JsonLD::fetchElementArray($actor, 'as:items');
1536                         if (!empty($actors) && !empty($actors[0]['@id'])) {
1537                                 $actor_url = $actor['@id'] . $actors[0]['@id'];
1538                         } else {
1539                                 $actor_url = '';
1540                         }
1541
1542                         return ['server' => $serverdata, 'actor' => $actor_url];
1543                 }
1544                 return ['server' => $serverdata, 'actor' => ''];
1545         }
1546
1547         /**
1548          * Detect if the given actor is a nomad account
1549          *
1550          * @param array $actor
1551          * @return boolean
1552          */
1553         private static function isNomad(array $actor): bool
1554         {
1555                 $tags = JsonLD::fetchElementArray($actor, 'as:tag');
1556                 if (empty($tags)) {
1557                         return false;
1558                 }
1559
1560                 foreach ($tags as $tag) {
1561                         if ((($tag['as:name'] ?? '') == 'Protocol') && (($tag['sc:value'] ?? '') == 'nomad')) {
1562                                 return true;
1563                         }
1564                 }
1565                 return false;
1566         }
1567
1568         /**
1569          * Fetch the name of Nomad implementation
1570          *
1571          * @param string $url
1572          * @return string
1573          */
1574         private static function getNomadName(string $url): string
1575         {
1576                 $name = 'nomad';
1577                 $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json');
1578                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1579                         return $name;
1580                 }
1581
1582                 $data = json_decode($curlResult->getBody(), true);
1583                 if (empty($data)) {
1584                         return $name;
1585                 }
1586
1587                 return $data['name'] ?? $name;
1588         }
1589
1590         /**
1591          * Fetch the version of the Nomad installation
1592          *
1593          * @param string $url
1594          * @return string
1595          */
1596         private static function getNomadVersion(string $url): string
1597         {
1598                 $curlResult = DI::httpClient()->get($url . '/api/z/1.0/version', HttpClientAccept::JSON);
1599                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1600                         return '';
1601                 }
1602
1603                 $data = json_decode($curlResult->getBody(), true);
1604                 if (empty($data)) {
1605                         return '';
1606                 }
1607                 return $data ?? '';
1608         }
1609
1610         /**
1611          * Checks if the server contains a valid host meta file
1612          *
1613          * @param string $url URL of the given server
1614          *
1615          * @return boolean 'true' if the server seems to be vital
1616          */
1617         private static function validHostMeta(string $url): bool
1618         {
1619                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1620                 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1621                 if (!$curlResult->isSuccess()) {
1622                         return false;
1623                 }
1624
1625                 $xrd = XML::parseString($curlResult->getBody(), true);
1626                 if (!is_object($xrd)) {
1627                         return false;
1628                 }
1629
1630                 $elements = XML::elementToArray($xrd);
1631                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1632                         return false;
1633                 }
1634
1635                 $valid = false;
1636                 foreach ($elements['xrd']['link'] as $link) {
1637                         // When there is more than a single "link" element, the array looks slightly different
1638                         if (!empty($link['@attributes'])) {
1639                                 $link = $link['@attributes'];
1640                         }
1641
1642                         if (empty($link['rel']) || empty($link['template'])) {
1643                                 continue;
1644                         }
1645
1646                         if ($link['rel'] == 'lrdd') {
1647                                 // When the webfinger host is the same like the system host, it should be ok.
1648                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1649                         }
1650                 }
1651
1652                 return $valid;
1653         }
1654
1655         /**
1656          * Detect the network of the given server via their known contacts
1657          *
1658          * @param string $url        URL of the given server
1659          * @param array  $serverdata array with server data
1660          *
1661          * @return array server data
1662          */
1663         private static function detectNetworkViaContacts(string $url, array $serverdata): array
1664         {
1665                 $contacts = [];
1666
1667                 $nurl = Strings::normaliseLink($url);
1668
1669                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1670                 while ($apcontact = DBA::fetch($apcontacts)) {
1671                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1672                 }
1673                 DBA::close($apcontacts);
1674
1675                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1676                 while ($pcontact = DBA::fetch($pcontacts)) {
1677                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1678                 }
1679                 DBA::close($pcontacts);
1680
1681                 if (empty($contacts)) {
1682                         return $serverdata;
1683                 }
1684
1685                 $time = time();
1686                 foreach ($contacts as $contact) {
1687                         // Endlosschleife verhindern wegen gsid!
1688                         $data = Probe::uri($contact);
1689                         if (in_array($data['network'], Protocol::FEDERATED)) {
1690                                 $serverdata['network'] = $data['network'];
1691
1692                                 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1693                                         $serverdata['detection-method'] = self::DETECT_CONTACTS;
1694                                 }
1695                                 break;
1696                         } elseif ((time() - $time) > 10) {
1697                                 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1698                                 break;
1699                         }
1700                 }
1701
1702                 return $serverdata;
1703         }
1704
1705         /**
1706          * Checks if the given server does have a '/poco' endpoint.
1707          * This is used for the 'PortableContact' functionality,
1708          * which is used by both Friendica and Hubzilla.
1709          *
1710          * @param string $url        URL of the given server
1711          * @param array  $serverdata array with server data
1712          *
1713          * @return array server data
1714          */
1715         private static function checkPoCo(string $url, array $serverdata): array
1716         {
1717                 $serverdata['poco'] = '';
1718
1719                 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1720                 if (!$curlResult->isSuccess()) {
1721                         return $serverdata;
1722                 }
1723
1724                 $data = json_decode($curlResult->getBody(), true);
1725                 if (empty($data)) {
1726                         return $serverdata;
1727                 }
1728
1729                 if (!empty($data['totalResults'])) {
1730                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1731                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1732                         $serverdata['directory-type'] = self::DT_POCO;
1733                         $serverdata['poco'] = $url . '/poco';
1734                 }
1735
1736                 return $serverdata;
1737         }
1738
1739         /**
1740          * Checks if the given server does have a Mastodon style directory endpoint.
1741          *
1742          * @param string $url        URL of the given server
1743          * @param array  $serverdata array with server data
1744          *
1745          * @return array server data
1746          */
1747         public static function checkMastodonDirectory(string $url, array $serverdata): array
1748         {
1749                 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1750                 if (!$curlResult->isSuccess()) {
1751                         return $serverdata;
1752                 }
1753
1754                 $data = json_decode($curlResult->getBody(), true);
1755                 if (empty($data)) {
1756                         return $serverdata;
1757                 }
1758
1759                 if (count($data) == 1) {
1760                         $serverdata['directory-type'] = self::DT_MASTODON;
1761                 }
1762
1763                 return $serverdata;
1764         }
1765
1766         /**
1767          * Detects Peertube via their known endpoint
1768          *
1769          * @param string $url        URL of the given server
1770          * @param array  $serverdata array with server data
1771          *
1772          * @return array server data
1773          */
1774         private static function detectPeertube(string $url, array $serverdata): array
1775         {
1776                 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1777                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1778                         return $serverdata;
1779                 }
1780
1781                 $data = json_decode($curlResult->getBody(), true);
1782                 if (empty($data)) {
1783                         return $serverdata;
1784                 }
1785
1786                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1787                         $serverdata['platform'] = 'peertube';
1788                         $serverdata['version'] = $data['serverVersion'];
1789                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1790
1791                         if (!empty($data['instance']['name'])) {
1792                                 $serverdata['site_name'] = $data['instance']['name'];
1793                         }
1794
1795                         if (!empty($data['instance']['shortDescription'])) {
1796                                 $serverdata['info'] = $data['instance']['shortDescription'];
1797                         }
1798
1799                         if (!empty($data['signup'])) {
1800                                 if (!empty($data['signup']['allowed'])) {
1801                                         $serverdata['register_policy'] = Register::OPEN;
1802                                 }
1803                         }
1804
1805                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1806                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1807                         }
1808                 }
1809
1810                 return $serverdata;
1811         }
1812
1813         /**
1814          * Detects the version number of a given server when it was a NextCloud installation
1815          *
1816          * @param string $url        URL of the given server
1817          * @param array  $serverdata array with server data
1818          * @param bool   $validHostMeta
1819          *
1820          * @return array server data
1821          */
1822         private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1823         {
1824                 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1825                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1826                         return $serverdata;
1827                 }
1828
1829                 $data = json_decode($curlResult->getBody(), true);
1830                 if (empty($data)) {
1831                         return $serverdata;
1832                 }
1833
1834                 if (!empty($data['version'])) {
1835                         $serverdata['platform'] = 'nextcloud';
1836                         $serverdata['version'] = $data['version'];
1837
1838                         if ($validHostMeta) {
1839                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1840                         }
1841
1842                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1843                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1844                         }
1845                 }
1846
1847                 return $serverdata;
1848         }
1849
1850         /**
1851          * Fetches weekly usage data
1852          *
1853          * @param string $url        URL of the given server
1854          * @param array  $serverdata array with server data
1855          *
1856          * @return array server data
1857          */
1858         private static function fetchWeeklyUsage(string $url, array $serverdata): array
1859         {
1860                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1861                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1862                         return $serverdata;
1863                 }
1864
1865                 $data = json_decode($curlResult->getBody(), true);
1866                 if (empty($data)) {
1867                         return $serverdata;
1868                 }
1869
1870                 $current_week = [];
1871                 foreach ($data as $week) {
1872                         // Use only data from a full week
1873                         if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1874                                 continue;
1875                         }
1876
1877                         // Most likely the data is sorted correctly. But we better are safe than sorry
1878                         if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1879                                 $current_week = $week;
1880                         }
1881                 }
1882
1883                 if (!empty($current_week['logins'])) {
1884                         $serverdata['active-week-users'] = max($current_week['logins'], 0);
1885                 }
1886
1887                 return $serverdata;
1888         }
1889
1890         /**
1891          * Detects data from a given server url if it was a mastodon alike system
1892          *
1893          * @param string $url        URL of the given server
1894          * @param array  $serverdata array with server data
1895          *
1896          * @return array server data
1897          */
1898         private static function detectMastodonAlikes(string $url, array $serverdata): array
1899         {
1900                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1901                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1902                         return $serverdata;
1903                 }
1904
1905                 $data = json_decode($curlResult->getBody(), true);
1906                 if (empty($data)) {
1907                         return $serverdata;
1908                 }
1909
1910                 $valid = false;
1911
1912                 if (!empty($data['version'])) {
1913                         $serverdata['platform'] = 'mastodon';
1914                         $serverdata['version'] = $data['version'] ?? '';
1915                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1916                         $valid = true;
1917                 }
1918
1919                 if (!empty($data['title'])) {
1920                         $serverdata['site_name'] = $data['title'];
1921                 }
1922
1923                 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1924                         $serverdata['platform'] = 'mastodon';
1925                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1926                         $valid = true;
1927                 }
1928
1929                 if (!empty($data['description'])) {
1930                         $serverdata['info'] = trim($data['description']);
1931                 }
1932
1933                 if (!empty($data['stats']['user_count'])) {
1934                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1935                 }
1936
1937                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1938                         $serverdata['platform'] = strtolower($matches[1]);
1939                         $serverdata['version'] = $matches[2];
1940                         $valid = true;
1941                 }
1942
1943                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1944                         $serverdata['platform'] = 'pleroma';
1945                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1946                         $valid = true;
1947                 }
1948
1949                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1950                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1951                         $serverdata['platform'] = 'pleroma';
1952                         $valid = true;
1953                 }
1954
1955                 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1956                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1957                 }
1958
1959                 return $serverdata;
1960         }
1961
1962         /**
1963          * Detects data from typical Hubzilla endpoints
1964          *
1965          * @param string $url        URL of the given server
1966          * @param array  $serverdata array with server data
1967          *
1968          * @return array server data
1969          */
1970         private static function detectHubzilla(string $url, array $serverdata): array
1971         {
1972                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1973                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1974                         return $serverdata;
1975                 }
1976
1977                 $data = json_decode($curlResult->getBody(), true);
1978                 if (empty($data) || empty($data['site'])) {
1979                         return $serverdata;
1980                 }
1981
1982                 if (!empty($data['site']['name'])) {
1983                         $serverdata['site_name'] = $data['site']['name'];
1984                 }
1985
1986                 if (!empty($data['site']['platform'])) {
1987                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1988                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1989                         $serverdata['network'] = Protocol::ZOT;
1990                 }
1991
1992                 if (!empty($data['site']['hubzilla'])) {
1993                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1994                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1995                         $serverdata['network'] = Protocol::ZOT;
1996                 }
1997
1998                 if (!empty($data['site']['redmatrix'])) {
1999                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
2000                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
2001                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
2002                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
2003                         }
2004
2005                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
2006                         $serverdata['network'] = Protocol::ZOT;
2007                 }
2008
2009                 $private = false;
2010                 $inviteonly = false;
2011                 $closed = false;
2012
2013                 if (!empty($data['site']['closed'])) {
2014                         $closed = self::toBoolean($data['site']['closed']);
2015                 }
2016
2017                 if (!empty($data['site']['private'])) {
2018                         $private = self::toBoolean($data['site']['private']);
2019                 }
2020
2021                 if (!empty($data['site']['inviteonly'])) {
2022                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
2023                 }
2024
2025                 if (!$closed && !$private and $inviteonly) {
2026                         $serverdata['register_policy'] = Register::APPROVE;
2027                 } elseif (!$closed && !$private) {
2028                         $serverdata['register_policy'] = Register::OPEN;
2029                 } else {
2030                         $serverdata['register_policy'] = Register::CLOSED;
2031                 }
2032
2033                 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2034                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
2035                 }
2036
2037                 return $serverdata;
2038         }
2039
2040         /**
2041          * Converts input value to a boolean value
2042          *
2043          * @param string|integer $val
2044          *
2045          * @return boolean
2046          */
2047         private static function toBoolean($val): bool
2048         {
2049                 if (($val == 'true') || ($val == 1)) {
2050                         return true;
2051                 } elseif (($val == 'false') || ($val == 0)) {
2052                         return false;
2053                 }
2054
2055                 return $val;
2056         }
2057
2058         /**
2059          * Detect if the URL belongs to a GNU Social server
2060          *
2061          * @param string $url        URL of the given server
2062          * @param array  $serverdata array with server data
2063          *
2064          * @return array server data
2065          */
2066         private static function detectGNUSocial(string $url, array $serverdata): array
2067         {
2068                 // Test for GNU Social
2069                 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
2070                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2071                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2072                         $serverdata['platform'] = 'gnusocial';
2073                         // Remove junk that some GNU Social servers return
2074                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
2075                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2076                         $serverdata['version'] = trim($serverdata['version'], '"');
2077                         $serverdata['network'] = Protocol::OSTATUS;
2078
2079                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2080                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
2081                         }
2082
2083                         return $serverdata;
2084                 }
2085
2086                 // Test for Statusnet
2087                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
2088                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2089                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2090
2091                         // Remove junk that some GNU Social servers return
2092                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
2093                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2094                         $serverdata['version'] = trim($serverdata['version'], '"');
2095
2096                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
2097                                 $serverdata['platform'] = 'pleroma';
2098                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
2099                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
2100                         } else {
2101                                 $serverdata['platform'] = 'statusnet';
2102                                 $serverdata['network'] = Protocol::OSTATUS;
2103                         }
2104
2105                         if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2106                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
2107                         }
2108                 }
2109
2110                 return $serverdata;
2111         }
2112
2113         /**
2114          * Detect if the URL belongs to a Friendica server
2115          *
2116          * @param string $url        URL of the given server
2117          * @param array  $serverdata array with server data
2118          *
2119          * @return array server data
2120          */
2121         private static function detectFriendica(string $url, array $serverdata): array
2122         {
2123                 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
2124                 // Because of this me must not use ACCEPT_JSON here.
2125                 $curlResult = DI::httpClient()->get($url . '/friendica/json');
2126                 if (!$curlResult->isSuccess()) {
2127                         $curlResult = DI::httpClient()->get($url . '/friendika/json');
2128                         $friendika = true;
2129                         $platform = 'Friendika';
2130                 } else {
2131                         $friendika = false;
2132                         $platform = 'Friendica';
2133                 }
2134
2135                 if (!$curlResult->isSuccess()) {
2136                         return $serverdata;
2137                 }
2138
2139                 $data = json_decode($curlResult->getBody(), true);
2140                 if (empty($data) || empty($data['version'])) {
2141                         return $serverdata;
2142                 }
2143
2144                 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2145                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2146                 }
2147
2148                 $serverdata['network'] = Protocol::DFRN;
2149                 $serverdata['version'] = $data['version'];
2150
2151                 if (!empty($data['no_scrape_url'])) {
2152                         $serverdata['noscrape'] = $data['no_scrape_url'];
2153                 }
2154
2155                 if (!empty($data['site_name'])) {
2156                         $serverdata['site_name'] = $data['site_name'];
2157                 }
2158
2159                 if (!empty($data['info'])) {
2160                         $serverdata['info'] = trim($data['info']);
2161                 }
2162
2163                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2164                 switch ($register_policy) {
2165                         case 'REGISTER_OPEN':
2166                                 $serverdata['register_policy'] = Register::OPEN;
2167                                 break;
2168
2169                         case 'REGISTER_APPROVE':
2170                                 $serverdata['register_policy'] = Register::APPROVE;
2171                                 break;
2172
2173                         case 'REGISTER_CLOSED':
2174                         case 'REGISTER_INVITATION':
2175                                 $serverdata['register_policy'] = Register::CLOSED;
2176                                 break;
2177                         default:
2178                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2179                                 $serverdata['register_policy'] = Register::CLOSED;
2180                                 break;
2181                 }
2182
2183                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2184
2185                 return $serverdata;
2186         }
2187
2188         /**
2189          * Analyses the landing page of a given server for hints about type and system of that server
2190          *
2191          * @param object $curlResult result of curl execution
2192          * @param array  $serverdata array with server data
2193          *
2194          * @return array server data
2195          */
2196         private static function analyseRootBody($curlResult, array $serverdata): array
2197         {
2198                 if (empty($curlResult->getBody())) {
2199                         return $serverdata;
2200                 }
2201
2202                 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2203                         require __DIR__ . '/../../static/platforms.config.php';
2204                 } else {
2205                         throw new HTTPException\InternalServerErrorException('Invalid platform file');
2206                 }
2207
2208                 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2209
2210                 $doc = new DOMDocument();
2211                 @$doc->loadHTML($curlResult->getBody());
2212                 $xpath = new DOMXPath($doc);
2213                 $assigned = false;
2214
2215                 // We can only detect honk via some HTML element on their page
2216                 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2217                         $serverdata['platform'] = 'honk';
2218                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2219                         $assigned = true;
2220                 }
2221
2222                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2223                 if (!empty($title)) {
2224                         $serverdata['site_name'] = $title;
2225                 }
2226
2227                 $list = $xpath->query('//meta[@name]');
2228
2229                 foreach ($list as $node) {
2230                         $attr = [];
2231                         if ($node->attributes->length) {
2232                                 foreach ($node->attributes as $attribute) {
2233                                         $value = trim($attribute->value);
2234                                         if (empty($value)) {
2235                                                 continue;
2236                                         }
2237
2238                                         $attr[$attribute->name] = $value;
2239                                 }
2240
2241                                 if (empty($attr['name']) || empty($attr['content'])) {
2242                                         continue;
2243                                 }
2244                         }
2245
2246                         if ($attr['name'] == 'description') {
2247                                 $serverdata['info'] = $attr['content'];
2248                         }
2249
2250                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2251                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2252                                 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2253                                 $platform = str_replace('/', ' ', $platform);
2254                                 $platform_parts = explode(' ', $platform);
2255                                 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2256                                         $platform = $platform_parts[0];
2257                                         $serverdata['version'] = $platform_parts[1];
2258                                 }
2259                                 if (in_array($platform, array_values($dfrn_platforms))) {
2260                                         $serverdata['network'] = Protocol::DFRN;
2261                                 } elseif (in_array($platform, array_values($ap_platforms))) {
2262                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2263                                 } elseif (in_array($platform, array_values($zap_platforms))) {
2264                                         $serverdata['network'] = Protocol::ZOT;
2265                                 }
2266                                 if (in_array($platform, array_values($platforms))) {
2267                                         $serverdata['platform'] = $platform;
2268                                         $assigned = true;
2269                                 }
2270                         }
2271                 }
2272
2273                 $list = $xpath->query('//meta[@property]');
2274
2275                 foreach ($list as $node) {
2276                         $attr = [];
2277                         if ($node->attributes->length) {
2278                                 foreach ($node->attributes as $attribute) {
2279                                         $value = trim($attribute->value);
2280                                         if (empty($value)) {
2281                                                 continue;
2282                                         }
2283
2284                                         $attr[$attribute->name] = $value;
2285                                 }
2286
2287                                 if (empty($attr['property']) || empty($attr['content'])) {
2288                                         continue;
2289                                 }
2290                         }
2291
2292                         if ($attr['property'] == 'og:site_name') {
2293                                 $serverdata['site_name'] = $attr['content'];
2294                         }
2295
2296                         if ($attr['property'] == 'og:description') {
2297                                 $serverdata['info'] = $attr['content'];
2298                         }
2299
2300                         if (in_array($attr['property'], ['og:platform', 'generator'])) {
2301                                 if (in_array($attr['content'], array_keys($platforms))) {
2302                                         $serverdata['platform'] = $platforms[$attr['content']];
2303                                         $assigned = true;
2304                                 }
2305
2306                                 if (in_array($attr['content'], array_keys($ap_platforms))) {
2307                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2308                                 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2309                                         $serverdata['network'] = Protocol::ZOT;
2310                                 }
2311                         }
2312                 }
2313
2314                 $list = $xpath->query('//link[@rel="me"]');
2315                 foreach ($list as $node) {
2316                         foreach ($node->attributes as $attribute) {
2317                                 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2318                                         $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2319                                         $serverdata['platform'] = 'microblog';
2320                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2321                                         $assigned = true;
2322                                 }
2323                         }
2324                 }
2325
2326                 if ($serverdata['platform'] != 'microblog') {
2327                         $list = $xpath->query('//link[@rel="micropub"]');
2328                         foreach ($list as $node) {
2329                                 foreach ($node->attributes as $attribute) {
2330                                         if (trim($attribute->value) == 'https://micro.blog/micropub') {
2331                                                 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2332                                                 $serverdata['platform'] = 'microblog';
2333                                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
2334                                                 $assigned = true;
2335                                         }
2336                                 }
2337                         }
2338                 }
2339
2340                 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2341                         $serverdata['detection-method'] = self::DETECT_BODY;
2342                 }
2343
2344                 return $serverdata;
2345         }
2346
2347         /**
2348          * Analyses the header data of a given server for hints about type and system of that server
2349          *
2350          * @param object $curlResult result of curl execution
2351          * @param array  $serverdata array with server data
2352          *
2353          * @return array server data
2354          */
2355         private static function analyseRootHeader($curlResult, array $serverdata): array
2356         {
2357                 if ($curlResult->getHeader('server') == 'Mastodon') {
2358                         $serverdata['platform'] = 'mastodon';
2359                         $serverdata['network'] = Protocol::ACTIVITYPUB;
2360                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2361                         $serverdata['platform'] = 'diaspora';
2362                         $serverdata['network'] = Protocol::DIASPORA;
2363                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2364                 } elseif ($curlResult->inHeader('x-friendica-version')) {
2365                         $serverdata['platform'] = 'friendica';
2366                         $serverdata['network'] = Protocol::DFRN;
2367                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2368                 } else {
2369                         return $serverdata;
2370                 }
2371
2372                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2373                         $serverdata['detection-method'] = self::DETECT_HEADER;
2374                 }
2375
2376                 return $serverdata;
2377         }
2378
2379         /**
2380          * Update GServer entries
2381          */
2382         public static function discover()
2383         {
2384                 if (!DI::config('system', 'discover_servers')) {
2385                         return;
2386                 }
2387
2388                 // Update the server list
2389                 self::discoverFederation();
2390
2391                 $no_of_queries = 5;
2392
2393                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2394
2395                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2396
2397                 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2398                         ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2399                         ['order' => ['RAND()']]);
2400
2401                 while ($gserver = DBA::fetch($gservers)) {
2402                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2403                         Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2404
2405                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2406                         Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2407
2408                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2409                         self::update($fields, ['nurl' => $gserver['nurl']]);
2410
2411                         if (--$no_of_queries == 0) {
2412                                 break;
2413                         }
2414                 }
2415
2416                 DBA::close($gservers);
2417         }
2418
2419         /**
2420          * Discover federated servers
2421          */
2422         private static function discoverFederation()
2423         {
2424                 $last = DI::keyValue()->get('poco_last_federation_discovery');
2425
2426                 if ($last) {
2427                         $next = $last + (24 * 60 * 60);
2428
2429                         if ($next > time()) {
2430                                 return;
2431                         }
2432                 }
2433
2434                 // Discover federated servers
2435                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2436                 foreach ($protocols as $protocol) {
2437                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2438                         $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2439                         if (!empty($curlResult)) {
2440                                 $data = json_decode($curlResult, true);
2441                                 if (!empty($data['data']['nodes'])) {
2442                                         foreach ($data['data']['nodes'] as $server) {
2443                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2444                                                 self::add('https://' . $server['host'], true);
2445                                         }
2446                                 }
2447                         }
2448                 }
2449
2450                 // Discover Mastodon servers
2451                 $accesstoken = DI::config()->get('system', 'instances_social_key');
2452
2453                 if (!empty($accesstoken)) {
2454                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
2455                         $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2456                         if ($curlResult->isSuccess()) {
2457                                 $servers = json_decode($curlResult->getBody(), true);
2458
2459                                 if (!empty($servers['instances'])) {
2460                                         foreach ($servers['instances'] as $server) {
2461                                                 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2462                                                 self::add($url);
2463                                         }
2464                                 }
2465                         }
2466                 }
2467
2468                 DI::keyValue()->set('poco_last_federation_discovery', time());
2469         }
2470
2471         /**
2472          * Set the protocol for the given server
2473          *
2474          * @param int $gsid     Server id
2475          * @param int $protocol Protocol id
2476          *
2477          * @throws Exception
2478          */
2479         public static function setProtocol(int $gsid, int $protocol)
2480         {
2481                 if (empty($gsid)) {
2482                         return;
2483                 }
2484
2485                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2486                 if (!DBA::isResult($gserver)) {
2487                         return;
2488                 }
2489
2490                 $old = $gserver['protocol'];
2491
2492                 if (!is_null($old)) {
2493                         /*
2494                         The priority for the protocols is:
2495                                 1. ActivityPub
2496                                 2. DFRN via Diaspora
2497                                 3. Legacy DFRN
2498                                 4. Diaspora
2499                                 5. OStatus
2500                         */
2501
2502                         // We don't need to change it when nothing is to be changed
2503                         if ($old == $protocol) {
2504                                 return;
2505                         }
2506
2507                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2508                         if ($protocol == Post\DeliveryData::OSTATUS) {
2509                                 return;
2510                         }
2511
2512                         // If the server is marked as ActivityPub then we won't change it to anything different
2513                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
2514                                 return;
2515                         }
2516
2517                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2518                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2519                                 return;
2520                         }
2521
2522                         // Don't change it to Diaspora when it is a legacy DFRN server
2523                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2524                                 return;
2525                         }
2526                 }
2527
2528                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]);
2529                 self::update(['protocol' => $protocol], ['id' => $gsid]);
2530         }
2531
2532         /**
2533          * Fetch the protocol of the given server
2534          *
2535          * @param int $gsid Server id
2536          *
2537          * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2538          *
2539          * @throws Exception
2540          */
2541         public static function getProtocol(int $gsid): ?int
2542         {
2543                 if (empty($gsid)) {
2544                         return null;
2545                 }
2546
2547                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2548                 if (DBA::isResult($gserver)) {
2549                         return $gserver['protocol'];
2550                 }
2551
2552                 return null;
2553         }
2554
2555         /**
2556          * Update rows in the gserver table.
2557          * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2558          *
2559          * @param array $fields
2560          * @param array $condition
2561          *
2562          * @return bool
2563          *
2564          * @throws Exception
2565          */
2566         public static function update(array $fields, array $condition): bool
2567         {
2568                 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2569
2570                 return DBA::update('gserver', $fields, $condition);
2571         }
2572
2573         /**
2574          * Insert a row into the gserver table.
2575          * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2576          *
2577          * @param array $fields
2578          * @param int   $duplicate_mode What to do on a duplicated entry
2579          *
2580          * @return bool
2581          *
2582          * @throws Exception
2583          */
2584         public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2585         {
2586                 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2587
2588                 return DBA::insert('gserver', $fields, $duplicate_mode);
2589         }
2590 }