]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Update src/Model/GServer.php
[friendica.git] / src / Model / GServer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Exception;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
37 use Friendica\Protocol\Relay;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
41 use Friendica\Util\XML;
42
43 /**
44  * This class handles GServer related functions
45  */
46 class GServer
47 {
48         // Directory types
49         const DT_NONE = 0;
50         const DT_POCO = 1;
51         const DT_MASTODON = 2;
52
53         // Methods to detect server types
54
55         // Non endpoint specific methods
56         const DETECT_MANUAL = 0;
57         const DETECT_HEADER = 1;
58         const DETECT_BODY = 2;
59
60         // Implementation specific endpoints
61         const DETECT_FRIENDIKA = 10;
62         const DETECT_FRIENDICA = 11;
63         const DETECT_STATUSNET = 12;
64         const DETECT_GNUSOCIAL = 13;
65         const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
66         const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
67         const DETECT_MASTODON_API = 16;
68         const DETECT_STATUS_PHP = 17; // Nextcloud
69         const DETECT_V1_CONFIG = 18;
70         const DETECT_PUMPIO = 19;
71
72         // Standardized endpoints
73         const DETECT_STATISTICS_JSON = 100;
74         const DETECT_NODEINFO_1 = 101;
75         const DETECT_NODEINFO_2 = 102;
76
77         /**
78          * Check for the existance of a server and adds it in the background if not existant
79          *
80          * @param string $url
81          * @param boolean $only_nodeinfo
82          * @return void
83          */
84         public static function add(string $url, bool $only_nodeinfo = false)
85         {
86                 if (self::getID($url, false)) {
87                         return;
88                 }
89
90                 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
91         }
92
93         /**
94          * Get the ID for the given server URL
95          *
96          * @param string $url
97          * @param boolean $no_check Don't check if the server hadn't been found
98          * @return int gserver id
99          */
100         public static function getID(string $url, bool $no_check = false)
101         {
102                 if (empty($url)) {
103                         return null;
104                 }
105
106                 $url = self::cleanURL($url);
107
108                 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
109                 if (DBA::isResult($gserver)) {
110                         Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
111                         return $gserver['id'];
112                 }
113
114                 if ($no_check || !self::check($url)) {
115                         return null;
116                 }
117
118                 return self::getID($url, true);
119         }
120
121         /**
122          * Retrieves all the servers which base domain are matching the provided domain pattern
123          *
124          * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
125          *
126          * @param string $pattern
127          * @return array
128          * @throws Exception
129          */
130         public static function listByDomainPattern(string $pattern): array
131         {
132                 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
133
134                 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
135                 // eventual server path and keep only the server domain which we're matching against the pattern.
136                 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
137                         FROM `gserver`
138                         LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
139                         WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
140                         AND NOT `gserver`.`failed`
141                         GROUP BY `gserver`.`id`";
142
143                 $stmt = DI::dba()->p($sql, $likePattern);
144
145                 return DI::dba()->toArray($stmt);
146         }
147
148         /**
149          * Checks if the given server is reachable
150          *
151          * @param string  $profile URL of the given profile
152          * @param string  $server  URL of the given server (If empty, taken from profile)
153          * @param string  $network Network value that is used, when detection failed
154          * @param boolean $force   Force an update.
155          *
156          * @return boolean 'true' if server seems vital
157          */
158         public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
159         {
160                 if ($server == '') {
161                         $contact = Contact::getByURL($profile, null, ['baseurl']);
162                         if (!empty($contact['baseurl'])) {
163                                 $server = $contact['baseurl'];
164                         }
165                 }
166
167                 if ($server == '') {
168                         return true;
169                 }
170
171                 return self::check($server, $network, $force);
172         }
173
174         public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
175         {
176                 // On successful contact process check again next week
177                 if ($success) {
178                         return DateTimeFormat::utc('now +7 day');
179                 }
180
181                 $now = strtotime(DateTimeFormat::utcNow());
182
183                 if ($created > $last_contact) {
184                         $contact_time = strtotime($created);
185                 } else {
186                         $contact_time = strtotime($last_contact);
187                 }
188
189                 // If the last contact was less than 6 hours before then try again in 6 hours
190                 if (($now - $contact_time) < (60 * 60 * 6)) {
191                         return DateTimeFormat::utc('now +6 hour');
192                 }
193
194                 // If the last contact was less than 12 hours before then try again in 12 hours
195                 if (($now - $contact_time) < (60 * 60 * 12)) {
196                         return DateTimeFormat::utc('now +12 hour');
197                 }
198
199                 // If the last contact was less than 24 hours before then try tomorrow again
200                 if (($now - $contact_time) < (60 * 60 * 24)) {
201                         return DateTimeFormat::utc('now +1 day');
202                 }
203
204                 // If the last contact was less than a week before then try again in a week
205                 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
206                         return DateTimeFormat::utc('now +1 week');
207                 }
208
209                 // If the last contact was less than two weeks before then try again in two week
210                 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
211                         return DateTimeFormat::utc('now +2 week');
212                 }
213
214                 // If the last contact was less than a month before then try again in a month
215                 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
216                         return DateTimeFormat::utc('now +1 month');
217                 }
218
219                 // The system hadn't been successul contacted for more than a month, so try again in three months
220                 return DateTimeFormat::utc('now +3 month');
221         }
222
223         /**
224          * Checks the state of the given server.
225          *
226          * @param string  $server_url    URL of the given server
227          * @param string  $network       Network value that is used, when detection failed
228          * @param boolean $force         Force an update.
229          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
230          *
231          * @return boolean 'true' if server seems vital
232          */
233         public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
234         {
235                 $server_url = self::cleanURL($server_url);
236                 if ($server_url == '') {
237                         return false;
238                 }
239
240                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
241                 if (DBA::isResult($gserver)) {
242                         if ($gserver['created'] <= DBA::NULL_DATETIME) {
243                                 $fields = ['created' => DateTimeFormat::utcNow()];
244                                 $condition = ['nurl' => Strings::normaliseLink($server_url)];
245                                 DBA::update('gserver', $fields, $condition);
246                         }
247
248                         if (!$force && (strtotime($gserver['next_contact']) > time())) {
249                                 Logger::info('No update needed', ['server' => $server_url]);
250                                 return (!$gserver['failed']);
251                         }
252                         Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
253                 } else {
254                         Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
255                 }
256
257                 return self::detect($server_url, $network, $only_nodeinfo);
258         }
259
260         /**
261          * Set failed server status
262          *
263          * @param string $url
264          */
265         public static function setFailure(string $url)
266         {
267                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
268                 if (DBA::isResult($gserver)) {
269                         $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
270                         DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
271                         'next_contact' => $next_update, 'detection-method' => null],
272                         ['nurl' => Strings::normaliseLink($url)]);
273                         Logger::info('Set failed status for existing server', ['url' => $url]);
274                         return;
275                 }
276                 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
277                         'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
278                         'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
279                 Logger::info('Set failed status for new server', ['url' => $url]);
280         }
281
282         /**
283          * Remove unwanted content from the given URL
284          *
285          * @param string $url
286          * @return string cleaned URL
287          */
288         public static function cleanURL(string $url)
289         {
290                 $url = trim($url, '/');
291                 $url = str_replace('/index.php', '', $url);
292
293                 $urlparts = parse_url($url);
294                 unset($urlparts['user']);
295                 unset($urlparts['pass']);
296                 unset($urlparts['query']);
297                 unset($urlparts['fragment']);
298                 return Network::unparseURL($urlparts);
299         }
300
301         /**
302          * Return the base URL
303          *
304          * @param string $url
305          * @return string base URL
306          */
307         private static function getBaseURL(string $url)
308         {
309                 $urlparts = parse_url(self::cleanURL($url));
310                 unset($urlparts['path']);
311                 return Network::unparseURL($urlparts);
312         }
313
314         /**
315          * Detect server data (type, protocol, version number, ...)
316          * The detected data is then updated or inserted in the gserver table.
317          *
318          * @param string  $url           URL of the given server
319          * @param string  $network       Network value that is used, when detection failed
320          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
321          *
322          * @return boolean 'true' if server could be detected
323          */
324         public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
325         {
326                 Logger::info('Detect server type', ['server' => $url]);
327                 $serverdata = ['detection-method' => self::DETECT_MANUAL];
328
329                 $original_url = $url;
330
331                 // Remove URL content that is not supposed to exist for a server url
332                 $url = self::cleanURL($url);
333
334                 // Get base URL
335                 $baseurl = self::getBaseURL($url);
336
337                 // If the URL missmatches, then we mark the old entry as failure
338                 if ($url != $original_url) {
339                         /// @todo What to do with "next_contact" here?
340                         DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
341                                 ['nurl' => Strings::normaliseLink($original_url)]);
342                 }
343
344                 // When a nodeinfo is present, we don't need to dig further
345                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
346                 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
347                 if ($curlResult->isTimeout()) {
348                         self::setFailure($url);
349                         return false;
350                 }
351
352                 // On a redirect follow the new host but mark the old one as failure
353                 if ($curlResult->isSuccess() && !empty($curlResult->getRedirectUrl()) && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
354                         $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
355                         if (!empty($curlResult->getRedirectUrl()) && parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
356                                 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
357                                 self::setFailure($url);
358                                 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
359                                 return false;
360                         }
361                 }
362
363                 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
364                 if ($only_nodeinfo && empty($nodeinfo)) {
365                         Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
366                         self::setFailure($url);
367                         return false;
368                 }
369
370                 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
371                 if (empty($nodeinfo)) {
372                         $nodeinfo = self::fetchStatistics($url);
373                 }
374
375                 // If that didn't work out well, we use some protocol specific endpoints
376                 // For Friendica and Zot based networks we have to dive deeper to reveal more details
377                 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
378                         if (!empty($nodeinfo['detection-method'])) {
379                                 $serverdata['detection-method'] = $nodeinfo['detection-method'];
380                         }
381
382                         // Fetch the landing page, possibly it reveals some data
383                         if (empty($nodeinfo['network'])) {
384                                 if ($baseurl == $url) {
385                                         $basedata = $serverdata;
386                                 } else {
387                                         $basedata = ['detection-method' => self::DETECT_MANUAL];
388                                 }
389
390                                 $curlResult = DI::httpClient()->get($baseurl, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
391                                 if ($curlResult->isSuccess()) {
392                                         if (!empty($curlResult->getRedirectUrl()) && (parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
393                                                 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
394                                                 self::setFailure($url);
395                                                 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
396                                                 return false;
397                                         }
398
399                                         $basedata = self::analyseRootHeader($curlResult, $basedata);
400                                         $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
401                                 }
402
403                                 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
404                                         self::setFailure($url);
405                                         return false;
406                                 }
407
408                                 if ($baseurl == $url) {
409                                         $serverdata = $basedata;
410                                 } else {
411                                         // When the base path doesn't seem to contain a social network we try the complete path.
412                                         // Most detectable system have to be installed in the root directory.
413                                         // We checked the base to avoid false positives.
414                                         $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
415                                         if ($curlResult->isSuccess()) {
416                                                 $urldata = self::analyseRootHeader($curlResult, $serverdata);
417                                                 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
418
419                                                 $comparebase = $basedata;
420                                                 unset($comparebase['info']);
421                                                 unset($comparebase['site_name']);
422                                                 $compareurl = $urldata;
423                                                 unset($compareurl['info']);
424                                                 unset($compareurl['site_name']);
425
426                                                 // We assume that no one will install the identical system in the root and a subfolder
427                                                 if (!empty(array_diff($comparebase, $compareurl))) {
428                                                         $serverdata = $urldata;
429                                                 }
430                                         }
431                                 }
432                         }
433
434                         if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
435                                 $serverdata = self::detectMastodonAlikes($url, $serverdata);
436                         }
437
438                         // All following checks are done for systems that always have got a "host-meta" endpoint.
439                         // With this check we don't have to waste time and ressources for dead systems.
440                         // Also this hopefully prevents us from receiving abuse messages.
441                         if (empty($serverdata['network']) && !self::validHostMeta($url)) {
442                                 self::setFailure($url);
443                                 return false;
444                         }
445
446                         if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
447                                 $serverdata = self::detectFriendica($url, $serverdata);
448                         }
449
450                         // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
451                         if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
452                                 $serverdata = self::fetchSiteinfo($url, $serverdata);
453                         }
454
455                         // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
456                         if (empty($serverdata['network'])) {
457                                 $serverdata = self::detectHubzilla($url, $serverdata);
458                         }
459
460                         if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
461                                 $serverdata = self::detectPeertube($url, $serverdata);
462                         }
463
464                         if (empty($serverdata['network'])) {
465                                 $serverdata = self::detectNextcloud($url, $serverdata);
466                         }
467
468                         if (empty($serverdata['network'])) {
469                                 $serverdata = self::detectGNUSocial($url, $serverdata);
470                         }
471
472                         if (empty($serverdata['network'])) {
473                                 $serverdata = self::detectPumpIO($url, $serverdata);
474                         }
475
476                         $serverdata = array_merge($nodeinfo, $serverdata);
477                 } else {
478                         $serverdata = $nodeinfo;
479                 }
480
481                 // Detect the directory type
482                 $serverdata['directory-type'] = self::DT_NONE;
483                 $serverdata = self::checkPoCo($url, $serverdata);
484                 $serverdata = self::checkMastodonDirectory($url, $serverdata);
485
486                 // We can't detect the network type. Possibly it is some system that we don't know yet
487                 if (empty($serverdata['network'])) {
488                         $serverdata['network'] = Protocol::PHANTOM;
489                 }
490
491                 // When we hadn't been able to detect the network type, we use the hint from the parameter
492                 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
493                         $serverdata['network'] = $network;
494                 }
495
496                 $serverdata['url'] = $url;
497                 $serverdata['nurl'] = Strings::normaliseLink($url);
498
499                 // We take the highest number that we do find
500                 $registeredUsers = $serverdata['registered-users'] ?? 0;
501
502                 // On an active server there has to be at least a single user
503                 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
504                         $registeredUsers = 1;
505                 }
506
507                 if ($serverdata['network'] == Protocol::PHANTOM) {
508                         $serverdata['registered-users'] = max($registeredUsers, 1);
509                         $serverdata = self::detectNetworkViaContacts($url, $serverdata);
510                 }
511
512                 $serverdata['next_contact'] = self::getNextUpdateDate(true);
513
514                 $serverdata['last_contact'] = DateTimeFormat::utcNow();
515                 $serverdata['failed'] = false;
516
517                 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
518                 if (!DBA::isResult($gserver)) {
519                         $serverdata['created'] = DateTimeFormat::utcNow();
520                         $ret = DBA::insert('gserver', $serverdata);
521                         $id = DBA::lastInsertId();
522                 } else {
523                         // Don't override the network with 'unknown' when there had been a valid entry before
524                         if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
525                                 unset($serverdata['network']);
526                         }
527
528                         $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
529                         $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
530                         if (DBA::isResult($gserver)) {
531                                 $id = $gserver['id'];
532                         }
533                 }
534
535                 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
536                         $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
537                         $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
538                         $max_users = max($apcontacts, $contacts, $registeredUsers, 1);
539                         if ($max_users > $registeredUsers) {
540                                 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
541                                 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
542                         }
543                 }
544
545                 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
546                         self::discoverRelay($url);
547                 }
548
549                 return $ret;
550         }
551
552         /**
553          * Fetch relay data from a given server url
554          *
555          * @param string $server_url address of the server
556          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
557          */
558         private static function discoverRelay(string $server_url)
559         {
560                 Logger::info('Discover relay data', ['server' => $server_url]);
561
562                 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay');
563                 if (!$curlResult->isSuccess()) {
564                         return;
565                 }
566
567                 $data = json_decode($curlResult->getBody(), true);
568                 if (!is_array($data)) {
569                         return;
570                 }
571
572                 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
573                 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
574
575                 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
576                         $data['scope'] = '';
577                         $data['subscribe'] = false;
578                         $data['tags'] = [];
579                 }
580
581                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
582                 if (!DBA::isResult($gserver)) {
583                         return;
584                 }
585
586                 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
587                         $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
588                         DBA::update('gserver', $fields, ['id' => $gserver['id']]);
589                 }
590
591                 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
592
593                 if ($data['scope'] == 'tags') {
594                         // Avoid duplicates
595                         $tags = [];
596                         foreach ($data['tags'] as $tag) {
597                                 $tag = mb_strtolower($tag);
598                                 if (strlen($tag) < 100) {
599                                         $tags[$tag] = $tag;
600                                 }
601                         }
602
603                         foreach ($tags as $tag) {
604                                 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
605                         }
606                 }
607
608                 // Create or update the relay contact
609                 $fields = [];
610                 if (isset($data['protocols'])) {
611                         if (isset($data['protocols']['diaspora'])) {
612                                 $fields['network'] = Protocol::DIASPORA;
613
614                                 if (isset($data['protocols']['diaspora']['receive'])) {
615                                         $fields['batch'] = $data['protocols']['diaspora']['receive'];
616                                 } elseif (is_string($data['protocols']['diaspora'])) {
617                                         $fields['batch'] = $data['protocols']['diaspora'];
618                                 }
619                         }
620
621                         if (isset($data['protocols']['dfrn'])) {
622                                 $fields['network'] = Protocol::DFRN;
623
624                                 if (isset($data['protocols']['dfrn']['receive'])) {
625                                         $fields['batch'] = $data['protocols']['dfrn']['receive'];
626                                 } elseif (is_string($data['protocols']['dfrn'])) {
627                                         $fields['batch'] = $data['protocols']['dfrn'];
628                                 }
629                         }
630
631                         if (isset($data['protocols']['activitypub'])) {
632                                 $fields['network'] = Protocol::ACTIVITYPUB;
633
634                                 if (!empty($data['protocols']['activitypub']['actor'])) {
635                                         $fields['url'] = $data['protocols']['activitypub']['actor'];
636                                 }
637                                 if (!empty($data['protocols']['activitypub']['receive'])) {
638                                         $fields['batch'] = $data['protocols']['activitypub']['receive'];
639                                 }
640                         }
641                 }
642
643                 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
644
645                 Relay::updateContact($gserver, $fields);
646         }
647
648         /**
649          * Fetch server data from '/statistics.json' on the given server
650          *
651          * @param string $url URL of the given server
652          *
653          * @return array server data
654          */
655         private static function fetchStatistics(string $url)
656         {
657                 $curlResult = DI::httpClient()->get($url . '/statistics.json');
658                 if (!$curlResult->isSuccess()) {
659                         return [];
660                 }
661
662                 $data = json_decode($curlResult->getBody(), true);
663                 if (empty($data)) {
664                         return [];
665                 }
666
667                 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
668
669                 if (!empty($data['version'])) {
670                         $serverdata['version'] = $data['version'];
671                         // Version numbers on statistics.json are presented with additional info, e.g.:
672                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
673                         $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
674                 }
675
676                 if (!empty($data['name'])) {
677                         $serverdata['site_name'] = $data['name'];
678                 }
679
680                 if (!empty($data['network'])) {
681                         $serverdata['platform'] = strtolower($data['network']);
682
683                         if ($serverdata['platform'] == 'diaspora') {
684                                 $serverdata['network'] = Protocol::DIASPORA;
685                         } elseif ($serverdata['platform'] == 'friendica') {
686                                 $serverdata['network'] = Protocol::DFRN;
687                         } elseif ($serverdata['platform'] == 'hubzilla') {
688                                 $serverdata['network'] = Protocol::ZOT;
689                         } elseif ($serverdata['platform'] == 'redmatrix') {
690                                 $serverdata['network'] = Protocol::ZOT;
691                         }
692                 }
693
694
695                 if (!empty($data['registrations_open'])) {
696                         $serverdata['register_policy'] = Register::OPEN;
697                 } else {
698                         $serverdata['register_policy'] = Register::CLOSED;
699                 }
700
701                 return $serverdata;
702         }
703
704         /**
705          * Detect server type by using the nodeinfo data
706          *
707          * @param string                  $url        address of the server
708          * @param ICanHandleHttpResponses $httpResult
709          *
710          * @return array Server data
711          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
712          */
713         private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
714         {
715                 if (!$httpResult->isSuccess()) {
716                         return [];
717                 }
718
719                 $nodeinfo = json_decode($httpResult->getBody(), true);
720
721                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
722                         return [];
723                 }
724
725                 $nodeinfo1_url = '';
726                 $nodeinfo2_url = '';
727
728                 foreach ($nodeinfo['links'] as $link) {
729                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
730                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
731                                 continue;
732                         }
733                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
734                                 $nodeinfo1_url = $link['href'];
735                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
736                                 $nodeinfo2_url = $link['href'];
737                         }
738                 }
739
740                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
741                         return [];
742                 }
743
744                 $server = [];
745
746                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
747                 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
748                         $server = self::parseNodeinfo2($nodeinfo2_url);
749                 }
750
751                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
752                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
753                         $server = self::parseNodeinfo1($nodeinfo1_url);
754                 }
755
756                 return $server;
757         }
758
759         /**
760          * Parses Nodeinfo 1
761          *
762          * @param string $nodeinfo_url address of the nodeinfo path
763          * @return array Server data
764          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
765          */
766         private static function parseNodeinfo1(string $nodeinfo_url)
767         {
768                 $curlResult = DI::httpClient()->get($nodeinfo_url);
769
770                 if (!$curlResult->isSuccess()) {
771                         return [];
772                 }
773
774                 $nodeinfo = json_decode($curlResult->getBody(), true);
775
776                 if (!is_array($nodeinfo)) {
777                         return [];
778                 }
779
780                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
781                         'register_policy' => Register::CLOSED];
782
783                 if (!empty($nodeinfo['openRegistrations'])) {
784                         $server['register_policy'] = Register::OPEN;
785                 }
786
787                 if (is_array($nodeinfo['software'])) {
788                         if (!empty($nodeinfo['software']['name'])) {
789                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
790                         }
791
792                         if (!empty($nodeinfo['software']['version'])) {
793                                 $server['version'] = $nodeinfo['software']['version'];
794                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
795                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
796                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
797                         }
798                 }
799
800                 if (!empty($nodeinfo['metadata']['nodeName'])) {
801                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
802                 }
803
804                 if (!empty($nodeinfo['usage']['users']['total'])) {
805                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
806                 }
807
808                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
809                         $protocols = [];
810                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
811                                 $protocols[$protocol] = true;
812                         }
813
814                         if (!empty($protocols['friendica'])) {
815                                 $server['network'] = Protocol::DFRN;
816                         } elseif (!empty($protocols['activitypub'])) {
817                                 $server['network'] = Protocol::ACTIVITYPUB;
818                         } elseif (!empty($protocols['diaspora'])) {
819                                 $server['network'] = Protocol::DIASPORA;
820                         } elseif (!empty($protocols['ostatus'])) {
821                                 $server['network'] = Protocol::OSTATUS;
822                         } elseif (!empty($protocols['gnusocial'])) {
823                                 $server['network'] = Protocol::OSTATUS;
824                         } elseif (!empty($protocols['zot'])) {
825                                 $server['network'] = Protocol::ZOT;
826                         }
827                 }
828
829                 if (empty($server)) {
830                         return [];
831                 }
832
833                 return $server;
834         }
835
836         /**
837          * Parses Nodeinfo 2
838          *
839          * @see https://git.feneas.org/jaywink/nodeinfo2
840          * @param string $nodeinfo_url address of the nodeinfo path
841          * @return array Server data
842          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
843          */
844         private static function parseNodeinfo2(string $nodeinfo_url)
845         {
846                 $curlResult = DI::httpClient()->get($nodeinfo_url);
847                 if (!$curlResult->isSuccess()) {
848                         return [];
849                 }
850
851                 $nodeinfo = json_decode($curlResult->getBody(), true);
852
853                 if (!is_array($nodeinfo)) {
854                         return [];
855                 }
856
857                 $server = ['detection-method' => self::DETECT_NODEINFO_2,
858                         'register_policy' => Register::CLOSED];
859
860                 if (!empty($nodeinfo['openRegistrations'])) {
861                         $server['register_policy'] = Register::OPEN;
862                 }
863
864                 if (is_array($nodeinfo['software'])) {
865                         if (!empty($nodeinfo['software']['name'])) {
866                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
867                         }
868
869                         if (!empty($nodeinfo['software']['version'])) {
870                                 $server['version'] = $nodeinfo['software']['version'];
871                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
872                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
873                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
874                         }
875                 }
876
877                 if (!empty($nodeinfo['metadata']['nodeName'])) {
878                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
879                 }
880
881                 if (!empty($nodeinfo['usage']['users']['total'])) {
882                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
883                 }
884
885                 if (!empty($nodeinfo['protocols'])) {
886                         $protocols = [];
887                         foreach ($nodeinfo['protocols'] as $protocol) {
888                                 if (is_string($protocol)) {
889                                         $protocols[$protocol] = true;
890                                 }
891                         }
892
893                         if (!empty($protocols['dfrn'])) {
894                                 $server['network'] = Protocol::DFRN;
895                         } elseif (!empty($protocols['activitypub'])) {
896                                 $server['network'] = Protocol::ACTIVITYPUB;
897                         } elseif (!empty($protocols['diaspora'])) {
898                                 $server['network'] = Protocol::DIASPORA;
899                         } elseif (!empty($protocols['ostatus'])) {
900                                 $server['network'] = Protocol::OSTATUS;
901                         } elseif (!empty($protocols['gnusocial'])) {
902                                 $server['network'] = Protocol::OSTATUS;
903                         } elseif (!empty($protocols['zot'])) {
904                                 $server['network'] = Protocol::ZOT;
905                         }
906                 }
907
908                 if (empty($server)) {
909                         return [];
910                 }
911
912                 return $server;
913         }
914
915         /**
916          * Fetch server information from a 'siteinfo.json' file on the given server
917          *
918          * @param string $url        URL of the given server
919          * @param array  $serverdata array with server data
920          *
921          * @return array server data
922          */
923         private static function fetchSiteinfo(string $url, array $serverdata)
924         {
925                 $curlResult = DI::httpClient()->get($url . '/siteinfo.json');
926                 if (!$curlResult->isSuccess()) {
927                         return $serverdata;
928                 }
929
930                 $data = json_decode($curlResult->getBody(), true);
931                 if (empty($data)) {
932                         return $serverdata;
933                 }
934
935                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
936                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
937                 }
938
939                 if (!empty($data['url'])) {
940                         $serverdata['platform'] = strtolower($data['platform']);
941                         $serverdata['version'] = $data['version'];
942                 }
943
944                 if (!empty($data['plugins'])) {
945                         if (in_array('pubcrawl', $data['plugins'])) {
946                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
947                         } elseif (in_array('diaspora', $data['plugins'])) {
948                                 $serverdata['network'] = Protocol::DIASPORA;
949                         } elseif (in_array('gnusoc', $data['plugins'])) {
950                                 $serverdata['network'] = Protocol::OSTATUS;
951                         } else {
952                                 $serverdata['network'] = Protocol::ZOT;
953                         }
954                 }
955
956                 if (!empty($data['site_name'])) {
957                         $serverdata['site_name'] = $data['site_name'];
958                 }
959
960                 if (!empty($data['channels_total'])) {
961                         $serverdata['registered-users'] = max($data['channels_total'], 1);
962                 }
963
964                 if (!empty($data['register_policy'])) {
965                         switch ($data['register_policy']) {
966                                 case 'REGISTER_OPEN':
967                                         $serverdata['register_policy'] = Register::OPEN;
968                                         break;
969
970                                 case 'REGISTER_APPROVE':
971                                         $serverdata['register_policy'] = Register::APPROVE;
972                                         break;
973
974                                 case 'REGISTER_CLOSED':
975                                 default:
976                                         $serverdata['register_policy'] = Register::CLOSED;
977                                         break;
978                         }
979                 }
980
981                 return $serverdata;
982         }
983
984         /**
985          * Checks if the server contains a valid host meta file
986          *
987          * @param string $url URL of the given server
988          *
989          * @return boolean 'true' if the server seems to be vital
990          */
991         private static function validHostMeta(string $url)
992         {
993                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
994                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
995                 if (!$curlResult->isSuccess()) {
996                         return false;
997                 }
998
999                 $xrd = XML::parseString($curlResult->getBody());
1000                 if (!is_object($xrd)) {
1001                         return false;
1002                 }
1003
1004                 $elements = XML::elementToArray($xrd);
1005                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1006                         return false;
1007                 }
1008
1009                 $valid = false;
1010                 foreach ($elements['xrd']['link'] as $link) {
1011                         // When there is more than a single "link" element, the array looks slightly different
1012                         if (!empty($link['@attributes'])) {
1013                                 $link = $link['@attributes'];
1014                         }
1015
1016                         if (empty($link['rel']) || empty($link['template'])) {
1017                                 continue;
1018                         }
1019
1020                         if ($link['rel'] == 'lrdd') {
1021                                 // When the webfinger host is the same like the system host, it should be ok.
1022                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1023                         }
1024                 }
1025
1026                 return $valid;
1027         }
1028
1029         /**
1030          * Detect the network of the given server via their known contacts
1031          *
1032          * @param string $url        URL of the given server
1033          * @param array  $serverdata array with server data
1034          *
1035          * @return array server data
1036          */
1037         private static function detectNetworkViaContacts(string $url, array $serverdata)
1038         {
1039                 $contacts = [];
1040
1041                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1042                 while ($apcontact = DBA::fetch($apcontacts)) {
1043                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1044                 }
1045                 DBA::close($apcontacts);
1046
1047                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1048                 while ($pcontact = DBA::fetch($pcontacts)) {
1049                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1050                 }
1051                 DBA::close($pcontacts);
1052
1053                 if (empty($contacts)) {
1054                         return $serverdata;
1055                 }
1056
1057                 foreach ($contacts as $contact) {
1058                         $probed = Contact::getByURL($contact);
1059                         if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
1060                                 $serverdata['network'] = $probed['network'];
1061                                 break;
1062                         }
1063                 }
1064
1065                 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts), 1);
1066
1067                 return $serverdata;
1068         }
1069
1070         /**
1071          * Checks if the given server does have a '/poco' endpoint.
1072          * This is used for the 'PortableContact' functionality,
1073          * which is used by both Friendica and Hubzilla.
1074          *
1075          * @param string $url        URL of the given server
1076          * @param array  $serverdata array with server data
1077          *
1078          * @return array server data
1079          */
1080         private static function checkPoCo(string $url, array $serverdata)
1081         {
1082                 $serverdata['poco'] = '';
1083
1084                 $curlResult = DI::httpClient()->get($url . '/poco');
1085                 if (!$curlResult->isSuccess()) {
1086                         return $serverdata;
1087                 }
1088
1089                 $data = json_decode($curlResult->getBody(), true);
1090                 if (empty($data)) {
1091                         return $serverdata;
1092                 }
1093
1094                 if (!empty($data['totalResults'])) {
1095                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1096                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1097                         $serverdata['directory-type'] = self::DT_POCO;
1098                         $serverdata['poco'] = $url . '/poco';
1099                 }
1100
1101                 return $serverdata;
1102         }
1103
1104         /**
1105          * Checks if the given server does have a Mastodon style directory endpoint.
1106          *
1107          * @param string $url        URL of the given server
1108          * @param array  $serverdata array with server data
1109          *
1110          * @return array server data
1111          */
1112         public static function checkMastodonDirectory(string $url, array $serverdata)
1113         {
1114                 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1');
1115                 if (!$curlResult->isSuccess()) {
1116                         return $serverdata;
1117                 }
1118
1119                 $data = json_decode($curlResult->getBody(), true);
1120                 if (empty($data)) {
1121                         return $serverdata;
1122                 }
1123
1124                 if (count($data) == 1) {
1125                         $serverdata['directory-type'] = self::DT_MASTODON;
1126                 }
1127
1128                 return $serverdata;
1129         }
1130
1131         /**
1132          * Detects Peertube via their known endpoint
1133          *
1134          * @param string $url        URL of the given server
1135          * @param array  $serverdata array with server data
1136          *
1137          * @return array server data
1138          */
1139         private static function detectPeertube(string $url, array $serverdata)
1140         {
1141                 $curlResult = DI::httpClient()->get($url . '/api/v1/config');
1142
1143                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1144                         return $serverdata;
1145                 }
1146
1147                 $data = json_decode($curlResult->getBody(), true);
1148                 if (empty($data)) {
1149                         return $serverdata;
1150                 }
1151
1152                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1153                         $serverdata['platform'] = 'peertube';
1154                         $serverdata['version'] = $data['serverVersion'];
1155                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1156
1157                         if (!empty($data['instance']['name'])) {
1158                                 $serverdata['site_name'] = $data['instance']['name'];
1159                         }
1160
1161                         if (!empty($data['instance']['shortDescription'])) {
1162                                 $serverdata['info'] = $data['instance']['shortDescription'];
1163                         }
1164
1165                         if (!empty($data['signup'])) {
1166                                 if (!empty($data['signup']['allowed'])) {
1167                                         $serverdata['register_policy'] = Register::OPEN;
1168                                 }
1169                         }
1170
1171                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1172                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1173                         }
1174                 }
1175
1176                 return $serverdata;
1177         }
1178
1179         /**
1180          * Detects the version number of a given server when it was a NextCloud installation
1181          *
1182          * @param string $url        URL of the given server
1183          * @param array  $serverdata array with server data
1184          *
1185          * @return array server data
1186          */
1187         private static function detectNextcloud(string $url, array $serverdata)
1188         {
1189                 $curlResult = DI::httpClient()->get($url . '/status.php');
1190
1191                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1192                         return $serverdata;
1193                 }
1194
1195                 $data = json_decode($curlResult->getBody(), true);
1196                 if (empty($data)) {
1197                         return $serverdata;
1198                 }
1199
1200                 if (!empty($data['version'])) {
1201                         $serverdata['platform'] = 'nextcloud';
1202                         $serverdata['version'] = $data['version'];
1203                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1204
1205                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1206                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1207                         }
1208                 }
1209
1210                 return $serverdata;
1211         }
1212
1213         /**
1214          * Detects data from a given server url if it was a mastodon alike system
1215          *
1216          * @param string $url        URL of the given server
1217          * @param array  $serverdata array with server data
1218          *
1219          * @return array server data
1220          */
1221         private static function detectMastodonAlikes(string $url, array $serverdata)
1222         {
1223                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance');
1224
1225                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1226                         return $serverdata;
1227                 }
1228
1229                 $data = json_decode($curlResult->getBody(), true);
1230                 if (empty($data)) {
1231                         return $serverdata;
1232                 }
1233
1234                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1235                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1236                 }
1237
1238                 if (!empty($data['version'])) {
1239                         $serverdata['platform'] = 'mastodon';
1240                         $serverdata['version'] = $data['version'] ?? '';
1241                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1242                 }
1243
1244                 if (!empty($data['title'])) {
1245                         $serverdata['site_name'] = $data['title'];
1246                 }
1247
1248                 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1249                         $serverdata['platform'] = 'mastodon';
1250                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1251                 }
1252
1253                 if (!empty($data['description'])) {
1254                         $serverdata['info'] = trim($data['description']);
1255                 }
1256
1257                 if (!empty($data['stats']['user_count'])) {
1258                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1259                 }
1260
1261                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1262                         $serverdata['platform'] = strtolower($matches[1]);
1263                         $serverdata['version'] = $matches[2];
1264                 }
1265
1266                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1267                         $serverdata['platform'] = 'pleroma';
1268                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1269                 }
1270
1271                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1272                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1273                         $serverdata['platform'] = 'pleroma';
1274                 }
1275
1276                 return $serverdata;
1277         }
1278
1279         /**
1280          * Detects data from typical Hubzilla endpoints
1281          *
1282          * @param string $url        URL of the given server
1283          * @param array  $serverdata array with server data
1284          *
1285          * @return array server data
1286          */
1287         private static function detectHubzilla(string $url, array $serverdata)
1288         {
1289                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json');
1290                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1291                         return $serverdata;
1292                 }
1293
1294                 $data = json_decode($curlResult->getBody(), true);
1295                 if (empty($data) || empty($data['site'])) {
1296                         return $serverdata;
1297                 }
1298
1299                 if (!empty($data['site']['name'])) {
1300                         $serverdata['site_name'] = $data['site']['name'];
1301                 }
1302
1303                 if (!empty($data['site']['platform'])) {
1304                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1305                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1306                         $serverdata['network'] = Protocol::ZOT;
1307                 }
1308
1309                 if (!empty($data['site']['hubzilla'])) {
1310                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1311                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1312                         $serverdata['network'] = Protocol::ZOT;
1313                 }
1314
1315                 if (!empty($data['site']['redmatrix'])) {
1316                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1317                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1318                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1319                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1320                         }
1321
1322                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1323                         $serverdata['network'] = Protocol::ZOT;
1324                 }
1325
1326                 $private = false;
1327                 $inviteonly = false;
1328                 $closed = false;
1329
1330                 if (!empty($data['site']['closed'])) {
1331                         $closed = self::toBoolean($data['site']['closed']);
1332                 }
1333
1334                 if (!empty($data['site']['private'])) {
1335                         $private = self::toBoolean($data['site']['private']);
1336                 }
1337
1338                 if (!empty($data['site']['inviteonly'])) {
1339                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
1340                 }
1341
1342                 if (!$closed && !$private and $inviteonly) {
1343                         $serverdata['register_policy'] = Register::APPROVE;
1344                 } elseif (!$closed && !$private) {
1345                         $serverdata['register_policy'] = Register::OPEN;
1346                 } else {
1347                         $serverdata['register_policy'] = Register::CLOSED;
1348                 }
1349
1350                 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1351                         [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1352                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1353                 }
1354
1355                 return $serverdata;
1356         }
1357
1358         /**
1359          * Converts input value to a boolean value
1360          *
1361          * @param string|integer $val
1362          *
1363          * @return boolean
1364          */
1365         private static function toBoolean($val)
1366         {
1367                 if (($val == 'true') || ($val == 1)) {
1368                         return true;
1369                 } elseif (($val == 'false') || ($val == 0)) {
1370                         return false;
1371                 }
1372
1373                 return $val;
1374         }
1375
1376         /**
1377          * Detect if the URL belongs to a pump.io server
1378          *
1379          * @param string $url        URL of the given server
1380          * @param array  $serverdata array with server data
1381          *
1382          * @return array server data
1383          */
1384         private static function detectPumpIO(string $url, array $serverdata)
1385         {
1386                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json');
1387                 if (!$curlResult->isSuccess()) {
1388                         return $serverdata;
1389                 }
1390
1391                 $data = json_decode($curlResult->getBody(), true);
1392                 if (empty($data['links'])) {
1393                         return $serverdata;
1394
1395                 }
1396
1397                 // We are looking for some endpoints that are typical for pump.io
1398                 $trust = 0;
1399                 foreach ($data['links'] as $link) {
1400                         if (empty($link['rel'])) {
1401                                 continue;
1402                         }
1403                         if (in_array($link['rel'], ['registration_endpoint', 'dialback', 'http://apinamespace.org/activitypub/whoami'])) {
1404                                 ++$trust;
1405                         }
1406                 }
1407
1408                 if ($trust == 3) {
1409                         $serverdata['detection-method'] = self::DETECT_PUMPIO;
1410
1411                         $serverdata['platform'] = 'pumpio';
1412                         $serverdata['version']  = '';
1413                         $serverdata['network']  = Protocol::PUMPIO;
1414
1415                         $servers = $curlResult->getHeader('Server');
1416                         foreach ($servers as $server) {
1417                                 if (preg_match("#pump.io/(.*)\s#U", $server, $matches)) {
1418                                         $serverdata['version']  = $matches[1];
1419                                 }
1420                         }
1421                 }
1422
1423                 return $serverdata;
1424         }
1425
1426         /**
1427          * Detect if the URL belongs to a GNU Social server
1428          *
1429          * @param string $url        URL of the given server
1430          * @param array  $serverdata array with server data
1431          *
1432          * @return array server data
1433          */
1434         private static function detectGNUSocial(string $url, array $serverdata)
1435         {
1436                 // Test for GNU Social
1437                 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json');
1438                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1439                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1440                         $serverdata['platform'] = 'gnusocial';
1441                         // Remove junk that some GNU Social servers return
1442                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1443                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1444                         $serverdata['version'] = trim($serverdata['version'], '"');
1445                         $serverdata['network'] = Protocol::OSTATUS;
1446
1447                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1448                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1449                         }
1450
1451                         return $serverdata;
1452                 }
1453
1454                 // Test for Statusnet
1455                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json');
1456                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1457                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1458
1459                         // Remove junk that some GNU Social servers return
1460                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1461                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1462                         $serverdata['version'] = trim($serverdata['version'], '"');
1463
1464                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1465                                 $serverdata['platform'] = 'pleroma';
1466                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1467                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1468                         } else {
1469                                 $serverdata['platform'] = 'statusnet';
1470                                 $serverdata['network'] = Protocol::OSTATUS;
1471                         }
1472
1473                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1474                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1475                         }
1476                 }
1477
1478                 return $serverdata;
1479         }
1480
1481         /**
1482          * Detect if the URL belongs to a Friendica server
1483          *
1484          * @param string $url        URL of the given server
1485          * @param array  $serverdata array with server data
1486          *
1487          * @return array server data
1488          */
1489         private static function detectFriendica(string $url, array $serverdata)
1490         {
1491                 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1492                 if (!$curlResult->isSuccess()) {
1493                         $curlResult = DI::httpClient()->get($url . '/friendika/json');
1494                         $friendika = true;
1495                         $platform = 'Friendika';
1496                 } else {
1497                         $friendika = false;
1498                         $platform = 'Friendica';
1499                 }
1500
1501                 if (!$curlResult->isSuccess()) {
1502                         return $serverdata;
1503                 }
1504
1505                 $data = json_decode($curlResult->getBody(), true);
1506                 if (empty($data) || empty($data['version'])) {
1507                         return $serverdata;
1508                 }
1509
1510                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1511                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1512                 }
1513
1514                 $serverdata['network'] = Protocol::DFRN;
1515                 $serverdata['version'] = $data['version'];
1516
1517                 if (!empty($data['no_scrape_url'])) {
1518                         $serverdata['noscrape'] = $data['no_scrape_url'];
1519                 }
1520
1521                 if (!empty($data['site_name'])) {
1522                         $serverdata['site_name'] = $data['site_name'];
1523                 }
1524
1525                 if (!empty($data['info'])) {
1526                         $serverdata['info'] = trim($data['info']);
1527                 }
1528
1529                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1530                 switch ($register_policy) {
1531                         case 'REGISTER_OPEN':
1532                                 $serverdata['register_policy'] = Register::OPEN;
1533                                 break;
1534
1535                         case 'REGISTER_APPROVE':
1536                                 $serverdata['register_policy'] = Register::APPROVE;
1537                                 break;
1538
1539                         case 'REGISTER_CLOSED':
1540                         case 'REGISTER_INVITATION':
1541                                 $serverdata['register_policy'] = Register::CLOSED;
1542                                 break;
1543                         default:
1544                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1545                                 $serverdata['register_policy'] = Register::CLOSED;
1546                                 break;
1547                 }
1548
1549                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1550
1551                 return $serverdata;
1552         }
1553
1554         /**
1555          * Analyses the landing page of a given server for hints about type and system of that server
1556          *
1557          * @param object $curlResult result of curl execution
1558          * @param array  $serverdata array with server data
1559          * @param string $url        Server URL
1560          *
1561          * @return array server data
1562          */
1563         private static function analyseRootBody($curlResult, array $serverdata, string $url)
1564         {
1565                 if (empty($curlResult->getBody())) {
1566                         return $serverdata;
1567                 }
1568
1569                 $doc = new DOMDocument();
1570                 @$doc->loadHTML($curlResult->getBody());
1571                 $xpath = new DOMXPath($doc);
1572
1573                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1574                 if (!empty($title)) {
1575                         $serverdata['site_name'] = $title;
1576                 }
1577
1578                 $list = $xpath->query('//meta[@name]');
1579
1580                 foreach ($list as $node) {
1581                         $attr = [];
1582                         if ($node->attributes->length) {
1583                                 foreach ($node->attributes as $attribute) {
1584                                         $value = trim($attribute->value);
1585                                         if (empty($value)) {
1586                                                 continue;
1587                                         }
1588
1589                                         $attr[$attribute->name] = $value;
1590                                 }
1591
1592                                 if (empty($attr['name']) || empty($attr['content'])) {
1593                                         continue;
1594                                 }
1595                         }
1596
1597                         if ($attr['name'] == 'description') {
1598                                 $serverdata['info'] = $attr['content'];
1599                         }
1600
1601                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1602                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1603                                 $serverdata['platform'] = strtolower($attr['content']);
1604                                 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1605                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1606                                 }
1607                         }
1608                         if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1609                                 $serverdata['platform'] = strtolower($attr['content']);
1610                                 $version_part = explode(' ', $attr['content']);
1611
1612                                 if (count($version_part) == 2) {
1613                                         if (in_array($version_part[0], ['WordPress'])) {
1614                                                 $serverdata['platform'] = 'wordpress';
1615                                                 $serverdata['version'] = $version_part[1];
1616
1617                                                 // We still do need a reliable test if some AP plugin is activated
1618                                                 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1619                                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1620                                                 } else {
1621                                                         $serverdata['network'] = Protocol::FEED;
1622                                                 }
1623
1624                                                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1625                                                         $serverdata['detection-method'] = self::DETECT_BODY;
1626                                                 }
1627                                         }
1628                                         if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1629                                                 $serverdata['platform'] = strtolower($version_part[0]);
1630                                                 $serverdata['version'] = $version_part[1];
1631                                                 $serverdata['network'] = Protocol::DFRN;
1632                                         }
1633                                 }
1634                         }
1635                 }
1636
1637                 $list = $xpath->query('//meta[@property]');
1638
1639                 foreach ($list as $node) {
1640                         $attr = [];
1641                         if ($node->attributes->length) {
1642                                 foreach ($node->attributes as $attribute) {
1643                                         $value = trim($attribute->value);
1644                                         if (empty($value)) {
1645                                                 continue;
1646                                         }
1647
1648                                         $attr[$attribute->name] = $value;
1649                                 }
1650
1651                                 if (empty($attr['property']) || empty($attr['content'])) {
1652                                         continue;
1653                                 }
1654                         }
1655
1656                         if ($attr['property'] == 'og:site_name') {
1657                                 $serverdata['site_name'] = $attr['content'];
1658                         }
1659
1660                         if ($attr['property'] == 'og:description') {
1661                                 $serverdata['info'] = $attr['content'];
1662                         }
1663
1664                         if ($attr['property'] == 'og:platform') {
1665                                 $serverdata['platform'] = strtolower($attr['content']);
1666
1667                                 if (in_array($attr['content'], ['PeerTube'])) {
1668                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1669                                 }
1670                         }
1671
1672                         if ($attr['property'] == 'generator') {
1673                                 $serverdata['platform'] = strtolower($attr['content']);
1674
1675                                 if (in_array($attr['content'], ['hubzilla'])) {
1676                                         // We later check which compatible protocol modules are loaded.
1677                                         $serverdata['network'] = Protocol::ZOT;
1678                                 }
1679                         }
1680                 }
1681
1682                 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1683                         $serverdata['detection-method'] = self::DETECT_BODY;
1684                 }
1685
1686                 return $serverdata;
1687         }
1688
1689         /**
1690          * Analyses the header data of a given server for hints about type and system of that server
1691          *
1692          * @param object $curlResult result of curl execution
1693          * @param array  $serverdata array with server data
1694          *
1695          * @return array server data
1696          */
1697         private static function analyseRootHeader($curlResult, array $serverdata)
1698         {
1699                 if ($curlResult->getHeader('server') == 'Mastodon') {
1700                         $serverdata['platform'] = 'mastodon';
1701                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1702                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1703                         $serverdata['platform'] = 'diaspora';
1704                         $serverdata['network'] = Protocol::DIASPORA;
1705                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1706                 } elseif ($curlResult->inHeader('x-friendica-version')) {
1707                         $serverdata['platform'] = 'friendica';
1708                         $serverdata['network'] = Protocol::DFRN;
1709                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1710                 } else {
1711                         return $serverdata;
1712                 }
1713
1714                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1715                         $serverdata['detection-method'] = self::DETECT_HEADER;
1716                 }
1717
1718                 return $serverdata;
1719         }
1720
1721         /**
1722          * Test if the body contains valid content
1723          *
1724          * @param string $body
1725          * @return boolean
1726          */
1727         private static function invalidBody(string $body)
1728         {
1729                 // Currently we only test for a HTML element.
1730                 // Possibly we enhance this in the future.
1731                 return !strpos($body, '>');
1732         }
1733
1734         /**
1735          * Update GServer entries
1736          */
1737         public static function discover()
1738         {
1739                 // Update the server list
1740                 self::discoverFederation();
1741
1742                 $no_of_queries = 5;
1743
1744                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1745
1746                 if ($requery_days == 0) {
1747                         $requery_days = 7;
1748                 }
1749
1750                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1751
1752                 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
1753                         ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
1754                         ['order' => ['RAND()']]);
1755
1756                 while ($gserver = DBA::fetch($gservers)) {
1757                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1758                         Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1759
1760                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1761                         Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1762
1763                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1764                         DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1765
1766                         if (--$no_of_queries == 0) {
1767                                 break;
1768                         }
1769                 }
1770
1771                 DBA::close($gservers);
1772         }
1773
1774         /**
1775          * Discover federated servers
1776          */
1777         private static function discoverFederation()
1778         {
1779                 $last = DI::config()->get('poco', 'last_federation_discovery');
1780
1781                 if ($last) {
1782                         $next = $last + (24 * 60 * 60);
1783
1784                         if ($next > time()) {
1785                                 return;
1786                         }
1787                 }
1788
1789                 // Discover federated servers
1790                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1791                 foreach ($protocols as $protocol) {
1792                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1793                         $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1794                         if (!empty($curlResult)) {
1795                                 $data = json_decode($curlResult, true);
1796                                 if (!empty($data['data']['nodes'])) {
1797                                         foreach ($data['data']['nodes'] as $server) {
1798                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1799                                                 self::add('https://' . $server['host'], true);
1800                                         }
1801                                 }
1802                         }
1803                 }
1804
1805                 // Disvover Mastodon servers
1806                 $accesstoken = DI::config()->get('system', 'instances_social_key');
1807
1808                 if (!empty($accesstoken)) {
1809                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
1810                         $curlResult = DI::httpClient()->get($api, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1811
1812                         if ($curlResult->isSuccess()) {
1813                                 $servers = json_decode($curlResult->getBody(), true);
1814
1815                                 foreach ($servers['instances'] as $server) {
1816                                         $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1817                                         self::add($url);
1818                                 }
1819                         }
1820                 }
1821
1822                 DI::config()->set('poco', 'last_federation_discovery', time());
1823         }
1824
1825         /**
1826          * Set the protocol for the given server
1827          *
1828          * @param int $gsid     Server id
1829          * @param int $protocol Protocol id
1830          * @return void
1831          * @throws Exception
1832          */
1833         public static function setProtocol(int $gsid, int $protocol)
1834         {
1835                 if (empty($gsid)) {
1836                         return;
1837                 }
1838
1839                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1840                 if (!DBA::isResult($gserver)) {
1841                         return;
1842                 }
1843
1844                 $old = $gserver['protocol'];
1845
1846                 if (!is_null($old)) {
1847                         /*
1848                         The priority for the protocols is:
1849                                 1. ActivityPub
1850                                 2. DFRN via Diaspora
1851                                 3. Legacy DFRN
1852                                 4. Diaspora
1853                                 5. OStatus
1854                         */
1855
1856                         // We don't need to change it when nothing is to be changed
1857                         if ($old == $protocol) {
1858                                 return;
1859                         }
1860
1861                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1862                         if ($protocol == Post\DeliveryData::OSTATUS) {
1863                                 return;
1864                         }
1865
1866                         // If the server is marked as ActivityPub then we won't change it to anything different
1867                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
1868                                 return;
1869                         }
1870
1871                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1872                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1873                                 return;
1874                         }
1875
1876                         // Don't change it to Diaspora when it is a legacy DFRN server
1877                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
1878                                 return;
1879                         }
1880                 }
1881
1882                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
1883                 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
1884         }
1885
1886         /**
1887          * Fetch the protocol of the given server
1888          *
1889          * @param int $gsid Server id
1890          * @return int
1891          * @throws Exception
1892          */
1893         public static function getProtocol(int $gsid)
1894         {
1895                 if (empty($gsid)) {
1896                         return null;
1897                 }
1898
1899                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
1900                 if (DBA::isResult($gserver)) {
1901                         return $gserver['protocol'];
1902                 }
1903
1904                 return null;
1905         }
1906 }