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;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Relay;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
46 use Friendica\Network\HTTPException;
47 use GuzzleHttp\Psr7\Uri;
50 * This class handles GServer related functions
57 const DT_MASTODON = 2;
59 // Methods to detect server types
61 // Non endpoint specific methods
62 const DETECT_MANUAL = 0;
63 const DETECT_HEADER = 1;
64 const DETECT_BODY = 2;
65 const DETECT_HOST_META = 3;
66 const DETECT_CONTACTS = 4;
67 const DETECT_AP_ACTOR = 5;
68 const DETECT_AP_COLLECTION = 6;
70 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
72 // Implementation specific endpoints
73 const DETECT_FRIENDIKA = 10;
74 const DETECT_FRIENDICA = 11;
75 const DETECT_STATUSNET = 12;
76 const DETECT_GNUSOCIAL = 13;
77 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
78 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
79 const DETECT_MASTODON_API = 16;
80 const DETECT_STATUS_PHP = 17; // Nextcloud
81 const DETECT_V1_CONFIG = 18;
82 const DETECT_PUMPIO = 19; // Deprecated
83 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
85 // Standardized endpoints
86 const DETECT_STATISTICS_JSON = 100;
87 const DETECT_NODEINFO_1 = 101;
88 const DETECT_NODEINFO_2 = 102;
89 const DETECT_NODEINFO_210 = 103;
92 * Check for the existance of a server and adds it in the background if not existant
95 * @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
114 * @return int|null gserver id or NULL on empty URL or failed check
116 public static function getID(string $url, bool $no_check = false): ?int
122 $url = self::cleanURL($url);
124 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
125 if (DBA::isResult($gserver)) {
126 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
127 return $gserver['id'];
130 if ($no_check || !self::check($url)) {
134 return self::getID($url, true);
138 * Retrieves all the servers which base domain are matching the provided domain pattern
140 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
142 * @param string $pattern
148 public static function listByDomainPattern(string $pattern): array
150 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
152 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
153 // eventual server path and keep only the server domain which we're matching against the pattern.
154 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
156 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
157 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
158 AND NOT `gserver`.`failed`
159 GROUP BY `gserver`.`id`";
161 $stmt = DI::dba()->p($sql, $likePattern);
163 return DI::dba()->toArray($stmt);
167 * Checks if the given server is reachable
169 * @param string $profile URL of the given profile
170 * @param string $server URL of the given server (If empty, taken from profile)
171 * @param string $network Network value that is used, when detection failed
172 * @param boolean $force Force an update.
174 * @return boolean 'true' if server seems vital
176 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false): bool
179 $contact = Contact::getByURL($profile, null, ['baseurl']);
180 if (!empty($contact['baseurl'])) {
181 $server = $contact['baseurl'];
189 return self::check($server, $network, $force);
193 * Calculate the next update day
195 * @param bool $success
196 * @param string $created
197 * @param string $last_contact
198 * @param bool $undetected
204 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
206 // On successful contact process check again next week when it is a detected system.
207 // When we haven't detected the system, it could be a static website or a really old system.
209 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
212 $now = strtotime(DateTimeFormat::utcNow());
214 if ($created > $last_contact) {
215 $contact_time = strtotime($created);
217 $contact_time = strtotime($last_contact);
220 // If the last contact was less than 6 hours before then try again in 6 hours
221 if (($now - $contact_time) < (60 * 60 * 6)) {
222 return DateTimeFormat::utc('now +6 hour');
225 // If the last contact was less than 12 hours before then try again in 12 hours
226 if (($now - $contact_time) < (60 * 60 * 12)) {
227 return DateTimeFormat::utc('now +12 hour');
230 // If the last contact was less than 24 hours before then try tomorrow again
231 if (($now - $contact_time) < (60 * 60 * 24)) {
232 return DateTimeFormat::utc('now +1 day');
235 // If the last contact was less than a week before then try again in a week
236 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
237 return DateTimeFormat::utc('now +1 week');
240 // If the last contact was less than two weeks before then try again in two week
241 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
242 return DateTimeFormat::utc('now +2 week');
245 // If the last contact was less than a month before then try again in a month
246 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
247 return DateTimeFormat::utc('now +1 month');
250 // The system hadn't been successul contacted for more than a month, so try again in three months
251 return DateTimeFormat::utc('now +3 month');
255 * Checks the state of the given server.
257 * @param string $server_url URL of the given server
258 * @param string $network Network value that is used, when detection failed
259 * @param boolean $force Force an update.
260 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
262 * @return boolean 'true' if server seems vital
264 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
266 $server_url = self::cleanURL($server_url);
267 if ($server_url == '') {
271 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
272 if (DBA::isResult($gserver)) {
273 if ($gserver['created'] <= DBA::NULL_DATETIME) {
274 $fields = ['created' => DateTimeFormat::utcNow()];
275 $condition = ['nurl' => Strings::normaliseLink($server_url)];
276 self::update($fields, $condition);
279 if (!$force && (strtotime($gserver['next_contact']) > time())) {
280 Logger::info('No update needed', ['server' => $server_url]);
281 return (!$gserver['failed']);
283 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
285 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
288 return self::detect($server_url, $network, $only_nodeinfo);
292 * Set failed server status
296 public static function setFailure(string $url)
298 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
299 if (DBA::isResult($gserver)) {
300 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
301 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
302 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
303 ['nurl' => Strings::normaliseLink($url)]);
304 Logger::info('Set failed status for existing server', ['url' => $url]);
307 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
308 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
309 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
310 Logger::info('Set failed status for new server', ['url' => $url]);
314 * Remove unwanted content from the given URL
318 * @return string cleaned URL
320 public static function cleanURL(string $url): string
322 $url = trim($url, '/');
323 $url = str_replace('/index.php', '', $url);
325 $urlparts = parse_url($url);
326 unset($urlparts['user']);
327 unset($urlparts['pass']);
328 unset($urlparts['query']);
329 unset($urlparts['fragment']);
330 return (string)Uri::fromParts($urlparts);
334 * Detect server data (type, protocol, version number, ...)
335 * The detected data is then updated or inserted in the gserver table.
337 * @param string $url URL of the given server
338 * @param string $network Network value that is used, when detection failed
339 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
341 * @return boolean 'true' if server could be detected
343 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
345 Logger::info('Detect server type', ['server' => $url]);
347 $original_url = $url;
349 // Remove URL content that is not supposed to exist for a server url
350 $url = rtrim(self::cleanURL($url), '/');
352 Logger::notice('Empty URL.');
356 // If the URL missmatches, then we mark the old entry as failure
357 if (!Strings::compareLink($url, $original_url)) {
358 self::setFailure($original_url);
359 if (!self::getID($url, true)) {
360 self::detect($url, $network, $only_nodeinfo);
365 $valid_url = Network::isUrlValid($url);
367 self::setFailure($url);
370 $valid_url = rtrim($valid_url, '/');
373 if (!Strings::compareLink($url, $valid_url)) {
374 // We only follow redirects when the path stays the same or the target url has no path.
375 // Some systems have got redirects on their landing page to a single account page. This check handles it.
376 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))) ||
377 (((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)))) {
378 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
379 self::setFailure($url);
380 if (!self::getID($valid_url, true)) {
381 self::detect($valid_url, $network, $only_nodeinfo);
386 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)) &&
387 (parse_url($url, PHP_URL_PATH) == '')) {
388 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
389 $parts = parse_url($valid_url);
390 unset($parts['path']);
391 $valid_url = (string)Uri::fromParts($parts);
393 self::setFailure($url);
394 if (!self::getID($valid_url, true)) {
395 self::detect($valid_url, $network, $only_nodeinfo);
399 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
402 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
403 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
404 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
408 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
410 // When a nodeinfo is present, we don't need to dig further
411 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
412 if ($curlResult->isTimeout()) {
413 self::setFailure($url);
417 $serverdata = self::parseNodeinfo210($curlResult);
418 if (empty($serverdata)) {
419 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
420 $serverdata = self::fetchNodeinfo($url, $curlResult);
423 if ($only_nodeinfo && empty($serverdata)) {
424 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
425 self::setFailure($url);
427 } elseif (empty($serverdata)) {
428 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
431 // When there is no Nodeinfo, then use some protocol specific endpoints
432 if ($serverdata['network'] == Protocol::PHANTOM) {
434 // Fetch the landing page, possibly it reveals some data
435 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
436 $curlResult = DI::httpClient()->get($url, $accept);
437 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
438 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
439 $html_fetched = true;
441 $html_fetched = false;
444 if ($curlResult->isSuccess()) {
445 $json = json_decode($curlResult->getBody(), true);
446 if (!empty($json) && is_array($json)) {
447 $data = self::fetchDataFromSystemActor($json, $serverdata);
448 $serverdata = $data['server'];
449 $systemactor = $data['actor'];
450 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
451 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
453 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
454 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
457 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
458 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
459 $serverdata = self::analyseRootBody($curlResult, $serverdata);
463 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
464 self::setFailure($url);
468 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
469 $serverdata = self::detectMastodonAlikes($url, $serverdata);
473 // All following checks are done for systems that always have got a "host-meta" endpoint.
474 // With this check we don't have to waste time and ressources for dead systems.
475 // Also this hopefully prevents us from receiving abuse messages.
476 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
477 $validHostMeta = self::validHostMeta($url);
479 $validHostMeta = false;
482 if ($validHostMeta) {
483 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
484 $serverdata['detection-method'] = self::DETECT_HOST_META;
487 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
488 $serverdata = self::detectFriendica($url, $serverdata);
491 // The following systems have to be installed in the root directory.
493 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
494 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
495 $serverdata = self::fetchSiteinfo($url, $serverdata);
498 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
499 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
500 $serverdata = self::detectHubzilla($url, $serverdata);
503 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
504 $serverdata = self::detectPeertube($url, $serverdata);
507 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
508 $serverdata = self::detectGNUSocial($url, $serverdata);
511 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
512 $serverdata = self::detectFriendica($url, $serverdata);
515 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
516 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
519 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
520 // Since this endpoint is only rarely used, we query it at a later time
521 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
522 $serverdata = self::fetchStatistics($url, $serverdata);
526 // When we hadn't been able to detect the network type, we use the hint from the parameter
527 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
528 $serverdata['network'] = $network;
531 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
532 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
533 self::setFailure($url);
537 $serverdata['url'] = $url;
538 $serverdata['nurl'] = Strings::normaliseLink($url);
540 // We have to prevent an endless loop here.
541 // When a server is new, then there is no gserver entry yet.
542 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
543 // and this can call this function here as well.
544 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
545 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
546 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
549 // Detect the directory type
550 $serverdata['directory-type'] = self::DT_NONE;
552 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
553 $serverdata = self::checkMastodonDirectory($url, $serverdata);
555 if ($serverdata['directory-type'] == self::DT_NONE) {
556 $serverdata = self::checkPoCo($url, $serverdata);
560 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
561 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
564 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
566 // On an active server there has to be at least a single user
567 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
568 $serverdata['registered-users'] = 1;
569 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
570 $serverdata['registered-users'] = 0;
573 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
575 $serverdata['last_contact'] = DateTimeFormat::utcNow();
576 $serverdata['failed'] = false;
578 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
579 if (!DBA::isResult($gserver)) {
580 $serverdata['created'] = DateTimeFormat::utcNow();
581 $ret = DBA::insert('gserver', $serverdata);
582 $id = DBA::lastInsertId();
584 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
585 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
586 if (DBA::isResult($gserver)) {
587 $id = $gserver['id'];
591 // Count the number of known contacts from this server
592 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
593 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
594 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
595 $max_users = max($apcontacts, $contacts);
596 if ($max_users > $serverdata['registered-users']) {
597 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
598 self::update(['registered-users' => $max_users], ['id' => $id]);
601 if (empty($serverdata['active-month-users'])) {
602 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
604 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
605 self::update(['active-month-users' => $contacts], ['id' => $id]);
609 if (empty($serverdata['active-halfyear-users'])) {
610 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
612 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
613 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
618 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
619 self::discoverRelay($url);
622 if (!empty($systemactor)) {
623 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
624 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
631 * Fetch relay data from a given server url
633 * @param string $server_url address of the server
637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
639 private static function discoverRelay(string $server_url)
641 Logger::info('Discover relay data', ['server' => $server_url]);
643 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
644 if (!$curlResult->isSuccess()) {
648 $data = json_decode($curlResult->getBody(), true);
649 if (!is_array($data)) {
653 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
654 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
656 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
658 $data['subscribe'] = false;
662 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
663 if (!DBA::isResult($gserver)) {
667 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
668 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
669 self::update($fields, ['id' => $gserver['id']]);
672 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
674 if ($data['scope'] == 'tags') {
677 foreach ($data['tags'] as $tag) {
678 $tag = mb_strtolower($tag);
679 if (strlen($tag) < 100) {
684 foreach ($tags as $tag) {
685 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
689 // Create or update the relay contact
691 if (isset($data['protocols'])) {
692 if (isset($data['protocols']['diaspora'])) {
693 $fields['network'] = Protocol::DIASPORA;
695 if (isset($data['protocols']['diaspora']['receive'])) {
696 $fields['batch'] = $data['protocols']['diaspora']['receive'];
697 } elseif (is_string($data['protocols']['diaspora'])) {
698 $fields['batch'] = $data['protocols']['diaspora'];
702 if (isset($data['protocols']['dfrn'])) {
703 $fields['network'] = Protocol::DFRN;
705 if (isset($data['protocols']['dfrn']['receive'])) {
706 $fields['batch'] = $data['protocols']['dfrn']['receive'];
707 } elseif (is_string($data['protocols']['dfrn'])) {
708 $fields['batch'] = $data['protocols']['dfrn'];
712 if (isset($data['protocols']['activitypub'])) {
713 $fields['network'] = Protocol::ACTIVITYPUB;
715 if (!empty($data['protocols']['activitypub']['actor'])) {
716 $fields['url'] = $data['protocols']['activitypub']['actor'];
718 if (!empty($data['protocols']['activitypub']['receive'])) {
719 $fields['batch'] = $data['protocols']['activitypub']['receive'];
724 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
726 Relay::updateContact($gserver, $fields);
730 * Fetch server data from '/statistics.json' on the given server
732 * @param string $url URL of the given server
734 * @return array server data
736 private static function fetchStatistics(string $url, array $serverdata): array
738 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
739 if (!$curlResult->isSuccess()) {
743 $data = json_decode($curlResult->getBody(), true);
748 // Some AP enabled systems return activity data that we don't expect here.
749 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
754 $old_serverdata = $serverdata;
756 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
758 if (!empty($data['version'])) {
760 $serverdata['version'] = $data['version'];
761 // Version numbers on statistics.json are presented with additional info, e.g.:
762 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
763 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
766 if (!empty($data['name'])) {
768 $serverdata['site_name'] = $data['name'];
771 if (!empty($data['network'])) {
773 $serverdata['platform'] = strtolower($data['network']);
775 if ($serverdata['platform'] == 'diaspora') {
776 $serverdata['network'] = Protocol::DIASPORA;
777 } elseif ($serverdata['platform'] == 'friendica') {
778 $serverdata['network'] = Protocol::DFRN;
779 } elseif ($serverdata['platform'] == 'hubzilla') {
780 $serverdata['network'] = Protocol::ZOT;
781 } elseif ($serverdata['platform'] == 'redmatrix') {
782 $serverdata['network'] = Protocol::ZOT;
786 if (!empty($data['total_users'])) {
788 $serverdata['registered-users'] = max($data['total_users'], 1);
791 if (!empty($data['active_users_monthly'])) {
793 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
796 if (!empty($data['active_users_halfyear'])) {
798 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
801 if (!empty($data['local_posts'])) {
803 $serverdata['local-posts'] = max($data['local_posts'], 0);
806 if (!empty($data['registrations_open'])) {
807 $serverdata['register_policy'] = Register::OPEN;
809 $serverdata['register_policy'] = Register::CLOSED;
813 return $old_serverdata;
820 * Detect server type by using the nodeinfo data
822 * @param string $url address of the server
823 * @param ICanHandleHttpResponses $httpResult
825 * @return array Server data
827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
831 if (!$httpResult->isSuccess()) {
835 $nodeinfo = json_decode($httpResult->getBody(), true);
837 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
844 foreach ($nodeinfo['links'] as $link) {
845 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
846 Logger::info('Invalid nodeinfo format', ['url' => $url]);
849 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
850 $nodeinfo1_url = $link['href'];
851 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
852 $nodeinfo2_url = $link['href'];
856 if ($nodeinfo1_url . $nodeinfo2_url == '') {
862 if (!empty($nodeinfo2_url)) {
863 $server = self::parseNodeinfo2($nodeinfo2_url);
866 if (empty($server) && !empty($nodeinfo1_url)) {
867 $server = self::parseNodeinfo1($nodeinfo1_url);
876 * @param string $nodeinfo_url address of the nodeinfo path
878 * @return array Server data
880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 private static function parseNodeinfo1(string $nodeinfo_url): array
884 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
885 if (!$curlResult->isSuccess()) {
889 $nodeinfo = json_decode($curlResult->getBody(), true);
891 if (!is_array($nodeinfo)) {
895 $server = ['detection-method' => self::DETECT_NODEINFO_1,
896 'register_policy' => Register::CLOSED];
898 if (!empty($nodeinfo['openRegistrations'])) {
899 $server['register_policy'] = Register::OPEN;
902 if (is_array($nodeinfo['software'])) {
903 if (!empty($nodeinfo['software']['name'])) {
904 $server['platform'] = strtolower($nodeinfo['software']['name']);
907 if (!empty($nodeinfo['software']['version'])) {
908 $server['version'] = $nodeinfo['software']['version'];
909 // Version numbers on Nodeinfo are presented with additional info, e.g.:
910 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
911 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
915 if (!empty($nodeinfo['metadata']['nodeName'])) {
916 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
919 if (!empty($nodeinfo['usage']['users']['total'])) {
920 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
923 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
924 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
927 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
928 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
931 if (!empty($nodeinfo['usage']['localPosts'])) {
932 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
935 if (!empty($nodeinfo['usage']['localComments'])) {
936 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
939 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
941 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
942 $protocols[$protocol] = true;
945 if (!empty($protocols['friendica'])) {
946 $server['network'] = Protocol::DFRN;
947 } elseif (!empty($protocols['activitypub'])) {
948 $server['network'] = Protocol::ACTIVITYPUB;
949 } elseif (!empty($protocols['diaspora'])) {
950 $server['network'] = Protocol::DIASPORA;
951 } elseif (!empty($protocols['ostatus'])) {
952 $server['network'] = Protocol::OSTATUS;
953 } elseif (!empty($protocols['gnusocial'])) {
954 $server['network'] = Protocol::OSTATUS;
955 } elseif (!empty($protocols['zot'])) {
956 $server['network'] = Protocol::ZOT;
960 if (empty($server)) {
964 if (empty($server['network'])) {
965 $server['network'] = Protocol::PHANTOM;
974 * @see https://git.feneas.org/jaywink/nodeinfo2
976 * @param string $nodeinfo_url address of the nodeinfo path
978 * @return array Server data
980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982 private static function parseNodeinfo2(string $nodeinfo_url): array
984 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
985 if (!$curlResult->isSuccess()) {
989 $nodeinfo = json_decode($curlResult->getBody(), true);
990 if (!is_array($nodeinfo)) {
995 'detection-method' => self::DETECT_NODEINFO_2,
996 'register_policy' => Register::CLOSED,
997 'platform' => 'unknown',
1000 if (!empty($nodeinfo['openRegistrations'])) {
1001 $server['register_policy'] = Register::OPEN;
1004 if (!empty($nodeinfo['software'])) {
1005 if (isset($nodeinfo['software']['name'])) {
1006 $server['platform'] = strtolower($nodeinfo['software']['name']);
1009 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1010 $server['version'] = $nodeinfo['software']['version'];
1011 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1012 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1013 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1015 // qoto advertises itself as Mastodon
1016 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1017 $server['platform'] = 'qoto';
1022 if (!empty($nodeinfo['metadata']['nodeName'])) {
1023 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1026 if (!empty($nodeinfo['usage']['users']['total'])) {
1027 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1030 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1031 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1034 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1035 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1038 if (!empty($nodeinfo['usage']['localPosts'])) {
1039 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1042 if (!empty($nodeinfo['usage']['localComments'])) {
1043 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1046 if (!empty($nodeinfo['protocols'])) {
1048 foreach ($nodeinfo['protocols'] as $protocol) {
1049 if (is_string($protocol)) {
1050 $protocols[$protocol] = true;
1054 if (!empty($protocols['dfrn'])) {
1055 $server['network'] = Protocol::DFRN;
1056 } elseif (!empty($protocols['activitypub'])) {
1057 $server['network'] = Protocol::ACTIVITYPUB;
1058 } elseif (!empty($protocols['diaspora'])) {
1059 $server['network'] = Protocol::DIASPORA;
1060 } elseif (!empty($protocols['ostatus'])) {
1061 $server['network'] = Protocol::OSTATUS;
1062 } elseif (!empty($protocols['gnusocial'])) {
1063 $server['network'] = Protocol::OSTATUS;
1064 } elseif (!empty($protocols['zot'])) {
1065 $server['network'] = Protocol::ZOT;
1069 if (empty($server)) {
1073 if (empty($server['network'])) {
1074 $server['network'] = Protocol::PHANTOM;
1081 * Parses NodeInfo2 protocol 1.0
1083 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1085 * @param string $nodeinfo_url address of the nodeinfo path
1087 * @return array Server data
1089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1091 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1093 if (!$httpResult->isSuccess()) {
1097 $nodeinfo = json_decode($httpResult->getBody(), true);
1099 if (!is_array($nodeinfo)) {
1103 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1104 'register_policy' => Register::CLOSED];
1106 if (!empty($nodeinfo['openRegistrations'])) {
1107 $server['register_policy'] = Register::OPEN;
1110 if (!empty($nodeinfo['server'])) {
1111 if (!empty($nodeinfo['server']['software'])) {
1112 $server['platform'] = strtolower($nodeinfo['server']['software']);
1115 if (!empty($nodeinfo['server']['version'])) {
1116 $server['version'] = $nodeinfo['server']['version'];
1117 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1118 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1119 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1122 if (!empty($nodeinfo['server']['name'])) {
1123 $server['site_name'] = $nodeinfo['server']['name'];
1127 if (!empty($nodeinfo['usage']['users']['total'])) {
1128 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1131 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1132 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1135 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1136 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1139 if (!empty($nodeinfo['usage']['localPosts'])) {
1140 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1143 if (!empty($nodeinfo['usage']['localComments'])) {
1144 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1147 if (!empty($nodeinfo['protocols'])) {
1149 foreach ($nodeinfo['protocols'] as $protocol) {
1150 if (is_string($protocol)) {
1151 $protocols[$protocol] = true;
1155 if (!empty($protocols['dfrn'])) {
1156 $server['network'] = Protocol::DFRN;
1157 } elseif (!empty($protocols['activitypub'])) {
1158 $server['network'] = Protocol::ACTIVITYPUB;
1159 } elseif (!empty($protocols['diaspora'])) {
1160 $server['network'] = Protocol::DIASPORA;
1161 } elseif (!empty($protocols['ostatus'])) {
1162 $server['network'] = Protocol::OSTATUS;
1163 } elseif (!empty($protocols['gnusocial'])) {
1164 $server['network'] = Protocol::OSTATUS;
1165 } elseif (!empty($protocols['zot'])) {
1166 $server['network'] = Protocol::ZOT;
1170 if (empty($server) || empty($server['platform'])) {
1174 if (empty($server['network'])) {
1175 $server['network'] = Protocol::PHANTOM;
1182 * Fetch server information from a 'siteinfo.json' file on the given server
1184 * @param string $url URL of the given server
1185 * @param array $serverdata array with server data
1187 * @return array server data
1189 private static function fetchSiteinfo(string $url, array $serverdata): array
1191 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1192 if (!$curlResult->isSuccess()) {
1196 $data = json_decode($curlResult->getBody(), true);
1201 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1202 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1205 if (!empty($data['url'])) {
1206 $serverdata['platform'] = strtolower($data['platform']);
1207 $serverdata['version'] = $data['version'];
1210 if (!empty($data['plugins'])) {
1211 if (in_array('pubcrawl', $data['plugins'])) {
1212 $serverdata['network'] = Protocol::ACTIVITYPUB;
1213 } elseif (in_array('diaspora', $data['plugins'])) {
1214 $serverdata['network'] = Protocol::DIASPORA;
1215 } elseif (in_array('gnusoc', $data['plugins'])) {
1216 $serverdata['network'] = Protocol::OSTATUS;
1218 $serverdata['network'] = Protocol::ZOT;
1222 if (!empty($data['site_name'])) {
1223 $serverdata['site_name'] = $data['site_name'];
1226 if (!empty($data['channels_total'])) {
1227 $serverdata['registered-users'] = max($data['channels_total'], 1);
1230 if (!empty($data['channels_active_monthly'])) {
1231 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1234 if (!empty($data['channels_active_halfyear'])) {
1235 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1238 if (!empty($data['local_posts'])) {
1239 $serverdata['local-posts'] = max($data['local_posts'], 0);
1242 if (!empty($data['local_comments'])) {
1243 $serverdata['local-comments'] = max($data['local_comments'], 0);
1246 if (!empty($data['register_policy'])) {
1247 switch ($data['register_policy']) {
1248 case 'REGISTER_OPEN':
1249 $serverdata['register_policy'] = Register::OPEN;
1252 case 'REGISTER_APPROVE':
1253 $serverdata['register_policy'] = Register::APPROVE;
1256 case 'REGISTER_CLOSED':
1258 $serverdata['register_policy'] = Register::CLOSED;
1267 * Fetches server data via an ActivityPub account with url of that server
1269 * @param string $url URL of the given server
1270 * @param array $serverdata array with server data
1272 * @return array server data
1276 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1279 return ['server' => $serverdata, 'actor' => ''];
1282 $actor = JsonLD::compact($data, false);
1283 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1284 $serverdata['network'] = Protocol::ACTIVITYPUB;
1285 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1286 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1287 if (!empty($actor['as:generator'])) {
1288 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1289 $serverdata['platform'] = strtolower(array_shift($generator));
1290 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1292 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1294 return ['server' => $serverdata, 'actor' => $actor['@id']];
1295 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1296 // By now only Ktistec seems to provide collections this way
1297 $serverdata['platform'] = 'ktistec';
1298 $serverdata['network'] = Protocol::ACTIVITYPUB;
1299 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1301 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1302 if (!empty($actors) && !empty($actors[0]['@id'])) {
1303 $actor_url = $actor['@id'] . $actors[0]['@id'];
1308 return ['server' => $serverdata, 'actor' => $actor_url];
1310 return ['server' => $serverdata, 'actor' => ''];
1314 * Checks if the server contains a valid host meta file
1316 * @param string $url URL of the given server
1318 * @return boolean 'true' if the server seems to be vital
1320 private static function validHostMeta(string $url): bool
1322 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1323 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1324 if (!$curlResult->isSuccess()) {
1328 $xrd = XML::parseString($curlResult->getBody());
1329 if (!is_object($xrd)) {
1333 $elements = XML::elementToArray($xrd);
1334 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1339 foreach ($elements['xrd']['link'] as $link) {
1340 // When there is more than a single "link" element, the array looks slightly different
1341 if (!empty($link['@attributes'])) {
1342 $link = $link['@attributes'];
1345 if (empty($link['rel']) || empty($link['template'])) {
1349 if ($link['rel'] == 'lrdd') {
1350 // When the webfinger host is the same like the system host, it should be ok.
1351 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1359 * Detect the network of the given server via their known contacts
1361 * @param string $url URL of the given server
1362 * @param array $serverdata array with server data
1364 * @return array server data
1366 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1370 $nurl = Strings::normaliseLink($url);
1372 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1373 while ($apcontact = DBA::fetch($apcontacts)) {
1374 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1376 DBA::close($apcontacts);
1378 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1379 while ($pcontact = DBA::fetch($pcontacts)) {
1380 $contacts[$pcontact['nurl']] = $pcontact['url'];
1382 DBA::close($pcontacts);
1384 if (empty($contacts)) {
1389 foreach ($contacts as $contact) {
1390 // Endlosschleife verhindern wegen gsid!
1391 $data = Probe::uri($contact);
1392 if (in_array($data['network'], Protocol::FEDERATED)) {
1393 $serverdata['network'] = $data['network'];
1395 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1396 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1399 } elseif ((time() - $time) > 10) {
1400 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1409 * Checks if the given server does have a '/poco' endpoint.
1410 * This is used for the 'PortableContact' functionality,
1411 * which is used by both Friendica and Hubzilla.
1413 * @param string $url URL of the given server
1414 * @param array $serverdata array with server data
1416 * @return array server data
1418 private static function checkPoCo(string $url, array $serverdata): array
1420 $serverdata['poco'] = '';
1422 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1423 if (!$curlResult->isSuccess()) {
1427 $data = json_decode($curlResult->getBody(), true);
1432 if (!empty($data['totalResults'])) {
1433 $registeredUsers = $serverdata['registered-users'] ?? 0;
1434 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1435 $serverdata['directory-type'] = self::DT_POCO;
1436 $serverdata['poco'] = $url . '/poco';
1443 * Checks if the given server does have a Mastodon style directory endpoint.
1445 * @param string $url URL of the given server
1446 * @param array $serverdata array with server data
1448 * @return array server data
1450 public static function checkMastodonDirectory(string $url, array $serverdata): array
1452 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1453 if (!$curlResult->isSuccess()) {
1457 $data = json_decode($curlResult->getBody(), true);
1462 if (count($data) == 1) {
1463 $serverdata['directory-type'] = self::DT_MASTODON;
1470 * Detects Peertube via their known endpoint
1472 * @param string $url URL of the given server
1473 * @param array $serverdata array with server data
1475 * @return array server data
1477 private static function detectPeertube(string $url, array $serverdata): array
1479 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1480 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1484 $data = json_decode($curlResult->getBody(), true);
1489 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1490 $serverdata['platform'] = 'peertube';
1491 $serverdata['version'] = $data['serverVersion'];
1492 $serverdata['network'] = Protocol::ACTIVITYPUB;
1494 if (!empty($data['instance']['name'])) {
1495 $serverdata['site_name'] = $data['instance']['name'];
1498 if (!empty($data['instance']['shortDescription'])) {
1499 $serverdata['info'] = $data['instance']['shortDescription'];
1502 if (!empty($data['signup'])) {
1503 if (!empty($data['signup']['allowed'])) {
1504 $serverdata['register_policy'] = Register::OPEN;
1508 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1509 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1517 * Detects the version number of a given server when it was a NextCloud installation
1519 * @param string $url URL of the given server
1520 * @param array $serverdata array with server data
1521 * @param bool $validHostMeta
1523 * @return array server data
1525 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1527 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1528 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1532 $data = json_decode($curlResult->getBody(), true);
1537 if (!empty($data['version'])) {
1538 $serverdata['platform'] = 'nextcloud';
1539 $serverdata['version'] = $data['version'];
1541 if ($validHostMeta) {
1542 $serverdata['network'] = Protocol::ACTIVITYPUB;
1545 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1546 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1554 * Fetches weekly usage data
1556 * @param string $url URL of the given server
1557 * @param array $serverdata array with server data
1559 * @return array server data
1561 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1563 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1564 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1568 $data = json_decode($curlResult->getBody(), true);
1574 foreach ($data as $week) {
1575 // Use only data from a full week
1576 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1580 // Most likely the data is sorted correctly. But we better are safe than sorry
1581 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1582 $current_week = $week;
1586 if (!empty($current_week['logins'])) {
1587 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1594 * Detects data from a given server url if it was a mastodon alike system
1596 * @param string $url URL of the given server
1597 * @param array $serverdata array with server data
1599 * @return array server data
1601 private static function detectMastodonAlikes(string $url, array $serverdata): array
1603 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1604 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1608 $data = json_decode($curlResult->getBody(), true);
1615 if (!empty($data['version'])) {
1616 $serverdata['platform'] = 'mastodon';
1617 $serverdata['version'] = $data['version'] ?? '';
1618 $serverdata['network'] = Protocol::ACTIVITYPUB;
1622 if (!empty($data['title'])) {
1623 $serverdata['site_name'] = $data['title'];
1626 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1627 $serverdata['platform'] = 'mastodon';
1628 $serverdata['network'] = Protocol::ACTIVITYPUB;
1632 if (!empty($data['description'])) {
1633 $serverdata['info'] = trim($data['description']);
1636 if (!empty($data['stats']['user_count'])) {
1637 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1640 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1641 $serverdata['platform'] = strtolower($matches[1]);
1642 $serverdata['version'] = $matches[2];
1646 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1647 $serverdata['platform'] = 'pleroma';
1648 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1652 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1653 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1654 $serverdata['platform'] = 'pleroma';
1658 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1659 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1666 * Detects data from typical Hubzilla endpoints
1668 * @param string $url URL of the given server
1669 * @param array $serverdata array with server data
1671 * @return array server data
1673 private static function detectHubzilla(string $url, array $serverdata): array
1675 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1676 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1680 $data = json_decode($curlResult->getBody(), true);
1681 if (empty($data) || empty($data['site'])) {
1685 if (!empty($data['site']['name'])) {
1686 $serverdata['site_name'] = $data['site']['name'];
1689 if (!empty($data['site']['platform'])) {
1690 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1691 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1692 $serverdata['network'] = Protocol::ZOT;
1695 if (!empty($data['site']['hubzilla'])) {
1696 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1697 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1698 $serverdata['network'] = Protocol::ZOT;
1701 if (!empty($data['site']['redmatrix'])) {
1702 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1703 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1704 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1705 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1708 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1709 $serverdata['network'] = Protocol::ZOT;
1713 $inviteonly = false;
1716 if (!empty($data['site']['closed'])) {
1717 $closed = self::toBoolean($data['site']['closed']);
1720 if (!empty($data['site']['private'])) {
1721 $private = self::toBoolean($data['site']['private']);
1724 if (!empty($data['site']['inviteonly'])) {
1725 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1728 if (!$closed && !$private and $inviteonly) {
1729 $serverdata['register_policy'] = Register::APPROVE;
1730 } elseif (!$closed && !$private) {
1731 $serverdata['register_policy'] = Register::OPEN;
1733 $serverdata['register_policy'] = Register::CLOSED;
1736 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1737 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1744 * Converts input value to a boolean value
1746 * @param string|integer $val
1750 private static function toBoolean($val): bool
1752 if (($val == 'true') || ($val == 1)) {
1754 } elseif (($val == 'false') || ($val == 0)) {
1762 * Detect if the URL belongs to a GNU Social server
1764 * @param string $url URL of the given server
1765 * @param array $serverdata array with server data
1767 * @return array server data
1769 private static function detectGNUSocial(string $url, array $serverdata): array
1771 // Test for GNU Social
1772 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1773 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1774 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1775 $serverdata['platform'] = 'gnusocial';
1776 // Remove junk that some GNU Social servers return
1777 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1778 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1779 $serverdata['version'] = trim($serverdata['version'], '"');
1780 $serverdata['network'] = Protocol::OSTATUS;
1782 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1783 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1789 // Test for Statusnet
1790 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1791 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1792 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1794 // Remove junk that some GNU Social servers return
1795 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1796 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1797 $serverdata['version'] = trim($serverdata['version'], '"');
1799 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1800 $serverdata['platform'] = 'pleroma';
1801 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1802 $serverdata['network'] = Protocol::ACTIVITYPUB;
1804 $serverdata['platform'] = 'statusnet';
1805 $serverdata['network'] = Protocol::OSTATUS;
1808 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1809 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1817 * Detect if the URL belongs to a Friendica server
1819 * @param string $url URL of the given server
1820 * @param array $serverdata array with server data
1822 * @return array server data
1824 private static function detectFriendica(string $url, array $serverdata): array
1826 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1827 // Because of this me must not use ACCEPT_JSON here.
1828 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1829 if (!$curlResult->isSuccess()) {
1830 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1832 $platform = 'Friendika';
1835 $platform = 'Friendica';
1838 if (!$curlResult->isSuccess()) {
1842 $data = json_decode($curlResult->getBody(), true);
1843 if (empty($data) || empty($data['version'])) {
1847 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1848 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1851 $serverdata['network'] = Protocol::DFRN;
1852 $serverdata['version'] = $data['version'];
1854 if (!empty($data['no_scrape_url'])) {
1855 $serverdata['noscrape'] = $data['no_scrape_url'];
1858 if (!empty($data['site_name'])) {
1859 $serverdata['site_name'] = $data['site_name'];
1862 if (!empty($data['info'])) {
1863 $serverdata['info'] = trim($data['info']);
1866 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1867 switch ($register_policy) {
1868 case 'REGISTER_OPEN':
1869 $serverdata['register_policy'] = Register::OPEN;
1872 case 'REGISTER_APPROVE':
1873 $serverdata['register_policy'] = Register::APPROVE;
1876 case 'REGISTER_CLOSED':
1877 case 'REGISTER_INVITATION':
1878 $serverdata['register_policy'] = Register::CLOSED;
1881 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1882 $serverdata['register_policy'] = Register::CLOSED;
1886 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1892 * Analyses the landing page of a given server for hints about type and system of that server
1894 * @param object $curlResult result of curl execution
1895 * @param array $serverdata array with server data
1897 * @return array server data
1899 private static function analyseRootBody($curlResult, array $serverdata): array
1901 if (empty($curlResult->getBody())) {
1905 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
1906 require __DIR__ . '/../../static/platforms.config.php';
1908 throw new HTTPException\InternalServerErrorException('Invalid platform file');
1911 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1913 $doc = new DOMDocument();
1914 @$doc->loadHTML($curlResult->getBody());
1915 $xpath = new DOMXPath($doc);
1918 // We can only detect honk via some HTML element on their page
1919 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1920 $serverdata['platform'] = 'honk';
1921 $serverdata['network'] = Protocol::ACTIVITYPUB;
1925 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1926 if (!empty($title)) {
1927 $serverdata['site_name'] = $title;
1930 $list = $xpath->query('//meta[@name]');
1932 foreach ($list as $node) {
1934 if ($node->attributes->length) {
1935 foreach ($node->attributes as $attribute) {
1936 $value = trim($attribute->value);
1937 if (empty($value)) {
1941 $attr[$attribute->name] = $value;
1944 if (empty($attr['name']) || empty($attr['content'])) {
1949 if ($attr['name'] == 'description') {
1950 $serverdata['info'] = $attr['content'];
1953 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1954 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
1955 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
1956 $platform = str_replace('/', ' ', $platform);
1957 $platform_parts = explode(' ', $platform);
1958 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
1959 $platform = $platform_parts[0];
1960 $serverdata['version'] = $platform_parts[1];
1962 if (in_array($platform, array_values($dfrn_platforms))) {
1963 $serverdata['network'] = Protocol::DFRN;
1964 } elseif (in_array($platform, array_values($ap_platforms))) {
1965 $serverdata['network'] = Protocol::ACTIVITYPUB;
1966 } elseif (in_array($platform, array_values($zap_platforms))) {
1967 $serverdata['network'] = Protocol::ZOT;
1969 if (in_array($platform, array_values($platforms))) {
1970 $serverdata['platform'] = $platform;
1976 $list = $xpath->query('//meta[@property]');
1978 foreach ($list as $node) {
1980 if ($node->attributes->length) {
1981 foreach ($node->attributes as $attribute) {
1982 $value = trim($attribute->value);
1983 if (empty($value)) {
1987 $attr[$attribute->name] = $value;
1990 if (empty($attr['property']) || empty($attr['content'])) {
1995 if ($attr['property'] == 'og:site_name') {
1996 $serverdata['site_name'] = $attr['content'];
1999 if ($attr['property'] == 'og:description') {
2000 $serverdata['info'] = $attr['content'];
2003 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2004 if (in_array($attr['content'], array_keys($platforms))) {
2005 $serverdata['platform'] = $platforms[$attr['content']];
2009 if (in_array($attr['content'], array_keys($ap_platforms))) {
2010 $serverdata['network'] = Protocol::ACTIVITYPUB;
2011 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2012 $serverdata['network'] = Protocol::ZOT;
2017 $list = $xpath->query('//link[@rel="me"]');
2018 foreach ($list as $node) {
2019 foreach ($node->attributes as $attribute) {
2020 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2021 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2022 $serverdata['platform'] = 'microblog';
2023 $serverdata['network'] = Protocol::ACTIVITYPUB;
2029 if ($serverdata['platform'] != 'microblog') {
2030 $list = $xpath->query('//link[@rel="micropub"]');
2031 foreach ($list as $node) {
2032 foreach ($node->attributes as $attribute) {
2033 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2034 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2035 $serverdata['platform'] = 'microblog';
2036 $serverdata['network'] = Protocol::ACTIVITYPUB;
2043 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2044 $serverdata['detection-method'] = self::DETECT_BODY;
2051 * Analyses the header data of a given server for hints about type and system of that server
2053 * @param object $curlResult result of curl execution
2054 * @param array $serverdata array with server data
2056 * @return array server data
2058 private static function analyseRootHeader($curlResult, array $serverdata): array
2060 if ($curlResult->getHeader('server') == 'Mastodon') {
2061 $serverdata['platform'] = 'mastodon';
2062 $serverdata['network'] = Protocol::ACTIVITYPUB;
2063 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2064 $serverdata['platform'] = 'diaspora';
2065 $serverdata['network'] = Protocol::DIASPORA;
2066 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2067 } elseif ($curlResult->inHeader('x-friendica-version')) {
2068 $serverdata['platform'] = 'friendica';
2069 $serverdata['network'] = Protocol::DFRN;
2070 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2075 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2076 $serverdata['detection-method'] = self::DETECT_HEADER;
2083 * Update GServer entries
2085 public static function discover()
2087 // Update the server list
2088 self::discoverFederation();
2092 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2094 if ($requery_days == 0) {
2098 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2100 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2101 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2102 ['order' => ['RAND()']]);
2104 while ($gserver = DBA::fetch($gservers)) {
2105 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2106 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2108 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2109 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2111 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2112 self::update($fields, ['nurl' => $gserver['nurl']]);
2114 if (--$no_of_queries == 0) {
2119 DBA::close($gservers);
2123 * Discover federated servers
2125 private static function discoverFederation()
2127 $last = DI::config()->get('poco', 'last_federation_discovery');
2130 $next = $last + (24 * 60 * 60);
2132 if ($next > time()) {
2137 // Discover federated servers
2138 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2139 foreach ($protocols as $protocol) {
2140 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2141 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2142 if (!empty($curlResult)) {
2143 $data = json_decode($curlResult, true);
2144 if (!empty($data['data']['nodes'])) {
2145 foreach ($data['data']['nodes'] as $server) {
2146 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2147 self::add('https://' . $server['host'], true);
2153 // Disvover Mastodon servers
2154 $accesstoken = DI::config()->get('system', 'instances_social_key');
2156 if (!empty($accesstoken)) {
2157 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2158 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2159 if ($curlResult->isSuccess()) {
2160 $servers = json_decode($curlResult->getBody(), true);
2162 foreach ($servers['instances'] as $server) {
2163 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2169 DI::config()->set('poco', 'last_federation_discovery', time());
2173 * Set the protocol for the given server
2175 * @param int $gsid Server id
2176 * @param int $protocol Protocol id
2180 public static function setProtocol(int $gsid, int $protocol)
2186 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2187 if (!DBA::isResult($gserver)) {
2191 $old = $gserver['protocol'];
2193 if (!is_null($old)) {
2195 The priority for the protocols is:
2197 2. DFRN via Diaspora
2203 // We don't need to change it when nothing is to be changed
2204 if ($old == $protocol) {
2208 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2209 if ($protocol == Post\DeliveryData::OSTATUS) {
2213 // If the server is marked as ActivityPub then we won't change it to anything different
2214 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2218 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2219 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2223 // Don't change it to Diaspora when it is a legacy DFRN server
2224 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2229 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2230 self::update(['protocol' => $protocol], ['id' => $gsid]);
2234 * Fetch the protocol of the given server
2236 * @param int $gsid Server id
2238 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2242 public static function getProtocol(int $gsid): ?int
2248 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2249 if (DBA::isResult($gserver)) {
2250 return $gserver['protocol'];
2257 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2259 * @param array $fields
2260 * @param array $condition
2266 public static function update(array $fields, array $condition): bool
2268 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2270 return DBA::update('gserver', $fields, $condition);