3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
33 use Friendica\Database\DBStructure;
35 use Friendica\Module\Register;
36 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
37 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
38 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
39 use Friendica\Network\Probe;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Relay;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\Network;
45 use Friendica\Util\Strings;
46 use Friendica\Util\XML;
47 use Friendica\Network\HTTPException;
48 use GuzzleHttp\Psr7\Uri;
51 * This class handles GServer related functions
58 const DT_MASTODON = 2;
60 // Methods to detect server types
62 // Non endpoint specific methods
63 const DETECT_MANUAL = 0;
64 const DETECT_HEADER = 1;
65 const DETECT_BODY = 2;
66 const DETECT_HOST_META = 3;
67 const DETECT_CONTACTS = 4;
68 const DETECT_AP_ACTOR = 5;
69 const DETECT_AP_COLLECTION = 6;
71 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
73 // Implementation specific endpoints
74 const DETECT_FRIENDIKA = 10;
75 const DETECT_FRIENDICA = 11;
76 const DETECT_STATUSNET = 12;
77 const DETECT_GNUSOCIAL = 13;
78 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
79 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
80 const DETECT_MASTODON_API = 16;
81 const DETECT_STATUS_PHP = 17; // Nextcloud
82 const DETECT_V1_CONFIG = 18;
83 const DETECT_PUMPIO = 19; // Deprecated
84 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
86 // Standardized endpoints
87 const DETECT_STATISTICS_JSON = 100;
88 const DETECT_NODEINFO_1 = 101;
89 const DETECT_NODEINFO_2 = 102;
90 const DETECT_NODEINFO_210 = 103;
93 * Check for the existance of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
99 public static function add(string $url, bool $only_nodeinfo = false)
101 if (self::getID($url, false)) {
105 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
109 * Get the ID for the given server URL
112 * @param boolean $no_check Don't check if the server hadn't been found
113 * @return int gserver id
115 public static function getID(string $url, bool $no_check = false)
121 $url = self::cleanURL($url);
123 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
124 if (DBA::isResult($gserver)) {
125 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
126 return $gserver['id'];
129 if ($no_check || !self::check($url)) {
133 return self::getID($url, true);
137 * Retrieves all the servers which base domain are matching the provided domain pattern
139 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
141 * @param string $pattern
145 public static function listByDomainPattern(string $pattern): array
147 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
149 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
150 // eventual server path and keep only the server domain which we're matching against the pattern.
151 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
153 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
154 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
155 AND NOT `gserver`.`failed`
156 GROUP BY `gserver`.`id`";
158 $stmt = DI::dba()->p($sql, $likePattern);
160 return DI::dba()->toArray($stmt);
164 * Checks if the given server is reachable
166 * @param string $profile URL of the given profile
167 * @param string $server URL of the given server (If empty, taken from profile)
168 * @param string $network Network value that is used, when detection failed
169 * @param boolean $force Force an update.
171 * @return boolean 'true' if server seems vital
173 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
176 $contact = Contact::getByURL($profile, null, ['baseurl']);
177 if (!empty($contact['baseurl'])) {
178 $server = $contact['baseurl'];
186 return self::check($server, $network, $force);
189 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false)
191 // On successful contact process check again next week when it is a detected system.
192 // When we haven't detected the system, it could be a static website or a really old system.
194 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
197 $now = strtotime(DateTimeFormat::utcNow());
199 if ($created > $last_contact) {
200 $contact_time = strtotime($created);
202 $contact_time = strtotime($last_contact);
205 // If the last contact was less than 6 hours before then try again in 6 hours
206 if (($now - $contact_time) < (60 * 60 * 6)) {
207 return DateTimeFormat::utc('now +6 hour');
210 // If the last contact was less than 12 hours before then try again in 12 hours
211 if (($now - $contact_time) < (60 * 60 * 12)) {
212 return DateTimeFormat::utc('now +12 hour');
215 // If the last contact was less than 24 hours before then try tomorrow again
216 if (($now - $contact_time) < (60 * 60 * 24)) {
217 return DateTimeFormat::utc('now +1 day');
220 // If the last contact was less than a week before then try again in a week
221 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
222 return DateTimeFormat::utc('now +1 week');
225 // If the last contact was less than two weeks before then try again in two week
226 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
227 return DateTimeFormat::utc('now +2 week');
230 // If the last contact was less than a month before then try again in a month
231 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
232 return DateTimeFormat::utc('now +1 month');
235 // The system hadn't been successul contacted for more than a month, so try again in three months
236 return DateTimeFormat::utc('now +3 month');
240 * Checks the state of the given server.
242 * @param string $server_url URL of the given server
243 * @param string $network Network value that is used, when detection failed
244 * @param boolean $force Force an update.
245 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
247 * @return boolean 'true' if server seems vital
249 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
251 $server_url = self::cleanURL($server_url);
252 if ($server_url == '') {
256 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
257 if (DBA::isResult($gserver)) {
258 if ($gserver['created'] <= DBA::NULL_DATETIME) {
259 $fields = ['created' => DateTimeFormat::utcNow()];
260 $condition = ['nurl' => Strings::normaliseLink($server_url)];
261 DBA::update('gserver', $fields, $condition);
264 if (!$force && (strtotime($gserver['next_contact']) > time())) {
265 Logger::info('No update needed', ['server' => $server_url]);
266 return (!$gserver['failed']);
268 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
270 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
273 return self::detect($server_url, $network, $only_nodeinfo);
277 * Set failed server status
281 public static function setFailure(string $url)
283 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
284 if (DBA::isResult($gserver)) {
285 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
286 DBA::update('gserver', ['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
287 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
288 ['nurl' => Strings::normaliseLink($url)]);
289 Logger::info('Set failed status for existing server', ['url' => $url]);
292 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
293 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
294 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
295 Logger::info('Set failed status for new server', ['url' => $url]);
299 * Remove unwanted content from the given URL
302 * @return string cleaned URL
304 public static function cleanURL(string $url)
306 $url = trim($url, '/');
307 $url = str_replace('/index.php', '', $url);
309 $urlparts = parse_url($url);
310 unset($urlparts['user']);
311 unset($urlparts['pass']);
312 unset($urlparts['query']);
313 unset($urlparts['fragment']);
314 return (string)Uri::fromParts($urlparts);
318 * Detect server data (type, protocol, version number, ...)
319 * The detected data is then updated or inserted in the gserver table.
321 * @param string $url URL of the given server
322 * @param string $network Network value that is used, when detection failed
323 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
325 * @return boolean 'true' if server could be detected
327 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
329 Logger::info('Detect server type', ['server' => $url]);
331 $original_url = $url;
333 // Remove URL content that is not supposed to exist for a server url
334 $url = rtrim(self::cleanURL($url), '/');
336 Logger::notice('Empty URL.');
340 // If the URL missmatches, then we mark the old entry as failure
341 if (!Strings::compareLink($url, $original_url)) {
342 self::setFailure($original_url);
343 if (!self::getID($url, true)) {
344 self::detect($url, $network, $only_nodeinfo);
349 $valid_url = Network::isUrlValid($url);
351 self::setFailure($url);
354 $valid_url = rtrim($valid_url, '/');
357 if (!Strings::compareLink($url, $valid_url)) {
358 // We only follow redirects when the path stays the same or the target url has no path.
359 // Some systems have got redirects on their landing page to a single account page. This check handles it.
360 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))) ||
361 (((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)))) {
362 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
363 self::setFailure($url);
364 if (!self::getID($valid_url, true)) {
365 self::detect($valid_url, $network, $only_nodeinfo);
370 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)) &&
371 (parse_url($url, PHP_URL_PATH) == '')) {
372 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
373 $parts = parse_url($valid_url);
374 unset($parts['path']);
375 $valid_url = (string)Uri::fromParts($parts);
377 self::setFailure($url);
378 if (!self::getID($valid_url, true)) {
379 self::detect($valid_url, $network, $only_nodeinfo);
383 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
386 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
387 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
388 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
392 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
394 // When a nodeinfo is present, we don't need to dig further
395 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
396 if ($curlResult->isTimeout()) {
397 self::setFailure($url);
401 $serverdata = self::parseNodeinfo210($curlResult);
402 if (empty($serverdata)) {
403 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
404 $serverdata = self::fetchNodeinfo($url, $curlResult);
407 if ($only_nodeinfo && empty($serverdata)) {
408 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
409 self::setFailure($url);
411 } elseif (empty($serverdata)) {
412 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
415 // When there is no Nodeinfo, then use some protocol specific endpoints
416 if ($serverdata['network'] == Protocol::PHANTOM) {
418 // Fetch the landing page, possibly it reveals some data
419 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
420 $curlResult = DI::httpClient()->get($url, $accept);
421 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
422 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
423 $html_fetched = true;
425 $html_fetched = false;
428 if ($curlResult->isSuccess()) {
429 $json = json_decode($curlResult->getBody(), true);
430 if (!empty($json) && is_array($json)) {
431 $data = self::fetchDataFromSystemActor($json, $serverdata);
432 $serverdata = $data['server'];
433 $systemactor = $data['actor'];
434 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
435 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
437 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
438 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
441 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
442 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
443 $serverdata = self::analyseRootBody($curlResult, $serverdata);
447 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
448 self::setFailure($url);
452 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
453 $serverdata = self::detectMastodonAlikes($url, $serverdata);
457 // All following checks are done for systems that always have got a "host-meta" endpoint.
458 // With this check we don't have to waste time and ressources for dead systems.
459 // Also this hopefully prevents us from receiving abuse messages.
460 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
461 $validHostMeta = self::validHostMeta($url);
463 $validHostMeta = false;
466 if ($validHostMeta) {
467 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
468 $serverdata['detection-method'] = self::DETECT_HOST_META;
471 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
472 $serverdata = self::detectFriendica($url, $serverdata);
475 // The following systems have to be installed in the root directory.
477 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
478 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
479 $serverdata = self::fetchSiteinfo($url, $serverdata);
482 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
483 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
484 $serverdata = self::detectHubzilla($url, $serverdata);
487 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
488 $serverdata = self::detectPeertube($url, $serverdata);
491 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
492 $serverdata = self::detectGNUSocial($url, $serverdata);
495 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
496 $serverdata = self::detectFriendica($url, $serverdata);
499 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
500 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
503 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
504 // Since this endpoint is only rarely used, we query it at a later time
505 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
506 $serverdata = self::fetchStatistics($url, $serverdata);
510 // When we hadn't been able to detect the network type, we use the hint from the parameter
511 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
512 $serverdata['network'] = $network;
515 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
516 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
517 self::setFailure($url);
521 $serverdata['url'] = $url;
522 $serverdata['nurl'] = Strings::normaliseLink($url);
524 // We have to prevent an endless loop here.
525 // When a server is new, then there is no gserver entry yet.
526 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
527 // and this can call this function here as well.
528 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
529 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
530 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
533 // Detect the directory type
534 $serverdata['directory-type'] = self::DT_NONE;
536 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
537 $serverdata = self::checkMastodonDirectory($url, $serverdata);
539 if ($serverdata['directory-type'] == self::DT_NONE) {
540 $serverdata = self::checkPoCo($url, $serverdata);
544 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
545 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
548 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
550 // On an active server there has to be at least a single user
551 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
552 $serverdata['registered-users'] = 1;
553 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
554 $serverdata['registered-users'] = 0;
557 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
559 $serverdata['last_contact'] = DateTimeFormat::utcNow();
560 $serverdata['failed'] = false;
562 // Limit the length on incoming fields
563 $serverdata = DBStructure::getFieldsForTable('gserver', $serverdata);
565 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
566 if (!DBA::isResult($gserver)) {
567 $serverdata['created'] = DateTimeFormat::utcNow();
568 $ret = DBA::insert('gserver', $serverdata);
569 $id = DBA::lastInsertId();
571 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
572 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
573 if (DBA::isResult($gserver)) {
574 $id = $gserver['id'];
578 // Count the number of known contacts from this server
579 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
580 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
581 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
582 $max_users = max($apcontacts, $contacts);
583 if ($max_users > $serverdata['registered-users']) {
584 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
585 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
588 if (empty($serverdata['active-month-users'])) {
589 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
591 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
592 DBA::update('gserver', ['active-month-users' => $contacts], ['id' => $id]);
596 if (empty($serverdata['active-halfyear-users'])) {
597 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
599 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
600 DBA::update('gserver', ['active-halfyear-users' => $contacts], ['id' => $id]);
605 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
606 self::discoverRelay($url);
609 if (!empty($systemactor)) {
610 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
611 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
618 * Fetch relay data from a given server url
620 * @param string $server_url address of the server
621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
623 private static function discoverRelay(string $server_url)
625 Logger::info('Discover relay data', ['server' => $server_url]);
627 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
628 if (!$curlResult->isSuccess()) {
632 $data = json_decode($curlResult->getBody(), true);
633 if (!is_array($data)) {
637 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
638 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
640 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
642 $data['subscribe'] = false;
646 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
647 if (!DBA::isResult($gserver)) {
651 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
652 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
653 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
656 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
658 if ($data['scope'] == 'tags') {
661 foreach ($data['tags'] as $tag) {
662 $tag = mb_strtolower($tag);
663 if (strlen($tag) < 100) {
668 foreach ($tags as $tag) {
669 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
673 // Create or update the relay contact
675 if (isset($data['protocols'])) {
676 if (isset($data['protocols']['diaspora'])) {
677 $fields['network'] = Protocol::DIASPORA;
679 if (isset($data['protocols']['diaspora']['receive'])) {
680 $fields['batch'] = $data['protocols']['diaspora']['receive'];
681 } elseif (is_string($data['protocols']['diaspora'])) {
682 $fields['batch'] = $data['protocols']['diaspora'];
686 if (isset($data['protocols']['dfrn'])) {
687 $fields['network'] = Protocol::DFRN;
689 if (isset($data['protocols']['dfrn']['receive'])) {
690 $fields['batch'] = $data['protocols']['dfrn']['receive'];
691 } elseif (is_string($data['protocols']['dfrn'])) {
692 $fields['batch'] = $data['protocols']['dfrn'];
696 if (isset($data['protocols']['activitypub'])) {
697 $fields['network'] = Protocol::ACTIVITYPUB;
699 if (!empty($data['protocols']['activitypub']['actor'])) {
700 $fields['url'] = $data['protocols']['activitypub']['actor'];
702 if (!empty($data['protocols']['activitypub']['receive'])) {
703 $fields['batch'] = $data['protocols']['activitypub']['receive'];
708 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
710 Relay::updateContact($gserver, $fields);
714 * Fetch server data from '/statistics.json' on the given server
716 * @param string $url URL of the given server
718 * @return array server data
720 private static function fetchStatistics(string $url, array $serverdata)
722 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
723 if (!$curlResult->isSuccess()) {
727 $data = json_decode($curlResult->getBody(), true);
732 // Some AP enabled systems return activity data that we don't expect here.
733 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
738 $old_serverdata = $serverdata;
740 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
742 if (!empty($data['version'])) {
744 $serverdata['version'] = $data['version'];
745 // Version numbers on statistics.json are presented with additional info, e.g.:
746 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
747 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
750 if (!empty($data['name'])) {
752 $serverdata['site_name'] = $data['name'];
755 if (!empty($data['network'])) {
757 $serverdata['platform'] = strtolower($data['network']);
759 if ($serverdata['platform'] == 'diaspora') {
760 $serverdata['network'] = Protocol::DIASPORA;
761 } elseif ($serverdata['platform'] == 'friendica') {
762 $serverdata['network'] = Protocol::DFRN;
763 } elseif ($serverdata['platform'] == 'hubzilla') {
764 $serverdata['network'] = Protocol::ZOT;
765 } elseif ($serverdata['platform'] == 'redmatrix') {
766 $serverdata['network'] = Protocol::ZOT;
770 if (!empty($data['total_users'])) {
772 $serverdata['registered-users'] = max($data['total_users'], 1);
775 if (!empty($data['active_users_monthly'])) {
777 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
780 if (!empty($data['active_users_halfyear'])) {
782 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
785 if (!empty($data['local_posts'])) {
787 $serverdata['local-posts'] = max($data['local_posts'], 0);
790 if (!empty($data['registrations_open'])) {
791 $serverdata['register_policy'] = Register::OPEN;
793 $serverdata['register_policy'] = Register::CLOSED;
797 return $old_serverdata;
804 * Detect server type by using the nodeinfo data
806 * @param string $url address of the server
807 * @param ICanHandleHttpResponses $httpResult
809 * @return array Server data
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
814 if (!$httpResult->isSuccess()) {
818 $nodeinfo = json_decode($httpResult->getBody(), true);
820 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
827 foreach ($nodeinfo['links'] as $link) {
828 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
829 Logger::info('Invalid nodeinfo format', ['url' => $url]);
832 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
833 $nodeinfo1_url = $link['href'];
834 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
835 $nodeinfo2_url = $link['href'];
839 if ($nodeinfo1_url . $nodeinfo2_url == '') {
845 if (!empty($nodeinfo2_url)) {
846 $server = self::parseNodeinfo2($nodeinfo2_url);
849 if (empty($server) && !empty($nodeinfo1_url)) {
850 $server = self::parseNodeinfo1($nodeinfo1_url);
859 * @param string $nodeinfo_url address of the nodeinfo path
860 * @return array Server data
861 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
863 private static function parseNodeinfo1(string $nodeinfo_url)
865 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
866 if (!$curlResult->isSuccess()) {
870 $nodeinfo = json_decode($curlResult->getBody(), true);
872 if (!is_array($nodeinfo)) {
876 $server = ['detection-method' => self::DETECT_NODEINFO_1,
877 'register_policy' => Register::CLOSED];
879 if (!empty($nodeinfo['openRegistrations'])) {
880 $server['register_policy'] = Register::OPEN;
883 if (is_array($nodeinfo['software'])) {
884 if (!empty($nodeinfo['software']['name'])) {
885 $server['platform'] = strtolower($nodeinfo['software']['name']);
888 if (!empty($nodeinfo['software']['version'])) {
889 $server['version'] = $nodeinfo['software']['version'];
890 // Version numbers on Nodeinfo are presented with additional info, e.g.:
891 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
892 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
896 if (!empty($nodeinfo['metadata']['nodeName'])) {
897 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
900 if (!empty($nodeinfo['usage']['users']['total'])) {
901 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
904 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
905 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
908 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
909 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
912 if (!empty($nodeinfo['usage']['localPosts'])) {
913 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
916 if (!empty($nodeinfo['usage']['localComments'])) {
917 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
920 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
922 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
923 $protocols[$protocol] = true;
926 if (!empty($protocols['friendica'])) {
927 $server['network'] = Protocol::DFRN;
928 } elseif (!empty($protocols['activitypub'])) {
929 $server['network'] = Protocol::ACTIVITYPUB;
930 } elseif (!empty($protocols['diaspora'])) {
931 $server['network'] = Protocol::DIASPORA;
932 } elseif (!empty($protocols['ostatus'])) {
933 $server['network'] = Protocol::OSTATUS;
934 } elseif (!empty($protocols['gnusocial'])) {
935 $server['network'] = Protocol::OSTATUS;
936 } elseif (!empty($protocols['zot'])) {
937 $server['network'] = Protocol::ZOT;
941 if (empty($server)) {
945 if (empty($server['network'])) {
946 $server['network'] = Protocol::PHANTOM;
955 * @see https://git.feneas.org/jaywink/nodeinfo2
956 * @param string $nodeinfo_url address of the nodeinfo path
957 * @return array Server data
958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
960 private static function parseNodeinfo2(string $nodeinfo_url)
962 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
963 if (!$curlResult->isSuccess()) {
967 $nodeinfo = json_decode($curlResult->getBody(), true);
968 if (!is_array($nodeinfo)) {
972 $server = ['detection-method' => self::DETECT_NODEINFO_2,
973 'register_policy' => Register::CLOSED];
975 if (!empty($nodeinfo['openRegistrations'])) {
976 $server['register_policy'] = Register::OPEN;
979 if (!empty($nodeinfo['software'])) {
980 if (isset($nodeinfo['software']['name'])) {
981 $server['platform'] = strtolower($nodeinfo['software']['name']);
984 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
985 $server['version'] = $nodeinfo['software']['version'];
986 // Version numbers on Nodeinfo are presented with additional info, e.g.:
987 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
988 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
990 // qoto advertises itself as Mastodon
991 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
992 $server['platform'] = 'qoto';
997 if (!empty($nodeinfo['metadata']['nodeName'])) {
998 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1001 if (!empty($nodeinfo['usage']['users']['total'])) {
1002 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1005 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1006 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1009 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1010 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1013 if (!empty($nodeinfo['usage']['localPosts'])) {
1014 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1017 if (!empty($nodeinfo['usage']['localComments'])) {
1018 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1021 if (!empty($nodeinfo['protocols'])) {
1023 foreach ($nodeinfo['protocols'] as $protocol) {
1024 if (is_string($protocol)) {
1025 $protocols[$protocol] = true;
1029 if (!empty($protocols['dfrn'])) {
1030 $server['network'] = Protocol::DFRN;
1031 } elseif (!empty($protocols['activitypub'])) {
1032 $server['network'] = Protocol::ACTIVITYPUB;
1033 } elseif (!empty($protocols['diaspora'])) {
1034 $server['network'] = Protocol::DIASPORA;
1035 } elseif (!empty($protocols['ostatus'])) {
1036 $server['network'] = Protocol::OSTATUS;
1037 } elseif (!empty($protocols['gnusocial'])) {
1038 $server['network'] = Protocol::OSTATUS;
1039 } elseif (!empty($protocols['zot'])) {
1040 $server['network'] = Protocol::ZOT;
1044 if (empty($server)) {
1048 if (empty($server['network'])) {
1049 $server['network'] = Protocol::PHANTOM;
1056 * Parses NodeInfo2 protocol 1.0
1058 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1059 * @param string $nodeinfo_url address of the nodeinfo path
1060 * @return array Server data
1061 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1063 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult)
1065 if (!$httpResult->isSuccess()) {
1069 $nodeinfo = json_decode($httpResult->getBody(), true);
1071 if (!is_array($nodeinfo)) {
1075 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1076 'register_policy' => Register::CLOSED];
1078 if (!empty($nodeinfo['openRegistrations'])) {
1079 $server['register_policy'] = Register::OPEN;
1082 if (!empty($nodeinfo['server'])) {
1083 if (!empty($nodeinfo['server']['software'])) {
1084 $server['platform'] = strtolower($nodeinfo['server']['software']);
1087 if (!empty($nodeinfo['server']['version'])) {
1088 $server['version'] = $nodeinfo['server']['version'];
1089 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1090 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1091 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1094 if (!empty($nodeinfo['server']['name'])) {
1095 $server['site_name'] = $nodeinfo['server']['name'];
1099 if (!empty($nodeinfo['usage']['users']['total'])) {
1100 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1103 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1104 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1107 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1108 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1111 if (!empty($nodeinfo['usage']['localPosts'])) {
1112 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1115 if (!empty($nodeinfo['usage']['localComments'])) {
1116 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1119 if (!empty($nodeinfo['protocols'])) {
1121 foreach ($nodeinfo['protocols'] as $protocol) {
1122 if (is_string($protocol)) {
1123 $protocols[$protocol] = true;
1127 if (!empty($protocols['dfrn'])) {
1128 $server['network'] = Protocol::DFRN;
1129 } elseif (!empty($protocols['activitypub'])) {
1130 $server['network'] = Protocol::ACTIVITYPUB;
1131 } elseif (!empty($protocols['diaspora'])) {
1132 $server['network'] = Protocol::DIASPORA;
1133 } elseif (!empty($protocols['ostatus'])) {
1134 $server['network'] = Protocol::OSTATUS;
1135 } elseif (!empty($protocols['gnusocial'])) {
1136 $server['network'] = Protocol::OSTATUS;
1137 } elseif (!empty($protocols['zot'])) {
1138 $server['network'] = Protocol::ZOT;
1142 if (empty($server) || empty($server['platform'])) {
1146 if (empty($server['network'])) {
1147 $server['network'] = Protocol::PHANTOM;
1154 * Fetch server information from a 'siteinfo.json' file on the given server
1156 * @param string $url URL of the given server
1157 * @param array $serverdata array with server data
1159 * @return array server data
1161 private static function fetchSiteinfo(string $url, array $serverdata)
1163 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1164 if (!$curlResult->isSuccess()) {
1168 $data = json_decode($curlResult->getBody(), true);
1173 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1174 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1177 if (!empty($data['url'])) {
1178 $serverdata['platform'] = strtolower($data['platform']);
1179 $serverdata['version'] = $data['version'];
1182 if (!empty($data['plugins'])) {
1183 if (in_array('pubcrawl', $data['plugins'])) {
1184 $serverdata['network'] = Protocol::ACTIVITYPUB;
1185 } elseif (in_array('diaspora', $data['plugins'])) {
1186 $serverdata['network'] = Protocol::DIASPORA;
1187 } elseif (in_array('gnusoc', $data['plugins'])) {
1188 $serverdata['network'] = Protocol::OSTATUS;
1190 $serverdata['network'] = Protocol::ZOT;
1194 if (!empty($data['site_name'])) {
1195 $serverdata['site_name'] = $data['site_name'];
1198 if (!empty($data['channels_total'])) {
1199 $serverdata['registered-users'] = max($data['channels_total'], 1);
1202 if (!empty($data['channels_active_monthly'])) {
1203 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1206 if (!empty($data['channels_active_halfyear'])) {
1207 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1210 if (!empty($data['local_posts'])) {
1211 $serverdata['local-posts'] = max($data['local_posts'], 0);
1214 if (!empty($data['local_comments'])) {
1215 $serverdata['local-comments'] = max($data['local_comments'], 0);
1218 if (!empty($data['register_policy'])) {
1219 switch ($data['register_policy']) {
1220 case 'REGISTER_OPEN':
1221 $serverdata['register_policy'] = Register::OPEN;
1224 case 'REGISTER_APPROVE':
1225 $serverdata['register_policy'] = Register::APPROVE;
1228 case 'REGISTER_CLOSED':
1230 $serverdata['register_policy'] = Register::CLOSED;
1238 private static function fetchDataFromSystemActor(array $data, array $serverdata)
1241 return ['server' => $serverdata, 'actor' => ''];
1244 $actor = JsonLD::compact($data, false);
1245 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1246 $serverdata['network'] = Protocol::ACTIVITYPUB;
1247 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1248 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1249 if (!empty($actor['as:generator'])) {
1250 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1251 $serverdata['platform'] = strtolower(array_shift($generator));
1252 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1254 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1256 return ['server' => $serverdata, 'actor' => $actor['@id']];
1257 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1258 // By now only Ktistec seems to provide collections this way
1259 $serverdata['platform'] = 'ktistec';
1260 $serverdata['network'] = Protocol::ACTIVITYPUB;
1261 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1263 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1264 if (!empty($actors) && !empty($actors[0]['@id'])) {
1265 $actor_url = $actor['@id'] . $actors[0]['@id'];
1270 return ['server' => $serverdata, 'actor' => $actor_url];
1272 return ['server' => $serverdata, 'actor' => ''];
1276 * Checks if the server contains a valid host meta file
1278 * @param string $url URL of the given server
1280 * @return boolean 'true' if the server seems to be vital
1282 private static function validHostMeta(string $url)
1284 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1285 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1286 if (!$curlResult->isSuccess()) {
1290 $xrd = XML::parseString($curlResult->getBody());
1291 if (!is_object($xrd)) {
1295 $elements = XML::elementToArray($xrd);
1296 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1301 foreach ($elements['xrd']['link'] as $link) {
1302 // When there is more than a single "link" element, the array looks slightly different
1303 if (!empty($link['@attributes'])) {
1304 $link = $link['@attributes'];
1307 if (empty($link['rel']) || empty($link['template'])) {
1311 if ($link['rel'] == 'lrdd') {
1312 // When the webfinger host is the same like the system host, it should be ok.
1313 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1321 * Detect the network of the given server via their known contacts
1323 * @param string $url URL of the given server
1324 * @param array $serverdata array with server data
1326 * @return array server data
1328 private static function detectNetworkViaContacts(string $url, array $serverdata)
1332 $nurl = Strings::normaliseLink($url);
1334 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1335 while ($apcontact = DBA::fetch($apcontacts)) {
1336 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1338 DBA::close($apcontacts);
1340 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1341 while ($pcontact = DBA::fetch($pcontacts)) {
1342 $contacts[$pcontact['nurl']] = $pcontact['url'];
1344 DBA::close($pcontacts);
1346 if (empty($contacts)) {
1351 foreach ($contacts as $contact) {
1352 // Endlosschleife verhindern wegen gsid!
1353 $data = Probe::uri($contact);
1354 if (in_array($data['network'], Protocol::FEDERATED)) {
1355 $serverdata['network'] = $data['network'];
1357 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1358 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1361 } elseif ((time() - $time) > 10) {
1362 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1371 * Checks if the given server does have a '/poco' endpoint.
1372 * This is used for the 'PortableContact' functionality,
1373 * which is used by both Friendica and Hubzilla.
1375 * @param string $url URL of the given server
1376 * @param array $serverdata array with server data
1378 * @return array server data
1380 private static function checkPoCo(string $url, array $serverdata)
1382 $serverdata['poco'] = '';
1384 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1385 if (!$curlResult->isSuccess()) {
1389 $data = json_decode($curlResult->getBody(), true);
1394 if (!empty($data['totalResults'])) {
1395 $registeredUsers = $serverdata['registered-users'] ?? 0;
1396 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1397 $serverdata['directory-type'] = self::DT_POCO;
1398 $serverdata['poco'] = $url . '/poco';
1405 * Checks if the given server does have a Mastodon style directory endpoint.
1407 * @param string $url URL of the given server
1408 * @param array $serverdata array with server data
1410 * @return array server data
1412 public static function checkMastodonDirectory(string $url, array $serverdata)
1414 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1415 if (!$curlResult->isSuccess()) {
1419 $data = json_decode($curlResult->getBody(), true);
1424 if (count($data) == 1) {
1425 $serverdata['directory-type'] = self::DT_MASTODON;
1432 * Detects Peertube via their known endpoint
1434 * @param string $url URL of the given server
1435 * @param array $serverdata array with server data
1437 * @return array server data
1439 private static function detectPeertube(string $url, array $serverdata)
1441 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1442 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1446 $data = json_decode($curlResult->getBody(), true);
1451 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1452 $serverdata['platform'] = 'peertube';
1453 $serverdata['version'] = $data['serverVersion'];
1454 $serverdata['network'] = Protocol::ACTIVITYPUB;
1456 if (!empty($data['instance']['name'])) {
1457 $serverdata['site_name'] = $data['instance']['name'];
1460 if (!empty($data['instance']['shortDescription'])) {
1461 $serverdata['info'] = $data['instance']['shortDescription'];
1464 if (!empty($data['signup'])) {
1465 if (!empty($data['signup']['allowed'])) {
1466 $serverdata['register_policy'] = Register::OPEN;
1470 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1471 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1479 * Detects the version number of a given server when it was a NextCloud installation
1481 * @param string $url URL of the given server
1482 * @param array $serverdata array with server data
1483 * @param bool $validHostMeta
1485 * @return array server data
1487 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta)
1489 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1490 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1494 $data = json_decode($curlResult->getBody(), true);
1499 if (!empty($data['version'])) {
1500 $serverdata['platform'] = 'nextcloud';
1501 $serverdata['version'] = $data['version'];
1503 if ($validHostMeta) {
1504 $serverdata['network'] = Protocol::ACTIVITYPUB;
1507 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1508 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1515 private static function fetchWeeklyUsage(string $url, array $serverdata) {
1516 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1517 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1521 $data = json_decode($curlResult->getBody(), true);
1527 foreach ($data as $week) {
1528 // Use only data from a full week
1529 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1533 // Most likely the data is sorted correctly. But we better are safe than sorry
1534 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1535 $current_week = $week;
1539 if (!empty($current_week['logins'])) {
1540 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1547 * Detects data from a given server url if it was a mastodon alike system
1549 * @param string $url URL of the given server
1550 * @param array $serverdata array with server data
1552 * @return array server data
1554 private static function detectMastodonAlikes(string $url, array $serverdata)
1556 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1557 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1561 $data = json_decode($curlResult->getBody(), true);
1568 if (!empty($data['version'])) {
1569 $serverdata['platform'] = 'mastodon';
1570 $serverdata['version'] = $data['version'] ?? '';
1571 $serverdata['network'] = Protocol::ACTIVITYPUB;
1575 if (!empty($data['title'])) {
1576 $serverdata['site_name'] = $data['title'];
1579 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1580 $serverdata['platform'] = 'mastodon';
1581 $serverdata['network'] = Protocol::ACTIVITYPUB;
1585 if (!empty($data['description'])) {
1586 $serverdata['info'] = trim($data['description']);
1589 if (!empty($data['stats']['user_count'])) {
1590 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1593 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1594 $serverdata['platform'] = strtolower($matches[1]);
1595 $serverdata['version'] = $matches[2];
1599 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1600 $serverdata['platform'] = 'pleroma';
1601 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1605 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1606 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1607 $serverdata['platform'] = 'pleroma';
1611 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1612 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1619 * Detects data from typical Hubzilla endpoints
1621 * @param string $url URL of the given server
1622 * @param array $serverdata array with server data
1624 * @return array server data
1626 private static function detectHubzilla(string $url, array $serverdata)
1628 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1629 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1633 $data = json_decode($curlResult->getBody(), true);
1634 if (empty($data) || empty($data['site'])) {
1638 if (!empty($data['site']['name'])) {
1639 $serverdata['site_name'] = $data['site']['name'];
1642 if (!empty($data['site']['platform'])) {
1643 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1644 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1645 $serverdata['network'] = Protocol::ZOT;
1648 if (!empty($data['site']['hubzilla'])) {
1649 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1650 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1651 $serverdata['network'] = Protocol::ZOT;
1654 if (!empty($data['site']['redmatrix'])) {
1655 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1656 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1657 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1658 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1661 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1662 $serverdata['network'] = Protocol::ZOT;
1666 $inviteonly = false;
1669 if (!empty($data['site']['closed'])) {
1670 $closed = self::toBoolean($data['site']['closed']);
1673 if (!empty($data['site']['private'])) {
1674 $private = self::toBoolean($data['site']['private']);
1677 if (!empty($data['site']['inviteonly'])) {
1678 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1681 if (!$closed && !$private and $inviteonly) {
1682 $serverdata['register_policy'] = Register::APPROVE;
1683 } elseif (!$closed && !$private) {
1684 $serverdata['register_policy'] = Register::OPEN;
1686 $serverdata['register_policy'] = Register::CLOSED;
1689 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1690 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1697 * Converts input value to a boolean value
1699 * @param string|integer $val
1703 private static function toBoolean($val)
1705 if (($val == 'true') || ($val == 1)) {
1707 } elseif (($val == 'false') || ($val == 0)) {
1715 * Detect if the URL belongs to a GNU Social server
1717 * @param string $url URL of the given server
1718 * @param array $serverdata array with server data
1720 * @return array server data
1722 private static function detectGNUSocial(string $url, array $serverdata)
1724 // Test for GNU Social
1725 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1726 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1727 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1728 $serverdata['platform'] = 'gnusocial';
1729 // Remove junk that some GNU Social servers return
1730 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1731 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1732 $serverdata['version'] = trim($serverdata['version'], '"');
1733 $serverdata['network'] = Protocol::OSTATUS;
1735 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1736 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1742 // Test for Statusnet
1743 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1744 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1745 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1747 // Remove junk that some GNU Social servers return
1748 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1749 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1750 $serverdata['version'] = trim($serverdata['version'], '"');
1752 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1753 $serverdata['platform'] = 'pleroma';
1754 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1755 $serverdata['network'] = Protocol::ACTIVITYPUB;
1757 $serverdata['platform'] = 'statusnet';
1758 $serverdata['network'] = Protocol::OSTATUS;
1761 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1762 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1770 * Detect if the URL belongs to a Friendica server
1772 * @param string $url URL of the given server
1773 * @param array $serverdata array with server data
1775 * @return array server data
1777 private static function detectFriendica(string $url, array $serverdata)
1779 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1780 // Because of this me must not use ACCEPT_JSON here.
1781 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1782 if (!$curlResult->isSuccess()) {
1783 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1785 $platform = 'Friendika';
1788 $platform = 'Friendica';
1791 if (!$curlResult->isSuccess()) {
1795 $data = json_decode($curlResult->getBody(), true);
1796 if (empty($data) || empty($data['version'])) {
1800 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1801 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1804 $serverdata['network'] = Protocol::DFRN;
1805 $serverdata['version'] = $data['version'];
1807 if (!empty($data['no_scrape_url'])) {
1808 $serverdata['noscrape'] = $data['no_scrape_url'];
1811 if (!empty($data['site_name'])) {
1812 $serverdata['site_name'] = $data['site_name'];
1815 if (!empty($data['info'])) {
1816 $serverdata['info'] = trim($data['info']);
1819 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1820 switch ($register_policy) {
1821 case 'REGISTER_OPEN':
1822 $serverdata['register_policy'] = Register::OPEN;
1825 case 'REGISTER_APPROVE':
1826 $serverdata['register_policy'] = Register::APPROVE;
1829 case 'REGISTER_CLOSED':
1830 case 'REGISTER_INVITATION':
1831 $serverdata['register_policy'] = Register::CLOSED;
1834 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1835 $serverdata['register_policy'] = Register::CLOSED;
1839 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1845 * Analyses the landing page of a given server for hints about type and system of that server
1847 * @param object $curlResult result of curl execution
1848 * @param array $serverdata array with server data
1850 * @return array server data
1852 private static function analyseRootBody($curlResult, array $serverdata)
1854 if (empty($curlResult->getBody())) {
1858 if (file_exists(__DIR__ . '/../../static/generator.config.php')) {
1859 require __DIR__ . '/../../static/generator.config.php';
1861 throw new HTTPException\InternalServerErrorException('Invalid generator file');
1864 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1866 $doc = new DOMDocument();
1867 @$doc->loadHTML($curlResult->getBody());
1868 $xpath = new DOMXPath($doc);
1871 // We can only detect honk via some HTML element on their page
1872 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1873 $serverdata['platform'] = 'honk';
1874 $serverdata['network'] = Protocol::ACTIVITYPUB;
1878 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1879 if (!empty($title)) {
1880 $serverdata['site_name'] = $title;
1883 $list = $xpath->query('//meta[@name]');
1885 foreach ($list as $node) {
1887 if ($node->attributes->length) {
1888 foreach ($node->attributes as $attribute) {
1889 $value = trim($attribute->value);
1890 if (empty($value)) {
1894 $attr[$attribute->name] = $value;
1897 if (empty($attr['name']) || empty($attr['content'])) {
1902 if ($attr['name'] == 'description') {
1903 $serverdata['info'] = $attr['content'];
1906 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1907 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
1908 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
1909 $platform = str_replace('/', ' ', $platform);
1910 $platform_parts = explode(' ', $platform);
1911 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
1912 $platform = $platform_parts[0];
1913 $serverdata['version'] = $platform_parts[1];
1915 if (in_array($platform, array_values($dfrn_platforms))) {
1916 $serverdata['network'] = Protocol::DFRN;
1917 } elseif (in_array($platform, array_values($ap_platforms))) {
1918 $serverdata['network'] = Protocol::ACTIVITYPUB;
1919 } elseif (in_array($platform, array_values($zap_platforms))) {
1920 $serverdata['network'] = Protocol::ZOT;
1922 if (in_array($platform, array_values($platforms))) {
1923 $serverdata['platform'] = $platform;
1929 $list = $xpath->query('//meta[@property]');
1931 foreach ($list as $node) {
1933 if ($node->attributes->length) {
1934 foreach ($node->attributes as $attribute) {
1935 $value = trim($attribute->value);
1936 if (empty($value)) {
1940 $attr[$attribute->name] = $value;
1943 if (empty($attr['property']) || empty($attr['content'])) {
1948 if ($attr['property'] == 'og:site_name') {
1949 $serverdata['site_name'] = $attr['content'];
1952 if ($attr['property'] == 'og:description') {
1953 $serverdata['info'] = $attr['content'];
1956 if (in_array($attr['property'], ['og:platform', 'generator'])) {
1957 if (in_array($attr['content'], array_keys($platforms))) {
1958 $serverdata['platform'] = $platforms[$attr['content']];
1962 if (in_array($attr['content'], array_keys($ap_platforms))) {
1963 $serverdata['network'] = Protocol::ACTIVITYPUB;
1964 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
1965 $serverdata['network'] = Protocol::ZOT;
1970 $list = $xpath->query('//link[@rel="me"]');
1971 foreach ($list as $node) {
1972 foreach ($node->attributes as $attribute) {
1973 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
1974 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
1975 $serverdata['platform'] = 'microblog';
1976 $serverdata['network'] = Protocol::ACTIVITYPUB;
1982 if ($serverdata['platform'] != 'microblog') {
1983 $list = $xpath->query('//link[@rel="micropub"]');
1984 foreach ($list as $node) {
1985 foreach ($node->attributes as $attribute) {
1986 if (trim($attribute->value) == 'https://micro.blog/micropub') {
1987 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
1988 $serverdata['platform'] = 'microblog';
1989 $serverdata['network'] = Protocol::ACTIVITYPUB;
1996 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
1997 $serverdata['detection-method'] = self::DETECT_BODY;
2004 * Analyses the header data of a given server for hints about type and system of that server
2006 * @param object $curlResult result of curl execution
2007 * @param array $serverdata array with server data
2009 * @return array server data
2011 private static function analyseRootHeader($curlResult, array $serverdata)
2013 if ($curlResult->getHeader('server') == 'Mastodon') {
2014 $serverdata['platform'] = 'mastodon';
2015 $serverdata['network'] = Protocol::ACTIVITYPUB;
2016 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2017 $serverdata['platform'] = 'diaspora';
2018 $serverdata['network'] = Protocol::DIASPORA;
2019 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2020 } elseif ($curlResult->inHeader('x-friendica-version')) {
2021 $serverdata['platform'] = 'friendica';
2022 $serverdata['network'] = Protocol::DFRN;
2023 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2028 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2029 $serverdata['detection-method'] = self::DETECT_HEADER;
2036 * Update GServer entries
2038 public static function discover()
2040 // Update the server list
2041 self::discoverFederation();
2045 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2047 if ($requery_days == 0) {
2051 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2053 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2054 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2055 ['order' => ['RAND()']]);
2057 while ($gserver = DBA::fetch($gservers)) {
2058 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2059 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2061 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2062 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2064 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2065 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
2067 if (--$no_of_queries == 0) {
2072 DBA::close($gservers);
2076 * Discover federated servers
2078 private static function discoverFederation()
2080 $last = DI::config()->get('poco', 'last_federation_discovery');
2083 $next = $last + (24 * 60 * 60);
2085 if ($next > time()) {
2090 // Discover federated servers
2091 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2092 foreach ($protocols as $protocol) {
2093 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2094 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2095 if (!empty($curlResult)) {
2096 $data = json_decode($curlResult, true);
2097 if (!empty($data['data']['nodes'])) {
2098 foreach ($data['data']['nodes'] as $server) {
2099 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2100 self::add('https://' . $server['host'], true);
2106 // Disvover Mastodon servers
2107 $accesstoken = DI::config()->get('system', 'instances_social_key');
2109 if (!empty($accesstoken)) {
2110 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2111 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2112 if ($curlResult->isSuccess()) {
2113 $servers = json_decode($curlResult->getBody(), true);
2115 foreach ($servers['instances'] as $server) {
2116 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2122 DI::config()->set('poco', 'last_federation_discovery', time());
2126 * Set the protocol for the given server
2128 * @param int $gsid Server id
2129 * @param int $protocol Protocol id
2133 public static function setProtocol(int $gsid, int $protocol)
2139 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2140 if (!DBA::isResult($gserver)) {
2144 $old = $gserver['protocol'];
2146 if (!is_null($old)) {
2148 The priority for the protocols is:
2150 2. DFRN via Diaspora
2156 // We don't need to change it when nothing is to be changed
2157 if ($old == $protocol) {
2161 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2162 if ($protocol == Post\DeliveryData::OSTATUS) {
2166 // If the server is marked as ActivityPub then we won't change it to anything different
2167 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2171 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2172 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2176 // Don't change it to Diaspora when it is a legacy DFRN server
2177 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2182 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2183 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
2187 * Fetch the protocol of the given server
2189 * @param int $gsid Server id
2193 public static function getProtocol(int $gsid)
2199 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2200 if (DBA::isResult($gserver)) {
2201 return $gserver['protocol'];