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