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