]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/GServer.php
Changes:
[friendica.git] / src / Model / GServer.php
index 3ea07dbc6fb0c474de531cd4a68b2f9d97002d98..a3f0c26077ecfd5718dc655f751d428988aa0ed6 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2022, the Friendica project
+ * @copyright Copyright (C) 2010-2024, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -26,11 +26,9 @@ use DOMXPath;
 use Exception;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
-use Friendica\Core\System;
 use Friendica\Core\Worker;
 use Friendica\Database\Database;
 use Friendica\Database\DBA;
-use Friendica\Database\DBStructure;
 use Friendica\DI;
 use Friendica\Module\Register;
 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
@@ -45,7 +43,9 @@ use Friendica\Util\Network;
 use Friendica\Util\Strings;
 use Friendica\Util\XML;
 use Friendica\Network\HTTPException;
+use Friendica\Worker\UpdateGServer;
 use GuzzleHttp\Psr7\Uri;
+use Psr\Http\Message\UriInterface;
 
 /**
  * This class handles GServer related functions
@@ -71,6 +71,7 @@ class GServer
        const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
 
        // Implementation specific endpoints
+       // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
        const DETECT_FRIENDIKA = 10;
        const DETECT_FRIENDICA = 11;
        const DETECT_STATUSNET = 12;
@@ -80,8 +81,8 @@ class GServer
        const DETECT_MASTODON_API = 16;
        const DETECT_STATUS_PHP = 17; // Nextcloud
        const DETECT_V1_CONFIG = 18;
-       const DETECT_PUMPIO = 19; // Deprecated
        const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
+       const DETECT_THREADS = 21;
 
        // Standardized endpoints
        const DETECT_STATISTICS_JSON = 100;
@@ -90,19 +91,20 @@ class GServer
        const DETECT_NODEINFO_210 = 103;
 
        /**
-        * Check for the existance of a server and adds it in the background if not existant
+        * Check for the existence of a server and adds it in the background if not existant
         *
         * @param string $url
         * @param boolean $only_nodeinfo
+        *
         * @return void
         */
        public static function add(string $url, bool $only_nodeinfo = false)
        {
-               if (self::getID($url, false)) {
+               if (self::getID($url)) {
                        return;
                }
 
-               Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
+               UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
        }
 
        /**
@@ -110,19 +112,27 @@ class GServer
         *
         * @param string $url
         * @param boolean $no_check Don't check if the server hadn't been found
-        * @return int gserver id
+        *
+        * @return int|null gserver id or NULL on empty URL or failed check
         */
-       public static function getID(string $url, bool $no_check = false)
+       public static function getID(string $url, bool $no_check = false): ?int
        {
+               $url = self::cleanURL($url);
+
                if (empty($url)) {
                        return null;
                }
 
-               $url = self::cleanURL($url);
-
                $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
                if (DBA::isResult($gserver)) {
-                       Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
+                       Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url]);
+
+                       if (Network::isUrlBlocked($url)) {
+                               self::setBlockedById($gserver['id']);
+                       } else {
+                               self::setUnblockedById($gserver['id']);
+                       }
+
                        return $gserver['id'];
                }
 
@@ -139,6 +149,7 @@ class GServer
         * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
         *
         * @param string $pattern
+        *
         * @return array
         * @throws Exception
         */
@@ -161,32 +172,113 @@ class GServer
        }
 
        /**
-        * Checks if the given server is reachable
+        * Checks if the given server array is unreachable for a long time now
         *
-        * @param string  $profile URL of the given profile
-        * @param string  $server  URL of the given server (If empty, taken from profile)
-        * @param string  $network Network value that is used, when detection failed
-        * @param boolean $force   Force an update.
+        * @param integer $gsid
+        * @return boolean
+        */
+       private static function isDefunct(array $gserver): bool
+       {
+               return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
+                       ($gserver['last_contact'] >= $gserver['created']) &&
+                       ($gserver['last_contact'] < $gserver['last_failure']) &&
+                       ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
+       }
+
+       /**
+        * Checks if the given server id is unreachable for a long time now
         *
-        * @return boolean 'true' if server seems vital
+        * @param integer $gsid
+        * @return boolean
+        */
+       public static function isDefunctById(int $gsid): bool
+       {
+               $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
+               if (empty($gserver)) {
+                       return false;
+               } else {
+                       if (strtotime($gserver['next_contact']) < time()) {
+                               UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
+                       }
+
+                       return self::isDefunct($gserver);
+               }
+       }
+
+       /**
+        * Checks if the given server id is reachable
+        *
+        * @param integer $gsid
+        * @return boolean
         */
