3 * @copyright Copyright (C) 2010-2023, 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 array is unreachable for a long time now
170 * @param integer $gsid
173 private static function isDefunct(array $gserver): bool
175 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
176 ($gserver['last_contact'] >= $gserver['created']) &&
177 ($gserver['last_contact'] < $gserver['last_failure']) &&
178 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
182 * Checks if the given server id is unreachable for a long time now
184 * @param integer $gsid
187 public static function isDefunctById(int $gsid): bool
189 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
190 if (empty($gserver)) {
193 if (strtotime($gserver['next_contact']) < time()) {
194 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
196 return self::isDefunct($gserver);
201 * Checks if the given server id is reachable
203 * @param integer $gsid
206 public static function isReachableById(int $gsid): bool
208 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
209 if (empty($gserver)) {
212 if (strtotime($gserver['next_contact']) < time()) {
213 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
215 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
220 * Checks if the given server is reachable
222 * @param array $contact Contact that should be checked
224 * @return boolean 'true' if server seems vital
226 public static function reachable(array $contact): bool
228 if (!empty($contact['gsid'])) {
229 $gsid = $contact['gsid'];
230 } elseif (!empty($contact['baseurl'])) {
231 $server = $contact['baseurl'];
232 } elseif ($contact['network'] == Protocol::DIASPORA) {
233 $parts = parse_url($contact['url']);
234 unset($parts['path']);
235 $server = (string)Uri::fromParts($parts);
241 $condition = ['id' => $gsid];
243 $condition = ['nurl' => Strings::normaliseLink($server)];
246 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
247 if (empty($gserver)) {
250 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
251 $server = $gserver['url'];
254 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
255 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $server, false);
262 * Calculate the next update day
264 * @param bool $success
265 * @param string $created
266 * @param string $last_contact
267 * @param bool $undetected
273 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
275 // On successful contact process check again next week when it is a detected system.
276 // When we haven't detected the system, it could be a static website or a really old system.
278 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
281 $now = strtotime(DateTimeFormat::utcNow());
283 if ($created > $last_contact) {
284 $contact_time = strtotime($created);
286 $contact_time = strtotime($last_contact);
289 // If the last contact was less than 6 hours before then try again in 6 hours
290 if (($now - $contact_time) < (60 * 60 * 6)) {
291 return DateTimeFormat::utc('now +6 hour');
294 // If the last contact was less than 12 hours before then try again in 12 hours
295 if (($now - $contact_time) < (60 * 60 * 12)) {
296 return DateTimeFormat::utc('now +12 hour');
299 // If the last contact was less than 24 hours before then try tomorrow again
300 if (($now - $contact_time) < (60 * 60 * 24)) {
301 return DateTimeFormat::utc('now +1 day');
304 // If the last contact was less than a week before then try again in a week
305 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
306 return DateTimeFormat::utc('now +1 week');
309 // If the last contact was less than two weeks before then try again in two week
310 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
311 return DateTimeFormat::utc('now +2 week');
314 // If the last contact was less than a month before then try again in a month
315 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
316 return DateTimeFormat::utc('now +1 month');
319 // The system hadn't been successul contacted for more than a month, so try again in three months
320 return DateTimeFormat::utc('now +3 month');
324 * Checks the state of the given server.
326 * @param string $server_url URL of the given server
327 * @param string $network Network value that is used, when detection failed
328 * @param boolean $force Force an update.
329 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
331 * @return boolean 'true' if server seems vital
333 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
335 $server_url = self::cleanURL($server_url);
336 if ($server_url == '') {
340 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
341 if (DBA::isResult($gserver)) {
342 if ($gserver['created'] <= DBA::NULL_DATETIME) {
343 $fields = ['created' => DateTimeFormat::utcNow()];
344 $condition = ['nurl' => Strings::normaliseLink($server_url)];
345 self::update($fields, $condition);
348 if (!$force && (strtotime($gserver['next_contact']) > time())) {
349 Logger::info('No update needed', ['server' => $server_url]);
350 return (!$gserver['failed']);
352 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
354 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
357 return self::detect($server_url, $network, $only_nodeinfo);
361 * Reset failed server status by gserver id
364 * @param string $network
366 public static function setReachableById(int $gsid, string $network)
368 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
369 if (DBA::isResult($gserver) && $gserver['failed']) {
370 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow()];
371 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
372 $fields['network'] = $network;
374 self::update($fields, ['id' => $gsid]);
375 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
377 if (strtotime($gserver['next_contact']) < time()) {
378 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
384 * Set failed server status by gserver id
388 public static function setFailureById(int $gsid)
390 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
391 if (DBA::isResult($gserver) && !$gserver['failed']) {
392 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
393 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
395 if (strtotime($gserver['next_contact']) < time()) {
396 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
402 * Set failed server status
406 public static function setFailureByUrl(string $url)
408 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
409 if (DBA::isResult($gserver)) {
410 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
411 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
412 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
413 ['nurl' => Strings::normaliseLink($url)]);
414 Logger::info('Set failed status for existing server', ['url' => $url]);
415 if (self::isDefunct($gserver)) {
416 self::archiveContacts($gserver['id']);
420 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
421 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
422 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
423 Logger::info('Set failed status for new server', ['url' => $url]);
427 * Archive server related contacts and inboxes
429 * @param integer $gsid
432 private static function archiveContacts(int $gsid)
434 Contact::update(['archive' => true], ['gsid' => $gsid]);
435 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
439 * Remove unwanted content from the given URL
441 * @param string $dirtyUrl
443 * @return string cleaned URL
446 public static function cleanURL(string $dirtyUrl): string
449 $url = str_replace('/index.php', '', trim($dirtyUrl, '/'));
450 return (string)(new Uri($url))->withUserInfo('')->withQuery('')->withFragment('');
451 } catch (\Throwable $e) {
452 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl, 'url' => $url]);
458 * Detect server data (type, protocol, version number, ...)
459 * The detected data is then updated or inserted in the gserver table.
461 * @param string $url URL of the given server
462 * @param string $network Network value that is used, when detection failed
463 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
465 * @return boolean 'true' if server could be detected
467 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
469 Logger::info('Detect server type', ['server' => $url]);
471 $original_url = $url;
473 // Remove URL content that is not supposed to exist for a server url
474 $url = rtrim(self::cleanURL($url), '/');
476 Logger::notice('Empty URL.');
480 // If the URL missmatches, then we mark the old entry as failure
481 if (!Strings::compareLink($url, $original_url)) {
482 self::setFailureByUrl($original_url);
483 if (!self::getID($url, true)) {
484 self::detect($url, $network, $only_nodeinfo);
489 $valid_url = Network::isUrlValid($url);
491 self::setFailureByUrl($url);
494 $valid_url = rtrim($valid_url, '/');
497 if (!Strings::compareLink($url, $valid_url)) {
498 // We only follow redirects when the path stays the same or the target url has no path.
499 // Some systems have got redirects on their landing page to a single account page. This check handles it.
500 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))) ||
501 (((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)))) {
502 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
503 self::setFailureByUrl($url);
504 if (!self::getID($valid_url, true)) {
505 self::detect($valid_url, $network, $only_nodeinfo);
510 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)) &&
511 (parse_url($url, PHP_URL_PATH) == '')) {
512 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
513 $parts = parse_url($valid_url);
514 unset($parts['path']);
515 $valid_url = (string)Uri::fromParts($parts);
517 self::setFailureByUrl($url);
518 if (!self::getID($valid_url, true)) {
519 self::detect($valid_url, $network, $only_nodeinfo);
523 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
526 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
527 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
528 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
532 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
534 // When a nodeinfo is present, we don't need to dig further
535 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
536 if ($curlResult->isTimeout()) {
537 self::setFailureByUrl($url);
541 $serverdata = self::parseNodeinfo210($curlResult);
542 if (empty($serverdata)) {
543 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
544 $serverdata = self::fetchNodeinfo($url, $curlResult);
547 if ($only_nodeinfo && empty($serverdata)) {
548 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
549 self::setFailureByUrl($url);
551 } elseif (empty($serverdata)) {
552 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
555 // When there is no Nodeinfo, then use some protocol specific endpoints
556 if ($serverdata['network'] == Protocol::PHANTOM) {
558 // Fetch the landing page, possibly it reveals some data
559 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
560 $curlResult = DI::httpClient()->get($url, $accept);
561 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
562 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
563 $html_fetched = true;
565 $html_fetched = false;
568 if ($curlResult->isSuccess()) {
569 $json = json_decode($curlResult->getBody(), true);
570 if (!empty($json) && is_array($json)) {
571 $data = self::fetchDataFromSystemActor($json, $serverdata);
572 $serverdata = $data['server'];
573 $systemactor = $data['actor'];
574 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
575 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
577 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
578 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
581 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
582 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
583 $serverdata = self::analyseRootBody($curlResult, $serverdata);
587 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
588 self::setFailureByUrl($url);
592 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
593 $serverdata = self::detectMastodonAlikes($url, $serverdata);
597 // All following checks are done for systems that always have got a "host-meta" endpoint.
598 // With this check we don't have to waste time and ressources for dead systems.
599 // Also this hopefully prevents us from receiving abuse messages.
600 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
601 $validHostMeta = self::validHostMeta($url);
603 $validHostMeta = false;
606 if ($validHostMeta) {
607 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
608 $serverdata['detection-method'] = self::DETECT_HOST_META;
611 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
612 $serverdata = self::detectFriendica($url, $serverdata);
615 // The following systems have to be installed in the root directory.
617 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
618 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
619 $serverdata = self::fetchSiteinfo($url, $serverdata);
622 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
623 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
624 $serverdata = self::detectHubzilla($url, $serverdata);
627 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
628 $serverdata = self::detectPeertube($url, $serverdata);
631 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
632 $serverdata = self::detectGNUSocial($url, $serverdata);
635 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
636 $serverdata = self::detectFriendica($url, $serverdata);
639 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
640 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
643 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
644 // Since this endpoint is only rarely used, we query it at a later time
645 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
646 $serverdata = self::fetchStatistics($url, $serverdata);
650 // When we hadn't been able to detect the network type, we use the hint from the parameter
651 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
652 $serverdata['network'] = $network;
655 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
656 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
657 self::setFailureByUrl($url);
661 $serverdata['url'] = $url;
662 $serverdata['nurl'] = Strings::normaliseLink($url);
664 // We have to prevent an endless loop here.
665 // When a server is new, then there is no gserver entry yet.
666 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
667 // and this can call this function here as well.
668 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
669 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
670 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
673 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
674 self::setFailureByUrl($url);
678 // Detect the directory type
679 $serverdata['directory-type'] = self::DT_NONE;
681 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
682 $serverdata = self::checkMastodonDirectory($url, $serverdata);
684 if ($serverdata['directory-type'] == self::DT_NONE) {
685 $serverdata = self::checkPoCo($url, $serverdata);
689 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
690 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
693 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
695 // Numbers above a reasonable value (10 millions) are ignored
696 if ($serverdata['registered-users'] > 10000000) {
697 $serverdata['registered-users'] = 0;
700 // On an active server there has to be at least a single user
701 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
702 $serverdata['registered-users'] = 1;
703 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
704 $serverdata['registered-users'] = 0;
707 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
709 $serverdata['last_contact'] = DateTimeFormat::utcNow();
710 $serverdata['failed'] = false;
712 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
713 if (!DBA::isResult($gserver)) {
714 $serverdata['created'] = DateTimeFormat::utcNow();
715 $ret = self::insert($serverdata);
716 $id = DBA::lastInsertId();
718 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
719 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
720 if (DBA::isResult($gserver)) {
721 $id = $gserver['id'];
725 // Count the number of known contacts from this server
726 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
727 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
728 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
729 $max_users = max($apcontacts, $contacts);
730 if ($max_users > $serverdata['registered-users']) {
731 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
732 self::update(['registered-users' => $max_users], ['id' => $id]);
735 if (empty($serverdata['active-month-users'])) {
736 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
738 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
739 self::update(['active-month-users' => $contacts], ['id' => $id]);
743 if (empty($serverdata['active-halfyear-users'])) {
744 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
746 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
747 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
752 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
753 self::discoverRelay($url);
756 if (!empty($systemactor)) {
757 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
758 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
765 * Fetch relay data from a given server url
767 * @param string $server_url address of the server
771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
773 private static function discoverRelay(string $server_url)
775 Logger::info('Discover relay data', ['server' => $server_url]);
777 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
778 if (!$curlResult->isSuccess()) {
782 $data = json_decode($curlResult->getBody(), true);
783 if (!is_array($data)) {
787 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
788 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
790 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
792 $data['subscribe'] = false;
796 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
797 if (!DBA::isResult($gserver)) {
801 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
802 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
803 self::update($fields, ['id' => $gserver['id']]);
806 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
808 if ($data['scope'] == 'tags') {
811 foreach ($data['tags'] as $tag) {
812 $tag = mb_strtolower($tag);
813 if (strlen($tag) < 100) {
818 foreach ($tags as $tag) {
819 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
823 // Create or update the relay contact
825 if (isset($data['protocols'])) {
826 if (isset($data['protocols']['diaspora'])) {
827 $fields['network'] = Protocol::DIASPORA;
829 if (isset($data['protocols']['diaspora']['receive'])) {
830 $fields['batch'] = $data['protocols']['diaspora']['receive'];
831 } elseif (is_string($data['protocols']['diaspora'])) {
832 $fields['batch'] = $data['protocols']['diaspora'];
836 if (isset($data['protocols']['dfrn'])) {
837 $fields['network'] = Protocol::DFRN;
839 if (isset($data['protocols']['dfrn']['receive'])) {
840 $fields['batch'] = $data['protocols']['dfrn']['receive'];
841 } elseif (is_string($data['protocols']['dfrn'])) {
842 $fields['batch'] = $data['protocols']['dfrn'];
846 if (isset($data['protocols']['activitypub'])) {
847 $fields['network'] = Protocol::ACTIVITYPUB;
849 if (!empty($data['protocols']['activitypub']['actor'])) {
850 $fields['url'] = $data['protocols']['activitypub']['actor'];
852 if (!empty($data['protocols']['activitypub']['receive'])) {
853 $fields['batch'] = $data['protocols']['activitypub']['receive'];
858 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
860 Relay::updateContact($gserver, $fields);
864 * Fetch server data from '/statistics.json' on the given server
866 * @param string $url URL of the given server
868 * @return array server data
870 private static function fetchStatistics(string $url, array $serverdata): array
872 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
873 if (!$curlResult->isSuccess()) {
877 $data = json_decode($curlResult->getBody(), true);
882 // Some AP enabled systems return activity data that we don't expect here.
883 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
888 $old_serverdata = $serverdata;
890 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
892 if (!empty($data['version'])) {
894 $serverdata['version'] = $data['version'];
895 // Version numbers on statistics.json are presented with additional info, e.g.:
896 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
897 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
900 if (!empty($data['name'])) {
902 $serverdata['site_name'] = $data['name'];
905 if (!empty($data['network'])) {
907 $serverdata['platform'] = strtolower($data['network']);
909 if ($serverdata['platform'] == 'diaspora') {
910 $serverdata['network'] = Protocol::DIASPORA;
911 } elseif ($serverdata['platform'] == 'friendica') {
912 $serverdata['network'] = Protocol::DFRN;
913 } elseif ($serverdata['platform'] == 'hubzilla') {
914 $serverdata['network'] = Protocol::ZOT;
915 } elseif ($serverdata['platform'] == 'redmatrix') {
916 $serverdata['network'] = Protocol::ZOT;
920 if (!empty($data['total_users'])) {
922 $serverdata['registered-users'] = max($data['total_users'], 1);
925 if (!empty($data['active_users_monthly'])) {
927 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
930 if (!empty($data['active_users_halfyear'])) {
932 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
935 if (!empty($data['local_posts'])) {
937 $serverdata['local-posts'] = max($data['local_posts'], 0);
940 if (!empty($data['registrations_open'])) {
941 $serverdata['register_policy'] = Register::OPEN;
943 $serverdata['register_policy'] = Register::CLOSED;
947 return $old_serverdata;
954 * Detect server type by using the nodeinfo data
956 * @param string $url address of the server
957 * @param ICanHandleHttpResponses $httpResult
959 * @return array Server data
961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
965 if (!$httpResult->isSuccess()) {
969 $nodeinfo = json_decode($httpResult->getBody(), true);
971 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
978 foreach ($nodeinfo['links'] as $link) {
979 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
980 Logger::info('Invalid nodeinfo format', ['url' => $url]);
983 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
984 $nodeinfo1_url = $link['href'];
985 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
986 $nodeinfo2_url = $link['href'];
990 if ($nodeinfo1_url . $nodeinfo2_url == '') {
996 if (!empty($nodeinfo2_url)) {
997 $server = self::parseNodeinfo2($nodeinfo2_url);
1000 if (empty($server) && !empty($nodeinfo1_url)) {
1001 $server = self::parseNodeinfo1($nodeinfo1_url);
1010 * @param string $nodeinfo_url address of the nodeinfo path
1012 * @return array Server data
1014 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016 private static function parseNodeinfo1(string $nodeinfo_url): array
1018 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1019 if (!$curlResult->isSuccess()) {
1023 $nodeinfo = json_decode($curlResult->getBody(), true);
1025 if (!is_array($nodeinfo)) {
1029 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1030 'register_policy' => Register::CLOSED];
1032 if (!empty($nodeinfo['openRegistrations'])) {
1033 $server['register_policy'] = Register::OPEN;
1036 if (is_array($nodeinfo['software'])) {
1037 if (!empty($nodeinfo['software']['name'])) {
1038 $server['platform'] = strtolower($nodeinfo['software']['name']);
1041 if (!empty($nodeinfo['software']['version'])) {
1042 $server['version'] = $nodeinfo['software']['version'];
1043 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1044 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1045 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1049 if (!empty($nodeinfo['metadata']['nodeName'])) {
1050 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1053 if (!empty($nodeinfo['usage']['users']['total'])) {
1054 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1057 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1058 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1061 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1062 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1065 if (!empty($nodeinfo['usage']['localPosts'])) {
1066 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1069 if (!empty($nodeinfo['usage']['localComments'])) {
1070 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1073 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1075 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1076 $protocols[$protocol] = true;
1079 if (!empty($protocols['friendica'])) {
1080 $server['network'] = Protocol::DFRN;
1081 } elseif (!empty($protocols['activitypub'])) {
1082 $server['network'] = Protocol::ACTIVITYPUB;
1083 } elseif (!empty($protocols['diaspora'])) {
1084 $server['network'] = Protocol::DIASPORA;
1085 } elseif (!empty($protocols['ostatus'])) {
1086 $server['network'] = Protocol::OSTATUS;
1087 } elseif (!empty($protocols['gnusocial'])) {
1088 $server['network'] = Protocol::OSTATUS;
1089 } elseif (!empty($protocols['zot'])) {
1090 $server['network'] = Protocol::ZOT;
1094 if (empty($server)) {
1098 if (empty($server['network'])) {
1099 $server['network'] = Protocol::PHANTOM;
1108 * @see https://git.feneas.org/jaywink/nodeinfo2
1110 * @param string $nodeinfo_url address of the nodeinfo path
1112 * @return array Server data
1114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1116 private static function parseNodeinfo2(string $nodeinfo_url): array
1118 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1119 if (!$curlResult->isSuccess()) {
1123 $nodeinfo = json_decode($curlResult->getBody(), true);
1124 if (!is_array($nodeinfo)) {
1129 'detection-method' => self::DETECT_NODEINFO_2,
1130 'register_policy' => Register::CLOSED,
1131 'platform' => 'unknown',
1134 if (!empty($nodeinfo['openRegistrations'])) {
1135 $server['register_policy'] = Register::OPEN;
1138 if (!empty($nodeinfo['software'])) {
1139 if (isset($nodeinfo['software']['name'])) {
1140 $server['platform'] = strtolower($nodeinfo['software']['name']);
1143 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1144 $server['version'] = $nodeinfo['software']['version'];
1145 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1146 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1147 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1149 // qoto advertises itself as Mastodon
1150 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1151 $server['platform'] = 'qoto';
1156 if (!empty($nodeinfo['metadata']['nodeName'])) {
1157 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1160 if (!empty($nodeinfo['usage']['users']['total'])) {
1161 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1164 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1165 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1168 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1169 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1172 if (!empty($nodeinfo['usage']['localPosts'])) {
1173 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1176 if (!empty($nodeinfo['usage']['localComments'])) {
1177 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1180 if (!empty($nodeinfo['protocols'])) {
1182 foreach ($nodeinfo['protocols'] as $protocol) {
1183 if (is_string($protocol)) {
1184 $protocols[$protocol] = true;
1188 if (!empty($protocols['dfrn'])) {
1189 $server['network'] = Protocol::DFRN;
1190 } elseif (!empty($protocols['activitypub'])) {
1191 $server['network'] = Protocol::ACTIVITYPUB;
1192 } elseif (!empty($protocols['diaspora'])) {
1193 $server['network'] = Protocol::DIASPORA;
1194 } elseif (!empty($protocols['ostatus'])) {
1195 $server['network'] = Protocol::OSTATUS;
1196 } elseif (!empty($protocols['gnusocial'])) {
1197 $server['network'] = Protocol::OSTATUS;
1198 } elseif (!empty($protocols['zot'])) {
1199 $server['network'] = Protocol::ZOT;
1203 if (empty($server)) {
1207 if (empty($server['network'])) {
1208 $server['network'] = Protocol::PHANTOM;
1215 * Parses NodeInfo2 protocol 1.0
1217 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1219 * @param string $nodeinfo_url address of the nodeinfo path
1221 * @return array Server data
1223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1225 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1227 if (!$httpResult->isSuccess()) {
1231 $nodeinfo = json_decode($httpResult->getBody(), true);
1233 if (!is_array($nodeinfo)) {
1237 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1238 'register_policy' => Register::CLOSED];
1240 if (!empty($nodeinfo['openRegistrations'])) {
1241 $server['register_policy'] = Register::OPEN;
1244 if (!empty($nodeinfo['server'])) {
1245 if (!empty($nodeinfo['server']['software'])) {
1246 $server['platform'] = strtolower($nodeinfo['server']['software']);
1249 if (!empty($nodeinfo['server']['version'])) {
1250 $server['version'] = $nodeinfo['server']['version'];
1251 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1252 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1253 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1256 if (!empty($nodeinfo['server']['name'])) {
1257 $server['site_name'] = $nodeinfo['server']['name'];
1261 if (!empty($nodeinfo['usage']['users']['total'])) {
1262 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1265 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1266 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1269 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1270 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1273 if (!empty($nodeinfo['usage']['localPosts'])) {
1274 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1277 if (!empty($nodeinfo['usage']['localComments'])) {
1278 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1281 if (!empty($nodeinfo['protocols'])) {
1283 foreach ($nodeinfo['protocols'] as $protocol) {
1284 if (is_string($protocol)) {
1285 $protocols[$protocol] = true;
1289 if (!empty($protocols['dfrn'])) {
1290 $server['network'] = Protocol::DFRN;
1291 } elseif (!empty($protocols['activitypub'])) {
1292 $server['network'] = Protocol::ACTIVITYPUB;
1293 } elseif (!empty($protocols['diaspora'])) {
1294 $server['network'] = Protocol::DIASPORA;
1295 } elseif (!empty($protocols['ostatus'])) {
1296 $server['network'] = Protocol::OSTATUS;
1297 } elseif (!empty($protocols['gnusocial'])) {
1298 $server['network'] = Protocol::OSTATUS;
1299 } elseif (!empty($protocols['zot'])) {
1300 $server['network'] = Protocol::ZOT;
1304 if (empty($server) || empty($server['platform'])) {
1308 if (empty($server['network'])) {
1309 $server['network'] = Protocol::PHANTOM;
1316 * Fetch server information from a 'siteinfo.json' file on the given server
1318 * @param string $url URL of the given server
1319 * @param array $serverdata array with server data
1321 * @return array server data
1323 private static function fetchSiteinfo(string $url, array $serverdata): array
1325 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1326 if (!$curlResult->isSuccess()) {
1330 $data = json_decode($curlResult->getBody(), true);
1335 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1336 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1339 if (!empty($data['url'])) {
1340 $serverdata['platform'] = strtolower($data['platform']);
1341 $serverdata['version'] = $data['version'] ?? 'N/A';
1344 if (!empty($data['plugins'])) {
1345 if (in_array('pubcrawl', $data['plugins'])) {
1346 $serverdata['network'] = Protocol::ACTIVITYPUB;
1347 } elseif (in_array('diaspora', $data['plugins'])) {
1348 $serverdata['network'] = Protocol::DIASPORA;
1349 } elseif (in_array('gnusoc', $data['plugins'])) {
1350 $serverdata['network'] = Protocol::OSTATUS;
1352 $serverdata['network'] = Protocol::ZOT;
1356 if (!empty($data['site_name'])) {
1357 $serverdata['site_name'] = $data['site_name'];
1360 if (!empty($data['channels_total'])) {
1361 $serverdata['registered-users'] = max($data['channels_total'], 1);
1364 if (!empty($data['channels_active_monthly'])) {
1365 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1368 if (!empty($data['channels_active_halfyear'])) {
1369 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1372 if (!empty($data['local_posts'])) {
1373 $serverdata['local-posts'] = max($data['local_posts'], 0);
1376 if (!empty($data['local_comments'])) {
1377 $serverdata['local-comments'] = max($data['local_comments'], 0);
1380 if (!empty($data['register_policy'])) {
1381 switch ($data['register_policy']) {
1382 case 'REGISTER_OPEN':
1383 $serverdata['register_policy'] = Register::OPEN;
1386 case 'REGISTER_APPROVE':
1387 $serverdata['register_policy'] = Register::APPROVE;
1390 case 'REGISTER_CLOSED':
1392 $serverdata['register_policy'] = Register::CLOSED;
1401 * Fetches server data via an ActivityPub account with url of that server
1403 * @param string $url URL of the given server
1404 * @param array $serverdata array with server data
1406 * @return array server data
1410 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1413 return ['server' => $serverdata, 'actor' => ''];
1416 $actor = JsonLD::compact($data, false);
1417 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1418 $serverdata['network'] = Protocol::ACTIVITYPUB;
1419 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1420 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1421 if (!empty($actor['as:generator'])) {
1422 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1423 $serverdata['platform'] = strtolower(array_shift($generator));
1424 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1426 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1428 return ['server' => $serverdata, 'actor' => $actor['@id']];
1429 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1430 // By now only Ktistec seems to provide collections this way
1431 $serverdata['platform'] = 'ktistec';
1432 $serverdata['network'] = Protocol::ACTIVITYPUB;
1433 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1435 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1436 if (!empty($actors) && !empty($actors[0]['@id'])) {
1437 $actor_url = $actor['@id'] . $actors[0]['@id'];
1442 return ['server' => $serverdata, 'actor' => $actor_url];
1444 return ['server' => $serverdata, 'actor' => ''];
1448 * Checks if the server contains a valid host meta file
1450 * @param string $url URL of the given server
1452 * @return boolean 'true' if the server seems to be vital
1454 private static function validHostMeta(string $url): bool
1456 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1457 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1458 if (!$curlResult->isSuccess()) {
1462 $xrd = XML::parseString($curlResult->getBody(), true);
1463 if (!is_object($xrd)) {
1467 $elements = XML::elementToArray($xrd);
1468 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1473 foreach ($elements['xrd']['link'] as $link) {
1474 // When there is more than a single "link" element, the array looks slightly different
1475 if (!empty($link['@attributes'])) {
1476 $link = $link['@attributes'];
1479 if (empty($link['rel']) || empty($link['template'])) {
1483 if ($link['rel'] == 'lrdd') {
1484 // When the webfinger host is the same like the system host, it should be ok.
1485 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1493 * Detect the network of the given server via their known contacts
1495 * @param string $url URL of the given server
1496 * @param array $serverdata array with server data
1498 * @return array server data
1500 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1504 $nurl = Strings::normaliseLink($url);
1506 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1507 while ($apcontact = DBA::fetch($apcontacts)) {
1508 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1510 DBA::close($apcontacts);
1512 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1513 while ($pcontact = DBA::fetch($pcontacts)) {
1514 $contacts[$pcontact['nurl']] = $pcontact['url'];
1516 DBA::close($pcontacts);
1518 if (empty($contacts)) {
1523 foreach ($contacts as $contact) {
1524 // Endlosschleife verhindern wegen gsid!
1525 $data = Probe::uri($contact);
1526 if (in_array($data['network'], Protocol::FEDERATED)) {
1527 $serverdata['network'] = $data['network'];
1529 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1530 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1533 } elseif ((time() - $time) > 10) {
1534 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1543 * Checks if the given server does have a '/poco' endpoint.
1544 * This is used for the 'PortableContact' functionality,
1545 * which is used by both Friendica and Hubzilla.
1547 * @param string $url URL of the given server
1548 * @param array $serverdata array with server data
1550 * @return array server data
1552 private static function checkPoCo(string $url, array $serverdata): array
1554 $serverdata['poco'] = '';
1556 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1557 if (!$curlResult->isSuccess()) {
1561 $data = json_decode($curlResult->getBody(), true);
1566 if (!empty($data['totalResults'])) {
1567 $registeredUsers = $serverdata['registered-users'] ?? 0;
1568 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1569 $serverdata['directory-type'] = self::DT_POCO;
1570 $serverdata['poco'] = $url . '/poco';
1577 * Checks if the given server does have a Mastodon style directory endpoint.
1579 * @param string $url URL of the given server
1580 * @param array $serverdata array with server data
1582 * @return array server data
1584 public static function checkMastodonDirectory(string $url, array $serverdata): array
1586 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1587 if (!$curlResult->isSuccess()) {
1591 $data = json_decode($curlResult->getBody(), true);
1596 if (count($data) == 1) {
1597 $serverdata['directory-type'] = self::DT_MASTODON;
1604 * Detects Peertube via their known endpoint
1606 * @param string $url URL of the given server
1607 * @param array $serverdata array with server data
1609 * @return array server data
1611 private static function detectPeertube(string $url, array $serverdata): array
1613 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1614 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1618 $data = json_decode($curlResult->getBody(), true);
1623 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1624 $serverdata['platform'] = 'peertube';
1625 $serverdata['version'] = $data['serverVersion'];
1626 $serverdata['network'] = Protocol::ACTIVITYPUB;
1628 if (!empty($data['instance']['name'])) {
1629 $serverdata['site_name'] = $data['instance']['name'];
1632 if (!empty($data['instance']['shortDescription'])) {
1633 $serverdata['info'] = $data['instance']['shortDescription'];
1636 if (!empty($data['signup'])) {
1637 if (!empty($data['signup']['allowed'])) {
1638 $serverdata['register_policy'] = Register::OPEN;
1642 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1643 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1651 * Detects the version number of a given server when it was a NextCloud installation
1653 * @param string $url URL of the given server
1654 * @param array $serverdata array with server data
1655 * @param bool $validHostMeta
1657 * @return array server data
1659 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1661 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1662 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1666 $data = json_decode($curlResult->getBody(), true);
1671 if (!empty($data['version'])) {
1672 $serverdata['platform'] = 'nextcloud';
1673 $serverdata['version'] = $data['version'];
1675 if ($validHostMeta) {
1676 $serverdata['network'] = Protocol::ACTIVITYPUB;
1679 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1680 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1688 * Fetches weekly usage data
1690 * @param string $url URL of the given server
1691 * @param array $serverdata array with server data
1693 * @return array server data
1695 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1697 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1698 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1702 $data = json_decode($curlResult->getBody(), true);
1708 foreach ($data as $week) {
1709 // Use only data from a full week
1710 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1714 // Most likely the data is sorted correctly. But we better are safe than sorry
1715 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1716 $current_week = $week;
1720 if (!empty($current_week['logins'])) {
1721 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1728 * Detects data from a given server url if it was a mastodon alike system
1730 * @param string $url URL of the given server
1731 * @param array $serverdata array with server data
1733 * @return array server data
1735 private static function detectMastodonAlikes(string $url, array $serverdata): array
1737 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1738 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1742 $data = json_decode($curlResult->getBody(), true);
1749 if (!empty($data['version'])) {
1750 $serverdata['platform'] = 'mastodon';
1751 $serverdata['version'] = $data['version'] ?? '';
1752 $serverdata['network'] = Protocol::ACTIVITYPUB;
1756 if (!empty($data['title'])) {
1757 $serverdata['site_name'] = $data['title'];
1760 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1761 $serverdata['platform'] = 'mastodon';
1762 $serverdata['network'] = Protocol::ACTIVITYPUB;
1766 if (!empty($data['description'])) {
1767 $serverdata['info'] = trim($data['description']);
1770 if (!empty($data['stats']['user_count'])) {
1771 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1774 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1775 $serverdata['platform'] = strtolower($matches[1]);
1776 $serverdata['version'] = $matches[2];
1780 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1781 $serverdata['platform'] = 'pleroma';
1782 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1786 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1787 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1788 $serverdata['platform'] = 'pleroma';
1792 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1793 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1800 * Detects data from typical Hubzilla endpoints
1802 * @param string $url URL of the given server
1803 * @param array $serverdata array with server data
1805 * @return array server data
1807 private static function detectHubzilla(string $url, array $serverdata): array
1809 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1810 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1814 $data = json_decode($curlResult->getBody(), true);
1815 if (empty($data) || empty($data['site'])) {
1819 if (!empty($data['site']['name'])) {
1820 $serverdata['site_name'] = $data['site']['name'];
1823 if (!empty($data['site']['platform'])) {
1824 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1825 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1826 $serverdata['network'] = Protocol::ZOT;
1829 if (!empty($data['site']['hubzilla'])) {
1830 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1831 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1832 $serverdata['network'] = Protocol::ZOT;
1835 if (!empty($data['site']['redmatrix'])) {
1836 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1837 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1838 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1839 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1842 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1843 $serverdata['network'] = Protocol::ZOT;
1847 $inviteonly = false;
1850 if (!empty($data['site']['closed'])) {
1851 $closed = self::toBoolean($data['site']['closed']);
1854 if (!empty($data['site']['private'])) {
1855 $private = self::toBoolean($data['site']['private']);
1858 if (!empty($data['site']['inviteonly'])) {
1859 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1862 if (!$closed && !$private and $inviteonly) {
1863 $serverdata['register_policy'] = Register::APPROVE;
1864 } elseif (!$closed && !$private) {
1865 $serverdata['register_policy'] = Register::OPEN;
1867 $serverdata['register_policy'] = Register::CLOSED;
1870 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1871 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1878 * Converts input value to a boolean value
1880 * @param string|integer $val
1884 private static function toBoolean($val): bool
1886 if (($val == 'true') || ($val == 1)) {
1888 } elseif (($val == 'false') || ($val == 0)) {
1896 * Detect if the URL belongs to a GNU Social server
1898 * @param string $url URL of the given server
1899 * @param array $serverdata array with server data
1901 * @return array server data
1903 private static function detectGNUSocial(string $url, array $serverdata): array
1905 // Test for GNU Social
1906 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1907 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1908 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1909 $serverdata['platform'] = 'gnusocial';
1910 // Remove junk that some GNU Social servers return
1911 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1912 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1913 $serverdata['version'] = trim($serverdata['version'], '"');
1914 $serverdata['network'] = Protocol::OSTATUS;
1916 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1917 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1923 // Test for Statusnet
1924 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1925 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1926 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1928 // Remove junk that some GNU Social servers return
1929 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1930 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1931 $serverdata['version'] = trim($serverdata['version'], '"');
1933 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1934 $serverdata['platform'] = 'pleroma';
1935 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1936 $serverdata['network'] = Protocol::ACTIVITYPUB;
1938 $serverdata['platform'] = 'statusnet';
1939 $serverdata['network'] = Protocol::OSTATUS;
1942 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1943 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1951 * Detect if the URL belongs to a Friendica server
1953 * @param string $url URL of the given server
1954 * @param array $serverdata array with server data
1956 * @return array server data
1958 private static function detectFriendica(string $url, array $serverdata): array
1960 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1961 // Because of this me must not use ACCEPT_JSON here.
1962 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1963 if (!$curlResult->isSuccess()) {
1964 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1966 $platform = 'Friendika';
1969 $platform = 'Friendica';
1972 if (!$curlResult->isSuccess()) {
1976 $data = json_decode($curlResult->getBody(), true);
1977 if (empty($data) || empty($data['version'])) {
1981 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1982 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1985 $serverdata['network'] = Protocol::DFRN;
1986 $serverdata['version'] = $data['version'];
1988 if (!empty($data['no_scrape_url'])) {
1989 $serverdata['noscrape'] = $data['no_scrape_url'];
1992 if (!empty($data['site_name'])) {
1993 $serverdata['site_name'] = $data['site_name'];
1996 if (!empty($data['info'])) {
1997 $serverdata['info'] = trim($data['info']);
2000 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2001 switch ($register_policy) {
2002 case 'REGISTER_OPEN':
2003 $serverdata['register_policy'] = Register::OPEN;
2006 case 'REGISTER_APPROVE':
2007 $serverdata['register_policy'] = Register::APPROVE;
2010 case 'REGISTER_CLOSED':
2011 case 'REGISTER_INVITATION':
2012 $serverdata['register_policy'] = Register::CLOSED;
2015 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2016 $serverdata['register_policy'] = Register::CLOSED;
2020 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2026 * Analyses the landing page of a given server for hints about type and system of that server
2028 * @param object $curlResult result of curl execution
2029 * @param array $serverdata array with server data
2031 * @return array server data
2033 private static function analyseRootBody($curlResult, array $serverdata): array
2035 if (empty($curlResult->getBody())) {
2039 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2040 require __DIR__ . '/../../static/platforms.config.php';
2042 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2045 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2047 $doc = new DOMDocument();
2048 @$doc->loadHTML($curlResult->getBody());
2049 $xpath = new DOMXPath($doc);
2052 // We can only detect honk via some HTML element on their page
2053 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2054 $serverdata['platform'] = 'honk';
2055 $serverdata['network'] = Protocol::ACTIVITYPUB;
2059 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2060 if (!empty($title)) {
2061 $serverdata['site_name'] = $title;
2064 $list = $xpath->query('//meta[@name]');
2066 foreach ($list as $node) {
2068 if ($node->attributes->length) {
2069 foreach ($node->attributes as $attribute) {
2070 $value = trim($attribute->value);
2071 if (empty($value)) {
2075 $attr[$attribute->name] = $value;
2078 if (empty($attr['name']) || empty($attr['content'])) {
2083 if ($attr['name'] == 'description') {
2084 $serverdata['info'] = $attr['content'];
2087 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2088 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2089 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2090 $platform = str_replace('/', ' ', $platform);
2091 $platform_parts = explode(' ', $platform);
2092 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2093 $platform = $platform_parts[0];
2094 $serverdata['version'] = $platform_parts[1];
2096 if (in_array($platform, array_values($dfrn_platforms))) {
2097 $serverdata['network'] = Protocol::DFRN;
2098 } elseif (in_array($platform, array_values($ap_platforms))) {
2099 $serverdata['network'] = Protocol::ACTIVITYPUB;
2100 } elseif (in_array($platform, array_values($zap_platforms))) {
2101 $serverdata['network'] = Protocol::ZOT;
2103 if (in_array($platform, array_values($platforms))) {
2104 $serverdata['platform'] = $platform;
2110 $list = $xpath->query('//meta[@property]');
2112 foreach ($list as $node) {
2114 if ($node->attributes->length) {
2115 foreach ($node->attributes as $attribute) {
2116 $value = trim($attribute->value);
2117 if (empty($value)) {
2121 $attr[$attribute->name] = $value;
2124 if (empty($attr['property']) || empty($attr['content'])) {
2129 if ($attr['property'] == 'og:site_name') {
2130 $serverdata['site_name'] = $attr['content'];
2133 if ($attr['property'] == 'og:description') {
2134 $serverdata['info'] = $attr['content'];
2137 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2138 if (in_array($attr['content'], array_keys($platforms))) {
2139 $serverdata['platform'] = $platforms[$attr['content']];
2143 if (in_array($attr['content'], array_keys($ap_platforms))) {
2144 $serverdata['network'] = Protocol::ACTIVITYPUB;
2145 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2146 $serverdata['network'] = Protocol::ZOT;
2151 $list = $xpath->query('//link[@rel="me"]');
2152 foreach ($list as $node) {
2153 foreach ($node->attributes as $attribute) {
2154 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2155 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2156 $serverdata['platform'] = 'microblog';
2157 $serverdata['network'] = Protocol::ACTIVITYPUB;
2163 if ($serverdata['platform'] != 'microblog') {
2164 $list = $xpath->query('//link[@rel="micropub"]');
2165 foreach ($list as $node) {
2166 foreach ($node->attributes as $attribute) {
2167 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2168 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2169 $serverdata['platform'] = 'microblog';
2170 $serverdata['network'] = Protocol::ACTIVITYPUB;
2177 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2178 $serverdata['detection-method'] = self::DETECT_BODY;
2185 * Analyses the header data of a given server for hints about type and system of that server
2187 * @param object $curlResult result of curl execution
2188 * @param array $serverdata array with server data
2190 * @return array server data
2192 private static function analyseRootHeader($curlResult, array $serverdata): array
2194 if ($curlResult->getHeader('server') == 'Mastodon') {
2195 $serverdata['platform'] = 'mastodon';
2196 $serverdata['network'] = Protocol::ACTIVITYPUB;
2197 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2198 $serverdata['platform'] = 'diaspora';
2199 $serverdata['network'] = Protocol::DIASPORA;
2200 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2201 } elseif ($curlResult->inHeader('x-friendica-version')) {
2202 $serverdata['platform'] = 'friendica';
2203 $serverdata['network'] = Protocol::DFRN;
2204 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2209 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2210 $serverdata['detection-method'] = self::DETECT_HEADER;
2217 * Update GServer entries
2219 public static function discover()
2221 // Update the server list
2222 self::discoverFederation();
2226 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2228 if ($requery_days == 0) {
2232 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2234 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2235 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2236 ['order' => ['RAND()']]);
2238 while ($gserver = DBA::fetch($gservers)) {
2239 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2240 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2242 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2243 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2245 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2246 self::update($fields, ['nurl' => $gserver['nurl']]);
2248 if (--$no_of_queries == 0) {
2253 DBA::close($gservers);
2257 * Discover federated servers
2259 private static function discoverFederation()
2261 $last = DI::keyValue()->get('poco_last_federation_discovery');
2264 $next = $last + (24 * 60 * 60);
2266 if ($next > time()) {
2271 // Discover federated servers
2272 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2273 foreach ($protocols as $protocol) {
2274 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2275 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2276 if (!empty($curlResult)) {
2277 $data = json_decode($curlResult, true);
2278 if (!empty($data['data']['nodes'])) {
2279 foreach ($data['data']['nodes'] as $server) {
2280 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2281 self::add('https://' . $server['host'], true);
2287 // Disvover Mastodon servers
2288 $accesstoken = DI::config()->get('system', 'instances_social_key');
2290 if (!empty($accesstoken)) {
2291 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2292 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2293 if ($curlResult->isSuccess()) {
2294 $servers = json_decode($curlResult->getBody(), true);
2296 if (!empty($servers['instances'])) {
2297 foreach ($servers['instances'] as $server) {
2298 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2305 DI::keyValue()->set('poco_last_federation_discovery', time());
2309 * Set the protocol for the given server
2311 * @param int $gsid Server id
2312 * @param int $protocol Protocol id
2316 public static function setProtocol(int $gsid, int $protocol)
2322 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2323 if (!DBA::isResult($gserver)) {
2327 $old = $gserver['protocol'];
2329 if (!is_null($old)) {
2331 The priority for the protocols is:
2333 2. DFRN via Diaspora
2339 // We don't need to change it when nothing is to be changed
2340 if ($old == $protocol) {
2344 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2345 if ($protocol == Post\DeliveryData::OSTATUS) {
2349 // If the server is marked as ActivityPub then we won't change it to anything different
2350 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2354 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2355 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2359 // Don't change it to Diaspora when it is a legacy DFRN server
2360 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2365 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2366 self::update(['protocol' => $protocol], ['id' => $gsid]);
2370 * Fetch the protocol of the given server
2372 * @param int $gsid Server id
2374 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2378 public static function getProtocol(int $gsid): ?int
2384 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2385 if (DBA::isResult($gserver)) {
2386 return $gserver['protocol'];
2393 * Update rows in the gserver table.
2394 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2396 * @param array $fields
2397 * @param array $condition
2403 public static function update(array $fields, array $condition): bool
2405 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2407 return DBA::update('gserver', $fields, $condition);
2411 * Insert a row into the gserver table.
2412 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2414 * @param array $fields
2415 * @param int $duplicate_mode What to do on a duplicated entry
2421 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2423 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2425 return DBA::insert('gserver', $fields, $duplicate_mode);