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 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
74 const DETECT_FRIENDIKA = 10;
75 const DETECT_FRIENDICA = 11;
76 const DETECT_STATUSNET = 12;
77 const DETECT_GNUSOCIAL = 13;
78 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
79 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
80 const DETECT_MASTODON_API = 16;
81 const DETECT_STATUS_PHP = 17; // Nextcloud
82 const DETECT_V1_CONFIG = 18;
83 const DETECT_PUMPIO = 19; // Deprecated
84 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
86 // Standardized endpoints
87 const DETECT_STATISTICS_JSON = 100;
88 const DETECT_NODEINFO_1 = 101;
89 const DETECT_NODEINFO_2 = 102;
90 const DETECT_NODEINFO_210 = 103;
93 * Check for the existance of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
100 public static function add(string $url, bool $only_nodeinfo = false)
102 if (self::getID($url, false)) {
106 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
110 * Get the ID for the given server URL
113 * @param boolean $no_check Don't check if the server hadn't been found
115 * @return int|null gserver id or NULL on empty URL or failed check
117 public static function getID(string $url, bool $no_check = false): ?int
119 $url = self::cleanURL($url);
125 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
126 if (DBA::isResult($gserver)) {
127 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
128 return $gserver['id'];
131 if ($no_check || !self::check($url)) {
135 return self::getID($url, true);
139 * Retrieves all the servers which base domain are matching the provided domain pattern
141 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
143 * @param string $pattern
149 public static function listByDomainPattern(string $pattern): array
151 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
153 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
154 // eventual server path and keep only the server domain which we're matching against the pattern.
155 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
157 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
158 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
159 AND NOT `gserver`.`failed`
160 GROUP BY `gserver`.`id`";
162 $stmt = DI::dba()->p($sql, $likePattern);
164 return DI::dba()->toArray($stmt);
168 * Checks if the given server is reachable
170 * @param string $profile URL of the given profile
171 * @param string $server URL of the given server (If empty, taken from profile)
172 * @param string $network Network value that is used, when detection failed
173 * @param boolean $force Force an update.
175 * @return boolean 'true' if server seems vital
177 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false): bool
180 $contact = Contact::getByURL($profile, null, ['baseurl']);
181 if (!empty($contact['baseurl'])) {
182 $server = $contact['baseurl'];
190 return self::check($server, $network, $force);
194 * Calculate the next update day
196 * @param bool $success
197 * @param string $created
198 * @param string $last_contact
199 * @param bool $undetected
205 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
207 // On successful contact process check again next week when it is a detected system.
208 // When we haven't detected the system, it could be a static website or a really old system.
210 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
213 $now = strtotime(DateTimeFormat::utcNow());
215 if ($created > $last_contact) {
216 $contact_time = strtotime($created);
218 $contact_time = strtotime($last_contact);
221 // If the last contact was less than 6 hours before then try again in 6 hours
222 if (($now - $contact_time) < (60 * 60 * 6)) {
223 return DateTimeFormat::utc('now +6 hour');
226 // If the last contact was less than 12 hours before then try again in 12 hours
227 if (($now - $contact_time) < (60 * 60 * 12)) {
228 return DateTimeFormat::utc('now +12 hour');
231 // If the last contact was less than 24 hours before then try tomorrow again
232 if (($now - $contact_time) < (60 * 60 * 24)) {
233 return DateTimeFormat::utc('now +1 day');
236 // If the last contact was less than a week before then try again in a week
237 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
238 return DateTimeFormat::utc('now +1 week');
241 // If the last contact was less than two weeks before then try again in two week
242 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
243 return DateTimeFormat::utc('now +2 week');
246 // If the last contact was less than a month before then try again in a month
247 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
248 return DateTimeFormat::utc('now +1 month');
251 // The system hadn't been successul contacted for more than a month, so try again in three months
252 return DateTimeFormat::utc('now +3 month');
256 * Checks the state of the given server.
258 * @param string $server_url URL of the given server
259 * @param string $network Network value that is used, when detection failed
260 * @param boolean $force Force an update.
261 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
263 * @return boolean 'true' if server seems vital
265 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
267 $server_url = self::cleanURL($server_url);
268 if ($server_url == '') {
272 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
273 if (DBA::isResult($gserver)) {
274 if ($gserver['created'] <= DBA::NULL_DATETIME) {
275 $fields = ['created' => DateTimeFormat::utcNow()];
276 $condition = ['nurl' => Strings::normaliseLink($server_url)];
277 self::update($fields, $condition);
280 if (!$force && (strtotime($gserver['next_contact']) > time())) {
281 Logger::info('No update needed', ['server' => $server_url]);
282 return (!$gserver['failed']);
284 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
286 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
289 return self::detect($server_url, $network, $only_nodeinfo);
293 * Set failed server status
297 public static function setFailure(string $url)
299 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
300 if (DBA::isResult($gserver)) {
301 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
302 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
303 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
304 ['nurl' => Strings::normaliseLink($url)]);
305 Logger::info('Set failed status for existing server', ['url' => $url]);
308 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
309 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
310 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
311 Logger::info('Set failed status for new server', ['url' => $url]);
315 * Remove unwanted content from the given URL
319 * @return string cleaned URL
321 public static function cleanURL(string $url): string
323 $url = trim($url, '/');
324 $url = str_replace('/index.php', '', $url);
326 $urlparts = parse_url($url);
327 if (empty($urlparts)) {
331 unset($urlparts['user']);
332 unset($urlparts['pass']);
333 unset($urlparts['query']);
334 unset($urlparts['fragment']);
335 return (string)Uri::fromParts($urlparts);
339 * Detect server data (type, protocol, version number, ...)
340 * The detected data is then updated or inserted in the gserver table.
342 * @param string $url URL of the given server
343 * @param string $network Network value that is used, when detection failed
344 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
346 * @return boolean 'true' if server could be detected
348 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
350 Logger::info('Detect server type', ['server' => $url]);
352 $original_url = $url;
354 // Remove URL content that is not supposed to exist for a server url
355 $url = rtrim(self::cleanURL($url), '/');
357 Logger::notice('Empty URL.');
361 // If the URL missmatches, then we mark the old entry as failure
362 if (!Strings::compareLink($url, $original_url)) {
363 self::setFailure($original_url);
364 if (!self::getID($url, true)) {
365 self::detect($url, $network, $only_nodeinfo);
370 $valid_url = Network::isUrlValid($url);
372 self::setFailure($url);
375 $valid_url = rtrim($valid_url, '/');
378 if (!Strings::compareLink($url, $valid_url)) {
379 // We only follow redirects when the path stays the same or the target url has no path.
380 // Some systems have got redirects on their landing page to a single account page. This check handles it.
381 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))) ||
382 (((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)))) {
383 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
384 self::setFailure($url);
385 if (!self::getID($valid_url, true)) {
386 self::detect($valid_url, $network, $only_nodeinfo);
391 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)) &&
392 (parse_url($url, PHP_URL_PATH) == '')) {
393 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
394 $parts = parse_url($valid_url);
395 unset($parts['path']);
396 $valid_url = (string)Uri::fromParts($parts);
398 self::setFailure($url);
399 if (!self::getID($valid_url, true)) {
400 self::detect($valid_url, $network, $only_nodeinfo);
404 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
407 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
408 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
409 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
413 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
415 // When a nodeinfo is present, we don't need to dig further
416 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
417 if ($curlResult->isTimeout()) {
418 self::setFailure($url);
422 $serverdata = self::parseNodeinfo210($curlResult);
423 if (empty($serverdata)) {
424 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
425 $serverdata = self::fetchNodeinfo($url, $curlResult);
428 if ($only_nodeinfo && empty($serverdata)) {
429 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
430 self::setFailure($url);
432 } elseif (empty($serverdata)) {
433 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
436 // When there is no Nodeinfo, then use some protocol specific endpoints
437 if ($serverdata['network'] == Protocol::PHANTOM) {
439 // Fetch the landing page, possibly it reveals some data
440 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
441 $curlResult = DI::httpClient()->get($url, $accept);
442 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
443 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
444 $html_fetched = true;
446 $html_fetched = false;
449 if ($curlResult->isSuccess()) {
450 $json = json_decode($curlResult->getBody(), true);
451 if (!empty($json) && is_array($json)) {
452 $data = self::fetchDataFromSystemActor($json, $serverdata);
453 $serverdata = $data['server'];
454 $systemactor = $data['actor'];
455 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
456 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
458 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
459 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
462 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
463 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
464 $serverdata = self::analyseRootBody($curlResult, $serverdata);
468 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
469 self::setFailure($url);
473 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
474 $serverdata = self::detectMastodonAlikes($url, $serverdata);
478 // All following checks are done for systems that always have got a "host-meta" endpoint.
479 // With this check we don't have to waste time and ressources for dead systems.
480 // Also this hopefully prevents us from receiving abuse messages.
481 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
482 $validHostMeta = self::validHostMeta($url);
484 $validHostMeta = false;
487 if ($validHostMeta) {
488 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
489 $serverdata['detection-method'] = self::DETECT_HOST_META;
492 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
493 $serverdata = self::detectFriendica($url, $serverdata);
496 // The following systems have to be installed in the root directory.
498 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
499 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
500 $serverdata = self::fetchSiteinfo($url, $serverdata);
503 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
504 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
505 $serverdata = self::detectHubzilla($url, $serverdata);
508 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
509 $serverdata = self::detectPeertube($url, $serverdata);
512 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
513 $serverdata = self::detectGNUSocial($url, $serverdata);
516 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
517 $serverdata = self::detectFriendica($url, $serverdata);
520 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
521 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
524 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
525 // Since this endpoint is only rarely used, we query it at a later time
526 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
527 $serverdata = self::fetchStatistics($url, $serverdata);
531 // When we hadn't been able to detect the network type, we use the hint from the parameter
532 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
533 $serverdata['network'] = $network;
536 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
537 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
538 self::setFailure($url);
542 $serverdata['url'] = $url;
543 $serverdata['nurl'] = Strings::normaliseLink($url);
545 // We have to prevent an endless loop here.
546 // When a server is new, then there is no gserver entry yet.
547 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
548 // and this can call this function here as well.
549 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
550 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
551 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
554 // Detect the directory type
555 $serverdata['directory-type'] = self::DT_NONE;
557 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
558 $serverdata = self::checkMastodonDirectory($url, $serverdata);
560 if ($serverdata['directory-type'] == self::DT_NONE) {
561 $serverdata = self::checkPoCo($url, $serverdata);
565 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
566 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
569 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
571 // Numbers above a reasonable value (10 millions) are ignored
572 if ($serverdata['registered-users'] > 10000000) {
573 $serverdata['registered-users'] = 0;
576 // On an active server there has to be at least a single user
577 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
578 $serverdata['registered-users'] = 1;
579 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
580 $serverdata['registered-users'] = 0;
583 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
585 $serverdata['last_contact'] = DateTimeFormat::utcNow();
586 $serverdata['failed'] = false;
588 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
589 if (!DBA::isResult($gserver)) {
590 $serverdata['created'] = DateTimeFormat::utcNow();
591 $ret = self::insert($serverdata);
592 $id = DBA::lastInsertId();
594 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
595 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
596 if (DBA::isResult($gserver)) {
597 $id = $gserver['id'];
601 // Count the number of known contacts from this server
602 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
603 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
604 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
605 $max_users = max($apcontacts, $contacts);
606 if ($max_users > $serverdata['registered-users']) {
607 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
608 self::update(['registered-users' => $max_users], ['id' => $id]);
611 if (empty($serverdata['active-month-users'])) {
612 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
614 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
615 self::update(['active-month-users' => $contacts], ['id' => $id]);
619 if (empty($serverdata['active-halfyear-users'])) {
620 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
622 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
623 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
628 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
629 self::discoverRelay($url);
632 if (!empty($systemactor)) {
633 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
634 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
641 * Fetch relay data from a given server url
643 * @param string $server_url address of the server
647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
649 private static function discoverRelay(string $server_url)
651 Logger::info('Discover relay data', ['server' => $server_url]);
653 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
654 if (!$curlResult->isSuccess()) {
658 $data = json_decode($curlResult->getBody(), true);
659 if (!is_array($data)) {
663 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
664 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
666 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
668 $data['subscribe'] = false;
672 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
673 if (!DBA::isResult($gserver)) {
677 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
678 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
679 self::update($fields, ['id' => $gserver['id']]);
682 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
684 if ($data['scope'] == 'tags') {
687 foreach ($data['tags'] as $tag) {
688 $tag = mb_strtolower($tag);
689 if (strlen($tag) < 100) {
694 foreach ($tags as $tag) {
695 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
699 // Create or update the relay contact
701 if (isset($data['protocols'])) {
702 if (isset($data['protocols']['diaspora'])) {
703 $fields['network'] = Protocol::DIASPORA;
705 if (isset($data['protocols']['diaspora']['receive'])) {
706 $fields['batch'] = $data['protocols']['diaspora']['receive'];
707 } elseif (is_string($data['protocols']['diaspora'])) {
708 $fields['batch'] = $data['protocols']['diaspora'];
712 if (isset($data['protocols']['dfrn'])) {
713 $fields['network'] = Protocol::DFRN;
715 if (isset($data['protocols']['dfrn']['receive'])) {
716 $fields['batch'] = $data['protocols']['dfrn']['receive'];
717 } elseif (is_string($data['protocols']['dfrn'])) {
718 $fields['batch'] = $data['protocols']['dfrn'];
722 if (isset($data['protocols']['activitypub'])) {
723 $fields['network'] = Protocol::ACTIVITYPUB;
725 if (!empty($data['protocols']['activitypub']['actor'])) {
726 $fields['url'] = $data['protocols']['activitypub']['actor'];
728 if (!empty($data['protocols']['activitypub']['receive'])) {
729 $fields['batch'] = $data['protocols']['activitypub']['receive'];
734 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
736 Relay::updateContact($gserver, $fields);
740 * Fetch server data from '/statistics.json' on the given server
742 * @param string $url URL of the given server
744 * @return array server data
746 private static function fetchStatistics(string $url, array $serverdata): array
748 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
749 if (!$curlResult->isSuccess()) {
753 $data = json_decode($curlResult->getBody(), true);
758 // Some AP enabled systems return activity data that we don't expect here.
759 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
764 $old_serverdata = $serverdata;
766 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
768 if (!empty($data['version'])) {
770 $serverdata['version'] = $data['version'];
771 // Version numbers on statistics.json are presented with additional info, e.g.:
772 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
773 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
776 if (!empty($data['name'])) {
778 $serverdata['site_name'] = $data['name'];
781 if (!empty($data['network'])) {
783 $serverdata['platform'] = strtolower($data['network']);
785 if ($serverdata['platform'] == 'diaspora') {
786 $serverdata['network'] = Protocol::DIASPORA;
787 } elseif ($serverdata['platform'] == 'friendica') {
788 $serverdata['network'] = Protocol::DFRN;
789 } elseif ($serverdata['platform'] == 'hubzilla') {
790 $serverdata['network'] = Protocol::ZOT;
791 } elseif ($serverdata['platform'] == 'redmatrix') {
792 $serverdata['network'] = Protocol::ZOT;
796 if (!empty($data['total_users'])) {
798 $serverdata['registered-users'] = max($data['total_users'], 1);
801 if (!empty($data['active_users_monthly'])) {
803 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
806 if (!empty($data['active_users_halfyear'])) {
808 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
811 if (!empty($data['local_posts'])) {
813 $serverdata['local-posts'] = max($data['local_posts'], 0);
816 if (!empty($data['registrations_open'])) {
817 $serverdata['register_policy'] = Register::OPEN;
819 $serverdata['register_policy'] = Register::CLOSED;
823 return $old_serverdata;
830 * Detect server type by using the nodeinfo data
832 * @param string $url address of the server
833 * @param ICanHandleHttpResponses $httpResult
835 * @return array Server data
837 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
839 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
841 if (!$httpResult->isSuccess()) {
845 $nodeinfo = json_decode($httpResult->getBody(), true);
847 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
854 foreach ($nodeinfo['links'] as $link) {
855 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
856 Logger::info('Invalid nodeinfo format', ['url' => $url]);
859 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
860 $nodeinfo1_url = $link['href'];
861 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
862 $nodeinfo2_url = $link['href'];
866 if ($nodeinfo1_url . $nodeinfo2_url == '') {
872 if (!empty($nodeinfo2_url)) {
873 $server = self::parseNodeinfo2($nodeinfo2_url);
876 if (empty($server) && !empty($nodeinfo1_url)) {
877 $server = self::parseNodeinfo1($nodeinfo1_url);
886 * @param string $nodeinfo_url address of the nodeinfo path
888 * @return array Server data
890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
892 private static function parseNodeinfo1(string $nodeinfo_url): array
894 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
895 if (!$curlResult->isSuccess()) {
899 $nodeinfo = json_decode($curlResult->getBody(), true);
901 if (!is_array($nodeinfo)) {
905 $server = ['detection-method' => self::DETECT_NODEINFO_1,
906 'register_policy' => Register::CLOSED];
908 if (!empty($nodeinfo['openRegistrations'])) {
909 $server['register_policy'] = Register::OPEN;
912 if (is_array($nodeinfo['software'])) {
913 if (!empty($nodeinfo['software']['name'])) {
914 $server['platform'] = strtolower($nodeinfo['software']['name']);
917 if (!empty($nodeinfo['software']['version'])) {
918 $server['version'] = $nodeinfo['software']['version'];
919 // Version numbers on Nodeinfo are presented with additional info, e.g.:
920 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
921 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
925 if (!empty($nodeinfo['metadata']['nodeName'])) {
926 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
929 if (!empty($nodeinfo['usage']['users']['total'])) {
930 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
933 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
934 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
937 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
938 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
941 if (!empty($nodeinfo['usage']['localPosts'])) {
942 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
945 if (!empty($nodeinfo['usage']['localComments'])) {
946 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
949 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
951 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
952 $protocols[$protocol] = true;
955 if (!empty($protocols['friendica'])) {
956 $server['network'] = Protocol::DFRN;
957 } elseif (!empty($protocols['activitypub'])) {
958 $server['network'] = Protocol::ACTIVITYPUB;
959 } elseif (!empty($protocols['diaspora'])) {
960 $server['network'] = Protocol::DIASPORA;
961 } elseif (!empty($protocols['ostatus'])) {
962 $server['network'] = Protocol::OSTATUS;
963 } elseif (!empty($protocols['gnusocial'])) {
964 $server['network'] = Protocol::OSTATUS;
965 } elseif (!empty($protocols['zot'])) {
966 $server['network'] = Protocol::ZOT;
970 if (empty($server)) {
974 if (empty($server['network'])) {
975 $server['network'] = Protocol::PHANTOM;
984 * @see https://git.feneas.org/jaywink/nodeinfo2
986 * @param string $nodeinfo_url address of the nodeinfo path
988 * @return array Server data
990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992 private static function parseNodeinfo2(string $nodeinfo_url): array
994 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
995 if (!$curlResult->isSuccess()) {
999 $nodeinfo = json_decode($curlResult->getBody(), true);
1000 if (!is_array($nodeinfo)) {
1005 'detection-method' => self::DETECT_NODEINFO_2,
1006 'register_policy' => Register::CLOSED,
1007 'platform' => 'unknown',
1010 if (!empty($nodeinfo['openRegistrations'])) {
1011 $server['register_policy'] = Register::OPEN;
1014 if (!empty($nodeinfo['software'])) {
1015 if (isset($nodeinfo['software']['name'])) {
1016 $server['platform'] = strtolower($nodeinfo['software']['name']);
1019 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1020 $server['version'] = $nodeinfo['software']['version'];
1021 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1022 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1023 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1025 // qoto advertises itself as Mastodon
1026 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1027 $server['platform'] = 'qoto';
1032 if (!empty($nodeinfo['metadata']['nodeName'])) {
1033 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1036 if (!empty($nodeinfo['usage']['users']['total'])) {
1037 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1040 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1041 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1044 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1045 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1048 if (!empty($nodeinfo['usage']['localPosts'])) {
1049 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1052 if (!empty($nodeinfo['usage']['localComments'])) {
1053 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1056 if (!empty($nodeinfo['protocols'])) {
1058 foreach ($nodeinfo['protocols'] as $protocol) {
1059 if (is_string($protocol)) {
1060 $protocols[$protocol] = true;
1064 if (!empty($protocols['dfrn'])) {
1065 $server['network'] = Protocol::DFRN;
1066 } elseif (!empty($protocols['activitypub'])) {
1067 $server['network'] = Protocol::ACTIVITYPUB;
1068 } elseif (!empty($protocols['diaspora'])) {
1069 $server['network'] = Protocol::DIASPORA;
1070 } elseif (!empty($protocols['ostatus'])) {
1071 $server['network'] = Protocol::OSTATUS;
1072 } elseif (!empty($protocols['gnusocial'])) {
1073 $server['network'] = Protocol::OSTATUS;
1074 } elseif (!empty($protocols['zot'])) {
1075 $server['network'] = Protocol::ZOT;
1079 if (empty($server)) {
1083 if (empty($server['network'])) {
1084 $server['network'] = Protocol::PHANTOM;
1091 * Parses NodeInfo2 protocol 1.0
1093 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1095 * @param string $nodeinfo_url address of the nodeinfo path
1097 * @return array Server data
1099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1101 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1103 if (!$httpResult->isSuccess()) {
1107 $nodeinfo = json_decode($httpResult->getBody(), true);
1109 if (!is_array($nodeinfo)) {
1113 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1114 'register_policy' => Register::CLOSED];
1116 if (!empty($nodeinfo['openRegistrations'])) {
1117 $server['register_policy'] = Register::OPEN;
1120 if (!empty($nodeinfo['server'])) {
1121 if (!empty($nodeinfo['server']['software'])) {
1122 $server['platform'] = strtolower($nodeinfo['server']['software']);
1125 if (!empty($nodeinfo['server']['version'])) {
1126 $server['version'] = $nodeinfo['server']['version'];
1127 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1128 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1129 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1132 if (!empty($nodeinfo['server']['name'])) {
1133 $server['site_name'] = $nodeinfo['server']['name'];
1137 if (!empty($nodeinfo['usage']['users']['total'])) {
1138 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1141 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1142 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1145 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1146 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1149 if (!empty($nodeinfo['usage']['localPosts'])) {
1150 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1153 if (!empty($nodeinfo['usage']['localComments'])) {
1154 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1157 if (!empty($nodeinfo['protocols'])) {
1159 foreach ($nodeinfo['protocols'] as $protocol) {
1160 if (is_string($protocol)) {
1161 $protocols[$protocol] = true;
1165 if (!empty($protocols['dfrn'])) {
1166 $server['network'] = Protocol::DFRN;
1167 } elseif (!empty($protocols['activitypub'])) {
1168 $server['network'] = Protocol::ACTIVITYPUB;
1169 } elseif (!empty($protocols['diaspora'])) {
1170 $server['network'] = Protocol::DIASPORA;
1171 } elseif (!empty($protocols['ostatus'])) {
1172 $server['network'] = Protocol::OSTATUS;
1173 } elseif (!empty($protocols['gnusocial'])) {
1174 $server['network'] = Protocol::OSTATUS;
1175 } elseif (!empty($protocols['zot'])) {
1176 $server['network'] = Protocol::ZOT;
1180 if (empty($server) || empty($server['platform'])) {
1184 if (empty($server['network'])) {
1185 $server['network'] = Protocol::PHANTOM;
1192 * Fetch server information from a 'siteinfo.json' file on the given server
1194 * @param string $url URL of the given server
1195 * @param array $serverdata array with server data
1197 * @return array server data
1199 private static function fetchSiteinfo(string $url, array $serverdata): array
1201 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1202 if (!$curlResult->isSuccess()) {
1206 $data = json_decode($curlResult->getBody(), true);
1211 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1212 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1215 if (!empty($data['url'])) {
1216 $serverdata['platform'] = strtolower($data['platform']);
1217 $serverdata['version'] = $data['version'] ?? 'N/A';
1220 if (!empty($data['plugins'])) {
1221 if (in_array('pubcrawl', $data['plugins'])) {
1222 $serverdata['network'] = Protocol::ACTIVITYPUB;
1223 } elseif (in_array('diaspora', $data['plugins'])) {
1224 $serverdata['network'] = Protocol::DIASPORA;
1225 } elseif (in_array('gnusoc', $data['plugins'])) {
1226 $serverdata['network'] = Protocol::OSTATUS;
1228 $serverdata['network'] = Protocol::ZOT;
1232 if (!empty($data['site_name'])) {
1233 $serverdata['site_name'] = $data['site_name'];
1236 if (!empty($data['channels_total'])) {
1237 $serverdata['registered-users'] = max($data['channels_total'], 1);
1240 if (!empty($data['channels_active_monthly'])) {
1241 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1244 if (!empty($data['channels_active_halfyear'])) {
1245 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1248 if (!empty($data['local_posts'])) {
1249 $serverdata['local-posts'] = max($data['local_posts'], 0);
1252 if (!empty($data['local_comments'])) {
1253 $serverdata['local-comments'] = max($data['local_comments'], 0);
1256 if (!empty($data['register_policy'])) {
1257 switch ($data['register_policy']) {
1258 case 'REGISTER_OPEN':
1259 $serverdata['register_policy'] = Register::OPEN;
1262 case 'REGISTER_APPROVE':
1263 $serverdata['register_policy'] = Register::APPROVE;
1266 case 'REGISTER_CLOSED':
1268 $serverdata['register_policy'] = Register::CLOSED;
1277 * Fetches server data via an ActivityPub account with url of that server
1279 * @param string $url URL of the given server
1280 * @param array $serverdata array with server data
1282 * @return array server data
1286 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1289 return ['server' => $serverdata, 'actor' => ''];
1292 $actor = JsonLD::compact($data, false);
1293 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1294 $serverdata['network'] = Protocol::ACTIVITYPUB;
1295 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1296 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1297 if (!empty($actor['as:generator'])) {
1298 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1299 $serverdata['platform'] = strtolower(array_shift($generator));
1300 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1302 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1304 return ['server' => $serverdata, 'actor' => $actor['@id']];
1305 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1306 // By now only Ktistec seems to provide collections this way
1307 $serverdata['platform'] = 'ktistec';
1308 $serverdata['network'] = Protocol::ACTIVITYPUB;
1309 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1311 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1312 if (!empty($actors) && !empty($actors[0]['@id'])) {
1313 $actor_url = $actor['@id'] . $actors[0]['@id'];
1318 return ['server' => $serverdata, 'actor' => $actor_url];
1320 return ['server' => $serverdata, 'actor' => ''];
1324 * Checks if the server contains a valid host meta file
1326 * @param string $url URL of the given server
1328 * @return boolean 'true' if the server seems to be vital
1330 private static function validHostMeta(string $url): bool
1332 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1333 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1334 if (!$curlResult->isSuccess()) {
1338 $xrd = XML::parseString($curlResult->getBody(), true);
1339 if (!is_object($xrd)) {
1343 $elements = XML::elementToArray($xrd);
1344 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1349 foreach ($elements['xrd']['link'] as $link) {
1350 // When there is more than a single "link" element, the array looks slightly different
1351 if (!empty($link['@attributes'])) {
1352 $link = $link['@attributes'];
1355 if (empty($link['rel']) || empty($link['template'])) {
1359 if ($link['rel'] == 'lrdd') {
1360 // When the webfinger host is the same like the system host, it should be ok.
1361 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1369 * Detect the network of the given server via their known contacts
1371 * @param string $url URL of the given server
1372 * @param array $serverdata array with server data
1374 * @return array server data
1376 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1380 $nurl = Strings::normaliseLink($url);
1382 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1383 while ($apcontact = DBA::fetch($apcontacts)) {
1384 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1386 DBA::close($apcontacts);
1388 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1389 while ($pcontact = DBA::fetch($pcontacts)) {
1390 $contacts[$pcontact['nurl']] = $pcontact['url'];
1392 DBA::close($pcontacts);
1394 if (empty($contacts)) {
1399 foreach ($contacts as $contact) {
1400 // Endlosschleife verhindern wegen gsid!
1401 $data = Probe::uri($contact);
1402 if (in_array($data['network'], Protocol::FEDERATED)) {
1403 $serverdata['network'] = $data['network'];
1405 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1406 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1409 } elseif ((time() - $time) > 10) {
1410 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1419 * Checks if the given server does have a '/poco' endpoint.
1420 * This is used for the 'PortableContact' functionality,
1421 * which is used by both Friendica and Hubzilla.
1423 * @param string $url URL of the given server
1424 * @param array $serverdata array with server data
1426 * @return array server data
1428 private static function checkPoCo(string $url, array $serverdata): array
1430 $serverdata['poco'] = '';
1432 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1433 if (!$curlResult->isSuccess()) {
1437 $data = json_decode($curlResult->getBody(), true);
1442 if (!empty($data['totalResults'])) {
1443 $registeredUsers = $serverdata['registered-users'] ?? 0;
1444 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1445 $serverdata['directory-type'] = self::DT_POCO;
1446 $serverdata['poco'] = $url . '/poco';
1453 * Checks if the given server does have a Mastodon style directory endpoint.
1455 * @param string $url URL of the given server
1456 * @param array $serverdata array with server data
1458 * @return array server data
1460 public static function checkMastodonDirectory(string $url, array $serverdata): array
1462 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1463 if (!$curlResult->isSuccess()) {
1467 $data = json_decode($curlResult->getBody(), true);
1472 if (count($data) == 1) {
1473 $serverdata['directory-type'] = self::DT_MASTODON;
1480 * Detects Peertube via their known endpoint
1482 * @param string $url URL of the given server
1483 * @param array $serverdata array with server data
1485 * @return array server data
1487 private static function detectPeertube(string $url, array $serverdata): array
1489 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1490 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1494 $data = json_decode($curlResult->getBody(), true);
1499 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1500 $serverdata['platform'] = 'peertube';
1501 $serverdata['version'] = $data['serverVersion'];
1502 $serverdata['network'] = Protocol::ACTIVITYPUB;
1504 if (!empty($data['instance']['name'])) {
1505 $serverdata['site_name'] = $data['instance']['name'];
1508 if (!empty($data['instance']['shortDescription'])) {
1509 $serverdata['info'] = $data['instance']['shortDescription'];
1512 if (!empty($data['signup'])) {
1513 if (!empty($data['signup']['allowed'])) {
1514 $serverdata['register_policy'] = Register::OPEN;
1518 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1519 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1527 * Detects the version number of a given server when it was a NextCloud installation
1529 * @param string $url URL of the given server
1530 * @param array $serverdata array with server data
1531 * @param bool $validHostMeta
1533 * @return array server data
1535 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1537 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1538 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1542 $data = json_decode($curlResult->getBody(), true);
1547 if (!empty($data['version'])) {
1548 $serverdata['platform'] = 'nextcloud';
1549 $serverdata['version'] = $data['version'];
1551 if ($validHostMeta) {
1552 $serverdata['network'] = Protocol::ACTIVITYPUB;
1555 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1556 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1564 * Fetches weekly usage data
1566 * @param string $url URL of the given server
1567 * @param array $serverdata array with server data
1569 * @return array server data
1571 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1573 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1574 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1578 $data = json_decode($curlResult->getBody(), true);
1584 foreach ($data as $week) {
1585 // Use only data from a full week
1586 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1590 // Most likely the data is sorted correctly. But we better are safe than sorry
1591 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1592 $current_week = $week;
1596 if (!empty($current_week['logins'])) {
1597 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1604 * Detects data from a given server url if it was a mastodon alike system
1606 * @param string $url URL of the given server
1607 * @param array $serverdata array with server data
1609 * @return array server data
1611 private static function detectMastodonAlikes(string $url, array $serverdata): array
1613 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1614 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1618 $data = json_decode($curlResult->getBody(), true);
1625 if (!empty($data['version'])) {
1626 $serverdata['platform'] = 'mastodon';
1627 $serverdata['version'] = $data['version'] ?? '';
1628 $serverdata['network'] = Protocol::ACTIVITYPUB;
1632 if (!empty($data['title'])) {
1633 $serverdata['site_name'] = $data['title'];
1636 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1637 $serverdata['platform'] = 'mastodon';
1638 $serverdata['network'] = Protocol::ACTIVITYPUB;
1642 if (!empty($data['description'])) {
1643 $serverdata['info'] = trim($data['description']);
1646 if (!empty($data['stats']['user_count'])) {
1647 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1650 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1651 $serverdata['platform'] = strtolower($matches[1]);
1652 $serverdata['version'] = $matches[2];
1656 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1657 $serverdata['platform'] = 'pleroma';
1658 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1662 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1663 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1664 $serverdata['platform'] = 'pleroma';
1668 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1669 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1676 * Detects data from typical Hubzilla endpoints
1678 * @param string $url URL of the given server
1679 * @param array $serverdata array with server data
1681 * @return array server data
1683 private static function detectHubzilla(string $url, array $serverdata): array
1685 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1686 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1690 $data = json_decode($curlResult->getBody(), true);
1691 if (empty($data) || empty($data['site'])) {
1695 if (!empty($data['site']['name'])) {
1696 $serverdata['site_name'] = $data['site']['name'];
1699 if (!empty($data['site']['platform'])) {
1700 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1701 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1702 $serverdata['network'] = Protocol::ZOT;
1705 if (!empty($data['site']['hubzilla'])) {
1706 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1707 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1708 $serverdata['network'] = Protocol::ZOT;
1711 if (!empty($data['site']['redmatrix'])) {
1712 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1713 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1714 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1715 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1718 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1719 $serverdata['network'] = Protocol::ZOT;
1723 $inviteonly = false;
1726 if (!empty($data['site']['closed'])) {
1727 $closed = self::toBoolean($data['site']['closed']);
1730 if (!empty($data['site']['private'])) {
1731 $private = self::toBoolean($data['site']['private']);
1734 if (!empty($data['site']['inviteonly'])) {
1735 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1738 if (!$closed && !$private and $inviteonly) {
1739 $serverdata['register_policy'] = Register::APPROVE;
1740 } elseif (!$closed && !$private) {
1741 $serverdata['register_policy'] = Register::OPEN;
1743 $serverdata['register_policy'] = Register::CLOSED;
1746 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1747 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1754 * Converts input value to a boolean value
1756 * @param string|integer $val
1760 private static function toBoolean($val): bool
1762 if (($val == 'true') || ($val == 1)) {
1764 } elseif (($val == 'false') || ($val == 0)) {
1772 * Detect if the URL belongs to a GNU Social server
1774 * @param string $url URL of the given server
1775 * @param array $serverdata array with server data
1777 * @return array server data
1779 private static function detectGNUSocial(string $url, array $serverdata): array
1781 // Test for GNU Social
1782 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1783 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1784 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1785 $serverdata['platform'] = 'gnusocial';
1786 // Remove junk that some GNU Social servers return
1787 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1788 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1789 $serverdata['version'] = trim($serverdata['version'], '"');
1790 $serverdata['network'] = Protocol::OSTATUS;
1792 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1793 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1799 // Test for Statusnet
1800 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1801 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1802 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1804 // Remove junk that some GNU Social servers return
1805 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1806 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1807 $serverdata['version'] = trim($serverdata['version'], '"');
1809 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1810 $serverdata['platform'] = 'pleroma';
1811 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1812 $serverdata['network'] = Protocol::ACTIVITYPUB;
1814 $serverdata['platform'] = 'statusnet';
1815 $serverdata['network'] = Protocol::OSTATUS;
1818 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1819 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1827 * Detect if the URL belongs to a Friendica server
1829 * @param string $url URL of the given server
1830 * @param array $serverdata array with server data
1832 * @return array server data
1834 private static function detectFriendica(string $url, array $serverdata): array
1836 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1837 // Because of this me must not use ACCEPT_JSON here.
1838 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1839 if (!$curlResult->isSuccess()) {
1840 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1842 $platform = 'Friendika';
1845 $platform = 'Friendica';
1848 if (!$curlResult->isSuccess()) {
1852 $data = json_decode($curlResult->getBody(), true);
1853 if (empty($data) || empty($data['version'])) {
1857 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1858 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1861 $serverdata['network'] = Protocol::DFRN;
1862 $serverdata['version'] = $data['version'];
1864 if (!empty($data['no_scrape_url'])) {
1865 $serverdata['noscrape'] = $data['no_scrape_url'];
1868 if (!empty($data['site_name'])) {
1869 $serverdata['site_name'] = $data['site_name'];
1872 if (!empty($data['info'])) {
1873 $serverdata['info'] = trim($data['info']);
1876 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1877 switch ($register_policy) {
1878 case 'REGISTER_OPEN':
1879 $serverdata['register_policy'] = Register::OPEN;
1882 case 'REGISTER_APPROVE':
1883 $serverdata['register_policy'] = Register::APPROVE;
1886 case 'REGISTER_CLOSED':
1887 case 'REGISTER_INVITATION':
1888 $serverdata['register_policy'] = Register::CLOSED;
1891 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1892 $serverdata['register_policy'] = Register::CLOSED;
1896 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1902 * Analyses the landing page of a given server for hints about type and system of that server
1904 * @param object $curlResult result of curl execution
1905 * @param array $serverdata array with server data
1907 * @return array server data
1909 private static function analyseRootBody($curlResult, array $serverdata): array
1911 if (empty($curlResult->getBody())) {
1915 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
1916 require __DIR__ . '/../../static/platforms.config.php';
1918 throw new HTTPException\InternalServerErrorException('Invalid platform file');
1921 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1923 $doc = new DOMDocument();
1924 @$doc->loadHTML($curlResult->getBody());
1925 $xpath = new DOMXPath($doc);
1928 // We can only detect honk via some HTML element on their page
1929 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1930 $serverdata['platform'] = 'honk';
1931 $serverdata['network'] = Protocol::ACTIVITYPUB;
1935 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1936 if (!empty($title)) {
1937 $serverdata['site_name'] = $title;
1940 $list = $xpath->query('//meta[@name]');
1942 foreach ($list as $node) {
1944 if ($node->attributes->length) {
1945 foreach ($node->attributes as $attribute) {
1946 $value = trim($attribute->value);
1947 if (empty($value)) {
1951 $attr[$attribute->name] = $value;
1954 if (empty($attr['name']) || empty($attr['content'])) {
1959 if ($attr['name'] == 'description') {
1960 $serverdata['info'] = $attr['content'];
1963 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1964 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
1965 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
1966 $platform = str_replace('/', ' ', $platform);
1967 $platform_parts = explode(' ', $platform);
1968 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
1969 $platform = $platform_parts[0];
1970 $serverdata['version'] = $platform_parts[1];
1972 if (in_array($platform, array_values($dfrn_platforms))) {
1973 $serverdata['network'] = Protocol::DFRN;
1974 } elseif (in_array($platform, array_values($ap_platforms))) {
1975 $serverdata['network'] = Protocol::ACTIVITYPUB;
1976 } elseif (in_array($platform, array_values($zap_platforms))) {
1977 $serverdata['network'] = Protocol::ZOT;
1979 if (in_array($platform, array_values($platforms))) {
1980 $serverdata['platform'] = $platform;
1986 $list = $xpath->query('//meta[@property]');
1988 foreach ($list as $node) {
1990 if ($node->attributes->length) {
1991 foreach ($node->attributes as $attribute) {
1992 $value = trim($attribute->value);
1993 if (empty($value)) {
1997 $attr[$attribute->name] = $value;
2000 if (empty($attr['property']) || empty($attr['content'])) {
2005 if ($attr['property'] == 'og:site_name') {
2006 $serverdata['site_name'] = $attr['content'];
2009 if ($attr['property'] == 'og:description') {
2010 $serverdata['info'] = $attr['content'];
2013 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2014 if (in_array($attr['content'], array_keys($platforms))) {
2015 $serverdata['platform'] = $platforms[$attr['content']];
2019 if (in_array($attr['content'], array_keys($ap_platforms))) {
2020 $serverdata['network'] = Protocol::ACTIVITYPUB;
2021 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2022 $serverdata['network'] = Protocol::ZOT;
2027 $list = $xpath->query('//link[@rel="me"]');
2028 foreach ($list as $node) {
2029 foreach ($node->attributes as $attribute) {
2030 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2031 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2032 $serverdata['platform'] = 'microblog';
2033 $serverdata['network'] = Protocol::ACTIVITYPUB;
2039 if ($serverdata['platform'] != 'microblog') {
2040 $list = $xpath->query('//link[@rel="micropub"]');
2041 foreach ($list as $node) {
2042 foreach ($node->attributes as $attribute) {
2043 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2044 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2045 $serverdata['platform'] = 'microblog';
2046 $serverdata['network'] = Protocol::ACTIVITYPUB;
2053 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2054 $serverdata['detection-method'] = self::DETECT_BODY;
2061 * Analyses the header data of a given server for hints about type and system of that server
2063 * @param object $curlResult result of curl execution
2064 * @param array $serverdata array with server data
2066 * @return array server data
2068 private static function analyseRootHeader($curlResult, array $serverdata): array
2070 if ($curlResult->getHeader('server') == 'Mastodon') {
2071 $serverdata['platform'] = 'mastodon';
2072 $serverdata['network'] = Protocol::ACTIVITYPUB;
2073 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2074 $serverdata['platform'] = 'diaspora';
2075 $serverdata['network'] = Protocol::DIASPORA;
2076 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2077 } elseif ($curlResult->inHeader('x-friendica-version')) {
2078 $serverdata['platform'] = 'friendica';
2079 $serverdata['network'] = Protocol::DFRN;
2080 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2085 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2086 $serverdata['detection-method'] = self::DETECT_HEADER;
2093 * Update GServer entries
2095 public static function discover()
2097 // Update the server list
2098 self::discoverFederation();
2102 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2104 if ($requery_days == 0) {
2108 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2110 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2111 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2112 ['order' => ['RAND()']]);
2114 while ($gserver = DBA::fetch($gservers)) {
2115 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2116 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2118 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2119 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2121 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2122 self::update($fields, ['nurl' => $gserver['nurl']]);
2124 if (--$no_of_queries == 0) {
2129 DBA::close($gservers);
2133 * Discover federated servers
2135 private static function discoverFederation()
2137 $last = DI::config()->get('poco', 'last_federation_discovery');
2140 $next = $last + (24 * 60 * 60);
2142 if ($next > time()) {
2147 // Discover federated servers
2148 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2149 foreach ($protocols as $protocol) {
2150 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2151 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2152 if (!empty($curlResult)) {
2153 $data = json_decode($curlResult, true);
2154 if (!empty($data['data']['nodes'])) {
2155 foreach ($data['data']['nodes'] as $server) {
2156 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2157 self::add('https://' . $server['host'], true);
2163 // Disvover Mastodon servers
2164 $accesstoken = DI::config()->get('system', 'instances_social_key');
2166 if (!empty($accesstoken)) {
2167 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2168 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2169 if ($curlResult->isSuccess()) {
2170 $servers = json_decode($curlResult->getBody(), true);
2172 if (!empty($servers['instances'])) {
2173 foreach ($servers['instances'] as $server) {
2174 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2181 DI::config()->set('poco', 'last_federation_discovery', time());
2185 * Set the protocol for the given server
2187 * @param int $gsid Server id
2188 * @param int $protocol Protocol id
2192 public static function setProtocol(int $gsid, int $protocol)
2198 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2199 if (!DBA::isResult($gserver)) {
2203 $old = $gserver['protocol'];
2205 if (!is_null($old)) {
2207 The priority for the protocols is:
2209 2. DFRN via Diaspora
2215 // We don't need to change it when nothing is to be changed
2216 if ($old == $protocol) {
2220 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2221 if ($protocol == Post\DeliveryData::OSTATUS) {
2225 // If the server is marked as ActivityPub then we won't change it to anything different
2226 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2230 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2231 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2235 // Don't change it to Diaspora when it is a legacy DFRN server
2236 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2241 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2242 self::update(['protocol' => $protocol], ['id' => $gsid]);
2246 * Fetch the protocol of the given server
2248 * @param int $gsid Server id
2250 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2254 public static function getProtocol(int $gsid): ?int
2260 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2261 if (DBA::isResult($gserver)) {
2262 return $gserver['protocol'];
2269 * Update rows in the gserver table.
2270 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2272 * @param array $fields
2273 * @param array $condition
2279 public static function update(array $fields, array $condition): bool
2281 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2283 return DBA::update('gserver', $fields, $condition);
2287 * Insert a row into the gserver table.
2288 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2290 * @param array $fields
2291 * @param int $duplicate_mode What to do on a duplicated entry
2297 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2299 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2301 return DBA::insert('gserver', $fields, $duplicate_mode);