3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Relay;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
46 use Friendica\Network\HTTPException;
47 use GuzzleHttp\Psr7\Uri;
50 * This class handles GServer related functions
57 const DT_MASTODON = 2;
59 // Methods to detect server types
61 // Non endpoint specific methods
62 const DETECT_MANUAL = 0;
63 const DETECT_HEADER = 1;
64 const DETECT_BODY = 2;
65 const DETECT_HOST_META = 3;
66 const DETECT_CONTACTS = 4;
67 const DETECT_AP_ACTOR = 5;
68 const DETECT_AP_COLLECTION = 6;
70 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
72 // Implementation specific endpoints
73 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
74 const DETECT_FRIENDIKA = 10;
75 const DETECT_FRIENDICA = 11;
76 const DETECT_STATUSNET = 12;
77 const DETECT_GNUSOCIAL = 13;
78 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
79 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
80 const DETECT_MASTODON_API = 16;
81 const DETECT_STATUS_PHP = 17; // Nextcloud
82 const DETECT_V1_CONFIG = 18;
83 const DETECT_PUMPIO = 19; // Deprecated
84 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
86 // Standardized endpoints
87 const DETECT_STATISTICS_JSON = 100;
88 const DETECT_NODEINFO_1 = 101;
89 const DETECT_NODEINFO_2 = 102;
90 const DETECT_NODEINFO_210 = 103;
93 * Check for the existance of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
100 public static function add(string $url, bool $only_nodeinfo = false)
102 if (self::getID($url, false)) {
106 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
110 * Get the ID for the given server URL
113 * @param boolean $no_check Don't check if the server hadn't been found
115 * @return int|null gserver id or NULL on empty URL or failed check
117 public static function getID(string $url, bool $no_check = false): ?int
119 $url = self::cleanURL($url);
125 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
126 if (DBA::isResult($gserver)) {
127 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
128 return $gserver['id'];
131 if ($no_check || !self::check($url)) {
135 return self::getID($url, true);
139 * Retrieves all the servers which base domain are matching the provided domain pattern
141 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
143 * @param string $pattern
149 public static function listByDomainPattern(string $pattern): array
151 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
153 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
154 // eventual server path and keep only the server domain which we're matching against the pattern.
155 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
157 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
158 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
159 AND NOT `gserver`.`failed`
160 GROUP BY `gserver`.`id`";
162 $stmt = DI::dba()->p($sql, $likePattern);
164 return DI::dba()->toArray($stmt);
168 * Checks if the given server id is reachable
170 * @param integer $gsid
173 public static function reachableById(int $gsid): bool
175 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
176 if (empty($gserver)) {
179 if (strtotime($gserver['next_contact']) < time()) {
180 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
182 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
187 * Checks if the given server is reachable
189 * @param array $contact Contact that should be checked
191 * @return boolean 'true' if server seems vital
193 public static function reachable(array $contact): bool
195 if (!empty($contact['gsid'])) {
196 $gsid = $contact['gsid'];
197 } elseif (!empty($contact['baseurl'])) {
198 $server = $contact['baseurl'];
199 } elseif ($contact['network'] == Protocol::DIASPORA) {
200 $parts = parse_url($contact['url']);
201 unset($parts['path']);
202 $server = (string)Uri::fromParts($parts);
208 $condition = ['id' => $gsid];
210 $condition = ['nurl' => Strings::normaliseLink($server)];
213 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
214 if (empty($gserver)) {
217 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
218 $server = $gserver['url'];
221 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
222 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $server, false);
229 * Calculate the next update day
231 * @param bool $success
232 * @param string $created
233 * @param string $last_contact
234 * @param bool $undetected
240 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
242 // On successful contact process check again next week when it is a detected system.
243 // When we haven't detected the system, it could be a static website or a really old system.
245 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
248 $now = strtotime(DateTimeFormat::utcNow());
250 if ($created > $last_contact) {
251 $contact_time = strtotime($created);
253 $contact_time = strtotime($last_contact);
256 // If the last contact was less than 6 hours before then try again in 6 hours
257 if (($now - $contact_time) < (60 * 60 * 6)) {
258 return DateTimeFormat::utc('now +6 hour');
261 // If the last contact was less than 12 hours before then try again in 12 hours
262 if (($now - $contact_time) < (60 * 60 * 12)) {
263 return DateTimeFormat::utc('now +12 hour');
266 // If the last contact was less than 24 hours before then try tomorrow again
267 if (($now - $contact_time) < (60 * 60 * 24)) {
268 return DateTimeFormat::utc('now +1 day');
271 // If the last contact was less than a week before then try again in a week
272 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
273 return DateTimeFormat::utc('now +1 week');
276 // If the last contact was less than two weeks before then try again in two week
277 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
278 return DateTimeFormat::utc('now +2 week');
281 // If the last contact was less than a month before then try again in a month
282 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
283 return DateTimeFormat::utc('now +1 month');
286 // The system hadn't been successul contacted for more than a month, so try again in three months
287 return DateTimeFormat::utc('now +3 month');
291 * Checks the state of the given server.
293 * @param string $server_url URL of the given server
294 * @param string $network Network value that is used, when detection failed
295 * @param boolean $force Force an update.
296 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
298 * @return boolean 'true' if server seems vital
300 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
302 $server_url = self::cleanURL($server_url);
303 if ($server_url == '') {
307 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
308 if (DBA::isResult($gserver)) {
309 if ($gserver['created'] <= DBA::NULL_DATETIME) {
310 $fields = ['created' => DateTimeFormat::utcNow()];
311 $condition = ['nurl' => Strings::normaliseLink($server_url)];
312 self::update($fields, $condition);
315 if (!$force && (strtotime($gserver['next_contact']) > time())) {
316 Logger::info('No update needed', ['server' => $server_url]);
317 return (!$gserver['failed']);
319 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
321 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
324 return self::detect($server_url, $network, $only_nodeinfo);
328 * Reset failed server status by gserver id
332 public static function setReachableById(int $gsid)
334 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
335 if (DBA::isResult($gserver) && $gserver['failed']) {
336 self::update(['failed' => false, 'last_contact' => DateTimeFormat::utcNow()], ['id' => $gsid]);
337 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
339 if (strtotime($gserver['next_contact']) < time()) {
340 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
346 * Set failed server status by gserver id
350 public static function setFailureById(int $gsid)
352 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
353 if (DBA::isResult($gserver) && !$gserver['failed']) {
354 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
355 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
357 if (strtotime($gserver['next_contact']) < time()) {
358 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
364 * Set failed server status
368 public static function setFailure(string $url)
370 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
371 if (DBA::isResult($gserver)) {
372 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
373 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
374 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
375 ['nurl' => Strings::normaliseLink($url)]);
376 Logger::info('Set failed status for existing server', ['url' => $url]);
379 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
380 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
381 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
382 Logger::info('Set failed status for new server', ['url' => $url]);
386 * Remove unwanted content from the given URL
388 * @param string $dirtyUrl
390 * @return string cleaned URL
393 public static function cleanURL(string $dirtyUrl): string
396 $url = str_replace('/index.php', '', trim($dirtyUrl, '/'));
397 return (string)(new Uri($url))->withUserInfo('')->withQuery('')->withFragment('');
398 } catch (\Throwable $e) {
399 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl, 'url' => $url]);
405 * Detect server data (type, protocol, version number, ...)
406 * The detected data is then updated or inserted in the gserver table.
408 * @param string $url URL of the given server
409 * @param string $network Network value that is used, when detection failed
410 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
412 * @return boolean 'true' if server could be detected
414 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
416 Logger::info('Detect server type', ['server' => $url]);
418 $original_url = $url;
420 // Remove URL content that is not supposed to exist for a server url
421 $url = rtrim(self::cleanURL($url), '/');
423 Logger::notice('Empty URL.');
427 // If the URL missmatches, then we mark the old entry as failure
428 if (!Strings::compareLink($url, $original_url)) {
429 self::setFailure($original_url);
430 if (!self::getID($url, true)) {
431 self::detect($url, $network, $only_nodeinfo);
436 $valid_url = Network::isUrlValid($url);
438 self::setFailure($url);
441 $valid_url = rtrim($valid_url, '/');
444 if (!Strings::compareLink($url, $valid_url)) {
445 // We only follow redirects when the path stays the same or the target url has no path.
446 // Some systems have got redirects on their landing page to a single account page. This check handles it.
447 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))) ||
448 (((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)))) {
449 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
450 self::setFailure($url);
451 if (!self::getID($valid_url, true)) {
452 self::detect($valid_url, $network, $only_nodeinfo);
457 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)) &&
458 (parse_url($url, PHP_URL_PATH) == '')) {
459 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
460 $parts = parse_url($valid_url);
461 unset($parts['path']);
462 $valid_url = (string)Uri::fromParts($parts);
464 self::setFailure($url);
465 if (!self::getID($valid_url, true)) {
466 self::detect($valid_url, $network, $only_nodeinfo);
470 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
473 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
474 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
475 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
479 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
481 // When a nodeinfo is present, we don't need to dig further
482 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
483 if ($curlResult->isTimeout()) {
484 self::setFailure($url);
488 $serverdata = self::parseNodeinfo210($curlResult);
489 if (empty($serverdata)) {
490 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
491 $serverdata = self::fetchNodeinfo($url, $curlResult);
494 if ($only_nodeinfo && empty($serverdata)) {
495 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
496 self::setFailure($url);
498 } elseif (empty($serverdata)) {
499 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
502 // When there is no Nodeinfo, then use some protocol specific endpoints
503 if ($serverdata['network'] == Protocol::PHANTOM) {
505 // Fetch the landing page, possibly it reveals some data
506 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
507 $curlResult = DI::httpClient()->get($url, $accept);
508 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
509 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
510 $html_fetched = true;
512 $html_fetched = false;
515 if ($curlResult->isSuccess()) {
516 $json = json_decode($curlResult->getBody(), true);
517 if (!empty($json) && is_array($json)) {
518 $data = self::fetchDataFromSystemActor($json, $serverdata);
519 $serverdata = $data['server'];
520 $systemactor = $data['actor'];
521 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
522 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
524 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
525 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
528 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
529 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
530 $serverdata = self::analyseRootBody($curlResult, $serverdata);
534 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
535 self::setFailure($url);
539 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
540 $serverdata = self::detectMastodonAlikes($url, $serverdata);
544 // All following checks are done for systems that always have got a "host-meta" endpoint.
545 // With this check we don't have to waste time and ressources for dead systems.
546 // Also this hopefully prevents us from receiving abuse messages.
547 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
548 $validHostMeta = self::validHostMeta($url);
550 $validHostMeta = false;
553 if ($validHostMeta) {
554 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
555 $serverdata['detection-method'] = self::DETECT_HOST_META;
558 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
559 $serverdata = self::detectFriendica($url, $serverdata);
562 // The following systems have to be installed in the root directory.
564 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
565 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
566 $serverdata = self::fetchSiteinfo($url, $serverdata);
569 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
570 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
571 $serverdata = self::detectHubzilla($url, $serverdata);
574 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
575 $serverdata = self::detectPeertube($url, $serverdata);
578 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
579 $serverdata = self::detectGNUSocial($url, $serverdata);
582 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
583 $serverdata = self::detectFriendica($url, $serverdata);
586 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
587 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
590 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
591 // Since this endpoint is only rarely used, we query it at a later time
592 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
593 $serverdata = self::fetchStatistics($url, $serverdata);
597 // When we hadn't been able to detect the network type, we use the hint from the parameter
598 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
599 $serverdata['network'] = $network;
602 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
603 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
604 self::setFailure($url);
608 $serverdata['url'] = $url;
609 $serverdata['nurl'] = Strings::normaliseLink($url);
611 // We have to prevent an endless loop here.
612 // When a server is new, then there is no gserver entry yet.
613 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
614 // and this can call this function here as well.
615 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
616 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
617 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
620 // Detect the directory type
621 $serverdata['directory-type'] = self::DT_NONE;
623 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
624 $serverdata = self::checkMastodonDirectory($url, $serverdata);
626 if ($serverdata['directory-type'] == self::DT_NONE) {
627 $serverdata = self::checkPoCo($url, $serverdata);
631 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
632 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
635 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
637 // Numbers above a reasonable value (10 millions) are ignored
638 if ($serverdata['registered-users'] > 10000000) {
639 $serverdata['registered-users'] = 0;
642 // On an active server there has to be at least a single user
643 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
644 $serverdata['registered-users'] = 1;
645 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
646 $serverdata['registered-users'] = 0;
649 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
651 $serverdata['last_contact'] = DateTimeFormat::utcNow();
652 $serverdata['failed'] = false;
654 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
655 if (!DBA::isResult($gserver)) {
656 $serverdata['created'] = DateTimeFormat::utcNow();
657 $ret = self::insert($serverdata);
658 $id = DBA::lastInsertId();
660 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
661 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
662 if (DBA::isResult($gserver)) {
663 $id = $gserver['id'];
667 // Count the number of known contacts from this server
668 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
669 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
670 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
671 $max_users = max($apcontacts, $contacts);
672 if ($max_users > $serverdata['registered-users']) {
673 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
674 self::update(['registered-users' => $max_users], ['id' => $id]);
677 if (empty($serverdata['active-month-users'])) {
678 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
680 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
681 self::update(['active-month-users' => $contacts], ['id' => $id]);
685 if (empty($serverdata['active-halfyear-users'])) {
686 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
688 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
689 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
694 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
695 self::discoverRelay($url);
698 if (!empty($systemactor)) {
699 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
700 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
707 * Fetch relay data from a given server url
709 * @param string $server_url address of the server
713 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
715 private static function discoverRelay(string $server_url)
717 Logger::info('Discover relay data', ['server' => $server_url]);
719 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
720 if (!$curlResult->isSuccess()) {
724 $data = json_decode($curlResult->getBody(), true);
725 if (!is_array($data)) {
729 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
730 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
732 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
734 $data['subscribe'] = false;
738 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
739 if (!DBA::isResult($gserver)) {
743 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
744 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
745 self::update($fields, ['id' => $gserver['id']]);
748 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
750 if ($data['scope'] == 'tags') {
753 foreach ($data['tags'] as $tag) {
754 $tag = mb_strtolower($tag);
755 if (strlen($tag) < 100) {
760 foreach ($tags as $tag) {
761 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
765 // Create or update the relay contact
767 if (isset($data['protocols'])) {
768 if (isset($data['protocols']['diaspora'])) {
769 $fields['network'] = Protocol::DIASPORA;
771 if (isset($data['protocols']['diaspora']['receive'])) {
772 $fields['batch'] = $data['protocols']['diaspora']['receive'];
773 } elseif (is_string($data['protocols']['diaspora'])) {
774 $fields['batch'] = $data['protocols']['diaspora'];
778 if (isset($data['protocols']['dfrn'])) {
779 $fields['network'] = Protocol::DFRN;
781 if (isset($data['protocols']['dfrn']['receive'])) {
782 $fields['batch'] = $data['protocols']['dfrn']['receive'];
783 } elseif (is_string($data['protocols']['dfrn'])) {
784 $fields['batch'] = $data['protocols']['dfrn'];
788 if (isset($data['protocols']['activitypub'])) {
789 $fields['network'] = Protocol::ACTIVITYPUB;
791 if (!empty($data['protocols']['activitypub']['actor'])) {
792 $fields['url'] = $data['protocols']['activitypub']['actor'];
794 if (!empty($data['protocols']['activitypub']['receive'])) {
795 $fields['batch'] = $data['protocols']['activitypub']['receive'];
800 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
802 Relay::updateContact($gserver, $fields);
806 * Fetch server data from '/statistics.json' on the given server
808 * @param string $url URL of the given server
810 * @return array server data
812 private static function fetchStatistics(string $url, array $serverdata): array
814 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
815 if (!$curlResult->isSuccess()) {
819 $data = json_decode($curlResult->getBody(), true);
824 // Some AP enabled systems return activity data that we don't expect here.
825 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
830 $old_serverdata = $serverdata;
832 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
834 if (!empty($data['version'])) {
836 $serverdata['version'] = $data['version'];
837 // Version numbers on statistics.json are presented with additional info, e.g.:
838 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
839 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
842 if (!empty($data['name'])) {
844 $serverdata['site_name'] = $data['name'];
847 if (!empty($data['network'])) {
849 $serverdata['platform'] = strtolower($data['network']);
851 if ($serverdata['platform'] == 'diaspora') {
852 $serverdata['network'] = Protocol::DIASPORA;
853 } elseif ($serverdata['platform'] == 'friendica') {
854 $serverdata['network'] = Protocol::DFRN;
855 } elseif ($serverdata['platform'] == 'hubzilla') {
856 $serverdata['network'] = Protocol::ZOT;
857 } elseif ($serverdata['platform'] == 'redmatrix') {
858 $serverdata['network'] = Protocol::ZOT;
862 if (!empty($data['total_users'])) {
864 $serverdata['registered-users'] = max($data['total_users'], 1);
867 if (!empty($data['active_users_monthly'])) {
869 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
872 if (!empty($data['active_users_halfyear'])) {
874 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
877 if (!empty($data['local_posts'])) {
879 $serverdata['local-posts'] = max($data['local_posts'], 0);
882 if (!empty($data['registrations_open'])) {
883 $serverdata['register_policy'] = Register::OPEN;
885 $serverdata['register_policy'] = Register::CLOSED;
889 return $old_serverdata;
896 * Detect server type by using the nodeinfo data
898 * @param string $url address of the server
899 * @param ICanHandleHttpResponses $httpResult
901 * @return array Server data
903 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
905 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
907 if (!$httpResult->isSuccess()) {
911 $nodeinfo = json_decode($httpResult->getBody(), true);
913 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
920 foreach ($nodeinfo['links'] as $link) {
921 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
922 Logger::info('Invalid nodeinfo format', ['url' => $url]);
925 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
926 $nodeinfo1_url = $link['href'];
927 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
928 $nodeinfo2_url = $link['href'];
932 if ($nodeinfo1_url . $nodeinfo2_url == '') {
938 if (!empty($nodeinfo2_url)) {
939 $server = self::parseNodeinfo2($nodeinfo2_url);
942 if (empty($server) && !empty($nodeinfo1_url)) {
943 $server = self::parseNodeinfo1($nodeinfo1_url);
952 * @param string $nodeinfo_url address of the nodeinfo path
954 * @return array Server data
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
958 private static function parseNodeinfo1(string $nodeinfo_url): array
960 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
961 if (!$curlResult->isSuccess()) {
965 $nodeinfo = json_decode($curlResult->getBody(), true);
967 if (!is_array($nodeinfo)) {
971 $server = ['detection-method' => self::DETECT_NODEINFO_1,
972 'register_policy' => Register::CLOSED];
974 if (!empty($nodeinfo['openRegistrations'])) {
975 $server['register_policy'] = Register::OPEN;
978 if (is_array($nodeinfo['software'])) {
979 if (!empty($nodeinfo['software']['name'])) {
980 $server['platform'] = strtolower($nodeinfo['software']['name']);
983 if (!empty($nodeinfo['software']['version'])) {
984 $server['version'] = $nodeinfo['software']['version'];
985 // Version numbers on Nodeinfo are presented with additional info, e.g.:
986 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
987 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
991 if (!empty($nodeinfo['metadata']['nodeName'])) {
992 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
995 if (!empty($nodeinfo['usage']['users']['total'])) {
996 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
999 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1000 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1003 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1004 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1007 if (!empty($nodeinfo['usage']['localPosts'])) {
1008 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1011 if (!empty($nodeinfo['usage']['localComments'])) {
1012 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1015 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1017 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1018 $protocols[$protocol] = true;
1021 if (!empty($protocols['friendica'])) {
1022 $server['network'] = Protocol::DFRN;
1023 } elseif (!empty($protocols['activitypub'])) {
1024 $server['network'] = Protocol::ACTIVITYPUB;
1025 } elseif (!empty($protocols['diaspora'])) {
1026 $server['network'] = Protocol::DIASPORA;
1027 } elseif (!empty($protocols['ostatus'])) {
1028 $server['network'] = Protocol::OSTATUS;
1029 } elseif (!empty($protocols['gnusocial'])) {
1030 $server['network'] = Protocol::OSTATUS;
1031 } elseif (!empty($protocols['zot'])) {
1032 $server['network'] = Protocol::ZOT;
1036 if (empty($server)) {
1040 if (empty($server['network'])) {
1041 $server['network'] = Protocol::PHANTOM;
1050 * @see https://git.feneas.org/jaywink/nodeinfo2
1052 * @param string $nodeinfo_url address of the nodeinfo path
1054 * @return array Server data
1056 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1058 private static function parseNodeinfo2(string $nodeinfo_url): array
1060 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1061 if (!$curlResult->isSuccess()) {
1065 $nodeinfo = json_decode($curlResult->getBody(), true);
1066 if (!is_array($nodeinfo)) {
1071 'detection-method' => self::DETECT_NODEINFO_2,
1072 'register_policy' => Register::CLOSED,
1073 'platform' => 'unknown',
1076 if (!empty($nodeinfo['openRegistrations'])) {
1077 $server['register_policy'] = Register::OPEN;
1080 if (!empty($nodeinfo['software'])) {
1081 if (isset($nodeinfo['software']['name'])) {
1082 $server['platform'] = strtolower($nodeinfo['software']['name']);
1085 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1086 $server['version'] = $nodeinfo['software']['version'];
1087 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1088 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1089 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1091 // qoto advertises itself as Mastodon
1092 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1093 $server['platform'] = 'qoto';
1098 if (!empty($nodeinfo['metadata']['nodeName'])) {
1099 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1102 if (!empty($nodeinfo['usage']['users']['total'])) {
1103 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1106 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1107 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1110 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1111 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1114 if (!empty($nodeinfo['usage']['localPosts'])) {
1115 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1118 if (!empty($nodeinfo['usage']['localComments'])) {
1119 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1122 if (!empty($nodeinfo['protocols'])) {
1124 foreach ($nodeinfo['protocols'] as $protocol) {
1125 if (is_string($protocol)) {
1126 $protocols[$protocol] = true;
1130 if (!empty($protocols['dfrn'])) {
1131 $server['network'] = Protocol::DFRN;
1132 } elseif (!empty($protocols['activitypub'])) {
1133 $server['network'] = Protocol::ACTIVITYPUB;
1134 } elseif (!empty($protocols['diaspora'])) {
1135 $server['network'] = Protocol::DIASPORA;
1136 } elseif (!empty($protocols['ostatus'])) {
1137 $server['network'] = Protocol::OSTATUS;
1138 } elseif (!empty($protocols['gnusocial'])) {
1139 $server['network'] = Protocol::OSTATUS;
1140 } elseif (!empty($protocols['zot'])) {
1141 $server['network'] = Protocol::ZOT;
1145 if (empty($server)) {
1149 if (empty($server['network'])) {
1150 $server['network'] = Protocol::PHANTOM;
1157 * Parses NodeInfo2 protocol 1.0
1159 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1161 * @param string $nodeinfo_url address of the nodeinfo path
1163 * @return array Server data
1165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1167 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1169 if (!$httpResult->isSuccess()) {
1173 $nodeinfo = json_decode($httpResult->getBody(), true);
1175 if (!is_array($nodeinfo)) {
1179 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1180 'register_policy' => Register::CLOSED];
1182 if (!empty($nodeinfo['openRegistrations'])) {
1183 $server['register_policy'] = Register::OPEN;
1186 if (!empty($nodeinfo['server'])) {
1187 if (!empty($nodeinfo['server']['software'])) {
1188 $server['platform'] = strtolower($nodeinfo['server']['software']);
1191 if (!empty($nodeinfo['server']['version'])) {
1192 $server['version'] = $nodeinfo['server']['version'];
1193 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1194 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1195 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1198 if (!empty($nodeinfo['server']['name'])) {
1199 $server['site_name'] = $nodeinfo['server']['name'];
1203 if (!empty($nodeinfo['usage']['users']['total'])) {
1204 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1207 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1208 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1211 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1212 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1215 if (!empty($nodeinfo['usage']['localPosts'])) {
1216 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1219 if (!empty($nodeinfo['usage']['localComments'])) {
1220 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1223 if (!empty($nodeinfo['protocols'])) {
1225 foreach ($nodeinfo['protocols'] as $protocol) {
1226 if (is_string($protocol)) {
1227 $protocols[$protocol] = true;
1231 if (!empty($protocols['dfrn'])) {
1232 $server['network'] = Protocol::DFRN;
1233 } elseif (!empty($protocols['activitypub'])) {
1234 $server['network'] = Protocol::ACTIVITYPUB;
1235 } elseif (!empty($protocols['diaspora'])) {
1236 $server['network'] = Protocol::DIASPORA;
1237 } elseif (!empty($protocols['ostatus'])) {
1238 $server['network'] = Protocol::OSTATUS;
1239 } elseif (!empty($protocols['gnusocial'])) {
1240 $server['network'] = Protocol::OSTATUS;
1241 } elseif (!empty($protocols['zot'])) {
1242 $server['network'] = Protocol::ZOT;
1246 if (empty($server) || empty($server['platform'])) {
1250 if (empty($server['network'])) {
1251 $server['network'] = Protocol::PHANTOM;
1258 * Fetch server information from a 'siteinfo.json' file on the given server
1260 * @param string $url URL of the given server
1261 * @param array $serverdata array with server data
1263 * @return array server data
1265 private static function fetchSiteinfo(string $url, array $serverdata): array
1267 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1268 if (!$curlResult->isSuccess()) {
1272 $data = json_decode($curlResult->getBody(), true);
1277 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1278 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1281 if (!empty($data['url'])) {
1282 $serverdata['platform'] = strtolower($data['platform']);
1283 $serverdata['version'] = $data['version'] ?? 'N/A';
1286 if (!empty($data['plugins'])) {
1287 if (in_array('pubcrawl', $data['plugins'])) {
1288 $serverdata['network'] = Protocol::ACTIVITYPUB;
1289 } elseif (in_array('diaspora', $data['plugins'])) {
1290 $serverdata['network'] = Protocol::DIASPORA;
1291 } elseif (in_array('gnusoc', $data['plugins'])) {
1292 $serverdata['network'] = Protocol::OSTATUS;
1294 $serverdata['network'] = Protocol::ZOT;
1298 if (!empty($data['site_name'])) {
1299 $serverdata['site_name'] = $data['site_name'];
1302 if (!empty($data['channels_total'])) {
1303 $serverdata['registered-users'] = max($data['channels_total'], 1);
1306 if (!empty($data['channels_active_monthly'])) {
1307 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1310 if (!empty($data['channels_active_halfyear'])) {
1311 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1314 if (!empty($data['local_posts'])) {
1315 $serverdata['local-posts'] = max($data['local_posts'], 0);
1318 if (!empty($data['local_comments'])) {
1319 $serverdata['local-comments'] = max($data['local_comments'], 0);
1322 if (!empty($data['register_policy'])) {
1323 switch ($data['register_policy']) {
1324 case 'REGISTER_OPEN':
1325 $serverdata['register_policy'] = Register::OPEN;
1328 case 'REGISTER_APPROVE':
1329 $serverdata['register_policy'] = Register::APPROVE;
1332 case 'REGISTER_CLOSED':
1334 $serverdata['register_policy'] = Register::CLOSED;
1343 * Fetches server data via an ActivityPub account with url of that server
1345 * @param string $url URL of the given server
1346 * @param array $serverdata array with server data
1348 * @return array server data
1352 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1355 return ['server' => $serverdata, 'actor' => ''];
1358 $actor = JsonLD::compact($data, false);
1359 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1360 $serverdata['network'] = Protocol::ACTIVITYPUB;
1361 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1362 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1363 if (!empty($actor['as:generator'])) {
1364 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1365 $serverdata['platform'] = strtolower(array_shift($generator));
1366 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1368 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1370 return ['server' => $serverdata, 'actor' => $actor['@id']];
1371 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1372 // By now only Ktistec seems to provide collections this way
1373 $serverdata['platform'] = 'ktistec';
1374 $serverdata['network'] = Protocol::ACTIVITYPUB;
1375 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1377 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1378 if (!empty($actors) && !empty($actors[0]['@id'])) {
1379 $actor_url = $actor['@id'] . $actors[0]['@id'];
1384 return ['server' => $serverdata, 'actor' => $actor_url];
1386 return ['server' => $serverdata, 'actor' => ''];
1390 * Checks if the server contains a valid host meta file
1392 * @param string $url URL of the given server
1394 * @return boolean 'true' if the server seems to be vital
1396 private static function validHostMeta(string $url): bool
1398 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1399 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1400 if (!$curlResult->isSuccess()) {
1404 $xrd = XML::parseString($curlResult->getBody(), true);
1405 if (!is_object($xrd)) {
1409 $elements = XML::elementToArray($xrd);
1410 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1415 foreach ($elements['xrd']['link'] as $link) {
1416 // When there is more than a single "link" element, the array looks slightly different
1417 if (!empty($link['@attributes'])) {
1418 $link = $link['@attributes'];
1421 if (empty($link['rel']) || empty($link['template'])) {
1425 if ($link['rel'] == 'lrdd') {
1426 // When the webfinger host is the same like the system host, it should be ok.
1427 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1435 * Detect the network of the given server via their known contacts
1437 * @param string $url URL of the given server
1438 * @param array $serverdata array with server data
1440 * @return array server data
1442 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1446 $nurl = Strings::normaliseLink($url);
1448 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1449 while ($apcontact = DBA::fetch($apcontacts)) {
1450 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1452 DBA::close($apcontacts);
1454 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1455 while ($pcontact = DBA::fetch($pcontacts)) {
1456 $contacts[$pcontact['nurl']] = $pcontact['url'];
1458 DBA::close($pcontacts);
1460 if (empty($contacts)) {
1465 foreach ($contacts as $contact) {
1466 // Endlosschleife verhindern wegen gsid!
1467 $data = Probe::uri($contact);
1468 if (in_array($data['network'], Protocol::FEDERATED)) {
1469 $serverdata['network'] = $data['network'];
1471 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1472 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1475 } elseif ((time() - $time) > 10) {
1476 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1485 * Checks if the given server does have a '/poco' endpoint.
1486 * This is used for the 'PortableContact' functionality,
1487 * which is used by both Friendica and Hubzilla.
1489 * @param string $url URL of the given server
1490 * @param array $serverdata array with server data
1492 * @return array server data
1494 private static function checkPoCo(string $url, array $serverdata): array
1496 $serverdata['poco'] = '';
1498 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1499 if (!$curlResult->isSuccess()) {
1503 $data = json_decode($curlResult->getBody(), true);
1508 if (!empty($data['totalResults'])) {
1509 $registeredUsers = $serverdata['registered-users'] ?? 0;
1510 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1511 $serverdata['directory-type'] = self::DT_POCO;
1512 $serverdata['poco'] = $url . '/poco';
1519 * Checks if the given server does have a Mastodon style directory endpoint.
1521 * @param string $url URL of the given server
1522 * @param array $serverdata array with server data
1524 * @return array server data
1526 public static function checkMastodonDirectory(string $url, array $serverdata): array
1528 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1529 if (!$curlResult->isSuccess()) {
1533 $data = json_decode($curlResult->getBody(), true);
1538 if (count($data) == 1) {
1539 $serverdata['directory-type'] = self::DT_MASTODON;
1546 * Detects Peertube via their known endpoint
1548 * @param string $url URL of the given server
1549 * @param array $serverdata array with server data
1551 * @return array server data
1553 private static function detectPeertube(string $url, array $serverdata): array
1555 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1556 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1560 $data = json_decode($curlResult->getBody(), true);
1565 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1566 $serverdata['platform'] = 'peertube';
1567 $serverdata['version'] = $data['serverVersion'];
1568 $serverdata['network'] = Protocol::ACTIVITYPUB;
1570 if (!empty($data['instance']['name'])) {
1571 $serverdata['site_name'] = $data['instance']['name'];
1574 if (!empty($data['instance']['shortDescription'])) {
1575 $serverdata['info'] = $data['instance']['shortDescription'];
1578 if (!empty($data['signup'])) {
1579 if (!empty($data['signup']['allowed'])) {
1580 $serverdata['register_policy'] = Register::OPEN;
1584 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1585 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1593 * Detects the version number of a given server when it was a NextCloud installation
1595 * @param string $url URL of the given server
1596 * @param array $serverdata array with server data
1597 * @param bool $validHostMeta
1599 * @return array server data
1601 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1603 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1604 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1608 $data = json_decode($curlResult->getBody(), true);
1613 if (!empty($data['version'])) {
1614 $serverdata['platform'] = 'nextcloud';
1615 $serverdata['version'] = $data['version'];
1617 if ($validHostMeta) {
1618 $serverdata['network'] = Protocol::ACTIVITYPUB;
1621 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1622 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1630 * Fetches weekly usage data
1632 * @param string $url URL of the given server
1633 * @param array $serverdata array with server data
1635 * @return array server data
1637 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1639 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1640 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1644 $data = json_decode($curlResult->getBody(), true);
1650 foreach ($data as $week) {
1651 // Use only data from a full week
1652 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1656 // Most likely the data is sorted correctly. But we better are safe than sorry
1657 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1658 $current_week = $week;
1662 if (!empty($current_week['logins'])) {
1663 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1670 * Detects data from a given server url if it was a mastodon alike system
1672 * @param string $url URL of the given server
1673 * @param array $serverdata array with server data
1675 * @return array server data
1677 private static function detectMastodonAlikes(string $url, array $serverdata): array
1679 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1680 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1684 $data = json_decode($curlResult->getBody(), true);
1691 if (!empty($data['version'])) {
1692 $serverdata['platform'] = 'mastodon';
1693 $serverdata['version'] = $data['version'] ?? '';
1694 $serverdata['network'] = Protocol::ACTIVITYPUB;
1698 if (!empty($data['title'])) {
1699 $serverdata['site_name'] = $data['title'];
1702 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1703 $serverdata['platform'] = 'mastodon';
1704 $serverdata['network'] = Protocol::ACTIVITYPUB;
1708 if (!empty($data['description'])) {
1709 $serverdata['info'] = trim($data['description']);
1712 if (!empty($data['stats']['user_count'])) {
1713 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1716 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1717 $serverdata['platform'] = strtolower($matches[1]);
1718 $serverdata['version'] = $matches[2];
1722 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1723 $serverdata['platform'] = 'pleroma';
1724 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1728 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1729 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1730 $serverdata['platform'] = 'pleroma';
1734 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1735 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1742 * Detects data from typical Hubzilla endpoints
1744 * @param string $url URL of the given server
1745 * @param array $serverdata array with server data
1747 * @return array server data
1749 private static function detectHubzilla(string $url, array $serverdata): array
1751 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1752 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1756 $data = json_decode($curlResult->getBody(), true);
1757 if (empty($data) || empty($data['site'])) {
1761 if (!empty($data['site']['name'])) {
1762 $serverdata['site_name'] = $data['site']['name'];
1765 if (!empty($data['site']['platform'])) {
1766 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1767 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1768 $serverdata['network'] = Protocol::ZOT;
1771 if (!empty($data['site']['hubzilla'])) {
1772 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1773 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1774 $serverdata['network'] = Protocol::ZOT;
1777 if (!empty($data['site']['redmatrix'])) {
1778 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1779 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1780 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1781 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1784 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1785 $serverdata['network'] = Protocol::ZOT;
1789 $inviteonly = false;
1792 if (!empty($data['site']['closed'])) {
1793 $closed = self::toBoolean($data['site']['closed']);
1796 if (!empty($data['site']['private'])) {
1797 $private = self::toBoolean($data['site']['private']);
1800 if (!empty($data['site']['inviteonly'])) {
1801 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1804 if (!$closed && !$private and $inviteonly) {
1805 $serverdata['register_policy'] = Register::APPROVE;
1806 } elseif (!$closed && !$private) {
1807 $serverdata['register_policy'] = Register::OPEN;
1809 $serverdata['register_policy'] = Register::CLOSED;
1812 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1813 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1820 * Converts input value to a boolean value
1822 * @param string|integer $val
1826 private static function toBoolean($val): bool
1828 if (($val == 'true') || ($val == 1)) {
1830 } elseif (($val == 'false') || ($val == 0)) {
1838 * Detect if the URL belongs to a GNU Social server
1840 * @param string $url URL of the given server
1841 * @param array $serverdata array with server data
1843 * @return array server data
1845 private static function detectGNUSocial(string $url, array $serverdata): array
1847 // Test for GNU Social
1848 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1849 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1850 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1851 $serverdata['platform'] = 'gnusocial';
1852 // Remove junk that some GNU Social servers return
1853 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1854 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1855 $serverdata['version'] = trim($serverdata['version'], '"');
1856 $serverdata['network'] = Protocol::OSTATUS;
1858 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1859 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1865 // Test for Statusnet
1866 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1867 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1868 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1870 // Remove junk that some GNU Social servers return
1871 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1872 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1873 $serverdata['version'] = trim($serverdata['version'], '"');
1875 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1876 $serverdata['platform'] = 'pleroma';
1877 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1878 $serverdata['network'] = Protocol::ACTIVITYPUB;
1880 $serverdata['platform'] = 'statusnet';
1881 $serverdata['network'] = Protocol::OSTATUS;
1884 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1885 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1893 * Detect if the URL belongs to a Friendica server
1895 * @param string $url URL of the given server
1896 * @param array $serverdata array with server data
1898 * @return array server data
1900 private static function detectFriendica(string $url, array $serverdata): array
1902 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1903 // Because of this me must not use ACCEPT_JSON here.
1904 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1905 if (!$curlResult->isSuccess()) {
1906 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1908 $platform = 'Friendika';
1911 $platform = 'Friendica';
1914 if (!$curlResult->isSuccess()) {
1918 $data = json_decode($curlResult->getBody(), true);
1919 if (empty($data) || empty($data['version'])) {
1923 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1924 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1927 $serverdata['network'] = Protocol::DFRN;
1928 $serverdata['version'] = $data['version'];
1930 if (!empty($data['no_scrape_url'])) {
1931 $serverdata['noscrape'] = $data['no_scrape_url'];
1934 if (!empty($data['site_name'])) {
1935 $serverdata['site_name'] = $data['site_name'];
1938 if (!empty($data['info'])) {
1939 $serverdata['info'] = trim($data['info']);
1942 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1943 switch ($register_policy) {
1944 case 'REGISTER_OPEN':
1945 $serverdata['register_policy'] = Register::OPEN;
1948 case 'REGISTER_APPROVE':
1949 $serverdata['register_policy'] = Register::APPROVE;
1952 case 'REGISTER_CLOSED':
1953 case 'REGISTER_INVITATION':
1954 $serverdata['register_policy'] = Register::CLOSED;
1957 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1958 $serverdata['register_policy'] = Register::CLOSED;
1962 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1968 * Analyses the landing page of a given server for hints about type and system of that server
1970 * @param object $curlResult result of curl execution
1971 * @param array $serverdata array with server data
1973 * @return array server data
1975 private static function analyseRootBody($curlResult, array $serverdata): array
1977 if (empty($curlResult->getBody())) {
1981 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
1982 require __DIR__ . '/../../static/platforms.config.php';
1984 throw new HTTPException\InternalServerErrorException('Invalid platform file');
1987 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1989 $doc = new DOMDocument();
1990 @$doc->loadHTML($curlResult->getBody());
1991 $xpath = new DOMXPath($doc);
1994 // We can only detect honk via some HTML element on their page
1995 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1996 $serverdata['platform'] = 'honk';
1997 $serverdata['network'] = Protocol::ACTIVITYPUB;
2001 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2002 if (!empty($title)) {
2003 $serverdata['site_name'] = $title;
2006 $list = $xpath->query('//meta[@name]');
2008 foreach ($list as $node) {
2010 if ($node->attributes->length) {
2011 foreach ($node->attributes as $attribute) {
2012 $value = trim($attribute->value);
2013 if (empty($value)) {
2017 $attr[$attribute->name] = $value;
2020 if (empty($attr['name']) || empty($attr['content'])) {
2025 if ($attr['name'] == 'description') {
2026 $serverdata['info'] = $attr['content'];
2029 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2030 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2031 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2032 $platform = str_replace('/', ' ', $platform);
2033 $platform_parts = explode(' ', $platform);
2034 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2035 $platform = $platform_parts[0];
2036 $serverdata['version'] = $platform_parts[1];
2038 if (in_array($platform, array_values($dfrn_platforms))) {
2039 $serverdata['network'] = Protocol::DFRN;
2040 } elseif (in_array($platform, array_values($ap_platforms))) {
2041 $serverdata['network'] = Protocol::ACTIVITYPUB;
2042 } elseif (in_array($platform, array_values($zap_platforms))) {
2043 $serverdata['network'] = Protocol::ZOT;
2045 if (in_array($platform, array_values($platforms))) {
2046 $serverdata['platform'] = $platform;
2052 $list = $xpath->query('//meta[@property]');
2054 foreach ($list as $node) {
2056 if ($node->attributes->length) {
2057 foreach ($node->attributes as $attribute) {
2058 $value = trim($attribute->value);
2059 if (empty($value)) {
2063 $attr[$attribute->name] = $value;
2066 if (empty($attr['property']) || empty($attr['content'])) {
2071 if ($attr['property'] == 'og:site_name') {
2072 $serverdata['site_name'] = $attr['content'];
2075 if ($attr['property'] == 'og:description') {
2076 $serverdata['info'] = $attr['content'];
2079 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2080 if (in_array($attr['content'], array_keys($platforms))) {
2081 $serverdata['platform'] = $platforms[$attr['content']];
2085 if (in_array($attr['content'], array_keys($ap_platforms))) {
2086 $serverdata['network'] = Protocol::ACTIVITYPUB;
2087 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2088 $serverdata['network'] = Protocol::ZOT;
2093 $list = $xpath->query('//link[@rel="me"]');
2094 foreach ($list as $node) {
2095 foreach ($node->attributes as $attribute) {
2096 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2097 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2098 $serverdata['platform'] = 'microblog';
2099 $serverdata['network'] = Protocol::ACTIVITYPUB;
2105 if ($serverdata['platform'] != 'microblog') {
2106 $list = $xpath->query('//link[@rel="micropub"]');
2107 foreach ($list as $node) {
2108 foreach ($node->attributes as $attribute) {
2109 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2110 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2111 $serverdata['platform'] = 'microblog';
2112 $serverdata['network'] = Protocol::ACTIVITYPUB;
2119 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2120 $serverdata['detection-method'] = self::DETECT_BODY;
2127 * Analyses the header data of a given server for hints about type and system of that server
2129 * @param object $curlResult result of curl execution
2130 * @param array $serverdata array with server data
2132 * @return array server data
2134 private static function analyseRootHeader($curlResult, array $serverdata): array
2136 if ($curlResult->getHeader('server') == 'Mastodon') {
2137 $serverdata['platform'] = 'mastodon';
2138 $serverdata['network'] = Protocol::ACTIVITYPUB;
2139 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2140 $serverdata['platform'] = 'diaspora';
2141 $serverdata['network'] = Protocol::DIASPORA;
2142 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2143 } elseif ($curlResult->inHeader('x-friendica-version')) {
2144 $serverdata['platform'] = 'friendica';
2145 $serverdata['network'] = Protocol::DFRN;
2146 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2151 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2152 $serverdata['detection-method'] = self::DETECT_HEADER;
2159 * Update GServer entries
2161 public static function discover()
2163 // Update the server list
2164 self::discoverFederation();
2168 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2170 if ($requery_days == 0) {
2174 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2176 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2177 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2178 ['order' => ['RAND()']]);
2180 while ($gserver = DBA::fetch($gservers)) {
2181 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2182 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2184 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2185 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2187 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2188 self::update($fields, ['nurl' => $gserver['nurl']]);
2190 if (--$no_of_queries == 0) {
2195 DBA::close($gservers);
2199 * Discover federated servers
2201 private static function discoverFederation()
2203 $last = DI::keyValue()->get('poco_last_federation_discovery');
2206 $next = $last + (24 * 60 * 60);
2208 if ($next > time()) {
2213 // Discover federated servers
2214 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2215 foreach ($protocols as $protocol) {
2216 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2217 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2218 if (!empty($curlResult)) {
2219 $data = json_decode($curlResult, true);
2220 if (!empty($data['data']['nodes'])) {
2221 foreach ($data['data']['nodes'] as $server) {
2222 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2223 self::add('https://' . $server['host'], true);
2229 // Disvover Mastodon servers
2230 $accesstoken = DI::config()->get('system', 'instances_social_key');
2232 if (!empty($accesstoken)) {
2233 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2234 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2235 if ($curlResult->isSuccess()) {
2236 $servers = json_decode($curlResult->getBody(), true);
2238 if (!empty($servers['instances'])) {
2239 foreach ($servers['instances'] as $server) {
2240 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2247 DI::keyValue()->set('poco_last_federation_discovery', time());
2251 * Set the protocol for the given server
2253 * @param int $gsid Server id
2254 * @param int $protocol Protocol id
2258 public static function setProtocol(int $gsid, int $protocol)
2264 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2265 if (!DBA::isResult($gserver)) {
2269 $old = $gserver['protocol'];
2271 if (!is_null($old)) {
2273 The priority for the protocols is:
2275 2. DFRN via Diaspora
2281 // We don't need to change it when nothing is to be changed
2282 if ($old == $protocol) {
2286 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2287 if ($protocol == Post\DeliveryData::OSTATUS) {
2291 // If the server is marked as ActivityPub then we won't change it to anything different
2292 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2296 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2297 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2301 // Don't change it to Diaspora when it is a legacy DFRN server
2302 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2307 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2308 self::update(['protocol' => $protocol], ['id' => $gsid]);
2312 * Fetch the protocol of the given server
2314 * @param int $gsid Server id
2316 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2320 public static function getProtocol(int $gsid): ?int
2326 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2327 if (DBA::isResult($gserver)) {
2328 return $gserver['protocol'];
2335 * Update rows in the gserver table.
2336 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2338 * @param array $fields
2339 * @param array $condition
2345 public static function update(array $fields, array $condition): bool
2347 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2349 return DBA::update('gserver', $fields, $condition);
2353 * Insert a row into the gserver table.
2354 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2356 * @param array $fields
2357 * @param int $duplicate_mode What to do on a duplicated entry
2363 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2365 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2367 return DBA::insert('gserver', $fields, $duplicate_mode);