]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/GServer.php
Merge pull request #12063 from Quix0r/fixes/type-hints-reformatting
[friendica.git] / src / Model / GServer.php
index d04186240c929d9ae9f418cbf8eb434fff97d493..1b39bae9eeadb9e1f8832d2f54140c1197247169 100644 (file)
@@ -30,7 +30,6 @@ 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;
@@ -44,8 +43,8 @@ use Friendica\Util\JsonLD;
 use Friendica\Util\Network;
 use Friendica\Util\Strings;
 use Friendica\Util\XML;
-use GuzzleHttp\Exception\TransferException;
 use Friendica\Network\HTTPException;
+use GuzzleHttp\Psr7\Uri;
 
 /**
  * This class handles GServer related functions
@@ -94,6 +93,7 @@ class GServer
         *
         * @param string $url
         * @param boolean $only_nodeinfo
+        *
         * @return void
         */
        public static function add(string $url, bool $only_nodeinfo = false)
@@ -102,7 +102,7 @@ class GServer
                        return;
                }
 
-               Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
+               Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
        }
 
        /**
@@ -110,9 +110,10 @@ 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
        {
                if (empty($url)) {
                        return null;
@@ -139,7 +140,9 @@ class GServer
         * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
         *
         * @param string $pattern
+        *
         * @return array
+        *
         * @throws Exception
         */
        public static function listByDomainPattern(string $pattern): array
@@ -170,7 +173,7 @@ class GServer
         *
         * @return boolean 'true' if server seems vital
         */
-       public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
+       public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false): bool
        {
                if ($server == '') {
                        $contact = Contact::getByURL($profile, null, ['baseurl']);
@@ -186,11 +189,24 @@ class GServer
                return self::check($server, $network, $force);
        }
 
-       public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
+       /**
+        * 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
+               // 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.
                if ($success) {
-                       return DateTimeFormat::utc('now +7 day');
+                       return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
                }
 
                $now = strtotime(DateTimeFormat::utcNow());
@@ -245,7 +261,7 @@ 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 == '') {
@@ -257,7 +273,7 @@ class 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())) {
@@ -282,13 +298,13 @@ class GServer
                $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
                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, 'last_failure' => DateTimeFormat::utcNow(),
                        'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
                        ['nurl' => Strings::normaliseLink($url)]);
                        Logger::info('Set failed status for existing server', ['url' => $url]);
                        return;
                }
-               DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
+               self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
                        'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
                        'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
                Logger::info('Set failed status for new server', ['url' => $url]);
@@ -298,9 +314,10 @@ class GServer
         * Remove unwanted content from the given URL
         *
         * @param string $url
+        *
         * @return string cleaned URL
         */
-       public static function cleanURL(string $url)
+       public static function cleanURL(string $url): string
        {
                $url = trim($url, '/');
                $url = str_replace('/index.php', '', $url);
@@ -310,7 +327,7 @@ class GServer
                unset($urlparts['pass']);
                unset($urlparts['query']);
                unset($urlparts['fragment']);
-               return Network::unparseURL($urlparts);
+               return (string)Uri::fromParts($urlparts);
        }
 
        /**
@@ -323,7 +340,7 @@ class GServer
         *
         * @return boolean 'true' if server could be detected
         */
-       public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
+       public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
        {
                Logger::info('Detect server type', ['server' => $url]);
 
@@ -331,45 +348,61 @@ class GServer
 
                // Remove URL content that is not supposed to exist for a server url
                $url = rtrim(self::cleanURL($url), '/');
-               if (!Network::isUrlValid($url)) {
-                       self::setFailure($url);
+               if (empty($url)) {
+                       Logger::notice('Empty URL.');
                        return false;
                }
 
                // If the URL missmatches, then we mark the old entry as failure
-               if (Strings::normaliseLink($url) != Strings::normaliseLink($original_url)) {
+               if (!Strings::compareLink($url, $original_url)) {
                        self::setFailure($original_url);
-                       self::detect($url, $network, $only_nodeinfo);
+                       if (!self::getID($url, true)) {
+                               self::detect($url, $network, $only_nodeinfo);
+                       }
                        return false;
                }
 
-               // On a redirect follow the new host but mark the old one as failure
-               try {
-                       $finalurl = rtrim(DI::httpClient()->finalUrl($url), '/');
-               } catch (TransferException $exception) {
-                       Logger::notice('Error fetching final URL.', ['url' => $url, 'exception' => $exception]);
+               $valid_url = Network::isUrlValid($url);
+               if (!$valid_url) {
                        self::setFailure($url);
                        return false;
-               }
+               } else {
+                       $valid_url = rtrim($valid_url, '/');
+               }
+
+               if (!Strings::compareLink($url, $valid_url)) {
+                       // We only follow redirects when the path stays the same or the target url has no path.
+                       // Some systems have got redirects on their landing page to a single account page. This check handles it.
+                       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::detect($valid_url, $network, $only_nodeinfo);
+                               }
+                               return false;
+                       }
 
-               // We only follow redirects when the path stays the same or the target url has no path.
-               // Some systems have got redirects on their landing page to a single account page. This check handles it.
-               if (((parse_url($url, PHP_URL_HOST) != parse_url($finalurl, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) == parse_url($finalurl, PHP_URL_PATH))) ||
-                       (((parse_url($url, PHP_URL_HOST) != parse_url($finalurl, PHP_URL_HOST)) || (parse_url($url, PHP_URL_PATH) != parse_url($finalurl, PHP_URL_PATH))) && empty(parse_url($finalurl, PHP_URL_PATH)))) {
-                       Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $finalurl]);
-                       self::setFailure($url);
-                       self::detect($finalurl, $network, $only_nodeinfo);
-                       return false;
-               }
+                       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);
+                               unset($parts['path']);
+                               $valid_url = (string)Uri::fromParts($parts);
 
