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