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(Worker::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
118 $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 self::insert(['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 if (empty($urlparts)) {
330 unset($urlparts['user']);
331 unset($urlparts['pass']);
332 unset($urlparts['query']);
333 unset($urlparts['fragment']);
334 return (string)Uri::fromParts($urlparts);
338 * Detect server data (type, protocol, version number, ...)
339 * The detected data is then updated or inserted in the gserver table.
341 * @param string $url URL of the given server
342 * @param string $network Network value that is used, when detection failed
343 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
345 * @return boolean 'true' if server could be detected
347 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
349 Logger::info('Detect server type', ['server' => $url]);
351 $original_url = $url;
353 // Remove URL content that is not supposed to exist for a server url
354 $url = rtrim(self::cleanURL($url), '/');
356 Logger::notice('Empty URL.');
360 // If the URL missmatches, then we mark the old entry as failure
361 if (!Strings::compareLink($url, $original_url)) {
362 self::setFailure($original_url);
363 if (!self::getID($url, true)) {
364 self::detect($url, $network, $only_nodeinfo);
369 $valid_url = Network::isUrlValid($url);
371 self::setFailure($url);
374 $valid_url = rtrim($valid_url, '/');
377 if (!Strings::compareLink($url, $valid_url)) {
378 // We only follow redirects when the path stays the same or the target url has no path.
379 // Some systems have got redirects on their landing page to a single account page. This check handles it.
380 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))) ||
381 (((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)))) {
382 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
383 self::setFailure($url);
384 if (!self::getID($valid_url, true)) {
385 self::detect($valid_url, $network, $only_nodeinfo);
390 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)) &&
391 (parse_url($url, PHP_URL_PATH) == '')) {
392 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
393 $parts = parse_url($valid_url);
394 unset($parts['path']);
395 $valid_url = (string)Uri::fromParts($parts);
397 self::setFailure($url);
398 if (!self::getID($valid_url, true)) {
399 self::detect($valid_url, $network, $only_nodeinfo);
403 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
406 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
407 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
408 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
412 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
414 // When a nodeinfo is present, we don't need to dig further
415 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
416 if ($curlResult->isTimeout()) {
417 self::setFailure($url);
421 $serverdata = self::parseNodeinfo210($curlResult);
422 if (empty($serverdata)) {
423 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
424 $serverdata = self::fetchNodeinfo($url, $curlResult);
427 if ($only_nodeinfo && empty($serverdata)) {
428 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
429 self::setFailure($url);
431 } elseif (empty($serverdata)) {
432 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
435 // When there is no Nodeinfo, then use some protocol specific endpoints
436 if ($serverdata['network'] == Protocol::PHANTOM) {
438 // Fetch the landing page, possibly it reveals some data
439 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
440 $curlResult = DI::httpClient()->get($url, $accept);
441 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
442 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
443 $html_fetched = true;
445 $html_fetched = false;
448 if ($curlResult->isSuccess()) {
449 $json = json_decode($curlResult->getBody(), true);
450 if (!empty($json) && is_array($json)) {
451 $data = self::fetchDataFromSystemActor($json, $serverdata);
452 $serverdata = $data['server'];
453 $systemactor = $data['actor'];
454 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
455 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
457 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
458 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
461 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
462 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
463 $serverdata = self::analyseRootBody($curlResult, $serverdata);
467 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
468 self::setFailure($url);
472 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
473 $serverdata = self::detectMastodonAlikes($url, $serverdata);
477 // All following checks are done for systems that always have got a "host-meta" endpoint.
478 // With this check we don't have to waste time and ressources for dead systems.
479 // Also this hopefully prevents us from receiving abuse messages.
480 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
481 $validHostMeta = self::validHostMeta($url);
483 $validHostMeta = false;
486 if ($validHostMeta) {
487 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
488 $serverdata['detection-method'] = self::DETECT_HOST_META;
491 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
492 $serverdata = self::detectFriendica($url, $serverdata);
495 // The following systems have to be installed in the root directory.
497 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
498 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
499 $serverdata = self::fetchSiteinfo($url, $serverdata);
502 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
503 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
504 $serverdata = self::detectHubzilla($url, $serverdata);
507 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
508 $serverdata = self::detectPeertube($url, $serverdata);
511 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
512 $serverdata = self::detectGNUSocial($url, $serverdata);
515 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
516 $serverdata = self::detectFriendica($url, $serverdata);
519 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
520 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
523 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
524 // Since this endpoint is only rarely used, we query it at a later time
525 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
526 $serverdata = self::fetchStatistics($url, $serverdata);
530 // When we hadn't been able to detect the network type, we use the hint from the parameter
531 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
532 $serverdata['network'] = $network;
535 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
536 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
537 self::setFailure($url);
541 $serverdata['url'] = $url;
542 $serverdata['nurl'] = Strings::normaliseLink($url);
544 // We have to prevent an endless loop here.
545 // When a server is new, then there is no gserver entry yet.
546 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
547 // and this can call this function here as well.
548 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
549 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
550 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
553 // Detect the directory type
554 $serverdata['directory-type'] = self::DT_NONE;
556 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
557 $serverdata = self::checkMastodonDirectory($url, $serverdata);
559 if ($serverdata['directory-type'] == self::DT_NONE) {
560 $serverdata = self::checkPoCo($url, $serverdata);
564 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
565 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
568 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
570 // Numbers above a reasonable value (10 millions) are ignored
571 if ($serverdata['registered-users'] > 10000000) {
572 $serverdata['registered-users'] = 0;
575 // On an active server there has to be at least a single user
576 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
577 $serverdata['registered-users'] = 1;
578 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
579 $serverdata['registered-users'] = 0;
582 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
584 $serverdata['last_contact'] = DateTimeFormat::utcNow();
585 $serverdata['failed'] = false;
587 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
588 if (!DBA::isResult($gserver)) {
589 $serverdata['created'] = DateTimeFormat::utcNow();
590 $ret = self::insert($serverdata);
591 $id = DBA::lastInsertId();
593 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
594 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
595 if (DBA::isResult($gserver)) {
596 $id = $gserver['id'];
600 // Count the number of known contacts from this server
601 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
602 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
603 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
604 $max_users = max($apcontacts, $contacts);
605 if ($max_users > $serverdata['registered-users']) {
606 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
607 self::update(['registered-users' => $max_users], ['id' => $id]);
610 if (empty($serverdata['active-month-users'])) {
611 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
613 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
614 self::update(['active-month-users' => $contacts], ['id' => $id]);
618 if (empty($serverdata['active-halfyear-users'])) {
619 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
621 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
622 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
627 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
628 self::discoverRelay($url);
631 if (!empty($systemactor)) {
632 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
633 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
640 * Fetch relay data from a given server url
642 * @param string $server_url address of the server
646 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
648 private static function discoverRelay(string $server_url)
650 Logger::info('Discover relay data', ['server' => $server_url]);
652 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
653 if (!$curlResult->isSuccess()) {
657 $data = json_decode($curlResult->getBody(), true);
658 if (!is_array($data)) {
662 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
663 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
665 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
667 $data['subscribe'] = false;
671 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
672 if (!DBA::isResult($gserver)) {
676 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
677 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
678 self::update($fields, ['id' => $gserver['id']]);
681 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
683 if ($data['scope'] == 'tags') {
686 foreach ($data['tags'] as $tag) {
687 $tag = mb_strtolower($tag);
688 if (strlen($tag) < 100) {
693 foreach ($tags as $tag) {
694 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
698 // Create or update the relay contact
700 if (isset($data['protocols'])) {
701 if (isset($data['protocols']['diaspora'])) {
702 $fields['network'] = Protocol::DIASPORA;
704 if (isset($data['protocols']['diaspora']['receive'])) {
705 $fields['batch'] = $data['protocols']['diaspora']['receive'];
706 } elseif (is_string($data['protocols']['diaspora'])) {
707 $fields['batch'] = $data['protocols']['diaspora'];
711 if (isset($data['protocols']['dfrn'])) {
712 $fields['network'] = Protocol::DFRN;
714 if (isset($data['protocols']['dfrn']['receive'])) {
715 $fields['batch'] = $data['protocols']['dfrn']['receive'];
716 } elseif (is_string($data['protocols']['dfrn'])) {
717 $fields['batch'] = $data['protocols']['dfrn'];
721 if (isset($data['protocols']['activitypub'])) {
722 $fields['network'] = Protocol::ACTIVITYPUB;
724 if (!empty($data['protocols']['activitypub']['actor'])) {
725 $fields['url'] = $data['protocols']['activitypub']['actor'];
727 if (!empty($data['protocols']['activitypub']['receive'])) {
728 $fields['batch'] = $data['protocols']['activitypub']['receive'];
733 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
735 Relay::updateContact($gserver, $fields);
739 * Fetch server data from '/statistics.json' on the given server
741 * @param string $url URL of the given server
743 * @return array server data
745 private static function fetchStatistics(string $url, array $serverdata): array
747 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
748 if (!$curlResult->isSuccess()) {
752 $data = json_decode($curlResult->getBody(), true);
757 // Some AP enabled systems return activity data that we don't expect here.
758 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
763 $old_serverdata = $serverdata;
765 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
767 if (!empty($data['version'])) {
769 $serverdata['version'] = $data['version'];
770 // Version numbers on statistics.json are presented with additional info, e.g.:
771 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
772 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
775 if (!empty($data['name'])) {
777 $serverdata['site_name'] = $data['name'];
780 if (!empty($data['network'])) {
782 $serverdata['platform'] = strtolower($data['network']);
784 if ($serverdata['platform'] == 'diaspora') {
785 $serverdata['network'] = Protocol::DIASPORA;
786 } elseif ($serverdata['platform'] == 'friendica') {
787 $serverdata['network'] = Protocol::DFRN;
788 } elseif ($serverdata['platform'] == 'hubzilla') {
789 $serverdata['network'] = Protocol::ZOT;
790 } elseif ($serverdata['platform'] == 'redmatrix') {
791 $serverdata['network'] = Protocol::ZOT;
795 if (!empty($data['total_users'])) {
797 $serverdata['registered-users'] = max($data['total_users'], 1);
800 if (!empty($data['active_users_monthly'])) {
802 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
805 if (!empty($data['active_users_halfyear'])) {
807 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
810 if (!empty($data['local_posts'])) {
812 $serverdata['local-posts'] = max($data['local_posts'], 0);
815 if (!empty($data['registrations_open'])) {
816 $serverdata['register_policy'] = Register::OPEN;
818 $serverdata['register_policy'] = Register::CLOSED;
822 return $old_serverdata;
829 * Detect server type by using the nodeinfo data
831 * @param string $url address of the server
832 * @param ICanHandleHttpResponses $httpResult
834 * @return array Server data
836 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
838 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
840 if (!$httpResult->isSuccess()) {
844 $nodeinfo = json_decode($httpResult->getBody(), true);
846 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
853 foreach ($nodeinfo['links'] as $link) {
854 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
855 Logger::info('Invalid nodeinfo format', ['url' => $url]);
858 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
859 $nodeinfo1_url = $link['href'];
860 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
861 $nodeinfo2_url = $link['href'];
865 if ($nodeinfo1_url . $nodeinfo2_url == '') {
871 if (!empty($nodeinfo2_url)) {
872 $server = self::parseNodeinfo2($nodeinfo2_url);
875 if (empty($server) && !empty($nodeinfo1_url)) {
876 $server = self::parseNodeinfo1($nodeinfo1_url);
885 * @param string $nodeinfo_url address of the nodeinfo path
887 * @return array Server data
889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891 private static function parseNodeinfo1(string $nodeinfo_url): array
893 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
894 if (!$curlResult->isSuccess()) {
898 $nodeinfo = json_decode($curlResult->getBody(), true);
900 if (!is_array($nodeinfo)) {
904 $server = ['detection-method' => self::DETECT_NODEINFO_1,
905 'register_policy' => Register::CLOSED];
907 if (!empty($nodeinfo['openRegistrations'])) {
908 $server['register_policy'] = Register::OPEN;
911 if (is_array($nodeinfo['software'])) {
912 if (!empty($nodeinfo['software']['name'])) {
913 $server['platform'] = strtolower($nodeinfo['software']['name']);
916 if (!empty($nodeinfo['software']['version'])) {
917 $server['version'] = $nodeinfo['software']['version'];
918 // Version numbers on Nodeinfo are presented with additional info, e.g.:
919 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
920 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
924 if (!empty($nodeinfo['metadata']['nodeName'])) {
925 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
928 if (!empty($nodeinfo['usage']['users']['total'])) {
929 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
932 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
933 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
936 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
937 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
940 if (!empty($nodeinfo['usage']['localPosts'])) {
941 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
944 if (!empty($nodeinfo['usage']['localComments'])) {
945 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
948 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
950 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
951 $protocols[$protocol] = true;
954 if (!empty($protocols['friendica'])) {
955 $server['network'] = Protocol::DFRN;
956 } elseif (!empty($protocols['activitypub'])) {
957 $server['network'] = Protocol::ACTIVITYPUB;
958 } elseif (!empty($protocols['diaspora'])) {
959 $server['network'] = Protocol::DIASPORA;
960 } elseif (!empty($protocols['ostatus'])) {
961 $server['network'] = Protocol::OSTATUS;
962 } elseif (!empty($protocols['gnusocial'])) {
963 $server['network'] = Protocol::OSTATUS;
964 } elseif (!empty($protocols['zot'])) {
965 $server['network'] = Protocol::ZOT;
969 if (empty($server)) {
973 if (empty($server['network'])) {
974 $server['network'] = Protocol::PHANTOM;
983 * @see https://git.feneas.org/jaywink/nodeinfo2
985 * @param string $nodeinfo_url address of the nodeinfo path
987 * @return array Server data
989 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991 private static function parseNodeinfo2(string $nodeinfo_url): array
993 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
994 if (!$curlResult->isSuccess()) {
998 $nodeinfo = json_decode($curlResult->getBody(), true);
999 if (!is_array($nodeinfo)) {
1004 'detection-method' => self::DETECT_NODEINFO_2,
1005 'register_policy' => Register::CLOSED,
1006 'platform' => 'unknown',
1009 if (!empty($nodeinfo['openRegistrations'])) {
1010 $server['register_policy'] = Register::OPEN;
1013 if (!empty($nodeinfo['software'])) {
1014 if (isset($nodeinfo['software']['name'])) {
1015 $server['platform'] = strtolower($nodeinfo['software']['name']);
1018 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1019 $server['version'] = $nodeinfo['software']['version'];
1020 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1021 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1022 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1024 // qoto advertises itself as Mastodon
1025 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1026 $server['platform'] = 'qoto';
1031 if (!empty($nodeinfo['metadata']['nodeName'])) {
1032 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1035 if (!empty($nodeinfo['usage']['users']['total'])) {
1036 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1039 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1040 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1043 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1044 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1047 if (!empty($nodeinfo['usage']['localPosts'])) {
1048 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1051 if (!empty($nodeinfo['usage']['localComments'])) {
1052 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1055 if (!empty($nodeinfo['protocols'])) {
1057 foreach ($nodeinfo['protocols'] as $protocol) {
1058 if (is_string($protocol)) {
1059 $protocols[$protocol] = true;
1063 if (!empty($protocols['dfrn'])) {
1064 $server['network'] = Protocol::DFRN;
1065 } elseif (!empty($protocols['activitypub'])) {
1066 $server['network'] = Protocol::ACTIVITYPUB;
1067 } elseif (!empty($protocols['diaspora'])) {
1068 $server['network'] = Protocol::DIASPORA;
1069 } elseif (!empty($protocols['ostatus'])) {
1070 $server['network'] = Protocol::OSTATUS;
1071 } elseif (!empty($protocols['gnusocial'])) {
1072 $server['network'] = Protocol::OSTATUS;
1073 } elseif (!empty($protocols['zot'])) {
1074 $server['network'] = Protocol::ZOT;
1078 if (empty($server)) {
1082 if (empty($server['network'])) {
1083 $server['network'] = Protocol::PHANTOM;
1090 * Parses NodeInfo2 protocol 1.0
1092 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1094 * @param string $nodeinfo_url address of the nodeinfo path
1096 * @return array Server data
1098 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1102 if (!$httpResult->isSuccess()) {
1106 $nodeinfo = json_decode($httpResult->getBody(), true);
1108 if (!is_array($nodeinfo)) {
1112 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1113 'register_policy' => Register::CLOSED];
1115 if (!empty($nodeinfo['openRegistrations'])) {
1116 $server['register_policy'] = Register::OPEN;
1119 if (!empty($nodeinfo['server'])) {
1120 if (!empty($nodeinfo['server']['software'])) {
1121 $server['platform'] = strtolower($nodeinfo['server']['software']);
1124 if (!empty($nodeinfo['server']['version'])) {
1125 $server['version'] = $nodeinfo['server']['version'];
1126 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1127 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1128 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1131 if (!empty($nodeinfo['server']['name'])) {
1132 $server['site_name'] = $nodeinfo['server']['name'];
1136 if (!empty($nodeinfo['usage']['users']['total'])) {
1137 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1140 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1141 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1144 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1145 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1148 if (!empty($nodeinfo['usage']['localPosts'])) {
1149 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1152 if (!empty($nodeinfo['usage']['localComments'])) {
1153 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1156 if (!empty($nodeinfo['protocols'])) {
1158 foreach ($nodeinfo['protocols'] as $protocol) {
1159 if (is_string($protocol)) {
1160 $protocols[$protocol] = true;
1164 if (!empty($protocols['dfrn'])) {
1165 $server['network'] = Protocol::DFRN;
1166 } elseif (!empty($protocols['activitypub'])) {
1167 $server['network'] = Protocol::ACTIVITYPUB;
1168 } elseif (!empty($protocols['diaspora'])) {
1169 $server['network'] = Protocol::DIASPORA;
1170 } elseif (!empty($protocols['ostatus'])) {
1171 $server['network'] = Protocol::OSTATUS;
1172 } elseif (!empty($protocols['gnusocial'])) {
1173 $server['network'] = Protocol::OSTATUS;
1174 } elseif (!empty($protocols['zot'])) {
1175 $server['network'] = Protocol::ZOT;
1179 if (empty($server) || empty($server['platform'])) {
1183 if (empty($server['network'])) {
1184 $server['network'] = Protocol::PHANTOM;
1191 * Fetch server information from a 'siteinfo.json' file on the given server
1193 * @param string $url URL of the given server
1194 * @param array $serverdata array with server data
1196 * @return array server data
1198 private static function fetchSiteinfo(string $url, array $serverdata): array
1200 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1201 if (!$curlResult->isSuccess()) {
1205 $data = json_decode($curlResult->getBody(), true);
1210 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1211 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1214 if (!empty($data['url'])) {
1215 $serverdata['platform'] = strtolower($data['platform']);
1216 $serverdata['version'] = $data['version'];
1219 if (!empty($data['plugins'])) {
1220 if (in_array('pubcrawl', $data['plugins'])) {
1221 $serverdata['network'] = Protocol::ACTIVITYPUB;
1222 } elseif (in_array('diaspora', $data['plugins'])) {
1223 $serverdata['network'] = Protocol::DIASPORA;
1224 } elseif (in_array('gnusoc', $data['plugins'])) {
1225 $serverdata['network'] = Protocol::OSTATUS;
1227 $serverdata['network'] = Protocol::ZOT;
1231 if (!empty($data['site_name'])) {
1232 $serverdata['site_name'] = $data['site_name'];
1235 if (!empty($data['channels_total'])) {
1236 $serverdata['registered-users'] = max($data['channels_total'], 1);
1239 if (!empty($data['channels_active_monthly'])) {
1240 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1243 if (!empty($data['channels_active_halfyear'])) {
1244 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1247 if (!empty($data['local_posts'])) {
1248 $serverdata['local-posts'] = max($data['local_posts'], 0);
1251 if (!empty($data['local_comments'])) {
1252 $serverdata['local-comments'] = max($data['local_comments'], 0);
1255 if (!empty($data['register_policy'])) {
1256 switch ($data['register_policy']) {
1257 case 'REGISTER_OPEN':
1258 $serverdata['register_policy'] = Register::OPEN;
1261 case 'REGISTER_APPROVE':
1262 $serverdata['register_policy'] = Register::APPROVE;
1265 case 'REGISTER_CLOSED':
1267 $serverdata['register_policy'] = Register::CLOSED;
1276 * Fetches server data via an ActivityPub account with url of that server
1278 * @param string $url URL of the given server
1279 * @param array $serverdata array with server data
1281 * @return array server data
1285 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1288 return ['server' => $serverdata, 'actor' => ''];
1291 $actor = JsonLD::compact($data, false);
1292 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1293 $serverdata['network'] = Protocol::ACTIVITYPUB;
1294 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1295 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1296 if (!empty($actor['as:generator'])) {
1297 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1298 $serverdata['platform'] = strtolower(array_shift($generator));
1299 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1301 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1303 return ['server' => $serverdata, 'actor' => $actor['@id']];
1304 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1305 // By now only Ktistec seems to provide collections this way
1306 $serverdata['platform'] = 'ktistec';
1307 $serverdata['network'] = Protocol::ACTIVITYPUB;
1308 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1310 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1311 if (!empty($actors) && !empty($actors[0]['@id'])) {
1312 $actor_url = $actor['@id'] . $actors[0]['@id'];
1317 return ['server' => $serverdata, 'actor' => $actor_url];
1319 return ['server' => $serverdata, 'actor' => ''];
1323 * Checks if the server contains a valid host meta file
1325 * @param string $url URL of the given server
1327 * @return boolean 'true' if the server seems to be vital
1329 private static function validHostMeta(string $url): bool
1331 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1332 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1333 if (!$curlResult->isSuccess()) {
1337 $xrd = XML::parseString($curlResult->getBody(), true);
1338 if (!is_object($xrd)) {
1342 $elements = XML::elementToArray($xrd);
1343 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1348 foreach ($elements['xrd']['link'] as $link) {
1349 // When there is more than a single "link" element, the array looks slightly different
1350 if (!empty($link['@attributes'])) {
1351 $link = $link['@attributes'];
1354 if (empty($link['rel']) || empty($link['template'])) {
1358 if ($link['rel'] == 'lrdd') {
1359 // When the webfinger host is the same like the system host, it should be ok.
1360 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1368 * Detect the network of the given server via their known contacts
1370 * @param string $url URL of the given server
1371 * @param array $serverdata array with server data
1373 * @return array server data
1375 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1379 $nurl = Strings::normaliseLink($url);
1381 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1382 while ($apcontact = DBA::fetch($apcontacts)) {
1383 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1385 DBA::close($apcontacts);
1387 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1388 while ($pcontact = DBA::fetch($pcontacts)) {
1389 $contacts[$pcontact['nurl']] = $pcontact['url'];
1391 DBA::close($pcontacts);
1393 if (empty($contacts)) {
1398 foreach ($contacts as $contact) {
1399 // Endlosschleife verhindern wegen gsid!
1400 $data = Probe::uri($contact);
1401 if (in_array($data['network'], Protocol::FEDERATED)) {
1402 $serverdata['network'] = $data['network'];
1404 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1405 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1408 } elseif ((time() - $time) > 10) {
1409 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1418 * Checks if the given server does have a '/poco' endpoint.
1419 * This is used for the 'PortableContact' functionality,
1420 * which is used by both Friendica and Hubzilla.
1422 * @param string $url URL of the given server
1423 * @param array $serverdata array with server data
1425 * @return array server data
1427 private static function checkPoCo(string $url, array $serverdata): array
1429 $serverdata['poco'] = '';
1431 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1432 if (!$curlResult->isSuccess()) {
1436 $data = json_decode($curlResult->getBody(), true);
1441 if (!empty($data['totalResults'])) {
1442 $registeredUsers = $serverdata['registered-users'] ?? 0;
1443 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1444 $serverdata['directory-type'] = self::DT_POCO;
1445 $serverdata['poco'] = $url . '/poco';
1452 * Checks if the given server does have a Mastodon style directory endpoint.
1454 * @param string $url URL of the given server
1455 * @param array $serverdata array with server data
1457 * @return array server data
1459 public static function checkMastodonDirectory(string $url, array $serverdata): array
1461 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1462 if (!$curlResult->isSuccess()) {
1466 $data = json_decode($curlResult->getBody(), true);
1471 if (count($data) == 1) {
1472 $serverdata['directory-type'] = self::DT_MASTODON;
1479 * Detects Peertube via their known endpoint
1481 * @param string $url URL of the given server
1482 * @param array $serverdata array with server data
1484 * @return array server data
1486 private static function detectPeertube(string $url, array $serverdata): array
1488 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1489 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1493 $data = json_decode($curlResult->getBody(), true);
1498 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1499 $serverdata['platform'] = 'peertube';
1500 $serverdata['version'] = $data['serverVersion'];
1501 $serverdata['network'] = Protocol::ACTIVITYPUB;
1503 if (!empty($data['instance']['name'])) {
1504 $serverdata['site_name'] = $data['instance']['name'];
1507 if (!empty($data['instance']['shortDescription'])) {
1508 $serverdata['info'] = $data['instance']['shortDescription'];
1511 if (!empty($data['signup'])) {
1512 if (!empty($data['signup']['allowed'])) {
1513 $serverdata['register_policy'] = Register::OPEN;
1517 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1518 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1526 * Detects the version number of a given server when it was a NextCloud installation
1528 * @param string $url URL of the given server
1529 * @param array $serverdata array with server data
1530 * @param bool $validHostMeta
1532 * @return array server data
1534 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1536 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1537 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1541 $data = json_decode($curlResult->getBody(), true);
1546 if (!empty($data['version'])) {
1547 $serverdata['platform'] = 'nextcloud';
1548 $serverdata['version'] = $data['version'];
1550 if ($validHostMeta) {
1551 $serverdata['network'] = Protocol::ACTIVITYPUB;
1554 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1555 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1563 * Fetches weekly usage data
1565 * @param string $url URL of the given server
1566 * @param array $serverdata array with server data
1568 * @return array server data
1570 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1572 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1573 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1577 $data = json_decode($curlResult->getBody(), true);
1583 foreach ($data as $week) {
1584 // Use only data from a full week
1585 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1589 // Most likely the data is sorted correctly. But we better are safe than sorry
1590 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1591 $current_week = $week;
1595 if (!empty($current_week['logins'])) {
1596 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1603 * Detects data from a given server url if it was a mastodon alike system
1605 * @param string $url URL of the given server
1606 * @param array $serverdata array with server data
1608 * @return array server data
1610 private static function detectMastodonAlikes(string $url, array $serverdata): array
1612 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1613 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1617 $data = json_decode($curlResult->getBody(), true);
1624 if (!empty($data['version'])) {
1625 $serverdata['platform'] = 'mastodon';
1626 $serverdata['version'] = $data['version'] ?? '';
1627 $serverdata['network'] = Protocol::ACTIVITYPUB;
1631 if (!empty($data['title'])) {
1632 $serverdata['site_name'] = $data['title'];
1635 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1636 $serverdata['platform'] = 'mastodon';
1637 $serverdata['network'] = Protocol::ACTIVITYPUB;
1641 if (!empty($data['description'])) {
1642 $serverdata['info'] = trim($data['description']);
1645 if (!empty($data['stats']['user_count'])) {
1646 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1649 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1650 $serverdata['platform'] = strtolower($matches[1]);
1651 $serverdata['version'] = $matches[2];
1655 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1656 $serverdata['platform'] = 'pleroma';
1657 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1661 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1662 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1663 $serverdata['platform'] = 'pleroma';
1667 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1668 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1675 * Detects data from typical Hubzilla endpoints
1677 * @param string $url URL of the given server
1678 * @param array $serverdata array with server data
1680 * @return array server data
1682 private static function detectHubzilla(string $url, array $serverdata): array
1684 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1685 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1689 $data = json_decode($curlResult->getBody(), true);
1690 if (empty($data) || empty($data['site'])) {
1694 if (!empty($data['site']['name'])) {
1695 $serverdata['site_name'] = $data['site']['name'];
1698 if (!empty($data['site']['platform'])) {
1699 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1700 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1701 $serverdata['network'] = Protocol::ZOT;
1704 if (!empty($data['site']['hubzilla'])) {
1705 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1706 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1707 $serverdata['network'] = Protocol::ZOT;
1710 if (!empty($data['site']['redmatrix'])) {
1711 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1712 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1713 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1714 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1717 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1718 $serverdata['network'] = Protocol::ZOT;
1722 $inviteonly = false;
1725 if (!empty($data['site']['closed'])) {
1726 $closed = self::toBoolean($data['site']['closed']);
1729 if (!empty($data['site']['private'])) {
1730 $private = self::toBoolean($data['site']['private']);
1733 if (!empty($data['site']['inviteonly'])) {
1734 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1737 if (!$closed && !$private and $inviteonly) {
1738 $serverdata['register_policy'] = Register::APPROVE;
1739 } elseif (!$closed && !$private) {
1740 $serverdata['register_policy'] = Register::OPEN;
1742 $serverdata['register_policy'] = Register::CLOSED;
1745 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1746 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1753 * Converts input value to a boolean value
1755 * @param string|integer $val
1759 private static function toBoolean($val): bool
1761 if (($val == 'true') || ($val == 1)) {
1763 } elseif (($val == 'false') || ($val == 0)) {
1771 * Detect if the URL belongs to a GNU Social server
1773 * @param string $url URL of the given server
1774 * @param array $serverdata array with server data
1776 * @return array server data
1778 private static function detectGNUSocial(string $url, array $serverdata): array
1780 // Test for GNU Social
1781 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1782 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1783 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1784 $serverdata['platform'] = 'gnusocial';
1785 // Remove junk that some GNU Social servers return
1786 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1787 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1788 $serverdata['version'] = trim($serverdata['version'], '"');
1789 $serverdata['network'] = Protocol::OSTATUS;
1791 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1792 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1798 // Test for Statusnet
1799 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1800 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1801 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1803 // Remove junk that some GNU Social servers return
1804 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1805 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1806 $serverdata['version'] = trim($serverdata['version'], '"');
1808 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1809 $serverdata['platform'] = 'pleroma';
1810 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1811 $serverdata['network'] = Protocol::ACTIVITYPUB;
1813 $serverdata['platform'] = 'statusnet';
1814 $serverdata['network'] = Protocol::OSTATUS;
1817 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1818 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1826 * Detect if the URL belongs to a Friendica server
1828 * @param string $url URL of the given server
1829 * @param array $serverdata array with server data
1831 * @return array server data
1833 private static function detectFriendica(string $url, array $serverdata): array
1835 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1836 // Because of this me must not use ACCEPT_JSON here.
1837 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1838 if (!$curlResult->isSuccess()) {
1839 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1841 $platform = 'Friendika';
1844 $platform = 'Friendica';
1847 if (!$curlResult->isSuccess()) {
1851 $data = json_decode($curlResult->getBody(), true);
1852 if (empty($data) || empty($data['version'])) {
1856 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1857 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1860 $serverdata['network'] = Protocol::DFRN;
1861 $serverdata['version'] = $data['version'];
1863 if (!empty($data['no_scrape_url'])) {
1864 $serverdata['noscrape'] = $data['no_scrape_url'];
1867 if (!empty($data['site_name'])) {
1868 $serverdata['site_name'] = $data['site_name'];
1871 if (!empty($data['info'])) {
1872 $serverdata['info'] = trim($data['info']);
1875 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1876 switch ($register_policy) {
1877 case 'REGISTER_OPEN':
1878 $serverdata['register_policy'] = Register::OPEN;
1881 case 'REGISTER_APPROVE':
1882 $serverdata['register_policy'] = Register::APPROVE;
1885 case 'REGISTER_CLOSED':
1886 case 'REGISTER_INVITATION':
1887 $serverdata['register_policy'] = Register::CLOSED;
1890 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1891 $serverdata['register_policy'] = Register::CLOSED;
1895 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1901 * Analyses the landing page of a given server for hints about type and system of that server
1903 * @param object $curlResult result of curl execution
1904 * @param array $serverdata array with server data
1906 * @return array server data
1908 private static function analyseRootBody($curlResult, array $serverdata): array
1910 if (empty($curlResult->getBody())) {
1914 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
1915 require __DIR__ . '/../../static/platforms.config.php';
1917 throw new HTTPException\InternalServerErrorException('Invalid platform file');
1920 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1922 $doc = new DOMDocument();
1923 @$doc->loadHTML($curlResult->getBody());
1924 $xpath = new DOMXPath($doc);
1927 // We can only detect honk via some HTML element on their page
1928 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1929 $serverdata['platform'] = 'honk';
1930 $serverdata['network'] = Protocol::ACTIVITYPUB;
1934 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1935 if (!empty($title)) {
1936 $serverdata['site_name'] = $title;
1939 $list = $xpath->query('//meta[@name]');
1941 foreach ($list as $node) {
1943 if ($node->attributes->length) {
1944 foreach ($node->attributes as $attribute) {
1945 $value = trim($attribute->value);
1946 if (empty($value)) {
1950 $attr[$attribute->name] = $value;
1953 if (empty($attr['name']) || empty($attr['content'])) {
1958 if ($attr['name'] == 'description') {
1959 $serverdata['info'] = $attr['content'];
1962 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1963 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
1964 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
1965 $platform = str_replace('/', ' ', $platform);
1966 $platform_parts = explode(' ', $platform);
1967 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
1968 $platform = $platform_parts[0];
1969 $serverdata['version'] = $platform_parts[1];
1971 if (in_array($platform, array_values($dfrn_platforms))) {
1972 $serverdata['network'] = Protocol::DFRN;
1973 } elseif (in_array($platform, array_values($ap_platforms))) {
1974 $serverdata['network'] = Protocol::ACTIVITYPUB;
1975 } elseif (in_array($platform, array_values($zap_platforms))) {
1976 $serverdata['network'] = Protocol::ZOT;
1978 if (in_array($platform, array_values($platforms))) {
1979 $serverdata['platform'] = $platform;
1985 $list = $xpath->query('//meta[@property]');
1987 foreach ($list as $node) {
1989 if ($node->attributes->length) {
1990 foreach ($node->attributes as $attribute) {
1991 $value = trim($attribute->value);
1992 if (empty($value)) {
1996 $attr[$attribute->name] = $value;
1999 if (empty($attr['property']) || empty($attr['content'])) {
2004 if ($attr['property'] == 'og:site_name') {
2005 $serverdata['site_name'] = $attr['content'];
2008 if ($attr['property'] == 'og:description') {
2009 $serverdata['info'] = $attr['content'];
2012 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2013 if (in_array($attr['content'], array_keys($platforms))) {
2014 $serverdata['platform'] = $platforms[$attr['content']];
2018 if (in_array($attr['content'], array_keys($ap_platforms))) {
2019 $serverdata['network'] = Protocol::ACTIVITYPUB;
2020 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2021 $serverdata['network'] = Protocol::ZOT;
2026 $list = $xpath->query('//link[@rel="me"]');
2027 foreach ($list as $node) {
2028 foreach ($node->attributes as $attribute) {
2029 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2030 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2031 $serverdata['platform'] = 'microblog';
2032 $serverdata['network'] = Protocol::ACTIVITYPUB;
2038 if ($serverdata['platform'] != 'microblog') {
2039 $list = $xpath->query('//link[@rel="micropub"]');
2040 foreach ($list as $node) {
2041 foreach ($node->attributes as $attribute) {
2042 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2043 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2044 $serverdata['platform'] = 'microblog';
2045 $serverdata['network'] = Protocol::ACTIVITYPUB;
2052 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2053 $serverdata['detection-method'] = self::DETECT_BODY;
2060 * Analyses the header data of a given server for hints about type and system of that server
2062 * @param object $curlResult result of curl execution
2063 * @param array $serverdata array with server data
2065 * @return array server data
2067 private static function analyseRootHeader($curlResult, array $serverdata): array
2069 if ($curlResult->getHeader('server') == 'Mastodon') {
2070 $serverdata['platform'] = 'mastodon';
2071 $serverdata['network'] = Protocol::ACTIVITYPUB;
2072 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2073 $serverdata['platform'] = 'diaspora';
2074 $serverdata['network'] = Protocol::DIASPORA;
2075 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2076 } elseif ($curlResult->inHeader('x-friendica-version')) {
2077 $serverdata['platform'] = 'friendica';
2078 $serverdata['network'] = Protocol::DFRN;
2079 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2084 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2085 $serverdata['detection-method'] = self::DETECT_HEADER;
2092 * Update GServer entries
2094 public static function discover()
2096 // Update the server list
2097 self::discoverFederation();
2101 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2103 if ($requery_days == 0) {
2107 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2109 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2110 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2111 ['order' => ['RAND()']]);
2113 while ($gserver = DBA::fetch($gservers)) {
2114 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2115 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2117 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2118 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2120 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2121 self::update($fields, ['nurl' => $gserver['nurl']]);
2123 if (--$no_of_queries == 0) {
2128 DBA::close($gservers);
2132 * Discover federated servers
2134 private static function discoverFederation()
2136 $last = DI::config()->get('poco', 'last_federation_discovery');
2139 $next = $last + (24 * 60 * 60);
2141 if ($next > time()) {
2146 // Discover federated servers
2147 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2148 foreach ($protocols as $protocol) {
2149 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2150 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2151 if (!empty($curlResult)) {
2152 $data = json_decode($curlResult, true);
2153 if (!empty($data['data']['nodes'])) {
2154 foreach ($data['data']['nodes'] as $server) {
2155 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2156 self::add('https://' . $server['host'], true);
2162 // Disvover Mastodon servers
2163 $accesstoken = DI::config()->get('system', 'instances_social_key');
2165 if (!empty($accesstoken)) {
2166 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2167 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2168 if ($curlResult->isSuccess()) {
2169 $servers = json_decode($curlResult->getBody(), true);
2171 if (!empty($servers['instances'])) {
2172 foreach ($servers['instances'] as $server) {
2173 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2180 DI::config()->set('poco', 'last_federation_discovery', time());
2184 * Set the protocol for the given server
2186 * @param int $gsid Server id
2187 * @param int $protocol Protocol id
2191 public static function setProtocol(int $gsid, int $protocol)
2197 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2198 if (!DBA::isResult($gserver)) {
2202 $old = $gserver['protocol'];
2204 if (!is_null($old)) {
2206 The priority for the protocols is:
2208 2. DFRN via Diaspora
2214 // We don't need to change it when nothing is to be changed
2215 if ($old == $protocol) {
2219 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2220 if ($protocol == Post\DeliveryData::OSTATUS) {
2224 // If the server is marked as ActivityPub then we won't change it to anything different
2225 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2229 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2230 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2234 // Don't change it to Diaspora when it is a legacy DFRN server
2235 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2240 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2241 self::update(['protocol' => $protocol], ['id' => $gsid]);
2245 * Fetch the protocol of the given server
2247 * @param int $gsid Server id
2249 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2253 public static function getProtocol(int $gsid): ?int
2259 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2260 if (DBA::isResult($gserver)) {
2261 return $gserver['protocol'];
2268 * Update rows in the gserver table.
2269 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2271 * @param array $fields
2272 * @param array $condition
2278 public static function update(array $fields, array $condition): bool
2280 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2282 return DBA::update('gserver', $fields, $condition);
2286 * Insert a row into the gserver table.
2287 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2289 * @param array $fields
2290 * @param int $duplicate_mode What to do on a duplicated entry
2296 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2298 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2300 return DBA::insert('gserver', $fields, $duplicate_mode);