-               if ((parse_url($url, PHP_URL_HOST) == parse_url($finalurl, PHP_URL_HOST)) &&
-                       (parse_url($url, PHP_URL_PATH) == parse_url($finalurl, PHP_URL_PATH)) &&
-                       (parse_url($url, PHP_URL_SCHEME) != parse_url($finalurl, PHP_URL_SCHEME))) {
-                       if (!Network::isUrlValid($finalurl)) {
-                               self::setFailure($finalurl);
+                               self::setFailure($url);
+                               if (!self::getID($valid_url, true)) {
+                                       self::detect($valid_url, $network, $only_nodeinfo);
+                               }
                                return false;
                        }
-                       $url = $finalurl;
+                       Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
+               }
+
+               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_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
+                       $url = $valid_url;
                }
 
                $in_webroot = empty(parse_url($url, PHP_URL_PATH));
@@ -410,11 +443,11 @@ class GServer
 
                                if ($curlResult->isSuccess()) {
                                        $json = json_decode($curlResult->getBody(), true);
-                                       if (!empty($json)) {
+                                       if (!empty($json) && is_array($json)) {
                                                $data = self::fetchDataFromSystemActor($json, $serverdata);
                                                $serverdata = $data['server'];
                                                $systemactor = $data['actor'];
-                                               if (!$html_fetched && ($serverdata['detection-method'] == self::DETECT_AP_ACTOR)) {
+                                               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)) {
@@ -447,9 +480,8 @@ class GServer
                        }
 
                        if ($validHostMeta) {
-                               if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
+                               if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
                                        $serverdata['detection-method'] = self::DETECT_HOST_META;
-                                       $serverdata['platform']         = '';
                                }
 
                                if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
@@ -476,6 +508,8 @@ class GServer
                                                $serverdata = self::detectGNUSocial($url, $serverdata);
                                        }
                                }
+                       } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
+                               $serverdata = self::detectFriendica($url, $serverdata);
                        }
 
                        if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
@@ -507,7 +541,8 @@ class GServer
                // When a server is new, then there is no gserver entry yet.
                // But in "detectNetworkViaContacts" it could happen that a contact is updated,
                // and this can call this function here as well.
-               if (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && self::getID($url, true)) {
+               if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
+                       in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
                        $serverdata = self::detectNetworkViaContacts($url, $serverdata);
                }
 
@@ -528,28 +563,30 @@ class GServer
 
                $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
 
+               // 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);
+               $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);
-
                $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'];
@@ -563,14 +600,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]);
                                }
                        }
 
@@ -578,7 +615,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]);
                                }
                        }
                }
@@ -599,6 +636,9 @@ 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)
@@ -631,7 +671,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']]);
@@ -698,7 +738,7 @@ 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()) {
@@ -788,9 +828,10 @@ 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 [];
@@ -838,10 +879,12 @@ 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()) {
@@ -934,11 +977,14 @@ 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()) {
@@ -950,8 +996,11 @@ class GServer
                        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;
@@ -1037,11 +1086,14 @@ 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
+        *
         * @return array Server data
+        *
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult)
+       private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
        {
                if (!$httpResult->isSuccess()) {
                        return [];
@@ -1139,7 +1191,7 @@ 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()) {
@@ -1216,19 +1268,30 @@ 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' => ''];
                }
 
-               $actor = JsonLD::compact($data);
+               $actor = JsonLD::compact($data, false);
                if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
                        $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'])) {
-                               $serverdata['platform'] = JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value');
+                               $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
+                               $serverdata['platform'] = strtolower(array_shift($generator));
                                $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
                        } else {
                                $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
@@ -1259,15 +1322,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->getBody(), true);
                if (!is_object($xrd)) {
                        return false;
                }
@@ -1305,7 +1368,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 = [];
 
@@ -1357,7 +1420,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'] = '';
 