-       public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
+       public static function isReachableById(int $gsid): bool
        {
-               if ($server == '') {
-                       $contact = Contact::getByURL($profile, null, ['baseurl']);
-                       if (!empty($contact['baseurl'])) {
-                               $server = $contact['baseurl'];
+               $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
+               if (empty($gserver)) {
+                       return true;
+               } else {
+                       if (strtotime($gserver['next_contact']) < time()) {
+                               UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
                        }
+
+                       return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
                }
+       }
 
-               if ($server == '') {
+       /**
+        * Checks if the given server is reachable
+        *
+        * @param array $contact Contact that should be checked
+        *
+        * @return boolean 'true' if server seems vital
+        */
+       public static function reachable(array $contact): bool
+       {
+               if (!empty($contact['gsid'])) {
+                       $gsid = $contact['gsid'];
+               } elseif (!empty($contact['baseurl'])) {
+                       $server = $contact['baseurl'];
+               } elseif ($contact['network'] == Protocol::DIASPORA) {
+                       $parts = (array)parse_url($contact['url']);
+                       unset($parts['path']);
+                       $server = (string)Uri::fromParts($parts);
+               } else {
                        return true;
                }
 
-               return self::check($server, $network, $force);
+               if (!empty($gsid)) {
+                       $condition = ['id' => $gsid];
+               } else {
+                       $condition = ['nurl' => Strings::normaliseLink($server)];
+               }
+
+               $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
+               if (empty($gserver)) {
+                       $reachable = true;
+               } else {
+                       $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
+                       $server    = $gserver['url'];
+               }
+
+               if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
+                       UpdateGServer::add(Worker::PRIORITY_LOW, $server);
+               }
+
+               return $reachable;
        }
 
-       public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false)
+       /**
+        * Calculate the next update day
+        *
+        * @param bool $success
+        * @param string $created
+        * @param string $last_contact
+        * @param bool $undetected
+        *
+        * @return string
+        * @throws Exception
+        */
+       public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
        {
                // On successful contact process check again next week when it is a detected system.
                // When we haven't detected the system, it could be a static website or a really old system.
@@ -232,7 +324,7 @@ class GServer
                        return DateTimeFormat::utc('now +1 month');
                }
 
-               // The system hadn't been successul contacted for more than a month, so try again in three months
+               // The system hadn't been successful contacted for more than a month, so try again in three months
                return DateTimeFormat::utc('now +3 month');
        }
 
@@ -246,19 +338,25 @@ class GServer
         *
         * @return boolean 'true' if server seems vital
         */
