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