]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Set the timeout to 10 seconds
[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                 if (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
500                         $serverdata = self::detectNetworkViaContacts($url, $serverdata);
501                 }
502
503                 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
504
505                 // On an active server there has to be at least a single user
506                 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
507                         $serverdata['registered-users'] = 1;
508                 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
509                         $serverdata['registered-users'] = 0;
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                         $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
524                         $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
525                         if (DBA::isResult($gserver)) {
526                                 $id = $gserver['id'];
527                         }
528                 }
529
530                 // Count the number of known contacts from this server
531                 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
532                         $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
533                         $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
534                         $max_users = max($apcontacts, $contacts);
535                         if ($max_users > $serverdata['registered-users']) {
536                                 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
537                                 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
538                         }
539                 }
540
541                 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
542                         self::discoverRelay($url);
543                 }
544
545                 return $ret;
546         }
547
548         /**
549          * Fetch relay data from a given server url
550          *
551          * @param string $server_url address of the server
552          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
553          */
554         private static function discoverRelay(string $server_url)
555         {
556                 Logger::info('Discover relay data', ['server' => $server_url]);
557
558                 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay');
559                 if (!$curlResult->isSuccess()) {
560                         return;
561                 }
562
563                 $data = json_decode($curlResult->getBody(), true);
564                 if (!is_array($data)) {
565                         return;
566                 }
567
568                 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
569                 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
570
571                 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
572                         $data['scope'] = '';
573                         $data['subscribe'] = false;
574                         $data['tags'] = [];
575                 }
576
577                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
578                 if (!DBA::isResult($gserver)) {
579                         return;
580                 }
581
582                 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
583                         $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
584                         DBA::update('gserver', $fields, ['id' => $gserver['id']]);
585                 }
586
587                 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
588
589                 if ($data['scope'] == 'tags') {
590                         // Avoid duplicates
591                         $tags = [];
592                         foreach ($data['tags'] as $tag) {
593                                 $tag = mb_strtolower($tag);
594                                 if (strlen($tag) < 100) {
595                                         $tags[$tag] = $tag;
596                                 }
597                         }
598
599                         foreach ($tags as $tag) {
600                                 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
601                         }
602                 }
603
604                 // Create or update the relay contact
605                 $fields = [];
606                 if (isset($data['protocols'])) {
607                         if (isset($data['protocols']['diaspora'])) {
608                                 $fields['network'] = Protocol::DIASPORA;
609
610                                 if (isset($data['protocols']['diaspora']['receive'])) {
611                                         $fields['batch'] = $data['protocols']['diaspora']['receive'];
612                                 } elseif (is_string($data['protocols']['diaspora'])) {
613                                         $fields['batch'] = $data['protocols']['diaspora'];
614                                 }
615                         }
616
617                         if (isset($data['protocols']['dfrn'])) {
618                                 $fields['network'] = Protocol::DFRN;
619
620                                 if (isset($data['protocols']['dfrn']['receive'])) {
621                                         $fields['batch'] = $data['protocols']['dfrn']['receive'];
622                                 } elseif (is_string($data['protocols']['dfrn'])) {
623                                         $fields['batch'] = $data['protocols']['dfrn'];
624                                 }
625                         }
626
627                         if (isset($data['protocols']['activitypub'])) {
628                                 $fields['network'] = Protocol::ACTIVITYPUB;
629
630                                 if (!empty($data['protocols']['activitypub']['actor'])) {
631                                         $fields['url'] = $data['protocols']['activitypub']['actor'];
632                                 }
633                                 if (!empty($data['protocols']['activitypub']['receive'])) {
634                                         $fields['batch'] = $data['protocols']['activitypub']['receive'];
635                                 }
636                         }
637                 }
638
639                 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
640
641                 Relay::updateContact($gserver, $fields);
642         }
643
644         /**
645          * Fetch server data from '/statistics.json' on the given server
646          *
647          * @param string $url URL of the given server
648          *
649          * @return array server data
650          */
651         private static function fetchStatistics(string $url)
652         {
653                 $curlResult = DI::httpClient()->get($url . '/statistics.json');
654                 if (!$curlResult->isSuccess()) {
655                         return [];
656                 }
657
658                 $data = json_decode($curlResult->getBody(), true);
659                 if (empty($data)) {
660                         return [];
661                 }
662
663                 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
664
665                 if (!empty($data['version'])) {
666                         $serverdata['version'] = $data['version'];
667                         // Version numbers on statistics.json are presented with additional info, e.g.:
668                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
669                         $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
670                 }
671
672                 if (!empty($data['name'])) {
673                         $serverdata['site_name'] = $data['name'];
674                 }
675
676                 if (!empty($data['network'])) {
677                         $serverdata['platform'] = strtolower($data['network']);
678
679                         if ($serverdata['platform'] == 'diaspora') {
680                                 $serverdata['network'] = Protocol::DIASPORA;
681                         } elseif ($serverdata['platform'] == 'friendica') {
682                                 $serverdata['network'] = Protocol::DFRN;
683                         } elseif ($serverdata['platform'] == 'hubzilla') {
684                                 $serverdata['network'] = Protocol::ZOT;
685                         } elseif ($serverdata['platform'] == 'redmatrix') {
686                                 $serverdata['network'] = Protocol::ZOT;
687                         }
688                 }
689
690
691                 if (!empty($data['registrations_open'])) {
692                         $serverdata['register_policy'] = Register::OPEN;
693                 } else {
694                         $serverdata['register_policy'] = Register::CLOSED;
695                 }
696
697                 return $serverdata;
698         }
699
700         /**
701          * Detect server type by using the nodeinfo data
702          *
703          * @param string                  $url        address of the server
704          * @param ICanHandleHttpResponses $httpResult
705          *
706          * @return array Server data
707          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
708          */
709         private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
710         {
711                 if (!$httpResult->isSuccess()) {
712                         return [];
713                 }
714
715                 $nodeinfo = json_decode($httpResult->getBody(), true);
716
717                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
718                         return [];
719                 }
720
721                 $nodeinfo1_url = '';
722                 $nodeinfo2_url = '';
723
724                 foreach ($nodeinfo['links'] as $link) {
725                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
726                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
727                                 continue;
728                         }
729                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
730                                 $nodeinfo1_url = $link['href'];
731                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
732                                 $nodeinfo2_url = $link['href'];
733                         }
734                 }
735
736                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
737                         return [];
738                 }
739
740                 $server = [];
741
742                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
743                 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
744                         $server = self::parseNodeinfo2($nodeinfo2_url);
745                 }
746
747                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
748                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
749                         $server = self::parseNodeinfo1($nodeinfo1_url);
750                 }
751
752                 return $server;
753         }
754
755         /**
756          * Parses Nodeinfo 1
757          *
758          * @param string $nodeinfo_url address of the nodeinfo path
759          * @return array Server data
760          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
761          */
762         private static function parseNodeinfo1(string $nodeinfo_url)
763         {
764                 $curlResult = DI::httpClient()->get($nodeinfo_url);
765
766                 if (!$curlResult->isSuccess()) {
767                         return [];
768                 }
769
770                 $nodeinfo = json_decode($curlResult->getBody(), true);
771
772                 if (!is_array($nodeinfo)) {
773                         return [];
774                 }
775
776                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
777                         'register_policy' => Register::CLOSED];
778
779                 if (!empty($nodeinfo['openRegistrations'])) {
780                         $server['register_policy'] = Register::OPEN;
781                 }
782
783                 if (is_array($nodeinfo['software'])) {
784                         if (!empty($nodeinfo['software']['name'])) {
785                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
786                         }
787
788                         if (!empty($nodeinfo['software']['version'])) {
789                                 $server['version'] = $nodeinfo['software']['version'];
790                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
791                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
792                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
793                         }
794                 }
795
796                 if (!empty($nodeinfo['metadata']['nodeName'])) {
797                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
798                 }
799
800                 if (!empty($nodeinfo['usage']['users']['total'])) {
801                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
802                 }
803
804                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
805                         $protocols = [];
806                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
807                                 $protocols[$protocol] = true;
808                         }
809
810                         if (!empty($protocols['friendica'])) {
811                                 $server['network'] = Protocol::DFRN;
812                         } elseif (!empty($protocols['activitypub'])) {
813                                 $server['network'] = Protocol::ACTIVITYPUB;
814                         } elseif (!empty($protocols['diaspora'])) {
815                                 $server['network'] = Protocol::DIASPORA;
816                         } elseif (!empty($protocols['ostatus'])) {
817                                 $server['network'] = Protocol::OSTATUS;
818                         } elseif (!empty($protocols['gnusocial'])) {
819                                 $server['network'] = Protocol::OSTATUS;
820                         } elseif (!empty($protocols['zot'])) {
821                                 $server['network'] = Protocol::ZOT;
822                         }
823                 }
824
825                 if (empty($server)) {
826                         return [];
827                 }
828
829                 return $server;
830         }
831
832         /**
833          * Parses Nodeinfo 2
834          *
835          * @see https://git.feneas.org/jaywink/nodeinfo2
836          * @param string $nodeinfo_url address of the nodeinfo path
837          * @return array Server data
838          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
839          */
840         private static function parseNodeinfo2(string $nodeinfo_url)
841         {
842                 $curlResult = DI::httpClient()->get($nodeinfo_url);
843                 if (!$curlResult->isSuccess()) {
844                         return [];
845                 }
846
847                 $nodeinfo = json_decode($curlResult->getBody(), true);
848
849                 if (!is_array($nodeinfo)) {
850                         return [];
851                 }
852
853                 $server = ['detection-method' => self::DETECT_NODEINFO_2,
854                         'register_policy' => Register::CLOSED];
855
856                 if (!empty($nodeinfo['openRegistrations'])) {
857                         $server['register_policy'] = Register::OPEN;
858                 }
859
860                 if (is_array($nodeinfo['software'])) {
861                         if (!empty($nodeinfo['software']['name'])) {
862                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
863                         }
864
865                         if (!empty($nodeinfo['software']['version'])) {
866                                 $server['version'] = $nodeinfo['software']['version'];
867                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
868                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
869                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
870                         }
871                 }
872
873                 if (!empty($nodeinfo['metadata']['nodeName'])) {
874                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
875                 }
876
877                 if (!empty($nodeinfo['usage']['users']['total'])) {
878                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
879                 }
880
881                 if (!empty($nodeinfo['protocols'])) {
882                         $protocols = [];
883                         foreach ($nodeinfo['protocols'] as $protocol) {
884                                 if (is_string($protocol)) {
885                                         $protocols[$protocol] = true;
886                                 }
887                         }
888
889                         if (!empty($protocols['dfrn'])) {
890                                 $server['network'] = Protocol::DFRN;
891                         } elseif (!empty($protocols['activitypub'])) {
892                                 $server['network'] = Protocol::ACTIVITYPUB;
893                         } elseif (!empty($protocols['diaspora'])) {
894                                 $server['network'] = Protocol::DIASPORA;
895                         } elseif (!empty($protocols['ostatus'])) {
896                                 $server['network'] = Protocol::OSTATUS;
897                         } elseif (!empty($protocols['gnusocial'])) {
898                                 $server['network'] = Protocol::OSTATUS;
899                         } elseif (!empty($protocols['zot'])) {
900                                 $server['network'] = Protocol::ZOT;
901                         }
902                 }
903
904                 if (empty($server)) {
905                         return [];
906                 }
907
908                 return $server;
909         }
910
911         /**
912          * Fetch server information from a 'siteinfo.json' file on the given server
913          *
914          * @param string $url        URL of the given server
915          * @param array  $serverdata array with server data
916          *
917          * @return array server data
918          */
919         private static function fetchSiteinfo(string $url, array $serverdata)
920         {
921                 $curlResult = DI::httpClient()->get($url . '/siteinfo.json');
922                 if (!$curlResult->isSuccess()) {
923                         return $serverdata;
924                 }
925
926                 $data = json_decode($curlResult->getBody(), true);
927                 if (empty($data)) {
928                         return $serverdata;
929                 }
930
931                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
932                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
933                 }
934
935                 if (!empty($data['url'])) {
936                         $serverdata['platform'] = strtolower($data['platform']);
937                         $serverdata['version'] = $data['version'];
938                 }
939
940                 if (!empty($data['plugins'])) {
941                         if (in_array('pubcrawl', $data['plugins'])) {
942                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
943                         } elseif (in_array('diaspora', $data['plugins'])) {
944                                 $serverdata['network'] = Protocol::DIASPORA;
945                         } elseif (in_array('gnusoc', $data['plugins'])) {
946                                 $serverdata['network'] = Protocol::OSTATUS;
947                         } else {
948                                 $serverdata['network'] = Protocol::ZOT;
949                         }
950                 }
951
952                 if (!empty($data['site_name'])) {
953                         $serverdata['site_name'] = $data['site_name'];
954                 }
955
956                 if (!empty($data['channels_total'])) {
957                         $serverdata['registered-users'] = max($data['channels_total'], 1);
958                 }
959
960                 if (!empty($data['register_policy'])) {
961                         switch ($data['register_policy']) {
962                                 case 'REGISTER_OPEN':
963                                         $serverdata['register_policy'] = Register::OPEN;
964                                         break;
965
966                                 case 'REGISTER_APPROVE':
967                                         $serverdata['register_policy'] = Register::APPROVE;
968                                         break;
969
970                                 case 'REGISTER_CLOSED':
971                                 default:
972                                         $serverdata['register_policy'] = Register::CLOSED;
973                                         break;
974                         }
975                 }
976
977                 return $serverdata;
978         }
979
980         /**
981          * Checks if the server contains a valid host meta file
982          *
983          * @param string $url URL of the given server
984          *
985          * @return boolean 'true' if the server seems to be vital
986          */
987         private static function validHostMeta(string $url)
988         {
989                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
990                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
991                 if (!$curlResult->isSuccess()) {
992                         return false;
993                 }
994
995                 $xrd = XML::parseString($curlResult->getBody());
996                 if (!is_object($xrd)) {
997                         return false;
998                 }
999
1000                 $elements = XML::elementToArray($xrd);
1001                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1002                         return false;
1003                 }
1004
1005                 $valid = false;
1006                 foreach ($elements['xrd']['link'] as $link) {
1007                         // When there is more than a single "link" element, the array looks slightly different
1008                         if (!empty($link['@attributes'])) {
1009                                 $link = $link['@attributes'];
1010                         }
1011
1012                         if (empty($link['rel']) || empty($link['template'])) {
1013                                 continue;
1014                         }
1015
1016                         if ($link['rel'] == 'lrdd') {
1017                                 // When the webfinger host is the same like the system host, it should be ok.
1018                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1019                         }
1020                 }
1021
1022                 return $valid;
1023         }
1024
1025         /**
1026          * Detect the network of the given server via their known contacts
1027          *
1028          * @param string $url        URL of the given server
1029          * @param array  $serverdata array with server data
1030          *
1031          * @return array server data
1032          */
1033         private static function detectNetworkViaContacts(string $url, array $serverdata)
1034         {
1035                 $contacts = [];
1036
1037                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1038                 while ($apcontact = DBA::fetch($apcontacts)) {
1039                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1040                 }
1041                 DBA::close($apcontacts);
1042
1043                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1044                 while ($pcontact = DBA::fetch($pcontacts)) {
1045                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1046                 }
1047                 DBA::close($pcontacts);
1048
1049                 if (empty($contacts)) {
1050                         return $serverdata;
1051                 }
1052
1053                 $time = time();
1054                 foreach ($contacts as $contact) {
1055                         $probed = Contact::getByURL($contact, true);
1056                         if (!empty($probed) && !$probed['failed'] && in_array($probed['network'], Protocol::FEDERATED)) {
1057                                 $serverdata['network'] = $probed['network'];
1058                                 break;
1059                         } elseif ((time() - $time) > 10) {
1060                                 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1061                                 break;
1062                         }
1063                 }
1064
1065                 return $serverdata;
1066         }
1067
1068         /**
1069          * Checks if the given server does have a '/poco' endpoint.
1070          * This is used for the 'PortableContact' functionality,
1071          * which is used by both Friendica and Hubzilla.
1072          *
1073          * @param string $url        URL of the given server
1074          * @param array  $serverdata array with server data
1075          *
1076          * @return array server data
1077          */
1078         private static function checkPoCo(string $url, array $serverdata)
1079         {
1080                 $serverdata['poco'] = '';
1081
1082                 $curlResult = DI::httpClient()->get($url . '/poco');
1083                 if (!$curlResult->isSuccess()) {
1084                         return $serverdata;
1085                 }
1086
1087                 $data = json_decode($curlResult->getBody(), true);
1088                 if (empty($data)) {
1089                         return $serverdata;
1090                 }
1091
1092                 if (!empty($data['totalResults'])) {
1093                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1094                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1095                         $serverdata['directory-type'] = self::DT_POCO;
1096                         $serverdata['poco'] = $url . '/poco';
1097                 }
1098
1099                 return $serverdata;
1100         }
1101
1102         /**
1103          * Checks if the given server does have a Mastodon style directory endpoint.
1104          *
1105          * @param string $url        URL of the given server
1106          * @param array  $serverdata array with server data
1107          *
1108          * @return array server data
1109          */
1110         public static function checkMastodonDirectory(string $url, array $serverdata)
1111         {
1112                 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1');
1113                 if (!$curlResult->isSuccess()) {
1114                         return $serverdata;
1115                 }
1116
1117                 $data = json_decode($curlResult->getBody(), true);
1118                 if (empty($data)) {
1119                         return $serverdata;
1120                 }
1121
1122                 if (count($data) == 1) {
1123                         $serverdata['directory-type'] = self::DT_MASTODON;
1124                 }
1125
1126                 return $serverdata;
1127         }
1128
1129         /**
1130          * Detects Peertube via their known endpoint
1131          *
1132          * @param string $url        URL of the given server
1133          * @param array  $serverdata array with server data
1134          *
1135          * @return array server data
1136          */
1137         private static function detectPeertube(string $url, array $serverdata)
1138         {
1139                 $curlResult = DI::httpClient()->get($url . '/api/v1/config');
1140
1141                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1142                         return $serverdata;
1143                 }
1144
1145                 $data = json_decode($curlResult->getBody(), true);
1146                 if (empty($data)) {
1147                         return $serverdata;
1148                 }
1149
1150                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1151                         $serverdata['platform'] = 'peertube';
1152                         $serverdata['version'] = $data['serverVersion'];
1153                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1154
1155                         if (!empty($data['instance']['name'])) {
1156                                 $serverdata['site_name'] = $data['instance']['name'];
1157                         }
1158
1159                         if (!empty($data['instance']['shortDescription'])) {
1160                                 $serverdata['info'] = $data['instance']['shortDescription'];
1161                         }
1162
1163                         if (!empty($data['signup'])) {
1164                                 if (!empty($data['signup']['allowed'])) {
1165                                         $serverdata['register_policy'] = Register::OPEN;
1166                                 }
1167                         }
1168
1169                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1170                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1171                         }
1172                 }
1173
1174                 return $serverdata;
1175         }
1176
1177         /**
1178          * Detects the version number of a given server when it was a NextCloud installation
1179          *
1180          * @param string $url        URL of the given server
1181          * @param array  $serverdata array with server data
1182          *
1183          * @return array server data
1184          */
1185         private static function detectNextcloud(string $url, array $serverdata)
1186         {
1187                 $curlResult = DI::httpClient()->get($url . '/status.php');
1188
1189                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1190                         return $serverdata;
1191                 }
1192
1193                 $data = json_decode($curlResult->getBody(), true);
1194                 if (empty($data)) {
1195                         return $serverdata;
1196                 }
1197
1198                 if (!empty($data['version'])) {
1199                         $serverdata['platform'] = 'nextcloud';
1200                         $serverdata['version'] = $data['version'];
1201                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1202
1203                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1204                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1205                         }
1206                 }
1207
1208                 return $serverdata;
1209         }
1210
1211         /**
1212          * Detects data from a given server url if it was a mastodon alike system
1213          *
1214          * @param string $url        URL of the given server
1215          * @param array  $serverdata array with server data
1216          *
1217          * @return array server data
1218          */
1219         private static function detectMastodonAlikes(string $url, array $serverdata)
1220         {
1221                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance');
1222
1223                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1224                         return $serverdata;
1225                 }
1226
1227                 $data = json_decode($curlResult->getBody(), true);
1228                 if (empty($data)) {
1229                         return $serverdata;
1230                 }
1231
1232                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1233                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1234                 }
1235
1236                 if (!empty($data['version'])) {
1237                         $serverdata['platform'] = 'mastodon';
1238                         $serverdata['version'] = $data['version'] ?? '';
1239                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1240                 }
1241
1242                 if (!empty($data['title'])) {
1243                         $serverdata['site_name'] = $data['title'];
1244                 }
1245
1246                 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1247                         $serverdata['platform'] = 'mastodon';
1248                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1249                 }
1250
1251                 if (!empty($data['description'])) {
1252                         $serverdata['info'] = trim($data['description']);
1253                 }
1254
1255                 if (!empty($data['stats']['user_count'])) {
1256                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1257                 }
1258
1259                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1260                         $serverdata['platform'] = strtolower($matches[1]);
1261                         $serverdata['version'] = $matches[2];
1262                 }
1263
1264                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1265                         $serverdata['platform'] = 'pleroma';
1266                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1267                 }
1268
1269                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1270                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1271                         $serverdata['platform'] = 'pleroma';
1272                 }
1273
1274                 return $serverdata;
1275         }
1276
1277         /**
1278          * Detects data from typical Hubzilla endpoints
1279          *
1280          * @param string $url        URL of the given server
1281          * @param array  $serverdata array with server data
1282          *
1283          * @return array server data
1284          */
1285         private static function detectHubzilla(string $url, array $serverdata)
1286         {
1287                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json');
1288                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1289                         return $serverdata;
1290                 }
1291
1292                 $data = json_decode($curlResult->getBody(), true);
1293                 if (empty($data) || empty($data['site'])) {
1294                         return $serverdata;
1295                 }
1296
1297                 if (!empty($data['site']['name'])) {
1298                         $serverdata['site_name'] = $data['site']['name'];
1299                 }
1300
1301                 if (!empty($data['site']['platform'])) {
1302                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1303                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1304                         $serverdata['network'] = Protocol::ZOT;
1305                 }
1306
1307                 if (!empty($data['site']['hubzilla'])) {
1308                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1309                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1310                         $serverdata['network'] = Protocol::ZOT;
1311                 }
1312
1313                 if (!empty($data['site']['redmatrix'])) {
1314                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1315                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1316                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1317                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1318                         }
1319
1320                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1321                         $serverdata['network'] = Protocol::ZOT;
1322                 }
1323
1324                 $private = false;
1325                 $inviteonly = false;
1326                 $closed = false;
1327
1328                 if (!empty($data['site']['closed'])) {
1329                         $closed = self::toBoolean($data['site']['closed']);
1330                 }
1331
1332                 if (!empty($data['site']['private'])) {
1333                         $private = self::toBoolean($data['site']['private']);
1334                 }
1335
1336                 if (!empty($data['site']['inviteonly'])) {
1337                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
1338                 }
1339
1340                 if (!$closed && !$private and $inviteonly) {
1341                         $serverdata['register_policy'] = Register::APPROVE;
1342                 } elseif (!$closed && !$private) {
1343                         $serverdata['register_policy'] = Register::OPEN;
1344                 } else {
1345                         $serverdata['register_policy'] = Register::CLOSED;
1346                 }
1347
1348                 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1349                         [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1350                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1351                 }
1352
1353                 return $serverdata;
1354         }
1355
1356         /**
1357          * Converts input value to a boolean value
1358          *
1359          * @param string|integer $val
1360          *
1361          * @return boolean
1362          */
1363         private static function toBoolean($val)
1364         {
1365                 if (($val == 'true') || ($val == 1)) {
1366                         return true;
1367                 } elseif (($val == 'false') || ($val == 0)) {
1368                         return false;
1369                 }
1370
1371                 return $val;
1372         }
1373
1374         /**
1375          * Detect if the URL belongs to a pump.io server
1376          *
1377          * @param string $url        URL of the given server
1378          * @param array  $serverdata array with server data
1379          *
1380          * @return array server data
1381          */
1382         private static function detectPumpIO(string $url, array $serverdata)
1383         {
1384                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json');
1385                 if (!$curlResult->isSuccess()) {
1386                         return $serverdata;
1387                 }
1388
1389                 $data = json_decode($curlResult->getBody(), true);
1390                 if (empty($data['links'])) {
1391                         return $serverdata;
1392
1393                 }
1394
1395                 // We are looking for some endpoints that are typical for pump.io
1396                 $trust = 0;
1397                 foreach ($data['links'] as $link) {
1398                         if (empty($link['rel'])) {
1399                                 continue;
1400                         }
1401                         if (in_array($link['rel'], ['registration_endpoint', 'dialback', 'http://apinamespace.org/activitypub/whoami'])) {
1402                                 ++$trust;
1403                         }
1404                 }
1405
1406                 if ($trust == 3) {
1407                         $serverdata['detection-method'] = self::DETECT_PUMPIO;
1408
1409                         $serverdata['platform'] = 'pumpio';
1410                         $serverdata['version']  = '';
1411                         $serverdata['network']  = Protocol::PUMPIO;
1412
1413                         $servers = $curlResult->getHeader('Server');
1414                         foreach ($servers as $server) {
1415                                 if (preg_match("#pump.io/(.*)\s#U", $server, $matches)) {
1416                                         $serverdata['version']  = $matches[1];
1417                                 }
1418                         }
1419                 }
1420
1421                 return $serverdata;
1422         }
1423
1424         /**
1425          * Detect if the URL belongs to a GNU Social server
1426          *
1427          * @param string $url        URL of the given server
1428          * @param array  $serverdata array with server data
1429          *
1430          * @return array server data
1431          */
1432         private static function detectGNUSocial(string $url, array $serverdata)
1433         {
1434                 // Test for GNU Social
1435                 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json');
1436                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1437                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1438                         $serverdata['platform'] = 'gnusocial';
1439                         // Remove junk that some GNU Social servers return
1440                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1441                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1442                         $serverdata['version'] = trim($serverdata['version'], '"');
1443                         $serverdata['network'] = Protocol::OSTATUS;
1444
1445                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1446                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1447                         }
1448
1449                         return $serverdata;
1450                 }
1451
1452                 // Test for Statusnet
1453                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json');
1454                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1455                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1456
1457                         // Remove junk that some GNU Social servers return
1458                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1459                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1460                         $serverdata['version'] = trim($serverdata['version'], '"');
1461
1462                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1463                                 $serverdata['platform'] = 'pleroma';
1464                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1465                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1466                         } else {
1467                                 $serverdata['platform'] = 'statusnet';
1468                                 $serverdata['network'] = Protocol::OSTATUS;
1469                         }
1470
1471                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1472                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1473                         }
1474                 }
1475
1476                 return $serverdata;
1477         }
1478
1479         /**
1480          * Detect if the URL belongs to a Friendica server
1481          *
1482          * @param string $url        URL of the given server
1483          * @param array  $serverdata array with server data
1484          *
1485          * @return array server data
1486          */
1487         private static function detectFriendica(string $url, array $serverdata)
1488         {
1489                 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1490                 if (!$curlResult->isSuccess()) {
1491                         $curlResult = DI::httpClient()->get($url . '/friendika/json');
1492                         $friendika = true;
1493                         $platform = 'Friendika';
1494                 } else {
1495                         $friendika = false;
1496                         $platform = 'Friendica';
1497                 }
1498
1499                 if (!$curlResult->isSuccess()) {
1500                         return $serverdata;
1501                 }
1502
1503                 $data = json_decode($curlResult->getBody(), true);
1504                 if (empty($data) || empty($data['version'])) {
1505                         return $serverdata;
1506                 }
1507
1508                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1509                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1510                 }
1511
1512                 $serverdata['network'] = Protocol::DFRN;
1513                 $serverdata['version'] = $data['version'];
1514
1515                 if (!empty($data['no_scrape_url'])) {
1516                         $serverdata['noscrape'] = $data['no_scrape_url'];
1517                 }
1518
1519                 if (!empty($data['site_name'])) {
1520                         $serverdata['site_name'] = $data['site_name'];
1521                 }
1522
1523                 if (!empty($data['info'])) {
1524                         $serverdata['info'] = trim($data['info']);
1525                 }
1526
1527                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1528                 switch ($register_policy) {
1529                         case 'REGISTER_OPEN':
1530                                 $serverdata['register_policy'] = Register::OPEN;
1531                                 break;
1532
1533                         case 'REGISTER_APPROVE':
1534                                 $serverdata['register_policy'] = Register::APPROVE;
1535                                 break;
1536
1537                         case 'REGISTER_CLOSED':
1538                         case 'REGISTER_INVITATION':
1539                                 $serverdata['register_policy'] = Register::CLOSED;
1540                                 break;
1541                         default:
1542                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1543                                 $serverdata['register_policy'] = Register::CLOSED;
1544                                 break;
1545                 }
1546
1547                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1548
1549                 return $serverdata;
1550         }
1551
1552         /**
1553          * Analyses the landing page of a given server for hints about type and system of that server
1554          *
1555          * @param object $curlResult result of curl execution
1556          * @param array  $serverdata array with server data
1557          * @param string $url        Server URL
1558          *
1559          * @return array server data
1560          */
1561         private static function analyseRootBody($curlResult, array $serverdata, string $url)
1562         {
1563                 if (empty($curlResult->getBody())) {
1564                         return $serverdata;
1565                 }
1566
1567                 // Using only body information we cannot safely detect a lot of systems.
1568                 // So we define a list of platforms that we can detect safely.
1569                 $valid_platforms = ['friendica', 'friendika', 'diaspora', 'mastodon', 'hubzilla', 'misskey', 'peertube', 'wordpress', 'write.as'];
1570
1571                 $doc = new DOMDocument();
1572                 @$doc->loadHTML($curlResult->getBody());
1573                 $xpath = new DOMXPath($doc);
1574
1575                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1576                 if (!empty($title)) {
1577                         $serverdata['site_name'] = $title;
1578                 }
1579
1580                 $list = $xpath->query('//meta[@name]');
1581
1582                 foreach ($list as $node) {
1583                         $attr = [];
1584                         if ($node->attributes->length) {
1585                                 foreach ($node->attributes as $attribute) {
1586                                         $value = trim($attribute->value);
1587                                         if (empty($value)) {
1588                                                 continue;
1589                                         }
1590
1591                                         $attr[$attribute->name] = $value;
1592                                 }
1593
1594                                 if (empty($attr['name']) || empty($attr['content'])) {
1595                                         continue;
1596                                 }
1597                         }
1598
1599                         if ($attr['name'] == 'description') {
1600                                 $serverdata['info'] = $attr['content'];
1601                         }
1602
1603                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1604                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1605                                 $serverdata['platform'] = strtolower($attr['content']);
1606                                 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1607                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1608                                 }
1609                         }
1610                         if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1611                                 $serverdata['platform'] = strtolower($attr['content']);
1612                                 $version_part = explode(' ', $attr['content']);
1613
1614                                 if (count($version_part) == 2) {
1615                                         if (in_array($version_part[0], ['WordPress'])) {
1616                                                 $serverdata['platform'] = 'wordpress';
1617                                                 $serverdata['version'] = $version_part[1];
1618
1619                                                 // We still do need a reliable test if some AP plugin is activated
1620                                                 // By now we just check in a later process for some known contacts
1621                                                 $serverdata['network'] = Protocol::FEED;
1622
1623                                                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1624                                                         $serverdata['detection-method'] = self::DETECT_BODY;
1625                                                 }
1626                                         }
1627                                         if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1628                                                 $serverdata['platform'] = strtolower($version_part[0]);
1629                                                 $serverdata['version'] = $version_part[1];
1630                                                 $serverdata['network'] = Protocol::DFRN;
1631                                         }
1632                                 }
1633                         }
1634                 }
1635
1636                 $list = $xpath->query('//meta[@property]');
1637
1638                 foreach ($list as $node) {
1639                         $attr = [];
1640                         if ($node->attributes->length) {
1641                                 foreach ($node->attributes as $attribute) {
1642                                         $value = trim($attribute->value);
1643                                         if (empty($value)) {
1644                                                 continue;
1645                                         }
1646
1647                                         $attr[$attribute->name] = $value;
1648                                 }
1649
1650                                 if (empty($attr['property']) || empty($attr['content'])) {
1651                                         continue;
1652                                 }
1653                         }
1654
1655                         if ($attr['property'] == 'og:site_name') {
1656                                 $serverdata['site_name'] = $attr['content'];
1657                         }
1658
1659                         if ($attr['property'] == 'og:description') {
1660                                 $serverdata['info'] = $attr['content'];
1661                         }
1662
1663                         if ($attr['property'] == 'og:platform') {
1664                                 $serverdata['platform'] = strtolower($attr['content']);
1665
1666                                 if (in_array($attr['content'], ['PeerTube'])) {
1667                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1668                                 }
1669                         }
1670
1671                         if ($attr['property'] == 'generator') {
1672                                 $serverdata['platform'] = strtolower($attr['content']);
1673
1674                                 if (in_array($attr['content'], ['hubzilla'])) {
1675                                         // We later check which compatible protocol modules are loaded.
1676                                         $serverdata['network'] = Protocol::ZOT;
1677                                 }
1678                         }
1679                 }
1680
1681                 if (!empty($serverdata['platform']) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY]) && !in_array($serverdata['platform'], $valid_platforms)) {
1682                         $serverdata['network'] = Protocol::PHANTOM;
1683                         $serverdata['version'] = '';
1684                         $serverdata['detection-method'] = self::DETECT_MANUAL;
1685                 } elseif (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1686                         $serverdata['detection-method'] = self::DETECT_BODY;
1687                 }
1688
1689                 return $serverdata;
1690         }
1691
1692         /**
1693          * Analyses the header data of a given server for hints about type and system of that server
1694          *
1695          * @param object $curlResult result of curl execution
1696          * @param array  $serverdata array with server data
1697          *
1698          * @return array server data
1699          */
1700         private static function analyseRootHeader($curlResult, array $serverdata)
1701         {
1702                 if ($curlResult->getHeader('server') == 'Mastodon') {
1703                         $serverdata['platform'] = 'mastodon';
1704                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1705                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1706                         $serverdata['platform'] = 'diaspora';
1707                         $serverdata['network'] = Protocol::DIASPORA;
1708                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1709                 } elseif ($curlResult->inHeader('x-friendica-version')) {
1710                         $serverdata['platform'] = 'friendica';
1711                         $serverdata['network'] = Protocol::DFRN;
1712                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1713                 } else {
1714                         return $serverdata;
1715                 }
1716
1717                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1718                         $serverdata['detection-method'] = self::DETECT_HEADER;
1719                 }
1720
1721                 return $serverdata;
1722         }
1723
1724         /**
1725          * Test if the body contains valid content
1726          *
1727          * @param string $body
1728          * @return boolean
1729          */
1730         private static function invalidBody(string $body)
1731         {
1732                 // Currently we only test for a HTML element.
1733                 // Possibly we enhance this in the future.
1734                 return !strpos($body, '>');
1735         }
1736
1737         /**
1738          * Update GServer entries
1739          */
1740         public static function discover()
1741         {
1742                 // Update the server list
1743                 self::discoverFederation();
1744
1745                 $no_of_queries = 5;
1746
1747                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1748
1749                 if ($requery_days == 0) {
1750                         $requery_days = 7;
1751                 }
1752
1753                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1754
1755                 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
1756                         ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
1757                         ['order' => ['RAND()']]);
1758
1759                 while ($gserver = DBA::fetch($gservers)) {
1760                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1761                         Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1762
1763                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1764                         Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1765
1766                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1767                         DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1768
1769                         if (--$no_of_queries == 0) {
1770                                 break;
1771                         }
1772                 }
1773
1774                 DBA::close($gservers);
1775         }
1776
1777         /**
1778          * Discover federated servers
1779          */
1780         private static function discoverFederation()
1781         {
1782                 $last = DI::config()->get('poco', 'last_federation_discovery');
1783
1784                 if ($last) {
1785                         $next = $last + (24 * 60 * 60);
1786
1787                         if ($next > time()) {
1788                                 return;
1789                         }
1790                 }
1791
1792                 // Discover federated servers
1793                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1794                 foreach ($protocols as $protocol) {
1795                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1796                         $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1797                         if (!empty($curlResult)) {
1798                                 $data = json_decode($curlResult, true);
1799                                 if (!empty($data['data']['nodes'])) {
1800                                         foreach ($data['data']['nodes'] as $server) {
1801                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1802                                                 self::add('https://' . $server['host'], true);
1803                                         }
1804                                 }
1805                         }
1806                 }
1807
1808                 // Disvover Mastodon servers
1809                 $accesstoken = DI::config()->get('system', 'instances_social_key');
1810
1811                 if (!empty($accesstoken)) {
1812                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
1813                         $curlResult = DI::httpClient()->get($api, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1814
1815                         if ($curlResult->isSuccess()) {
1816                                 $servers = json_decode($curlResult->getBody(), true);
1817
1818                                 foreach ($servers['instances'] as $server) {
1819                                         $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1820                                         self::add($url);
1821                                 }
1822                         }
1823                 }
1824
1825                 DI::config()->set('poco', 'last_federation_discovery', time());
1826         }
1827
1828         /**
1829          * Set the protocol for the given server
1830          *
1831          * @param int $gsid     Server id
1832          * @param int $protocol Protocol id
1833          * @return void
1834          * @throws Exception
1835          */
1836         public static function setProtocol(int $gsid, int $protocol)
1837         {
1838                 if (empty($gsid)) {
1839                         return;
1840                 }
1841
1842                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1843                 if (!DBA::isResult($gserver)) {
1844                         return;
1845                 }
1846
1847                 $old = $gserver['protocol'];
1848
1849                 if (!is_null($old)) {
1850                         /*
1851                         The priority for the protocols is:
1852                                 1. ActivityPub
1853                                 2. DFRN via Diaspora
1854                                 3. Legacy DFRN
1855                                 4. Diaspora
1856                                 5. OStatus
1857                         */
1858
1859                         // We don't need to change it when nothing is to be changed
1860                         if ($old == $protocol) {
1861                                 return;
1862                         }
1863
1864                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1865                         if ($protocol == Post\DeliveryData::OSTATUS) {
1866                                 return;
1867                         }
1868
1869                         // If the server is marked as ActivityPub then we won't change it to anything different
1870                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
1871                                 return;
1872                         }
1873
1874                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1875                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1876                                 return;
1877                         }
1878
1879                         // Don't change it to Diaspora when it is a legacy DFRN server
1880                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
1881                                 return;
1882                         }
1883                 }
1884
1885                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
1886                 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
1887         }
1888
1889         /**
1890          * Fetch the protocol of the given server
1891          *
1892          * @param int $gsid Server id
1893          * @return int
1894          * @throws Exception
1895          */
1896         public static function getProtocol(int $gsid)
1897         {
1898                 if (empty($gsid)) {
1899                         return null;
1900                 }
1901
1902                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
1903                 if (DBA::isResult($gserver)) {
1904                         return $gserver['protocol'];
1905                 }
1906
1907                 return null;
1908         }
1909 }