-       public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
+       public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
        {
                $server_url = self::cleanURL($server_url);
                if ($server_url == '') {
                        return false;
                }
 
+               if (Network::isUrlBlocked($server_url)) {
+                       Logger::info('Server is blocked', ['url' => $server_url]);
+                       self::setBlockedByUrl($server_url);
+                       return false;
+               }
+
                $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
                if (DBA::isResult($gserver)) {
                        if ($gserver['created'] <= DBA::NULL_DATETIME) {
                                $fields = ['created' => DateTimeFormat::utcNow()];
                                $condition = ['nurl' => Strings::normaliseLink($server_url)];
-                               DBA::update('gserver', $fields, $condition);
+                               self::update($fields, $condition);
                        }
 
                        if (!$force && (strtotime($gserver['next_contact']) > time())) {
@@ -273,45 +371,164 @@ class GServer
                return self::detect($server_url, $network, $only_nodeinfo);
        }
 
+       /**
+        * Reset failed server status by gserver id
+        *
+        * @param int    $gsid
+        * @param string $network
+        */
+       public static function setReachableById(int $gsid, string $network)
+       {
+               $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
+               if (!DBA::isResult($gserver)) {
+                       return;
+               }
+
+               $blocked = Network::isUrlBlocked($gserver['url']);
+               if ($gserver['failed']) {
+                       $fields = ['failed' => false, 'blocked' => $blocked, 'last_contact' => DateTimeFormat::utcNow()];
+                       if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
+                               $fields['network'] = $network;
+                       }
+                       self::update($fields, ['id' => $gsid]);
+                       Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
+
+                       if (strtotime($gserver['next_contact']) < time()) {
+                               UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
+                       }
+               } elseif ($blocked) {
+                       self::setBlockedById($gsid);
+               } else {
+                       self::setUnblockedById($gsid);
+               }
+       }
+
+       /**
+        * Set failed server status by gserver id
+        *
+        * @param int $gsid
+        */
+       public static function setFailureById(int $gsid)
+       {
+               $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
+               if (DBA::isResult($gserver) && !$gserver['failed']) {
+                       self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
+                       Logger::info('Set failed status for server', ['url' => $gserver['url']]);
+
+                       if (strtotime($gserver['next_contact']) < time()) {
+                               UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
+                       }
+               }
+       }
+
+       public static function setUnblockedById(int $gsid)
+       {
+               $gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
+               if (DBA::isResult($gserver)) {
+                       self::update(['blocked' => false], ['id' => $gsid]);
+                       Logger::info('Set unblocked status for server', ['url' => $gserver['url']]);
+               }
+       }
+
+       public static function setBlockedById(int $gsid)
+       {
+               $gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
+               if (DBA::isResult($gserver)) {
+                       self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
+                       Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
+               }
+       }
+
+       public static function setBlockedByUrl(string $url)
+       {
+               $gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
+               if (DBA::isResult($gserver)) {
+                       self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
+                       Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
+               }
+       }
+
        /**
         * Set failed server status
         *
         * @param string $url
+        * @return void
         */
-       public static function setFailure(string $url)
+       public static function setFailureByUrl(string $url)
        {
-               $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
+               $nurl = Strings::normaliseLink($url);
+
+               $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
                if (DBA::isResult($gserver)) {
                        $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
-                       DBA::update('gserver', ['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
+                       self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
                        'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
-                       ['nurl' => Strings::normaliseLink($url)]);
+                       ['nurl' => $nurl]);
                        Logger::info('Set failed status for existing server', ['url' => $url]);
+                       if (self::isDefunct($gserver)) {
+                               self::archiveContacts($gserver['id']);
+                       }
                        return;
                }
-               DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
+
+               self::insert(['url' => $url, 'nurl' => $nurl,
                        'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
                        'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
                Logger::info('Set failed status for new server', ['url' => $url]);
        }
 
+       /**
+        * Archive server related contacts and inboxes
+        *
+        * @param integer $gsid
+        * @return void
+        */
+       private static function archiveContacts(int $gsid)
+       {
+               Contact::update(['archive' => true], ['gsid' => $gsid]);
+               DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
+       }
+
        /**
         * Remove unwanted content from the given URL
         *
-        * @param string $url
+        * @param string $dirtyUrl
+        *
         * @return string cleaned URL
+        * @throws Exception
+        * @deprecated since 2023.03 Use cleanUri instead
         */
-       public static function cleanURL(string $url)
+       public static function cleanURL(string $dirtyUrl): string
        {
-               $url = trim($url, '/');
-               $url = str_replace('/index.php', '', $url);
-
-               $urlparts = parse_url($url);
-               unset($urlparts['user']);
-               unset($urlparts['pass']);
-               unset($urlparts['query']);
-               unset($urlparts['fragment']);
-               return (string)Uri::fromParts($urlparts);
+               try {
+                       return (string)self::cleanUri(new Uri($dirtyUrl));
+               } catch (\Throwable $e) {
+                       Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
+                       return '';
+               }
+       }
+
+       /**
+        * Remove unwanted content from the given URI
+        *
+        * @param UriInterface $dirtyUri
+        *
+        * @return UriInterface cleaned URI
+        * @throws Exception
+        */
+       public static function cleanUri(UriInterface $dirtyUri): string
+       {
+               return $dirtyUri
+                       ->withUserInfo('')
+                       ->withQuery('')
+                       ->withFragment('')
+                       ->withPath(
+                               preg_replace(
+                                       '#(?:^|/)index\.php#',
+                                       '',
+                                       rtrim($dirtyUri->getPath(), '/')
+                               )
+                       );
        }
 
        /**
@@ -324,7 +541,7 @@ class GServer
         *
         * @return boolean 'true' if server could be detected
         */
-       public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
+       private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
        {
                Logger::info('Detect server type', ['server' => $url]);
 
@@ -337,10 +554,10 @@ class GServer
                        return false;
                }
 
-               // If the URL missmatches, then we mark the old entry as failure
+               // If the URL mismatches, then we mark the old entry as failure
                if (!Strings::compareLink($url, $original_url)) {
-                       self::setFailure($original_url);
-                       if (!self::getID($url, true)) {
+                       self::setFailureByUrl($original_url);
+                       if (!self::getID($url, true) && !Network::isUrlBlocked($url)) {
                                self::detect($url, $network, $only_nodeinfo);
                        }
                        return false;
@@ -348,7 +565,7 @@ class GServer
 
                $valid_url = Network::isUrlValid($url);
                if (!$valid_url) {
-                       self::setFailure($url);
+                       self::setFailureByUrl($url);
                        return false;
                } else {
                        $valid_url = rtrim($valid_url, '/');
@@ -360,8 +577,8 @@ class GServer
                        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))) ||
                                (((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)))) {
                                Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
-                               self::setFailure($url);
-                               if (!self::getID($valid_url, true)) {
+                               self::setFailureByUrl($url);
+                               if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
                                        self::detect($valid_url, $network, $only_nodeinfo);
                                }
                                return false;
@@ -370,15 +587,15 @@ class GServer
                        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)) &&
                                (parse_url($url, PHP_URL_PATH) == '')) {
                                Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
-                               $parts = parse_url($valid_url);
+                               $parts = (array)parse_url($valid_url);
                                unset($parts['path']);
                                $valid_url = (string)Uri::fromParts($parts);
 
-                               self::setFailure($url);
-                               if (!self::getID($valid_url, true)) {
+                               self::setFailureByUrl($url);
+                               if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
                                        self::detect($valid_url, $network, $only_nodeinfo);
                                }
-                               return false;   
+                               return false;
                        }
                        Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
                }
