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 // Numbers above a reasonable value (10 millions) are ignored
567 if ($serverdata['registered-users'] > 10000000) {
568 $serverdata['registered-users'] = 0;
571 // On an active server there has to be at least a single user
572 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
573 $serverdata['registered-users'] = 1;
574 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
575 $serverdata['registered-users'] = 0;
578 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
580 $serverdata['last_contact'] = DateTimeFormat::utcNow();
581 $serverdata['failed'] = false;
583 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
584 if (!DBA::isResult($gserver)) {
585 $serverdata['created'] = DateTimeFormat::utcNow();
586 $ret = DBA::insert('gserver', $serverdata);
587 $id = DBA::lastInsertId();
589 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
590 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
591 if (DBA::isResult($gserver)) {
592 $id = $gserver['id'];
596 // Count the number of known contacts from this server
597 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
598 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
599 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
600 $max_users = max($apcontacts, $contacts);
601 if ($max_users > $serverdata['registered-users']) {
602 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
603 self::update(['registered-users' => $max_users], ['id' => $id]);
606 if (empty($serverdata['active-month-users'])) {
607 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
609 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
610 self::update(['active-month-users' => $contacts], ['id' => $id]);
614 if (empty($serverdata['active-halfyear-users'])) {
615 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
617 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
618 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
623 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
624 self::discoverRelay($url);
627 if (!empty($systemactor)) {
628 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
629 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
636 * Fetch relay data from a given server url
638 * @param string $server_url address of the server
642 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
644 private static function discoverRelay(string $server_url)
646 Logger::info('Discover relay data', ['server' => $server_url]);
648 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
649 if (!$curlResult->isSuccess()) {
653 $data = json_decode($curlResult->getBody(), true);
654 if (!is_array($data)) {
658 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
659 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
661 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
663 $data['subscribe'] = false;
667 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
668 if (!DBA::isResult($gserver)) {
672 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
673 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
674 self::update($fields, ['id' => $gserver['id']]);
677 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
679 if ($data['scope'] == 'tags') {
682 foreach ($data['tags'] as $tag) {
683 $tag = mb_strtolower($tag);
684 if (strlen($tag) < 100) {
689 foreach ($tags as $tag) {
690 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
694 // Create or update the relay contact
696 if (isset($data['protocols'])) {
697 if (isset($data['protocols']['diaspora'])) {
698 $fields['network'] = Protocol::DIASPORA;
700 if (isset($data['protocols']['diaspora']['receive'])) {
701 $fields['batch'] = $data['protocols']['diaspora']['receive'];
702 } elseif (is_string($data['protocols']['diaspora'])) {
703 $fields['batch'] = $data['protocols']['diaspora'];
707 if (isset($data['protocols']['dfrn'])) {
708 $fields['network'] = Protocol::DFRN;
710 if (isset($data['protocols']['dfrn']['receive'])) {
711 $fields['batch'] = $data['protocols']['dfrn']['receive'];
712 } elseif (is_string($data['protocols']['dfrn'])) {
713 $fields['batch'] = $data['protocols']['dfrn'];
717 if (isset($data['protocols']['activitypub'])) {
718 $fields['network'] = Protocol::ACTIVITYPUB;
720 if (!empty($data['protocols']['activitypub']['actor'])) {
721 $fields['url'] = $data['protocols']['activitypub']['actor'];
723 if (!empty($data['protocols']['activitypub']['receive'])) {
724 $fields['batch'] = $data['protocols']['activitypub']['receive'];
729 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
731 Relay::updateContact($gserver, $fields);
735 * Fetch server data from '/statistics.json' on the given server
737 * @param string $url URL of the given server
739 * @return array server data
741 private static function fetchStatistics(string $url, array $serverdata): array
743 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
744 if (!$curlResult->isSuccess()) {
748 $data = json_decode($curlResult->getBody(), true);
753 // Some AP enabled systems return activity data that we don't expect here.
754 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
759 $old_serverdata = $serverdata;
761 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
763 if (!empty($data['version'])) {
765 $serverdata['version'] = $data['version'];
766 // Version numbers on statistics.json are presented with additional info, e.g.:
767 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
768 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
771 if (!empty($data['name'])) {
773 $serverdata['site_name'] = $data['name'];
776 if (!empty($data['network'])) {
778 $serverdata['platform'] = strtolower($data['network']);
780 if ($serverdata['platform'] == 'diaspora') {
781 $serverdata['network'] = Protocol::DIASPORA;
782 } elseif ($serverdata['platform'] == 'friendica') {
783 $serverdata['network'] = Protocol::DFRN;
784 } elseif ($serverdata['platform'] == 'hubzilla') {
785 $serverdata['network'] = Protocol::ZOT;
786 } elseif ($serverdata['platform'] == 'redmatrix') {
787 $serverdata['network'] = Protocol::ZOT;
791 if (!empty($data['total_users'])) {
793 $serverdata['registered-users'] = max($data['total_users'], 1);
796 if (!empty($data['active_users_monthly'])) {
798 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
801 if (!empty($data['active_users_halfyear'])) {
803 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
806 if (!empty($data['local_posts'])) {
808 $serverdata['local-posts'] = max($data['local_posts'], 0);
811 if (!empty($data['registrations_open'])) {
812 $serverdata['register_policy'] = Register::OPEN;
814 $serverdata['register_policy'] = Register::CLOSED;
818 return $old_serverdata;
825 * Detect server type by using the nodeinfo data
827 * @param string $url address of the server
828 * @param ICanHandleHttpResponses $httpResult
830 * @return array Server data
832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
834 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
836 if (!$httpResult->isSuccess()) {
840 $nodeinfo = json_decode($httpResult->getBody(), true);
842 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
849 foreach ($nodeinfo['links'] as $link) {
850 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
851 Logger::info('Invalid nodeinfo format', ['url' => $url]);
854 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
855 $nodeinfo1_url = $link['href'];
856 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
857 $nodeinfo2_url = $link['href'];
861 if ($nodeinfo1_url . $nodeinfo2_url == '') {
867 if (!empty($nodeinfo2_url)) {
868 $server = self::parseNodeinfo2($nodeinfo2_url);
871 if (empty($server) && !empty($nodeinfo1_url)) {
872 $server = self::parseNodeinfo1($nodeinfo1_url);
881 * @param string $nodeinfo_url address of the nodeinfo path
883 * @return array Server data
885 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
887 private static function parseNodeinfo1(string $nodeinfo_url): array
889 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
890 if (!$curlResult->isSuccess()) {
894 $nodeinfo = json_decode($curlResult->getBody(), true);
896 if (!is_array($nodeinfo)) {
900 $server = ['detection-method' => self::DETECT_NODEINFO_1,
901 'register_policy' => Register::CLOSED];
903 if (!empty($nodeinfo['openRegistrations'])) {
904 $server['register_policy'] = Register::OPEN;
907 if (is_array($nodeinfo['software'])) {
908 if (!empty($nodeinfo['software']['name'])) {
909 $server['platform'] = strtolower($nodeinfo['software']['name']);
912 if (!empty($nodeinfo['software']['version'])) {
913 $server['version'] = $nodeinfo['software']['version'];
914 // Version numbers on Nodeinfo are presented with additional info, e.g.:
915 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
916 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
920 if (!empty($nodeinfo['metadata']['nodeName'])) {
921 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
924 if (!empty($nodeinfo['usage']['users']['total'])) {
925 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
928 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
929 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
932 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
933 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
936 if (!empty($nodeinfo['usage']['localPosts'])) {
937 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
940 if (!empty($nodeinfo['usage']['localComments'])) {
941 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
944 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
946 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
947 $protocols[$protocol] = true;
950 if (!empty($protocols['friendica'])) {
951 $server['network'] = Protocol::DFRN;
952 } elseif (!empty($protocols['activitypub'])) {
953 $server['network'] = Protocol::ACTIVITYPUB;
954 } elseif (!empty($protocols['diaspora'])) {
955 $server['network'] = Protocol::DIASPORA;
956 } elseif (!empty($protocols['ostatus'])) {
957 $server['network'] = Protocol::OSTATUS;
958 } elseif (!empty($protocols['gnusocial'])) {
959 $server['network'] = Protocol::OSTATUS;
960 } elseif (!empty($protocols['zot'])) {
961 $server['network'] = Protocol::ZOT;
965 if (empty($server)) {
969 if (empty($server['network'])) {
970 $server['network'] = Protocol::PHANTOM;
979 * @see https://git.feneas.org/jaywink/nodeinfo2
981 * @param string $nodeinfo_url address of the nodeinfo path
983 * @return array Server data
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 private static function parseNodeinfo2(string $nodeinfo_url): array
989 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
990 if (!$curlResult->isSuccess()) {
994 $nodeinfo = json_decode($curlResult->getBody(), true);
995 if (!is_array($nodeinfo)) {
1000 'detection-method' => self::DETECT_NODEINFO_2,
1001 'register_policy' => Register::CLOSED,
1002 'platform' => 'unknown',
1005 if (!empty($nodeinfo['openRegistrations'])) {
1006 $server['register_policy'] = Register::OPEN;
1009 if (!empty($nodeinfo['software'])) {
1010 if (isset($nodeinfo['software']['name'])) {
1011 $server['platform'] = strtolower($nodeinfo['software']['name']);
1014 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1015 $server['version'] = $nodeinfo['software']['version'];
1016 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1017 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1018 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1020 // qoto advertises itself as Mastodon
1021 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1022 $server['platform'] = 'qoto';
1027 if (!empty($nodeinfo['metadata']['nodeName'])) {
1028 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1031 if (!empty($nodeinfo['usage']['users']['total'])) {
1032 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1035 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1036 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1039 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1040 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1043 if (!empty($nodeinfo['usage']['localPosts'])) {
1044 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1047 if (!empty($nodeinfo['usage']['localComments'])) {
1048 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1051 if (!empty($nodeinfo['protocols'])) {
1053 foreach ($nodeinfo['protocols'] as $protocol) {
1054 if (is_string($protocol)) {
1055 $protocols[$protocol] = true;
1059 if (!empty($protocols['dfrn'])) {
1060 $server['network'] = Protocol::DFRN;
1061 } elseif (!empty($protocols['activitypub'])) {
1062 $server['network'] = Protocol::ACTIVITYPUB;
1063 } elseif (!empty($protocols['diaspora'])) {
1064 $server['network'] = Protocol::DIASPORA;
1065 } elseif (!empty($protocols['ostatus'])) {
1066 $server['network'] = Protocol::OSTATUS;
1067 } elseif (!empty($protocols['gnusocial'])) {
1068 $server['network'] = Protocol::OSTATUS;
1069 } elseif (!empty($protocols['zot'])) {
1070 $server['network'] = Protocol::ZOT;
1074 if (empty($server)) {
1078 if (empty($server['network'])) {
1079 $server['network'] = Protocol::PHANTOM;
1086 * Parses NodeInfo2 protocol 1.0
1088 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1090 * @param string $nodeinfo_url address of the nodeinfo path
1092 * @return array Server data
1094 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1098 if (!$httpResult->isSuccess()) {
1102 $nodeinfo = json_decode($httpResult->getBody(), true);
1104 if (!is_array($nodeinfo)) {
1108 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1109 'register_policy' => Register::CLOSED];
1111 if (!empty($nodeinfo['openRegistrations'])) {
1112 $server['register_policy'] = Register::OPEN;
1115 if (!empty($nodeinfo['server'])) {
1116 if (!empty($nodeinfo['server']['software'])) {
1117 $server['platform'] = strtolower($nodeinfo['server']['software']);
1120 if (!empty($nodeinfo['server']['version'])) {
1121 $server['version'] = $nodeinfo['server']['version'];
1122 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1123 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1124 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1127 if (!empty($nodeinfo['server']['name'])) {
1128 $server['site_name'] = $nodeinfo['server']['name'];
1132 if (!empty($nodeinfo['usage']['users']['total'])) {
1133 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1136 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1137 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1140 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1141 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1144 if (!empty($nodeinfo['usage']['localPosts'])) {
1145 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1148 if (!empty($nodeinfo['usage']['localComments'])) {
1149 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1152 if (!empty($nodeinfo['protocols'])) {
1154 foreach ($nodeinfo['protocols'] as $protocol) {
1155 if (is_string($protocol)) {
1156 $protocols[$protocol] = true;
1160 if (!empty($protocols['dfrn'])) {
1161 $server['network'] = Protocol::DFRN;
1162 } elseif (!empty($protocols['activitypub'])) {
1163 $server['network'] = Protocol::ACTIVITYPUB;
1164 } elseif (!empty($protocols['diaspora'])) {
1165 $server['network'] = Protocol::DIASPORA;
1166 } elseif (!empty($protocols['ostatus'])) {
1167 $server['network'] = Protocol::OSTATUS;
1168 } elseif (!empty($protocols['gnusocial'])) {
1169 $server['network'] = Protocol::OSTATUS;
1170 } elseif (!empty($protocols['zot'])) {
1171 $server['network'] = Protocol::ZOT;
1175 if (empty($server) || empty($server['platform'])) {
1179 if (empty($server['network'])) {
1180 $server['network'] = Protocol::PHANTOM;
1187 * Fetch server information from a 'siteinfo.json' file on the given server
1189 * @param string $url URL of the given server
1190 * @param array $serverdata array with server data
1192 * @return array server data
1194 private static function fetchSiteinfo(string $url, array $serverdata): array
1196 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1197 if (!$curlResult->isSuccess()) {
1201 $data = json_decode($curlResult->getBody(), true);
1206 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1207 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1210 if (!empty($data['url'])) {
1211 $serverdata['platform'] = strtolower($data['platform']);
1212 $serverdata['version'] = $data['version'];
1215 if (!empty($data['plugins'])) {
1216 if (in_array('pubcrawl', $data['plugins'])) {
1217 $serverdata['network'] = Protocol::ACTIVITYPUB;
1218 } elseif (in_array('diaspora', $data['plugins'])) {
1219 $serverdata['network'] = Protocol::DIASPORA;
1220 } elseif (in_array('gnusoc', $data['plugins'])) {
1221 $serverdata['network'] = Protocol::OSTATUS;
1223 $serverdata['network'] = Protocol::ZOT;
1227 if (!empty($data['site_name'])) {
1228 $serverdata['site_name'] = $data['site_name'];
1231 if (!empty($data['channels_total'])) {
1232 $serverdata['registered-users'] = max($data['channels_total'], 1);
1235 if (!empty($data['channels_active_monthly'])) {
1236 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1239 if (!empty($data['channels_active_halfyear'])) {
1240 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1243 if (!empty($data['local_posts'])) {
1244 $serverdata['local-posts'] = max($data['local_posts'], 0);
1247 if (!empty($data['local_comments'])) {
1248 $serverdata['local-comments'] = max($data['local_comments'], 0);
1251 if (!empty($data['register_policy'])) {
1252 switch ($data['register_policy']) {
1253 case 'REGISTER_OPEN':
1254 $serverdata['register_policy'] = Register::OPEN;
1257 case 'REGISTER_APPROVE':
1258 $serverdata['register_policy'] = Register::APPROVE;
1261 case 'REGISTER_CLOSED':
1263 $serverdata['register_policy'] = Register::CLOSED;
1272 * Fetches server data via an ActivityPub account with url of that server
1274 * @param string $url URL of the given server
1275 * @param array $serverdata array with server data
1277 * @return array server data
1281 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1284 return ['server' => $serverdata, 'actor' => ''];
1287 $actor = JsonLD::compact($data, false);
1288 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1289 $serverdata['network'] = Protocol::ACTIVITYPUB;
1290 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1291 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1292 if (!empty($actor['as:generator'])) {
1293 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1294 $serverdata['platform'] = strtolower(array_shift($generator));
1295 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1297 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1299 return ['server' => $serverdata, 'actor' => $actor['@id']];
1300 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1301 // By now only Ktistec seems to provide collections this way
1302 $serverdata['platform'] = 'ktistec';
1303 $serverdata['network'] = Protocol::ACTIVITYPUB;
1304 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1306 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1307 if (!empty($actors) && !empty($actors[0]['@id'])) {
1308 $actor_url = $actor['@id'] . $actors[0]['@id'];
1313 return ['server' => $serverdata, 'actor' => $actor_url];
1315 return ['server' => $serverdata, 'actor' => ''];
1319 * Checks if the server contains a valid host meta file
1321 * @param string $url URL of the given server
1323 * @return boolean 'true' if the server seems to be vital
1325 private static function validHostMeta(string $url): bool
1327 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1328 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1329 if (!$curlResult->isSuccess()) {
1333 $xrd = XML::parseString($curlResult->getBody(), true);
1334 if (!is_object($xrd)) {
1338 $elements = XML::elementToArray($xrd);
1339 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1344 foreach ($elements['xrd']['link'] as $link) {
1345 // When there is more than a single "link" element, the array looks slightly different
1346 if (!empty($link['@attributes'])) {
1347 $link = $link['@attributes'];
1350 if (empty($link['rel']) || empty($link['template'])) {
1354 if ($link['rel'] == 'lrdd') {
1355 // When the webfinger host is the same like the system host, it should be ok.
1356 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1364 * Detect the network of the given server via their known contacts
1366 * @param string $url URL of the given server
1367 * @param array $serverdata array with server data
1369 * @return array server data
1371 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1375 $nurl = Strings::normaliseLink($url);
1377 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1378 while ($apcontact = DBA::fetch($apcontacts)) {
1379 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1381 DBA::close($apcontacts);
1383 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1384 while ($pcontact = DBA::fetch($pcontacts)) {
1385 $contacts[$pcontact['nurl']] = $pcontact['url'];
1387 DBA::close($pcontacts);
1389 if (empty($contacts)) {
1394 foreach ($contacts as $contact) {
1395 // Endlosschleife verhindern wegen gsid!
1396 $data = Probe::uri($contact);
1397 if (in_array($data['network'], Protocol::FEDERATED)) {
1398 $serverdata['network'] = $data['network'];
1400 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1401 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1404 } elseif ((time() - $time) > 10) {
1405 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1414 * Checks if the given server does have a '/poco' endpoint.
1415 * This is used for the 'PortableContact' functionality,
1416 * which is used by both Friendica and Hubzilla.
1418 * @param string $url URL of the given server
1419 * @param array $serverdata array with server data
1421 * @return array server data
1423 private static function checkPoCo(string $url, array $serverdata): array
1425 $serverdata['poco'] = '';
1427 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1428 if (!$curlResult->isSuccess()) {
1432 $data = json_decode($curlResult->getBody(), true);
1437 if (!empty($data['totalResults'])) {
1438 $registeredUsers = $serverdata['registered-users'] ?? 0;
1439 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1440 $serverdata['directory-type'] = self::DT_POCO;
1441 $serverdata['poco'] = $url . '/poco';
1448 * Checks if the given server does have a Mastodon style directory endpoint.
1450 * @param string $url URL of the given server
1451 * @param array $serverdata array with server data
1453 * @return array server data
1455 public static function checkMastodonDirectory(string $url, array $serverdata): array
1457 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1458 if (!$curlResult->isSuccess()) {
1462 $data = json_decode($curlResult->getBody(), true);
1467 if (count($data) == 1) {
1468 $serverdata['directory-type'] = self::DT_MASTODON;
1475 * Detects Peertube via their known endpoint
1477 * @param string $url URL of the given server
1478 * @param array $serverdata array with server data
1480 * @return array server data
1482 private static function detectPeertube(string $url, array $serverdata): array
1484 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1485 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1489 $data = json_decode($curlResult->getBody(), true);
1494 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1495 $serverdata['platform'] = 'peertube';
1496 $serverdata['version'] = $data['serverVersion'];
1497 $serverdata['network'] = Protocol::ACTIVITYPUB;
1499 if (!empty($data['instance']['name'])) {
1500 $serverdata['site_name'] = $data['instance']['name'];
1503 if (!empty($data['instance']['shortDescription'])) {
1504 $serverdata['info'] = $data['instance']['shortDescription'];
1507 if (!empty($data['signup'])) {
1508 if (!empty($data['signup']['allowed'])) {
1509 $serverdata['register_policy'] = Register::OPEN;
1513 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1514 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1522 * Detects the version number of a given server when it was a NextCloud installation
1524 * @param string $url URL of the given server
1525 * @param array $serverdata array with server data
1526 * @param bool $validHostMeta
1528 * @return array server data
1530 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1532 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1533 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1537 $data = json_decode($curlResult->getBody(), true);
1542 if (!empty($data['version'])) {
1543 $serverdata['platform'] = 'nextcloud';
1544 $serverdata['version'] = $data['version'];
1546 if ($validHostMeta) {
1547 $serverdata['network'] = Protocol::ACTIVITYPUB;
1550 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1551 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1559 * Fetches weekly usage data
1561 * @param string $url URL of the given server
1562 * @param array $serverdata array with server data
1564 * @return array server data
1566 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1568 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1569 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1573 $data = json_decode($curlResult->getBody(), true);
1579 foreach ($data as $week) {
1580 // Use only data from a full week
1581 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1585 // Most likely the data is sorted correctly. But we better are safe than sorry
1586 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1587 $current_week = $week;
1591 if (!empty($current_week['logins'])) {
1592 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1599 * Detects data from a given server url if it was a mastodon alike system
1601 * @param string $url URL of the given server
1602 * @param array $serverdata array with server data
1604 * @return array server data
1606 private static function detectMastodonAlikes(string $url, array $serverdata): array
1608 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1609 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1613 $data = json_decode($curlResult->getBody(), true);
1620 if (!empty($data['version'])) {
1621 $serverdata['platform'] = 'mastodon';
1622 $serverdata['version'] = $data['version'] ?? '';
1623 $serverdata['network'] = Protocol::ACTIVITYPUB;
1627 if (!empty($data['title'])) {
1628 $serverdata['site_name'] = $data['title'];
1631 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1632 $serverdata['platform'] = 'mastodon';
1633 $serverdata['network'] = Protocol::ACTIVITYPUB;
1637 if (!empty($data['description'])) {
1638 $serverdata['info'] = trim($data['description']);
1641 if (!empty($data['stats']['user_count'])) {
1642 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1645 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1646 $serverdata['platform'] = strtolower($matches[1]);
1647 $serverdata['version'] = $matches[2];
1651 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1652 $serverdata['platform'] = 'pleroma';
1653 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1657 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1658 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1659 $serverdata['platform'] = 'pleroma';
1663 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1664 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1671 * Detects data from typical Hubzilla endpoints
1673 * @param string $url URL of the given server
1674 * @param array $serverdata array with server data
1676 * @return array server data
1678 private static function detectHubzilla(string $url, array $serverdata): array
1680 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1681 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1685 $data = json_decode($curlResult->getBody(), true);
1686 if (empty($data) || empty($data['site'])) {
1690 if (!empty($data['site']['name'])) {
1691 $serverdata['site_name'] = $data['site']['name'];
1694 if (!empty($data['site']['platform'])) {
1695 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1696 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1697 $serverdata['network'] = Protocol::ZOT;
1700 if (!empty($data['site']['hubzilla'])) {
1701 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1702 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1703 $serverdata['network'] = Protocol::ZOT;
1706 if (!empty($data['site']['redmatrix'])) {
1707 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1708 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1709 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1710 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1713 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1714 $serverdata['network'] = Protocol::ZOT;
1718 $inviteonly = false;
1721 if (!empty($data['site']['closed'])) {
1722 $closed = self::toBoolean($data['site']['closed']);
1725 if (!empty($data['site']['private'])) {
1726 $private = self::toBoolean($data['site']['private']);
1729 if (!empty($data['site']['inviteonly'])) {
1730 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1733 if (!$closed && !$private and $inviteonly) {
1734 $serverdata['register_policy'] = Register::APPROVE;
1735 } elseif (!$closed && !$private) {
1736 $serverdata['register_policy'] = Register::OPEN;
1738 $serverdata['register_policy'] = Register::CLOSED;
1741 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1742 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1749 * Converts input value to a boolean value
1751 * @param string|integer $val
1755 private static function toBoolean($val): bool
1757 if (($val == 'true') || ($val == 1)) {
1759 } elseif (($val == 'false') || ($val == 0)) {
1767 * Detect if the URL belongs to a GNU Social server
1769 * @param string $url URL of the given server
1770 * @param array $serverdata array with server data
1772 * @return array server data
1774 private static function detectGNUSocial(string $url, array $serverdata): array
1776 // Test for GNU Social
1777 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1778 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1779 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1780 $serverdata['platform'] = 'gnusocial';
1781 // Remove junk that some GNU Social servers return
1782 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1783 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1784 $serverdata['version'] = trim($serverdata['version'], '"');
1785 $serverdata['network'] = Protocol::OSTATUS;
1787 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1788 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1794 // Test for Statusnet
1795 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1796 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1797 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1799 // Remove junk that some GNU Social servers return
1800 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1801 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1802 $serverdata['version'] = trim($serverdata['version'], '"');
1804 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1805 $serverdata['platform'] = 'pleroma';
1806 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1807 $serverdata['network'] = Protocol::ACTIVITYPUB;
1809 $serverdata['platform'] = 'statusnet';
1810 $serverdata['network'] = Protocol::OSTATUS;
1813 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1814 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1822 * Detect if the URL belongs to a Friendica server
1824 * @param string $url URL of the given server
1825 * @param array $serverdata array with server data
1827 * @return array server data
1829 private static function detectFriendica(string $url, array $serverdata): array
1831 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1832 // Because of this me must not use ACCEPT_JSON here.
1833 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1834 if (!$curlResult->isSuccess()) {
1835 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1837 $platform = 'Friendika';
1840 $platform = 'Friendica';
1843 if (!$curlResult->isSuccess()) {
1847 $data = json_decode($curlResult->getBody(), true);
1848 if (empty($data) || empty($data['version'])) {
1852 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1853 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1856 $serverdata['network'] = Protocol::DFRN;
1857 $serverdata['version'] = $data['version'];
1859 if (!empty($data['no_scrape_url'])) {
1860 $serverdata['noscrape'] = $data['no_scrape_url'];
1863 if (!empty($data['site_name'])) {
1864 $serverdata['site_name'] = $data['site_name'];
1867 if (!empty($data['info'])) {
1868 $serverdata['info'] = trim($data['info']);
1871 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1872 switch ($register_policy) {
1873 case 'REGISTER_OPEN':
1874 $serverdata['register_policy'] = Register::OPEN;
1877 case 'REGISTER_APPROVE':
1878 $serverdata['register_policy'] = Register::APPROVE;
1881 case 'REGISTER_CLOSED':
1882 case 'REGISTER_INVITATION':
1883 $serverdata['register_policy'] = Register::CLOSED;
1886 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1887 $serverdata['register_policy'] = Register::CLOSED;
1891 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1897 * Analyses the landing page of a given server for hints about type and system of that server
1899 * @param object $curlResult result of curl execution
1900 * @param array $serverdata array with server data
1902 * @return array server data
1904 private static function analyseRootBody($curlResult, array $serverdata): array
1906 if (empty($curlResult->getBody())) {
1910 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
1911 require __DIR__ . '/../../static/platforms.config.php';
1913 throw new HTTPException\InternalServerErrorException('Invalid platform file');
1916 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1918 $doc = new DOMDocument();
1919 @$doc->loadHTML($curlResult->getBody());
1920 $xpath = new DOMXPath($doc);
1923 // We can only detect honk via some HTML element on their page
1924 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1925 $serverdata['platform'] = 'honk';
1926 $serverdata['network'] = Protocol::ACTIVITYPUB;
1930 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1931 if (!empty($title)) {
1932 $serverdata['site_name'] = $title;
1935 $list = $xpath->query('//meta[@name]');
1937 foreach ($list as $node) {
1939 if ($node->attributes->length) {
1940 foreach ($node->attributes as $attribute) {
1941 $value = trim($attribute->value);
1942 if (empty($value)) {
1946 $attr[$attribute->name] = $value;
1949 if (empty($attr['name']) || empty($attr['content'])) {
1954 if ($attr['name'] == 'description') {
1955 $serverdata['info'] = $attr['content'];
1958 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1959 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
1960 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
1961 $platform = str_replace('/', ' ', $platform);
1962 $platform_parts = explode(' ', $platform);
1963 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
1964 $platform = $platform_parts[0];
1965 $serverdata['version'] = $platform_parts[1];
1967 if (in_array($platform, array_values($dfrn_platforms))) {
1968 $serverdata['network'] = Protocol::DFRN;
1969 } elseif (in_array($platform, array_values($ap_platforms))) {
1970 $serverdata['network'] = Protocol::ACTIVITYPUB;
1971 } elseif (in_array($platform, array_values($zap_platforms))) {
1972 $serverdata['network'] = Protocol::ZOT;
1974 if (in_array($platform, array_values($platforms))) {
1975 $serverdata['platform'] = $platform;
1981 $list = $xpath->query('//meta[@property]');
1983 foreach ($list as $node) {
1985 if ($node->attributes->length) {
1986 foreach ($node->attributes as $attribute) {
1987 $value = trim($attribute->value);
1988 if (empty($value)) {
1992 $attr[$attribute->name] = $value;
1995 if (empty($attr['property']) || empty($attr['content'])) {
2000 if ($attr['property'] == 'og:site_name') {
2001 $serverdata['site_name'] = $attr['content'];
2004 if ($attr['property'] == 'og:description') {
2005 $serverdata['info'] = $attr['content'];
2008 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2009 if (in_array($attr['content'], array_keys($platforms))) {
2010 $serverdata['platform'] = $platforms[$attr['content']];
2014 if (in_array($attr['content'], array_keys($ap_platforms))) {
2015 $serverdata['network'] = Protocol::ACTIVITYPUB;
2016 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2017 $serverdata['network'] = Protocol::ZOT;
2022 $list = $xpath->query('//link[@rel="me"]');
2023 foreach ($list as $node) {
2024 foreach ($node->attributes as $attribute) {
2025 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2026 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2027 $serverdata['platform'] = 'microblog';
2028 $serverdata['network'] = Protocol::ACTIVITYPUB;
2034 if ($serverdata['platform'] != 'microblog') {
2035 $list = $xpath->query('//link[@rel="micropub"]');
2036 foreach ($list as $node) {
2037 foreach ($node->attributes as $attribute) {
2038 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2039 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2040 $serverdata['platform'] = 'microblog';
2041 $serverdata['network'] = Protocol::ACTIVITYPUB;
2048 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2049 $serverdata['detection-method'] = self::DETECT_BODY;
2056 * Analyses the header data of a given server for hints about type and system of that server
2058 * @param object $curlResult result of curl execution
2059 * @param array $serverdata array with server data
2061 * @return array server data
2063 private static function analyseRootHeader($curlResult, array $serverdata): array
2065 if ($curlResult->getHeader('server') == 'Mastodon') {
2066 $serverdata['platform'] = 'mastodon';
2067 $serverdata['network'] = Protocol::ACTIVITYPUB;
2068 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2069 $serverdata['platform'] = 'diaspora';
2070 $serverdata['network'] = Protocol::DIASPORA;
2071 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2072 } elseif ($curlResult->inHeader('x-friendica-version')) {
2073 $serverdata['platform'] = 'friendica';
2074 $serverdata['network'] = Protocol::DFRN;
2075 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2080 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2081 $serverdata['detection-method'] = self::DETECT_HEADER;
2088 * Update GServer entries
2090 public static function discover()
2092 // Update the server list
2093 self::discoverFederation();
2097 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2099 if ($requery_days == 0) {
2103 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2105 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2106 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2107 ['order' => ['RAND()']]);
2109 while ($gserver = DBA::fetch($gservers)) {
2110 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2111 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2113 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2114 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2116 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2117 self::update($fields, ['nurl' => $gserver['nurl']]);
2119 if (--$no_of_queries == 0) {
2124 DBA::close($gservers);
2128 * Discover federated servers
2130 private static function discoverFederation()
2132 $last = DI::config()->get('poco', 'last_federation_discovery');
2135 $next = $last + (24 * 60 * 60);
2137 if ($next > time()) {
2142 // Discover federated servers
2143 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2144 foreach ($protocols as $protocol) {
2145 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2146 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2147 if (!empty($curlResult)) {
2148 $data = json_decode($curlResult, true);
2149 if (!empty($data['data']['nodes'])) {
2150 foreach ($data['data']['nodes'] as $server) {
2151 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2152 self::add('https://' . $server['host'], true);
2158 // Disvover Mastodon servers
2159 $accesstoken = DI::config()->get('system', 'instances_social_key');
2161 if (!empty($accesstoken)) {
2162 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2163 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2164 if ($curlResult->isSuccess()) {
2165 $servers = json_decode($curlResult->getBody(), true);
2167 foreach ($servers['instances'] as $server) {
2168 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2174 DI::config()->set('poco', 'last_federation_discovery', time());
2178 * Set the protocol for the given server
2180 * @param int $gsid Server id
2181 * @param int $protocol Protocol id
2185 public static function setProtocol(int $gsid, int $protocol)
2191 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2192 if (!DBA::isResult($gserver)) {
2196 $old = $gserver['protocol'];
2198 if (!is_null($old)) {
2200 The priority for the protocols is:
2202 2. DFRN via Diaspora
2208 // We don't need to change it when nothing is to be changed
2209 if ($old == $protocol) {
2213 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2214 if ($protocol == Post\DeliveryData::OSTATUS) {
2218 // If the server is marked as ActivityPub then we won't change it to anything different
2219 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2223 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2224 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2228 // Don't change it to Diaspora when it is a legacy DFRN server
2229 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2234 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2235 self::update(['protocol' => $protocol], ['id' => $gsid]);
2239 * Fetch the protocol of the given server
2241 * @param int $gsid Server id
2243 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2247 public static function getProtocol(int $gsid): ?int
2253 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2254 if (DBA::isResult($gserver)) {
2255 return $gserver['protocol'];
2262 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2264 * @param array $fields
2265 * @param array $condition
2271 public static function update(array $fields, array $condition): bool
2273 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2275 return DBA::update('gserver', $fields, $condition);