@@ -1389,7 +1452,7 @@ 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()) {
@@ -1416,7 +1479,7 @@ 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() == '')) {
@@ -1464,7 +1527,7 @@ 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() == '')) {
@@ -1492,7 +1555,16 @@ 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() == '')) {
                        return $serverdata;
@@ -1531,7 +1603,7 @@ 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() == '')) {
@@ -1603,7 +1675,7 @@ 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() == '')) {
@@ -1680,7 +1752,7 @@ class GServer
         *
         * @return boolean
         */
-       private static function toBoolean($val)
+       private static function toBoolean($val): bool
        {
                if (($val == 'true') || ($val == 1)) {
                        return true;
@@ -1699,7 +1771,7 @@ 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);
@@ -1754,7 +1826,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.
@@ -1829,29 +1901,30 @@ 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);
-               $valid_platforms = array_values($platforms);
 
                $doc = new DOMDocument();
                @$doc->loadHTML($curlResult->getBody());
                $xpath = new DOMXPath($doc);
+               $assigned = false;
 
                // We can only detect honk via some HTML element on their page
                if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
                        $serverdata['platform'] = 'honk';
                        $serverdata['network'] = Protocol::ACTIVITYPUB;
+                       $assigned = true;
                }
 
                $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
@@ -1884,27 +1957,23 @@ class GServer
 
                        if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
                                'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
-                               $platform = str_replace(array_keys($platforms), array_values($platforms), $attr['content']);
-                               $platform = strtolower(str_replace('/', ' ', $platform));
-                               $version_part = explode(' ', $platform);
-
-                               if (count($version_part) >= 2) {
-                                       if (in_array($version_part[0], array_values($dfrn_platforms))) {
-                                               $serverdata['network'] = Protocol::DFRN;
-                                       } elseif (in_array($version_part[0], array_values($ap_platforms))) {
-                                               $serverdata['network'] = Protocol::ACTIVITYPUB;
-                                       } elseif (in_array($version_part[0], array_values($zap_platforms))) {
-                                               $serverdata['network'] = Protocol::ZOT;
-                                       }
-                                       if (in_array(strtolower($version_part[0]), $valid_platforms)) {
-                                               $platform = strtolower($version_part[0]);
-                                               $serverdata['version'] = $version_part[1];
-                                       }
+                               $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
+                               $platform = str_replace('/', ' ', $platform);
+                               $platform_parts = explode(' ', $platform);
+                               if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
+                                       $platform = $platform_parts[0];
+                                       $serverdata['version'] = $platform_parts[1];
+                               }
+                               if (in_array($platform, array_values($dfrn_platforms))) {
+                                       $serverdata['network'] = Protocol::DFRN;
+                               } elseif (in_array($platform, array_values($ap_platforms))) {
+                                       $serverdata['network'] = Protocol::ACTIVITYPUB;
+                               } elseif (in_array($platform, array_values($zap_platforms))) {
+                                       $serverdata['network'] = Protocol::ZOT;
                                }
                                if (in_array($platform, array_values($platforms))) {
                                        $serverdata['platform'] = $platform;
-                               } elseif (empty($serverdata['platform'])) {
-                                       print_r($attr);
+                                       $assigned = true;
                                }
                        }
                }
@@ -1939,8 +2008,7 @@ class GServer
                        if (in_array($attr['property'], ['og:platform', 'generator'])) {
                                if (in_array($attr['content'], array_keys($platforms))) {
                                        $serverdata['platform'] = $platforms[$attr['content']];
-                               } else {
-                                       print_r($attr);
+                                       $assigned = true;
                                }
 
                                if (in_array($attr['content'], array_keys($ap_platforms))) {
@@ -1951,7 +2019,33 @@ class GServer
                        }
                }
 
-               if (in_array($serverdata['platform'], $valid_platforms) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
+               $list = $xpath->query('//link[@rel="me"]');
+               foreach ($list as $node) {
+                       foreach ($node->attributes as $attribute) {
+                               if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
+                                       $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
+                                       $serverdata['platform'] = 'microblog';
+                                       $serverdata['network'] = Protocol::ACTIVITYPUB;
+                                       $assigned = true;
+                               }
+                       }
+               }
+
+               if ($serverdata['platform'] != 'microblog') {
+                       $list = $xpath->query('//link[@rel="micropub"]');
+                       foreach ($list as $node) {
+                               foreach ($node->attributes as $attribute) {
+                                       if (trim($attribute->value) == 'https://micro.blog/micropub') {
+                                               $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
+                                               $serverdata['platform'] = 'microblog';
+                                               $serverdata['network'] = Protocol::ACTIVITYPUB;
+                                               $assigned = true;
+                                       }
+                               }
+                       }
+               }
+
+               if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
                        $serverdata['detection-method'] = self::DETECT_BODY;
                }
 
@@ -1966,7 +2060,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';
@@ -2014,13 +2108,13 @@ class GServer
 
                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;
@@ -2070,9 +2164,11 @@ class GServer
                        if ($curlResult->isSuccess()) {
                                $servers = json_decode($curlResult->getBody(), 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);
+                                       }       
                                }
                        }
                }
@@ -2085,7 +2181,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)
@@ -2138,17 +2234,19 @@ 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]);
+               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;
@@ -2161,4 +2259,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);
+       }
 }