@@ -394,19 +611,23 @@ class GServer
                // When a nodeinfo is present, we don't need to dig further
                $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
                if ($curlResult->isTimeout()) {
-                       self::setFailure($url);
+                       self::setFailureByUrl($url);
                        return false;
                }
 
-               $serverdata = self::parseNodeinfo210($curlResult);
-               if (empty($serverdata)) {
-                       $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
-                       $serverdata = self::fetchNodeinfo($url, $curlResult);
+               if (!empty($network) && !in_array($network, Protocol::NATIVE_SUPPORT)) {
+                       $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => $network, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
+               } else {
+                       $serverdata = self::parseNodeinfo210($curlResult);
+                       if (empty($serverdata)) {
+                               $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
+                               $serverdata = self::fetchNodeinfo($url, $curlResult);
+                       }
                }
 
                if ($only_nodeinfo && empty($serverdata)) {
                        Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
-                       self::setFailure($url);
+                       self::setFailureByUrl($url);
                        return false;
                } elseif (empty($serverdata)) {
                        $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
@@ -426,7 +647,7 @@ class GServer
                                }
 
                                if ($curlResult->isSuccess()) {
-                                       $json = json_decode($curlResult->getBody(), true);
+                                       $json = json_decode($curlResult->getBodyString(), true);
                                        if (!empty($json) && is_array($json)) {
                                                $data = self::fetchDataFromSystemActor($json, $serverdata);
                                                $serverdata = $data['server'];
@@ -434,7 +655,7 @@ class GServer
                                                if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
                                                        $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
                                                }
-                                       } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
+                                       } elseif (!$html_fetched && (strlen($curlResult->getBodyString()) < 1000)) {
                                                $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
                                        }
 
@@ -444,18 +665,24 @@ class GServer
                                        }
                                }
 
-                               if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
-                                       self::setFailure($url);
+                               if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) {
+                                       self::setFailureByUrl($url);
                                        return false;
                                }
 
+                               if (in_array($url, ['https://www.threads.net', 'https://threads.net'])) {
+                                       $serverdata['detection-method'] = self::DETECT_THREADS;
+                                       $serverdata['network']          = Protocol::ACTIVITYPUB;
+                                       $serverdata['platform']         = 'threads';
+                               }
+
                                if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
                                        $serverdata = self::detectMastodonAlikes($url, $serverdata);
                                }
                        }
 
                        // All following checks are done for systems that always have got a "host-meta" endpoint.
-                       // With this check we don't have to waste time and ressources for dead systems.
+                       // With this check we don't have to waste time and resources for dead systems.
                        // Also this hopefully prevents us from receiving abuse messages.
                        if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
                                $validHostMeta = self::validHostMeta($url);
@@ -514,7 +741,7 @@ class GServer
 
                // Most servers aren't installed in a subdirectory, so we declare this entry as failed
                if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
-                       self::setFailure($url);
+                       self::setFailureByUrl($url);
                        return false;
                }
 
@@ -530,6 +757,15 @@ class GServer
                        $serverdata = self::detectNetworkViaContacts($url, $serverdata);
                }
 
+               if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
+                       self::setFailureByUrl($url);
+                       return false;
+               }
+
+               if (empty($serverdata['version']) && in_array($serverdata['platform'], ['osada']) && in_array($serverdata['detection-method'], [self::DETECT_CONTACTS, self::DETECT_BODY])) {
+                       $serverdata['version'] = self::getNomadVersion($url);
+               }
+
                // Detect the directory type
                $serverdata['directory-type'] = self::DT_NONE;
 
@@ -546,29 +782,34 @@ class GServer
                }
 
                $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
+               $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
+               $serverdata['last_contact'] = DateTimeFormat::utcNow();
+               $serverdata['failed'] = false;
+
+               // Numbers above a reasonable value (10 millions) are ignored
+               if ($serverdata['registered-users'] > 10000000) {
+                       $serverdata['registered-users'] = 0;
+               }
 
                // On an active server there has to be at least a single user
-               if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
+               if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
                        $serverdata['registered-users'] = 1;
                } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
                        $serverdata['registered-users'] = 0;
                }
 
                $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
-
                $serverdata['last_contact'] = DateTimeFormat::utcNow();
-               $serverdata['failed'] = false;
-
-               // Limit the length on incoming fields
-               $serverdata = DBStructure::getFieldsForTable('gserver', $serverdata);
+               $serverdata['failed']       = false;
+               $serverdata['blocked']      = false;
 
                $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
                if (!DBA::isResult($gserver)) {
                        $serverdata['created'] = DateTimeFormat::utcNow();
-                       $ret = DBA::insert('gserver', $serverdata);
+                       $ret = self::insert($serverdata);
                        $id = DBA::lastInsertId();
                } else {
-                       $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
+                       $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
                        $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
                        if (DBA::isResult($gserver)) {
                                $id = $gserver['id'];
@@ -582,14 +823,14 @@ class GServer
                        $max_users = max($apcontacts, $contacts);
                        if ($max_users > $serverdata['registered-users']) {
                                Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
-                               DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
+                               self::update(['registered-users' => $max_users], ['id' => $id]);
                        }
 
                        if (empty($serverdata['active-month-users'])) {
                                $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
                                if ($contacts > 0) {
                                        Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
-                                       DBA::update('gserver', ['active-month-users' => $contacts], ['id' => $id]);
+                                       self::update(['active-month-users' => $contacts], ['id' => $id]);
                                }
                        }
 
@@ -597,7 +838,7 @@ class GServer
                                $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
                                if ($contacts > 0) {
                                        Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
-                                       DBA::update('gserver', ['active-halfyear-users' => $contacts], ['id' => $id]);
+                                       self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
                                }
                        }
                }
