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