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