@@ -618,6 +859,8 @@ class GServer
         * Fetch relay data from a given server url
         *
         * @param string $server_url address of the server
+        *
+        * @return void
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function discoverRelay(string $server_url)
@@ -629,13 +872,13 @@ class GServer
                        return;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (!is_array($data)) {
                        return;
                }
 
                // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
-               $data['subscribe'] = (bool)$data['subscribe'] ?? false;
+               $data['subscribe'] = (bool)($data['subscribe'] ?? false);
 
                if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
                        $data['scope'] = '';
@@ -650,7 +893,7 @@ class GServer
 
                if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
                        $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
-                       DBA::update('gserver', $fields, ['id' => $gserver['id']]);
+                       self::update($fields, ['id' => $gserver['id']]);
                }
 
                DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
@@ -717,14 +960,14 @@ class GServer
         *
         * @return array server data
         */
-       private static function fetchStatistics(string $url, array $serverdata)
+       private static function fetchStatistics(string $url, array $serverdata): array
        {
                $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
                if (!$curlResult->isSuccess()) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -807,15 +1050,16 @@ class GServer
         * @param ICanHandleHttpResponses $httpResult
         *
         * @return array Server data
+        *
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
+       private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
        {
                if (!$httpResult->isSuccess()) {
                        return [];
                }
 
-               $nodeinfo = json_decode($httpResult->getBody(), true);
+               $nodeinfo = json_decode($httpResult->getBodyString(), true);
 
                if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
                        return [];
@@ -829,10 +1073,11 @@ class GServer
                                Logger::info('Invalid nodeinfo format', ['url' => $url]);
                                continue;
                        }
+
                        if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
-                               $nodeinfo1_url = $link['href'];
+                               $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl());
                        } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
-                               $nodeinfo2_url = $link['href'];
+                               $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl());
                        }
                }
 
@@ -857,17 +1102,19 @@ class GServer
         * Parses Nodeinfo 1
         *
         * @param string $nodeinfo_url address of the nodeinfo path
+        *
         * @return array Server data
