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;
48 use Psr\Http\Message\UriInterface;
51 * This class handles GServer related functions
58 const DT_MASTODON = 2;
60 // Methods to detect server types
62 // Non endpoint specific methods
63 const DETECT_MANUAL = 0;
64 const DETECT_HEADER = 1;
65 const DETECT_BODY = 2;
66 const DETECT_HOST_META = 3;
67 const DETECT_CONTACTS = 4;
68 const DETECT_AP_ACTOR = 5;
69 const DETECT_AP_COLLECTION = 6;
71 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
73 // Implementation specific endpoints
74 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
75 const DETECT_FRIENDIKA = 10;
76 const DETECT_FRIENDICA = 11;
77 const DETECT_STATUSNET = 12;
78 const DETECT_GNUSOCIAL = 13;
79 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
80 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
81 const DETECT_MASTODON_API = 16;
82 const DETECT_STATUS_PHP = 17; // Nextcloud
83 const DETECT_V1_CONFIG = 18;
84 const DETECT_PUMPIO = 19; // Deprecated
85 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
87 // Standardized endpoints
88 const DETECT_STATISTICS_JSON = 100;
89 const DETECT_NODEINFO_1 = 101;
90 const DETECT_NODEINFO_2 = 102;
91 const DETECT_NODEINFO_210 = 103;
94 * Check for the existance of a server and adds it in the background if not existant
97 * @param boolean $only_nodeinfo
101 public static function add(string $url, bool $only_nodeinfo = false)
103 if (self::getID($url, false)) {
107 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
111 * Get the ID for the given server URL
114 * @param boolean $no_check Don't check if the server hadn't been found
116 * @return int|null gserver id or NULL on empty URL or failed check
118 public static function getID(string $url, bool $no_check = false): ?int
120 $url = self::cleanURL($url);
126 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
127 if (DBA::isResult($gserver)) {
128 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
129 return $gserver['id'];
132 if ($no_check || !self::check($url)) {
136 return self::getID($url, true);
140 * Retrieves all the servers which base domain are matching the provided domain pattern
142 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
144 * @param string $pattern
150 public static function listByDomainPattern(string $pattern): array
152 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
154 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
155 // eventual server path and keep only the server domain which we're matching against the pattern.
156 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
158 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
159 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
160 AND NOT `gserver`.`failed`
161 GROUP BY `gserver`.`id`";
163 $stmt = DI::dba()->p($sql, $likePattern);
165 return DI::dba()->toArray($stmt);
169 * Checks if the given server is reachable
171 * @param array $contact Contact that should be checked
173 * @return boolean 'true' if server seems vital
175 public static function reachable(array $contact): bool
177 if (!empty($contact['gsid'])) {
178 $gsid = $contact['gsid'];
179 } elseif (!empty($contact['baseurl'])) {
180 $server = $contact['baseurl'];
181 } elseif ($contact['network'] == Protocol::DIASPORA) {
182 $parts = parse_url($contact['url']);
183 unset($parts['path']);
184 $server = (string)Uri::fromParts($parts);
190 $condition = ['id' => $gsid];
192 $condition = ['nurl' => Strings::normaliseLink($server)];
195 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed'], $condition);
196 if (empty($gserver)) {
199 $reachable = !$gserver['failed'];
200 $server = $gserver['url'];
203 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
204 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $server, false);
211 * Calculate the next update day
213 * @param bool $success
214 * @param string $created
215 * @param string $last_contact
216 * @param bool $undetected
222 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
224 // On successful contact process check again next week when it is a detected system.
225 // When we haven't detected the system, it could be a static website or a really old system.
227 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
230 $now = strtotime(DateTimeFormat::utcNow());
232 if ($created > $last_contact) {
233 $contact_time = strtotime($created);
235 $contact_time = strtotime($last_contact);
238 // If the last contact was less than 6 hours before then try again in 6 hours
239 if (($now - $contact_time) < (60 * 60 * 6)) {
240 return DateTimeFormat::utc('now +6 hour');
243 // If the last contact was less than 12 hours before then try again in 12 hours
244 if (($now - $contact_time) < (60 * 60 * 12)) {
245 return DateTimeFormat::utc('now +12 hour');
248 // If the last contact was less than 24 hours before then try tomorrow again
249 if (($now - $contact_time) < (60 * 60 * 24)) {
250 return DateTimeFormat::utc('now +1 day');
253 // If the last contact was less than a week before then try again in a week
254 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
255 return DateTimeFormat::utc('now +1 week');
258 // If the last contact was less than two weeks before then try again in two week
259 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
260 return DateTimeFormat::utc('now +2 week');
263 // If the last contact was less than a month before then try again in a month
264 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
265 return DateTimeFormat::utc('now +1 month');
268 // The system hadn't been successul contacted for more than a month, so try again in three months
269 return DateTimeFormat::utc('now +3 month');
273 * Checks the state of the given server.
275 * @param string $server_url URL of the given server
276 * @param string $network Network value that is used, when detection failed
277 * @param boolean $force Force an update.
278 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
280 * @return boolean 'true' if server seems vital
282 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
284 $server_url = self::cleanURL($server_url);
285 if ($server_url == '') {
289 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
290 if (DBA::isResult($gserver)) {
291 if ($gserver['created'] <= DBA::NULL_DATETIME) {
292 $fields = ['created' => DateTimeFormat::utcNow()];
293 $condition = ['nurl' => Strings::normaliseLink($server_url)];
294 self::update($fields, $condition);
297 if (!$force && (strtotime($gserver['next_contact']) > time())) {
298 Logger::info('No update needed', ['server' => $server_url]);
299 return (!$gserver['failed']);
301 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
303 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
306 return self::detect($server_url, $network, $only_nodeinfo);
310 * Set failed server status
314 public static function setFailure(string $url)
316 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
317 if (DBA::isResult($gserver)) {
318 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
319 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
320 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
321 ['nurl' => Strings::normaliseLink($url)]);
322 Logger::info('Set failed status for existing server', ['url' => $url]);
325 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
326 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
327 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
328 Logger::info('Set failed status for new server', ['url' => $url]);
332 * Remove unwanted content from the given URL
334 * @param string $dirtyUrl
336 * @return string cleaned URL
338 * @deprecated since 2023.03 Use cleanUri instead
340 public static function cleanURL(string $dirtyUrl): string
343 return (string)self::cleanUri(new Uri($dirtyUrl));
344 } catch (\Throwable $e) {
345 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
351 * Remove unwanted content from the given URI
353 * @param UriInterface $dirtyUri
355 * @return UriInterface cleaned URI
358 public static function cleanUri(UriInterface $dirtyUri): string
366 '#(?:^|/)index\.php#',
368 rtrim($dirtyUri->getPath(), '/')
374 * Detect server data (type, protocol, version number, ...)
375 * The detected data is then updated or inserted in the gserver table.
377 * @param string $url URL of the given server
378 * @param string $network Network value that is used, when detection failed
379 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
381 * @return boolean 'true' if server could be detected
383 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
385 Logger::info('Detect server type', ['server' => $url]);
387 $original_url = $url;
389 // Remove URL content that is not supposed to exist for a server url
390 $url = rtrim(self::cleanURL($url), '/');
392 Logger::notice('Empty URL.');
396 // If the URL missmatches, then we mark the old entry as failure
397 if (!Strings::compareLink($url, $original_url)) {
398 self::setFailure($original_url);
399 if (!self::getID($url, true)) {
400 self::detect($url, $network, $only_nodeinfo);
405 $valid_url = Network::isUrlValid($url);
407 self::setFailure($url);
410 $valid_url = rtrim($valid_url, '/');
413 if (!Strings::compareLink($url, $valid_url)) {
414 // We only follow redirects when the path stays the same or the target url has no path.
415 // Some systems have got redirects on their landing page to a single account page. This check handles it.
416 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))) ||
417 (((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)))) {
418 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
419 self::setFailure($url);
420 if (!self::getID($valid_url, true)) {
421 self::detect($valid_url, $network, $only_nodeinfo);
426 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)) &&
427 (parse_url($url, PHP_URL_PATH) == '')) {
428 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
429 $parts = parse_url($valid_url);
430 unset($parts['path']);
431 $valid_url = (string)Uri::fromParts($parts);
433 self::setFailure($url);
434 if (!self::getID($valid_url, true)) {
435 self::detect($valid_url, $network, $only_nodeinfo);
439 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
442 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
443 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
444 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
448 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
450 // When a nodeinfo is present, we don't need to dig further
451 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
452 if ($curlResult->isTimeout()) {
453 self::setFailure($url);
457 $serverdata = self::parseNodeinfo210($curlResult);
458 if (empty($serverdata)) {
459 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
460 $serverdata = self::fetchNodeinfo($url, $curlResult);
463 if ($only_nodeinfo && empty($serverdata)) {
464 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
465 self::setFailure($url);
467 } elseif (empty($serverdata)) {
468 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
471 // When there is no Nodeinfo, then use some protocol specific endpoints
472 if ($serverdata['network'] == Protocol::PHANTOM) {
474 // Fetch the landing page, possibly it reveals some data
475 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
476 $curlResult = DI::httpClient()->get($url, $accept);
477 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
478 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
479 $html_fetched = true;
481 $html_fetched = false;
484 if ($curlResult->isSuccess()) {
485 $json = json_decode($curlResult->getBody(), true);
486 if (!empty($json) && is_array($json)) {
487 $data = self::fetchDataFromSystemActor($json, $serverdata);
488 $serverdata = $data['server'];
489 $systemactor = $data['actor'];
490 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
491 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
493 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
494 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
497 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
498 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
499 $serverdata = self::analyseRootBody($curlResult, $serverdata);
503 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
504 self::setFailure($url);
508 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
509 $serverdata = self::detectMastodonAlikes($url, $serverdata);
513 // All following checks are done for systems that always have got a "host-meta" endpoint.
514 // With this check we don't have to waste time and ressources for dead systems.
515 // Also this hopefully prevents us from receiving abuse messages.
516 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
517 $validHostMeta = self::validHostMeta($url);
519 $validHostMeta = false;
522 if ($validHostMeta) {
523 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
524 $serverdata['detection-method'] = self::DETECT_HOST_META;
527 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
528 $serverdata = self::detectFriendica($url, $serverdata);
531 // The following systems have to be installed in the root directory.
533 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
534 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
535 $serverdata = self::fetchSiteinfo($url, $serverdata);
538 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
539 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
540 $serverdata = self::detectHubzilla($url, $serverdata);
543 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
544 $serverdata = self::detectPeertube($url, $serverdata);
547 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
548 $serverdata = self::detectGNUSocial($url, $serverdata);
551 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
552 $serverdata = self::detectFriendica($url, $serverdata);
555 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
556 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
559 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
560 // Since this endpoint is only rarely used, we query it at a later time
561 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
562 $serverdata = self::fetchStatistics($url, $serverdata);
566 // When we hadn't been able to detect the network type, we use the hint from the parameter
567 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
568 $serverdata['network'] = $network;
571 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
572 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
573 self::setFailure($url);
577 $serverdata['url'] = $url;
578 $serverdata['nurl'] = Strings::normaliseLink($url);
580 // We have to prevent an endless loop here.
581 // When a server is new, then there is no gserver entry yet.
582 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
583 // and this can call this function here as well.
584 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
585 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
586 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
589 // Detect the directory type
590 $serverdata['directory-type'] = self::DT_NONE;
592 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
593 $serverdata = self::checkMastodonDirectory($url, $serverdata);
595 if ($serverdata['directory-type'] == self::DT_NONE) {
596 $serverdata = self::checkPoCo($url, $serverdata);
600 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
601 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
604 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
606 // Numbers above a reasonable value (10 millions) are ignored
607 if ($serverdata['registered-users'] > 10000000) {
608 $serverdata['registered-users'] = 0;
611 // On an active server there has to be at least a single user
612 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
613 $serverdata['registered-users'] = 1;
614 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
615 $serverdata['registered-users'] = 0;
618 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
620 $serverdata['last_contact'] = DateTimeFormat::utcNow();
621 $serverdata['failed'] = false;
623 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
624 if (!DBA::isResult($gserver)) {
625 $serverdata['created'] = DateTimeFormat::utcNow();
626 $ret = self::insert($serverdata);
627 $id = DBA::lastInsertId();
629 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
630 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
631 if (DBA::isResult($gserver)) {
632 $id = $gserver['id'];
636 // Count the number of known contacts from this server
637 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
638 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
639 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
640 $max_users = max($apcontacts, $contacts);
641 if ($max_users > $serverdata['registered-users']) {
642 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
643 self::update(['registered-users' => $max_users], ['id' => $id]);
646 if (empty($serverdata['active-month-users'])) {
647 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
649 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
650 self::update(['active-month-users' => $contacts], ['id' => $id]);
654 if (empty($serverdata['active-halfyear-users'])) {
655 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
657 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
658 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
663 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
664 self::discoverRelay($url);
667 if (!empty($systemactor)) {
668 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
669 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
676 * Fetch relay data from a given server url
678 * @param string $server_url address of the server
682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 private static function discoverRelay(string $server_url)
686 Logger::info('Discover relay data', ['server' => $server_url]);
688 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
689 if (!$curlResult->isSuccess()) {
693 $data = json_decode($curlResult->getBody(), true);
694 if (!is_array($data)) {
698 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
699 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
701 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
703 $data['subscribe'] = false;
707 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
708 if (!DBA::isResult($gserver)) {
712 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
713 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
714 self::update($fields, ['id' => $gserver['id']]);
717 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
719 if ($data['scope'] == 'tags') {
722 foreach ($data['tags'] as $tag) {
723 $tag = mb_strtolower($tag);
724 if (strlen($tag) < 100) {
729 foreach ($tags as $tag) {
730 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
734 // Create or update the relay contact
736 if (isset($data['protocols'])) {
737 if (isset($data['protocols']['diaspora'])) {
738 $fields['network'] = Protocol::DIASPORA;
740 if (isset($data['protocols']['diaspora']['receive'])) {
741 $fields['batch'] = $data['protocols']['diaspora']['receive'];
742 } elseif (is_string($data['protocols']['diaspora'])) {
743 $fields['batch'] = $data['protocols']['diaspora'];
747 if (isset($data['protocols']['dfrn'])) {
748 $fields['network'] = Protocol::DFRN;
750 if (isset($data['protocols']['dfrn']['receive'])) {
751 $fields['batch'] = $data['protocols']['dfrn']['receive'];
752 } elseif (is_string($data['protocols']['dfrn'])) {
753 $fields['batch'] = $data['protocols']['dfrn'];
757 if (isset($data['protocols']['activitypub'])) {
758 $fields['network'] = Protocol::ACTIVITYPUB;
760 if (!empty($data['protocols']['activitypub']['actor'])) {
761 $fields['url'] = $data['protocols']['activitypub']['actor'];
763 if (!empty($data['protocols']['activitypub']['receive'])) {
764 $fields['batch'] = $data['protocols']['activitypub']['receive'];
769 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
771 Relay::updateContact($gserver, $fields);
775 * Fetch server data from '/statistics.json' on the given server
777 * @param string $url URL of the given server
779 * @return array server data
781 private static function fetchStatistics(string $url, array $serverdata): array
783 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
784 if (!$curlResult->isSuccess()) {
788 $data = json_decode($curlResult->getBody(), true);
793 // Some AP enabled systems return activity data that we don't expect here.
794 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
799 $old_serverdata = $serverdata;
801 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
803 if (!empty($data['version'])) {
805 $serverdata['version'] = $data['version'];
806 // Version numbers on statistics.json are presented with additional info, e.g.:
807 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
808 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
811 if (!empty($data['name'])) {
813 $serverdata['site_name'] = $data['name'];
816 if (!empty($data['network'])) {
818 $serverdata['platform'] = strtolower($data['network']);
820 if ($serverdata['platform'] == 'diaspora') {
821 $serverdata['network'] = Protocol::DIASPORA;
822 } elseif ($serverdata['platform'] == 'friendica') {
823 $serverdata['network'] = Protocol::DFRN;
824 } elseif ($serverdata['platform'] == 'hubzilla') {
825 $serverdata['network'] = Protocol::ZOT;
826 } elseif ($serverdata['platform'] == 'redmatrix') {
827 $serverdata['network'] = Protocol::ZOT;
831 if (!empty($data['total_users'])) {
833 $serverdata['registered-users'] = max($data['total_users'], 1);
836 if (!empty($data['active_users_monthly'])) {
838 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
841 if (!empty($data['active_users_halfyear'])) {
843 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
846 if (!empty($data['local_posts'])) {
848 $serverdata['local-posts'] = max($data['local_posts'], 0);
851 if (!empty($data['registrations_open'])) {
852 $serverdata['register_policy'] = Register::OPEN;
854 $serverdata['register_policy'] = Register::CLOSED;
858 return $old_serverdata;
865 * Detect server type by using the nodeinfo data
867 * @param string $url address of the server
868 * @param ICanHandleHttpResponses $httpResult
870 * @return array Server data
872 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
874 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
876 if (!$httpResult->isSuccess()) {
880 $nodeinfo = json_decode($httpResult->getBody(), true);
882 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
889 foreach ($nodeinfo['links'] as $link) {
890 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
891 Logger::info('Invalid nodeinfo format', ['url' => $url]);
894 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
895 $nodeinfo1_url = $link['href'];
896 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
897 $nodeinfo2_url = $link['href'];
901 if ($nodeinfo1_url . $nodeinfo2_url == '') {
907 if (!empty($nodeinfo2_url)) {
908 $server = self::parseNodeinfo2($nodeinfo2_url);
911 if (empty($server) && !empty($nodeinfo1_url)) {
912 $server = self::parseNodeinfo1($nodeinfo1_url);
921 * @param string $nodeinfo_url address of the nodeinfo path
923 * @return array Server data
925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
927 private static function parseNodeinfo1(string $nodeinfo_url): array
929 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
930 if (!$curlResult->isSuccess()) {
934 $nodeinfo = json_decode($curlResult->getBody(), true);
936 if (!is_array($nodeinfo)) {
940 $server = ['detection-method' => self::DETECT_NODEINFO_1,
941 'register_policy' => Register::CLOSED];
943 if (!empty($nodeinfo['openRegistrations'])) {
944 $server['register_policy'] = Register::OPEN;
947 if (is_array($nodeinfo['software'])) {
948 if (!empty($nodeinfo['software']['name'])) {
949 $server['platform'] = strtolower($nodeinfo['software']['name']);
952 if (!empty($nodeinfo['software']['version'])) {
953 $server['version'] = $nodeinfo['software']['version'];
954 // Version numbers on Nodeinfo are presented with additional info, e.g.:
955 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
956 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
960 if (!empty($nodeinfo['metadata']['nodeName'])) {
961 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
964 if (!empty($nodeinfo['usage']['users']['total'])) {
965 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
968 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
969 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
972 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
973 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
976 if (!empty($nodeinfo['usage']['localPosts'])) {
977 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
980 if (!empty($nodeinfo['usage']['localComments'])) {
981 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
984 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
986 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
987 $protocols[$protocol] = true;
990 if (!empty($protocols['friendica'])) {
991 $server['network'] = Protocol::DFRN;
992 } elseif (!empty($protocols['activitypub'])) {
993 $server['network'] = Protocol::ACTIVITYPUB;
994 } elseif (!empty($protocols['diaspora'])) {
995 $server['network'] = Protocol::DIASPORA;
996 } elseif (!empty($protocols['ostatus'])) {
997 $server['network'] = Protocol::OSTATUS;
998 } elseif (!empty($protocols['gnusocial'])) {
999 $server['network'] = Protocol::OSTATUS;
1000 } elseif (!empty($protocols['zot'])) {
1001 $server['network'] = Protocol::ZOT;
1005 if (empty($server)) {
1009 if (empty($server['network'])) {
1010 $server['network'] = Protocol::PHANTOM;
1019 * @see https://git.feneas.org/jaywink/nodeinfo2
1021 * @param string $nodeinfo_url address of the nodeinfo path
1023 * @return array Server data
1025 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 private static function parseNodeinfo2(string $nodeinfo_url): array
1029 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1030 if (!$curlResult->isSuccess()) {
1034 $nodeinfo = json_decode($curlResult->getBody(), true);
1035 if (!is_array($nodeinfo)) {
1040 'detection-method' => self::DETECT_NODEINFO_2,
1041 'register_policy' => Register::CLOSED,
1042 'platform' => 'unknown',
1045 if (!empty($nodeinfo['openRegistrations'])) {
1046 $server['register_policy'] = Register::OPEN;
1049 if (!empty($nodeinfo['software'])) {
1050 if (isset($nodeinfo['software']['name'])) {
1051 $server['platform'] = strtolower($nodeinfo['software']['name']);
1054 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1055 $server['version'] = $nodeinfo['software']['version'];
1056 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1057 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1058 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1060 // qoto advertises itself as Mastodon
1061 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1062 $server['platform'] = 'qoto';
1067 if (!empty($nodeinfo['metadata']['nodeName'])) {
1068 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1071 if (!empty($nodeinfo['usage']['users']['total'])) {
1072 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1075 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1076 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1079 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1080 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1083 if (!empty($nodeinfo['usage']['localPosts'])) {
1084 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1087 if (!empty($nodeinfo['usage']['localComments'])) {
1088 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1091 if (!empty($nodeinfo['protocols'])) {
1093 foreach ($nodeinfo['protocols'] as $protocol) {
1094 if (is_string($protocol)) {
1095 $protocols[$protocol] = true;
1099 if (!empty($protocols['dfrn'])) {
1100 $server['network'] = Protocol::DFRN;
1101 } elseif (!empty($protocols['activitypub'])) {
1102 $server['network'] = Protocol::ACTIVITYPUB;
1103 } elseif (!empty($protocols['diaspora'])) {
1104 $server['network'] = Protocol::DIASPORA;
1105 } elseif (!empty($protocols['ostatus'])) {
1106 $server['network'] = Protocol::OSTATUS;
1107 } elseif (!empty($protocols['gnusocial'])) {
1108 $server['network'] = Protocol::OSTATUS;
1109 } elseif (!empty($protocols['zot'])) {
1110 $server['network'] = Protocol::ZOT;
1114 if (empty($server)) {
1118 if (empty($server['network'])) {
1119 $server['network'] = Protocol::PHANTOM;
1126 * Parses NodeInfo2 protocol 1.0
1128 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1130 * @param string $nodeinfo_url address of the nodeinfo path
1132 * @return array Server data
1134 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1136 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1138 if (!$httpResult->isSuccess()) {
1142 $nodeinfo = json_decode($httpResult->getBody(), true);
1144 if (!is_array($nodeinfo)) {
1148 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1149 'register_policy' => Register::CLOSED];
1151 if (!empty($nodeinfo['openRegistrations'])) {
1152 $server['register_policy'] = Register::OPEN;
1155 if (!empty($nodeinfo['server'])) {
1156 if (!empty($nodeinfo['server']['software'])) {
1157 $server['platform'] = strtolower($nodeinfo['server']['software']);
1160 if (!empty($nodeinfo['server']['version'])) {
1161 $server['version'] = $nodeinfo['server']['version'];
1162 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1163 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1164 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1167 if (!empty($nodeinfo['server']['name'])) {
1168 $server['site_name'] = $nodeinfo['server']['name'];
1172 if (!empty($nodeinfo['usage']['users']['total'])) {
1173 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1176 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1177 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1180 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1181 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1184 if (!empty($nodeinfo['usage']['localPosts'])) {
1185 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1188 if (!empty($nodeinfo['usage']['localComments'])) {
1189 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1192 if (!empty($nodeinfo['protocols'])) {
1194 foreach ($nodeinfo['protocols'] as $protocol) {
1195 if (is_string($protocol)) {
1196 $protocols[$protocol] = true;
1200 if (!empty($protocols['dfrn'])) {
1201 $server['network'] = Protocol::DFRN;
1202 } elseif (!empty($protocols['activitypub'])) {
1203 $server['network'] = Protocol::ACTIVITYPUB;
1204 } elseif (!empty($protocols['diaspora'])) {
1205 $server['network'] = Protocol::DIASPORA;
1206 } elseif (!empty($protocols['ostatus'])) {
1207 $server['network'] = Protocol::OSTATUS;
1208 } elseif (!empty($protocols['gnusocial'])) {
1209 $server['network'] = Protocol::OSTATUS;
1210 } elseif (!empty($protocols['zot'])) {
1211 $server['network'] = Protocol::ZOT;
1215 if (empty($server) || empty($server['platform'])) {
1219 if (empty($server['network'])) {
1220 $server['network'] = Protocol::PHANTOM;
1227 * Fetch server information from a 'siteinfo.json' file on the given server
1229 * @param string $url URL of the given server
1230 * @param array $serverdata array with server data
1232 * @return array server data
1234 private static function fetchSiteinfo(string $url, array $serverdata): array
1236 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1237 if (!$curlResult->isSuccess()) {
1241 $data = json_decode($curlResult->getBody(), true);
1246 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1247 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1250 if (!empty($data['url'])) {
1251 $serverdata['platform'] = strtolower($data['platform']);
1252 $serverdata['version'] = $data['version'] ?? 'N/A';
1255 if (!empty($data['plugins'])) {
1256 if (in_array('pubcrawl', $data['plugins'])) {
1257 $serverdata['network'] = Protocol::ACTIVITYPUB;
1258 } elseif (in_array('diaspora', $data['plugins'])) {
1259 $serverdata['network'] = Protocol::DIASPORA;
1260 } elseif (in_array('gnusoc', $data['plugins'])) {
1261 $serverdata['network'] = Protocol::OSTATUS;
1263 $serverdata['network'] = Protocol::ZOT;
1267 if (!empty($data['site_name'])) {
1268 $serverdata['site_name'] = $data['site_name'];
1271 if (!empty($data['channels_total'])) {
1272 $serverdata['registered-users'] = max($data['channels_total'], 1);
1275 if (!empty($data['channels_active_monthly'])) {
1276 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1279 if (!empty($data['channels_active_halfyear'])) {
1280 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1283 if (!empty($data['local_posts'])) {
1284 $serverdata['local-posts'] = max($data['local_posts'], 0);
1287 if (!empty($data['local_comments'])) {
1288 $serverdata['local-comments'] = max($data['local_comments'], 0);
1291 if (!empty($data['register_policy'])) {
1292 switch ($data['register_policy']) {
1293 case 'REGISTER_OPEN':
1294 $serverdata['register_policy'] = Register::OPEN;
1297 case 'REGISTER_APPROVE':
1298 $serverdata['register_policy'] = Register::APPROVE;
1301 case 'REGISTER_CLOSED':
1303 $serverdata['register_policy'] = Register::CLOSED;
1312 * Fetches server data via an ActivityPub account with url of that server
1314 * @param string $url URL of the given server
1315 * @param array $serverdata array with server data
1317 * @return array server data
1321 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1324 return ['server' => $serverdata, 'actor' => ''];
1327 $actor = JsonLD::compact($data, false);
1328 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1329 $serverdata['network'] = Protocol::ACTIVITYPUB;
1330 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1331 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1332 if (!empty($actor['as:generator'])) {
1333 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1334 $serverdata['platform'] = strtolower(array_shift($generator));
1335 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1337 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1339 return ['server' => $serverdata, 'actor' => $actor['@id']];
1340 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1341 // By now only Ktistec seems to provide collections this way
1342 $serverdata['platform'] = 'ktistec';
1343 $serverdata['network'] = Protocol::ACTIVITYPUB;
1344 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1346 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1347 if (!empty($actors) && !empty($actors[0]['@id'])) {
1348 $actor_url = $actor['@id'] . $actors[0]['@id'];
1353 return ['server' => $serverdata, 'actor' => $actor_url];
1355 return ['server' => $serverdata, 'actor' => ''];
1359 * Checks if the server contains a valid host meta file
1361 * @param string $url URL of the given server
1363 * @return boolean 'true' if the server seems to be vital
1365 private static function validHostMeta(string $url): bool
1367 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1368 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1369 if (!$curlResult->isSuccess()) {
1373 $xrd = XML::parseString($curlResult->getBody(), true);
1374 if (!is_object($xrd)) {
1378 $elements = XML::elementToArray($xrd);
1379 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1384 foreach ($elements['xrd']['link'] as $link) {
1385 // When there is more than a single "link" element, the array looks slightly different
1386 if (!empty($link['@attributes'])) {
1387 $link = $link['@attributes'];
1390 if (empty($link['rel']) || empty($link['template'])) {
1394 if ($link['rel'] == 'lrdd') {
1395 // When the webfinger host is the same like the system host, it should be ok.
1396 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1404 * Detect the network of the given server via their known contacts
1406 * @param string $url URL of the given server
1407 * @param array $serverdata array with server data
1409 * @return array server data
1411 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1415 $nurl = Strings::normaliseLink($url);
1417 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1418 while ($apcontact = DBA::fetch($apcontacts)) {
1419 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1421 DBA::close($apcontacts);
1423 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1424 while ($pcontact = DBA::fetch($pcontacts)) {
1425 $contacts[$pcontact['nurl']] = $pcontact['url'];
1427 DBA::close($pcontacts);
1429 if (empty($contacts)) {
1434 foreach ($contacts as $contact) {
1435 // Endlosschleife verhindern wegen gsid!
1436 $data = Probe::uri($contact);
1437 if (in_array($data['network'], Protocol::FEDERATED)) {
1438 $serverdata['network'] = $data['network'];
1440 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1441 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1444 } elseif ((time() - $time) > 10) {
1445 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1454 * Checks if the given server does have a '/poco' endpoint.
1455 * This is used for the 'PortableContact' functionality,
1456 * which is used by both Friendica and Hubzilla.
1458 * @param string $url URL of the given server
1459 * @param array $serverdata array with server data
1461 * @return array server data
1463 private static function checkPoCo(string $url, array $serverdata): array
1465 $serverdata['poco'] = '';
1467 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1468 if (!$curlResult->isSuccess()) {
1472 $data = json_decode($curlResult->getBody(), true);
1477 if (!empty($data['totalResults'])) {
1478 $registeredUsers = $serverdata['registered-users'] ?? 0;
1479 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1480 $serverdata['directory-type'] = self::DT_POCO;
1481 $serverdata['poco'] = $url . '/poco';
1488 * Checks if the given server does have a Mastodon style directory endpoint.
1490 * @param string $url URL of the given server
1491 * @param array $serverdata array with server data
1493 * @return array server data
1495 public static function checkMastodonDirectory(string $url, array $serverdata): array
1497 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1498 if (!$curlResult->isSuccess()) {
1502 $data = json_decode($curlResult->getBody(), true);
1507 if (count($data) == 1) {
1508 $serverdata['directory-type'] = self::DT_MASTODON;
1515 * Detects Peertube via their known endpoint
1517 * @param string $url URL of the given server
1518 * @param array $serverdata array with server data
1520 * @return array server data
1522 private static function detectPeertube(string $url, array $serverdata): array
1524 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1525 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1529 $data = json_decode($curlResult->getBody(), true);
1534 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1535 $serverdata['platform'] = 'peertube';
1536 $serverdata['version'] = $data['serverVersion'];
1537 $serverdata['network'] = Protocol::ACTIVITYPUB;
1539 if (!empty($data['instance']['name'])) {
1540 $serverdata['site_name'] = $data['instance']['name'];
1543 if (!empty($data['instance']['shortDescription'])) {
1544 $serverdata['info'] = $data['instance']['shortDescription'];
1547 if (!empty($data['signup'])) {
1548 if (!empty($data['signup']['allowed'])) {
1549 $serverdata['register_policy'] = Register::OPEN;
1553 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1554 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1562 * Detects the version number of a given server when it was a NextCloud installation
1564 * @param string $url URL of the given server
1565 * @param array $serverdata array with server data
1566 * @param bool $validHostMeta
1568 * @return array server data
1570 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1572 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1573 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1577 $data = json_decode($curlResult->getBody(), true);
1582 if (!empty($data['version'])) {
1583 $serverdata['platform'] = 'nextcloud';
1584 $serverdata['version'] = $data['version'];
1586 if ($validHostMeta) {
1587 $serverdata['network'] = Protocol::ACTIVITYPUB;
1590 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1591 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1599 * Fetches weekly usage data
1601 * @param string $url URL of the given server
1602 * @param array $serverdata array with server data
1604 * @return array server data
1606 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1608 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1609 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1613 $data = json_decode($curlResult->getBody(), true);
1619 foreach ($data as $week) {
1620 // Use only data from a full week
1621 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1625 // Most likely the data is sorted correctly. But we better are safe than sorry
1626 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1627 $current_week = $week;
1631 if (!empty($current_week['logins'])) {
1632 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1639 * Detects data from a given server url if it was a mastodon alike system
1641 * @param string $url URL of the given server
1642 * @param array $serverdata array with server data
1644 * @return array server data
1646 private static function detectMastodonAlikes(string $url, array $serverdata): array
1648 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1649 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1653 $data = json_decode($curlResult->getBody(), true);
1660 if (!empty($data['version'])) {
1661 $serverdata['platform'] = 'mastodon';
1662 $serverdata['version'] = $data['version'] ?? '';
1663 $serverdata['network'] = Protocol::ACTIVITYPUB;
1667 if (!empty($data['title'])) {
1668 $serverdata['site_name'] = $data['title'];
1671 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1672 $serverdata['platform'] = 'mastodon';
1673 $serverdata['network'] = Protocol::ACTIVITYPUB;
1677 if (!empty($data['description'])) {
1678 $serverdata['info'] = trim($data['description']);
1681 if (!empty($data['stats']['user_count'])) {
1682 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1685 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1686 $serverdata['platform'] = strtolower($matches[1]);
1687 $serverdata['version'] = $matches[2];
1691 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1692 $serverdata['platform'] = 'pleroma';
1693 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1697 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1698 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1699 $serverdata['platform'] = 'pleroma';
1703 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1704 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1711 * Detects data from typical Hubzilla endpoints
1713 * @param string $url URL of the given server
1714 * @param array $serverdata array with server data
1716 * @return array server data
1718 private static function detectHubzilla(string $url, array $serverdata): array
1720 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1721 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1725 $data = json_decode($curlResult->getBody(), true);
1726 if (empty($data) || empty($data['site'])) {
1730 if (!empty($data['site']['name'])) {
1731 $serverdata['site_name'] = $data['site']['name'];
1734 if (!empty($data['site']['platform'])) {
1735 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1736 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1737 $serverdata['network'] = Protocol::ZOT;
1740 if (!empty($data['site']['hubzilla'])) {
1741 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1742 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1743 $serverdata['network'] = Protocol::ZOT;
1746 if (!empty($data['site']['redmatrix'])) {
1747 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1748 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1749 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1750 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1753 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1754 $serverdata['network'] = Protocol::ZOT;
1758 $inviteonly = false;
1761 if (!empty($data['site']['closed'])) {
1762 $closed = self::toBoolean($data['site']['closed']);
1765 if (!empty($data['site']['private'])) {
1766 $private = self::toBoolean($data['site']['private']);
1769 if (!empty($data['site']['inviteonly'])) {
1770 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1773 if (!$closed && !$private and $inviteonly) {
1774 $serverdata['register_policy'] = Register::APPROVE;
1775 } elseif (!$closed && !$private) {
1776 $serverdata['register_policy'] = Register::OPEN;
1778 $serverdata['register_policy'] = Register::CLOSED;
1781 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1782 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1789 * Converts input value to a boolean value
1791 * @param string|integer $val
1795 private static function toBoolean($val): bool
1797 if (($val == 'true') || ($val == 1)) {
1799 } elseif (($val == 'false') || ($val == 0)) {
1807 * Detect if the URL belongs to a GNU Social server
1809 * @param string $url URL of the given server
1810 * @param array $serverdata array with server data
1812 * @return array server data
1814 private static function detectGNUSocial(string $url, array $serverdata): array
1816 // Test for GNU Social
1817 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1818 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1819 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1820 $serverdata['platform'] = 'gnusocial';
1821 // Remove junk that some GNU Social servers return
1822 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1823 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1824 $serverdata['version'] = trim($serverdata['version'], '"');
1825 $serverdata['network'] = Protocol::OSTATUS;
1827 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1828 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1834 // Test for Statusnet
1835 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1836 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1837 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1839 // Remove junk that some GNU Social servers return
1840 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1841 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1842 $serverdata['version'] = trim($serverdata['version'], '"');
1844 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1845 $serverdata['platform'] = 'pleroma';
1846 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1847 $serverdata['network'] = Protocol::ACTIVITYPUB;
1849 $serverdata['platform'] = 'statusnet';
1850 $serverdata['network'] = Protocol::OSTATUS;
1853 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1854 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1862 * Detect if the URL belongs to a Friendica server
1864 * @param string $url URL of the given server
1865 * @param array $serverdata array with server data
1867 * @return array server data
1869 private static function detectFriendica(string $url, array $serverdata): array
1871 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1872 // Because of this me must not use ACCEPT_JSON here.
1873 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1874 if (!$curlResult->isSuccess()) {
1875 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1877 $platform = 'Friendika';
1880 $platform = 'Friendica';
1883 if (!$curlResult->isSuccess()) {
1887 $data = json_decode($curlResult->getBody(), true);
1888 if (empty($data) || empty($data['version'])) {
1892 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1893 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1896 $serverdata['network'] = Protocol::DFRN;
1897 $serverdata['version'] = $data['version'];
1899 if (!empty($data['no_scrape_url'])) {
1900 $serverdata['noscrape'] = $data['no_scrape_url'];
1903 if (!empty($data['site_name'])) {
1904 $serverdata['site_name'] = $data['site_name'];
1907 if (!empty($data['info'])) {
1908 $serverdata['info'] = trim($data['info']);
1911 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1912 switch ($register_policy) {
1913 case 'REGISTER_OPEN':
1914 $serverdata['register_policy'] = Register::OPEN;
1917 case 'REGISTER_APPROVE':
1918 $serverdata['register_policy'] = Register::APPROVE;
1921 case 'REGISTER_CLOSED':
1922 case 'REGISTER_INVITATION':
1923 $serverdata['register_policy'] = Register::CLOSED;
1926 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1927 $serverdata['register_policy'] = Register::CLOSED;
1931 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1937 * Analyses the landing page of a given server for hints about type and system of that server
1939 * @param object $curlResult result of curl execution
1940 * @param array $serverdata array with server data
1942 * @return array server data
1944 private static function analyseRootBody($curlResult, array $serverdata): array
1946 if (empty($curlResult->getBody())) {
1950 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
1951 require __DIR__ . '/../../static/platforms.config.php';
1953 throw new HTTPException\InternalServerErrorException('Invalid platform file');
1956 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1958 $doc = new DOMDocument();
1959 @$doc->loadHTML($curlResult->getBody());
1960 $xpath = new DOMXPath($doc);
1963 // We can only detect honk via some HTML element on their page
1964 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1965 $serverdata['platform'] = 'honk';
1966 $serverdata['network'] = Protocol::ACTIVITYPUB;
1970 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1971 if (!empty($title)) {
1972 $serverdata['site_name'] = $title;
1975 $list = $xpath->query('//meta[@name]');
1977 foreach ($list as $node) {
1979 if ($node->attributes->length) {
1980 foreach ($node->attributes as $attribute) {
1981 $value = trim($attribute->value);
1982 if (empty($value)) {
1986 $attr[$attribute->name] = $value;
1989 if (empty($attr['name']) || empty($attr['content'])) {
1994 if ($attr['name'] == 'description') {
1995 $serverdata['info'] = $attr['content'];
1998 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1999 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2000 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2001 $platform = str_replace('/', ' ', $platform);
2002 $platform_parts = explode(' ', $platform);
2003 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2004 $platform = $platform_parts[0];
2005 $serverdata['version'] = $platform_parts[1];
2007 if (in_array($platform, array_values($dfrn_platforms))) {
2008 $serverdata['network'] = Protocol::DFRN;
2009 } elseif (in_array($platform, array_values($ap_platforms))) {
2010 $serverdata['network'] = Protocol::ACTIVITYPUB;
2011 } elseif (in_array($platform, array_values($zap_platforms))) {
2012 $serverdata['network'] = Protocol::ZOT;
2014 if (in_array($platform, array_values($platforms))) {
2015 $serverdata['platform'] = $platform;
2021 $list = $xpath->query('//meta[@property]');
2023 foreach ($list as $node) {
2025 if ($node->attributes->length) {
2026 foreach ($node->attributes as $attribute) {
2027 $value = trim($attribute->value);
2028 if (empty($value)) {
2032 $attr[$attribute->name] = $value;
2035 if (empty($attr['property']) || empty($attr['content'])) {
2040 if ($attr['property'] == 'og:site_name') {
2041 $serverdata['site_name'] = $attr['content'];
2044 if ($attr['property'] == 'og:description') {
2045 $serverdata['info'] = $attr['content'];
2048 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2049 if (in_array($attr['content'], array_keys($platforms))) {
2050 $serverdata['platform'] = $platforms[$attr['content']];
2054 if (in_array($attr['content'], array_keys($ap_platforms))) {
2055 $serverdata['network'] = Protocol::ACTIVITYPUB;
2056 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2057 $serverdata['network'] = Protocol::ZOT;
2062 $list = $xpath->query('//link[@rel="me"]');
2063 foreach ($list as $node) {
2064 foreach ($node->attributes as $attribute) {
2065 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2066 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2067 $serverdata['platform'] = 'microblog';
2068 $serverdata['network'] = Protocol::ACTIVITYPUB;
2074 if ($serverdata['platform'] != 'microblog') {
2075 $list = $xpath->query('//link[@rel="micropub"]');
2076 foreach ($list as $node) {
2077 foreach ($node->attributes as $attribute) {
2078 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2079 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2080 $serverdata['platform'] = 'microblog';
2081 $serverdata['network'] = Protocol::ACTIVITYPUB;
2088 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2089 $serverdata['detection-method'] = self::DETECT_BODY;
2096 * Analyses the header data of a given server for hints about type and system of that server
2098 * @param object $curlResult result of curl execution
2099 * @param array $serverdata array with server data
2101 * @return array server data
2103 private static function analyseRootHeader($curlResult, array $serverdata): array
2105 if ($curlResult->getHeader('server') == 'Mastodon') {
2106 $serverdata['platform'] = 'mastodon';
2107 $serverdata['network'] = Protocol::ACTIVITYPUB;
2108 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2109 $serverdata['platform'] = 'diaspora';
2110 $serverdata['network'] = Protocol::DIASPORA;
2111 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2112 } elseif ($curlResult->inHeader('x-friendica-version')) {
2113 $serverdata['platform'] = 'friendica';
2114 $serverdata['network'] = Protocol::DFRN;
2115 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2120 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2121 $serverdata['detection-method'] = self::DETECT_HEADER;
2128 * Update GServer entries
2130 public static function discover()
2132 // Update the server list
2133 self::discoverFederation();
2137 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2139 if ($requery_days == 0) {
2143 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2145 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2146 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2147 ['order' => ['RAND()']]);
2149 while ($gserver = DBA::fetch($gservers)) {
2150 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2151 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2153 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2154 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2156 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2157 self::update($fields, ['nurl' => $gserver['nurl']]);
2159 if (--$no_of_queries == 0) {
2164 DBA::close($gservers);
2168 * Discover federated servers
2170 private static function discoverFederation()
2172 $last = DI::config()->get('poco', 'last_federation_discovery');
2175 $next = $last + (24 * 60 * 60);
2177 if ($next > time()) {
2182 // Discover federated servers
2183 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2184 foreach ($protocols as $protocol) {
2185 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2186 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2187 if (!empty($curlResult)) {
2188 $data = json_decode($curlResult, true);
2189 if (!empty($data['data']['nodes'])) {
2190 foreach ($data['data']['nodes'] as $server) {
2191 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2192 self::add('https://' . $server['host'], true);
2198 // Disvover Mastodon servers
2199 $accesstoken = DI::config()->get('system', 'instances_social_key');
2201 if (!empty($accesstoken)) {
2202 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2203 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2204 if ($curlResult->isSuccess()) {
2205 $servers = json_decode($curlResult->getBody(), true);
2207 if (!empty($servers['instances'])) {
2208 foreach ($servers['instances'] as $server) {
2209 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2216 DI::config()->set('poco', 'last_federation_discovery', time());
2220 * Set the protocol for the given server
2222 * @param int $gsid Server id
2223 * @param int $protocol Protocol id
2227 public static function setProtocol(int $gsid, int $protocol)
2233 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2234 if (!DBA::isResult($gserver)) {
2238 $old = $gserver['protocol'];
2240 if (!is_null($old)) {
2242 The priority for the protocols is:
2244 2. DFRN via Diaspora
2250 // We don't need to change it when nothing is to be changed
2251 if ($old == $protocol) {
2255 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2256 if ($protocol == Post\DeliveryData::OSTATUS) {
2260 // If the server is marked as ActivityPub then we won't change it to anything different
2261 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2265 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2266 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2270 // Don't change it to Diaspora when it is a legacy DFRN server
2271 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2276 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2277 self::update(['protocol' => $protocol], ['id' => $gsid]);
2281 * Fetch the protocol of the given server
2283 * @param int $gsid Server id
2285 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2289 public static function getProtocol(int $gsid): ?int
2295 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2296 if (DBA::isResult($gserver)) {
2297 return $gserver['protocol'];
2304 * Update rows in the gserver table.
2305 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2307 * @param array $fields
2308 * @param array $condition
2314 public static function update(array $fields, array $condition): bool
2316 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2318 return DBA::update('gserver', $fields, $condition);
2322 * Insert a row into the gserver table.
2323 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2325 * @param array $fields
2326 * @param int $duplicate_mode What to do on a duplicated entry
2332 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2334 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2336 return DBA::insert('gserver', $fields, $duplicate_mode);