+        *
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       private static function parseNodeinfo1(string $nodeinfo_url)
+       private static function parseNodeinfo1(string $nodeinfo_url): array
        {
                $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
                if (!$curlResult->isSuccess()) {
                        return [];
                }
 
-               $nodeinfo = json_decode($curlResult->getBody(), true);
+               $nodeinfo = json_decode($curlResult->getBodyString(), true);
 
                if (!is_array($nodeinfo)) {
                        return [];
@@ -953,24 +1200,30 @@ class GServer
         * Parses Nodeinfo 2
         *
         * @see https://git.feneas.org/jaywink/nodeinfo2
+        *
         * @param string $nodeinfo_url address of the nodeinfo path
+        *
         * @return array Server data
+        *
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       private static function parseNodeinfo2(string $nodeinfo_url)
+       private static function parseNodeinfo2(string $nodeinfo_url): array
        {
                $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
                if (!$curlResult->isSuccess()) {
                        return [];
                }
 
-               $nodeinfo = json_decode($curlResult->getBody(), true);
+               $nodeinfo = json_decode($curlResult->getBodyString(), true);
                if (!is_array($nodeinfo)) {
                        return [];
                }
 
-               $server = ['detection-method' => self::DETECT_NODEINFO_2,
-                       'register_policy' => Register::CLOSED];
+               $server = [
+                       'detection-method' => self::DETECT_NODEINFO_2,
+                       'register_policy' => Register::CLOSED,
+                       'platform' => 'unknown',
+               ];
 
                if (!empty($nodeinfo['openRegistrations'])) {
                        $server['register_policy'] = Register::OPEN;
@@ -994,6 +1247,11 @@ class GServer
                        }
                }
 
+               // Special treatment for NextCloud, since there you can freely define your software name
+               if (!empty($nodeinfo['rootUrl']) && in_array(parse_url($nodeinfo['rootUrl'], PHP_URL_PATH), ['/index.php/apps/social', '/apps/social'])) {
+                       $server['platform'] = 'nextcloud';
+               }
+
                if (!empty($nodeinfo['metadata']['nodeName'])) {
                        $server['site_name'] = $nodeinfo['metadata']['nodeName'];
                }
@@ -1020,9 +1278,13 @@ class GServer
 
                if (!empty($nodeinfo['protocols'])) {
                        $protocols = [];
-                       foreach ($nodeinfo['protocols'] as $protocol) {
-                               if (is_string($protocol)) {
-                                       $protocols[$protocol] = true;
+                       if (is_string($nodeinfo['protocols'])) {
+                               $protocols[$nodeinfo['protocols']] = true;
+                       } else {
+                               foreach ($nodeinfo['protocols'] as $protocol) {
+                                       if (is_string($protocol)) {
+                                               $protocols[$protocol] = true;
+                                       }
                                }
                        }
 
@@ -1055,18 +1317,19 @@ class GServer
        /**
         * Parses NodeInfo2 protocol 1.0
         *
-        * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
-        * @param string $nodeinfo_url address of the nodeinfo path
+        * @param ICanHandleHttpResponses $httpResult
+        *
         * @return array Server data
+        * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult)
+       private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
        {
                if (!$httpResult->isSuccess()) {
                        return [];
                }
 
-               $nodeinfo = json_decode($httpResult->getBody(), true);
+               $nodeinfo = json_decode($httpResult->getBodyString(), true);
 
                if (!is_array($nodeinfo)) {
                        return [];
@@ -1118,9 +1381,13 @@ class GServer
 
                if (!empty($nodeinfo['protocols'])) {
                        $protocols = [];
-                       foreach ($nodeinfo['protocols'] as $protocol) {
-                               if (is_string($protocol)) {
-                                       $protocols[$protocol] = true;
+                       if (is_string($nodeinfo['protocols'])) {
+                               $protocols[$nodeinfo['protocols']] = true;
+                       } else {
+                               foreach ($nodeinfo['protocols'] as $protocol) {
+                                       if (is_string($protocol)) {
+                                               $protocols[$protocol] = true;
+                                       }
                                }
                        }
 
@@ -1158,14 +1425,14 @@ class GServer
         *
         * @return array server data
         */
-       private static function fetchSiteinfo(string $url, array $serverdata)
+       private static function fetchSiteinfo(string $url, array $serverdata): array
        {
                $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
                if (!$curlResult->isSuccess()) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1174,9 +1441,9 @@ class GServer
                        $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
                }
 
-               if (!empty($data['url'])) {
+               if (!empty($data['platform'])) {
                        $serverdata['platform'] = strtolower($data['platform']);
-                       $serverdata['version'] = $data['version'];
+                       $serverdata['version'] = $data['version'] ?? 'N/A';
                }
 
                if (!empty($data['plugins'])) {
@@ -1235,7 +1502,17 @@ class GServer
                return $serverdata;
        }
 
-       private static function fetchDataFromSystemActor(array $data, array $serverdata)
+       /**
+        * Fetches server data via an ActivityPub account with url of that server
+        *
+        * @param string $url        URL of the given server
+        * @param array  $serverdata array with server data
+        *
+        * @return array server data
+        *
+        * @throws Exception
+        */
+       private static function fetchDataFromSystemActor(array $data, array $serverdata): array
        {
                if (empty($data)) {
                        return ['server' => $serverdata, 'actor' => ''];
@@ -1246,9 +1523,14 @@ class GServer
                        $serverdata['network'] = Protocol::ACTIVITYPUB;
                        $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
                        $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
-                       if (!empty($actor['as:generator'])) {
+                       if (self::isNomad($actor)) {
+                               $serverdata['platform'] = self::getNomadName($actor['@id']);
+                               $serverdata['version'] = self::getNomadVersion($actor['@id']);
+                               $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
+                       } elseif (!empty($actor['as:generator'])) {
                                $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
                                $serverdata['platform'] = strtolower(array_shift($generator));
+                               $serverdata['version'] = self::getNomadVersion($actor['@id']);
                                $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
                        } else {
                                $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
@@ -1272,6 +1554,69 @@ class GServer
                return ['server' => $serverdata, 'actor' => ''];
        }
 
+       /**
+        * Detect if the given actor is a nomad account
+        *
+        * @param array $actor
+        * @return boolean
+        */
+       private static function isNomad(array $actor): bool
+       {
+               $tags = JsonLD::fetchElementArray($actor, 'as:tag');
+               if (empty($tags)) {
+                       return false;
+               }
+
+               foreach ($tags as $tag) {
+                       if ((($tag['as:name'] ?? '') == 'Protocol') && in_array('nomad', [$tag['sc:value'] ?? '', $tag['as:content'] ?? ''])) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Fetch the name of Nomad implementation
+        *
+        * @param string $url
+        * @return string
+        */
+       private static function getNomadName(string $url): string
+       {
+               $name = 'nomad';
+               $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json');
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
+                       return $name;
+               }
+
+               $data = json_decode($curlResult->getBodyString(), true);
+               if (empty($data)) {
+                       return $name;
+               }
+
+               return $data['name'] ?? $name;
+       }
+
+       /**
+        * Fetch the version of the Nomad installation
+        *
+        * @param string $url
+        * @return string
+        */
+       private static function getNomadVersion(string $url): string
+       {
+               $curlResult = DI::httpClient()->get($url . '/api/z/1.0/version', HttpClientAccept::JSON);
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
+                       return '';
+               }
+
+               $data = json_decode($curlResult->getBodyString(), true);
+               if (empty($data)) {
+                       return '';
+               }
+               return $data ?? '';
+       }
+
        /**
         * Checks if the server contains a valid host meta file
         *
@@ -1279,15 +1624,15 @@ class GServer
         *
         * @return boolean 'true' if the server seems to be vital
         */
-       private static function validHostMeta(string $url)
+       private static function validHostMeta(string $url): bool
        {
                $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
-               $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
+               $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
                if (!$curlResult->isSuccess()) {
                        return false;
                }
 
-               $xrd = XML::parseString($curlResult->getBody());
+               $xrd = XML::parseString($curlResult->getBodyString(), true);
                if (!is_object($xrd)) {
                        return false;
                }
@@ -1325,7 +1670,7 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectNetworkViaContacts(string $url, array $serverdata)
+       private static function detectNetworkViaContacts(string $url, array $serverdata): array
        {
                $contacts = [];
 
@@ -1377,7 +1722,7 @@ class GServer
         *
         * @return array server data
         */
-       private static function checkPoCo(string $url, array $serverdata)
+       private static function checkPoCo(string $url, array $serverdata): array
        {
                $serverdata['poco'] = '';
 
@@ -1386,7 +1731,7 @@ class GServer
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1409,14 +1754,14 @@ class GServer
         *
         * @return array server data
         */
-       public static function checkMastodonDirectory(string $url, array $serverdata)
+       public static function checkMastodonDirectory(string $url, array $serverdata): array
        {
                $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
                if (!$curlResult->isSuccess()) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1436,14 +1781,14 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectPeertube(string $url, array $serverdata)
+       private static function detectPeertube(string $url, array $serverdata): array
        {
                $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
-               if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1484,14 +1829,14 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta)
+       private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
        {
                $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
-               if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1512,13 +1857,22 @@ class GServer
                return $serverdata;
        }
 
-       private static function fetchWeeklyUsage(string $url, array $serverdata) {
+       /**
+        * Fetches weekly usage data
+        *
+        * @param string $url        URL of the given server
+        * @param array  $serverdata array with server data
+        *
+        * @return array server data
+        */
+       private static function fetchWeeklyUsage(string $url, array $serverdata): array
+       {
                $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
-               if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1551,14 +1905,14 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectMastodonAlikes(string $url, array $serverdata)
+       private static function detectMastodonAlikes(string $url, array $serverdata): array
        {
                $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
-               if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data)) {
                        return $serverdata;
                }
@@ -1623,14 +1977,14 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectHubzilla(string $url, array $serverdata)
+       private static function detectHubzilla(string $url, array $serverdata): array
        {
                $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
-               if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
+               if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) {
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data) || empty($data['site'])) {
                        return $serverdata;
                }
@@ -1700,7 +2054,7 @@ class GServer
         *
         * @return boolean
         */
-       private static function toBoolean($val)
+       private static function toBoolean($val): bool
        {
                if (($val == 'true') || ($val == 1)) {
                        return true;
@@ -1719,15 +2073,15 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectGNUSocial(string $url, array $serverdata)
+       private static function detectGNUSocial(string $url, array $serverdata): array
        {
                // Test for GNU Social
                $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
-               if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
-                       ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
+               if ($curlResult->isSuccess() && ($curlResult->getBodyString() != '{"error":"not implemented"}') &&
+                       ($curlResult->getBodyString() != '') && (strlen($curlResult->getBodyString()) < 30)) {
                        $serverdata['platform'] = 'gnusocial';
                        // Remove junk that some GNU Social servers return
-                       $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
+                       $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBodyString());
                        $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
                        $serverdata['version'] = trim($serverdata['version'], '"');
                        $serverdata['network'] = Protocol::OSTATUS;
@@ -1741,11 +2095,11 @@ class GServer
 
                // Test for Statusnet
                $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
-               if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
-                       ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
+               if ($curlResult->isSuccess() && ($curlResult->getBodyString() != '{"error":"not implemented"}') &&
+                       ($curlResult->getBodyString() != '') && (strlen($curlResult->getBodyString()) < 30)) {
 
                        // Remove junk that some GNU Social servers return
-                       $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
+                       $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBodyString());
                        $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
                        $serverdata['version'] = trim($serverdata['version'], '"');
 
@@ -1774,7 +2128,7 @@ class GServer
         *
         * @return array server data
         */
-       private static function detectFriendica(string $url, array $serverdata)
+       private static function detectFriendica(string $url, array $serverdata): array
        {
                // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
                // Because of this me must not use ACCEPT_JSON here.
@@ -1792,7 +2146,7 @@ class GServer
                        return $serverdata;
                }
 
-               $data = json_decode($curlResult->getBody(), true);
+               $data = json_decode($curlResult->getBodyString(), true);
                if (empty($data) || empty($data['version'])) {
                        return $serverdata;
                }
@@ -1849,16 +2203,16 @@ class GServer
         *
         * @return array server data
         */
-        private static function analyseRootBody($curlResult, array $serverdata)
+       private static function analyseRootBody($curlResult, array $serverdata): array
        {
                if (empty($curlResult->getBody())) {
                        return $serverdata;
                }
 
-               if (file_exists(__DIR__ . '/../../static/generator.config.php')) {
-                       require __DIR__ . '/../../static/generator.config.php';
+               if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
+                       require __DIR__ . '/../../static/platforms.config.php';
                } else {
-                       throw new HTTPException\InternalServerErrorException('Invalid generator file');
+                       throw new HTTPException\InternalServerErrorException('Invalid platform file');
                }
 
                $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
@@ -2008,7 +2362,7 @@ class GServer
         *
         * @return array server data
         */
-       private static function analyseRootHeader($curlResult, array $serverdata)
+       private static function analyseRootHeader($curlResult, array $serverdata): array
        {
                if ($curlResult->getHeader('server') == 'Mastodon') {
                        $serverdata['platform'] = 'mastodon';
@@ -2037,6 +2391,10 @@ class GServer
         */
        public static function discover()
        {
+               if (!DI::config('system', 'discover_servers')) {
+                       return;
+               }
+
                // Update the server list
                self::discoverFederation();
 
@@ -2044,25 +2402,21 @@ class GServer
 
                $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
 
-               if ($requery_days == 0) {
-                       $requery_days = 7;
-               }
-
                $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
 
                $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
-                       ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
+                       ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
                        ['order' => ['RAND()']]);
 
                while ($gserver = DBA::fetch($gservers)) {
                        Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
-                       Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
+                       Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
 
                        Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
-                       Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
+                       Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
 
                        $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
-                       DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
+                       self::update($fields, ['nurl' => $gserver['nurl']]);
 
                        if (--$no_of_queries == 0) {
                                break;
@@ -2077,7 +2431,7 @@ class GServer
         */
        private static function discoverFederation()
        {
-               $last = DI::config()->get('poco', 'last_federation_discovery');
+               $last = DI::keyValue()->get('poco_last_federation_discovery');
 
                if ($last) {
                        $next = $last + (24 * 60 * 60);
@@ -2103,23 +2457,25 @@ class GServer
                        }
                }
 
-               // Disvover Mastodon servers
+               // Discover Mastodon servers
                $accesstoken = DI::config()->get('system', 'instances_social_key');
 
                if (!empty($accesstoken)) {
                        $api = 'https://instances.social/api/1.0/instances/list?count=0';
                        $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
                        if ($curlResult->isSuccess()) {
-                               $servers = json_decode($curlResult->getBody(), true);
+                               $servers = json_decode($curlResult->getBodyString(), true);
 
-                               foreach ($servers['instances'] as $server) {
-                                       $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
-                                       self::add($url);
+                               if (!empty($servers['instances'])) {
+                                       foreach ($servers['instances'] as $server) {
+                                               $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
+                                               self::add($url);
+                                       }
                                }
                        }
                }
 
-               DI::config()->set('poco', 'last_federation_discovery', time());
+               DI::keyValue()->set('poco_last_federation_discovery', time());
        }
 
        /**
@@ -2127,7 +2483,7 @@ class GServer
         *
         * @param int $gsid     Server id
         * @param int $protocol Protocol id
-        * @return void
+        *
         * @throws Exception
         */
        public static function setProtocol(int $gsid, int $protocol)
@@ -2179,18 +2535,20 @@ class GServer
                        }
                }
 
-               Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
-               DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
+               Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]);
+               self::update(['protocol' => $protocol], ['id' => $gsid]);
        }
 
        /**
         * Fetch the protocol of the given server
         *
         * @param int $gsid Server id
-        * @return int
+        *
+        * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
+        *
         * @throws Exception
         */
-       public static function getProtocol(int $gsid)
+       public static function getProtocol(int $gsid): ?int
        {
                if (empty($gsid)) {
                        return null;
@@ -2203,4 +2561,40 @@ class GServer
 
                return null;
        }
+
+       /**
+        * Update rows in the gserver table.
+        * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
+        *
+        * @param array $fields
+        * @param array $condition
+        *
+        * @return bool
+        *
+        * @throws Exception
+        */
+       public static function update(array $fields, array $condition): bool
+       {
+               $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
+
+               return DBA::update('gserver', $fields, $condition);
+       }
+
+       /**
+        * Insert a row into the gserver table.
+        * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
+        *
+        * @param array $fields
+        * @param int   $duplicate_mode What to do on a duplicated entry
+        *
+        * @return bool
+        *
+        * @throws Exception
+        */
+       public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
+       {
+               $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
+
+               return DBA::insert('gserver', $fields, $duplicate_mode);
+       }
 }