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 Friendica\Worker\UpdateGServer;
48 use GuzzleHttp\Psr7\Uri;
49 use Psr\Http\Message\UriInterface;
52 * This class handles GServer related functions
59 const DT_MASTODON = 2;
61 // Methods to detect server types
63 // Non endpoint specific methods
64 const DETECT_MANUAL = 0;
65 const DETECT_HEADER = 1;
66 const DETECT_BODY = 2;
67 const DETECT_HOST_META = 3;
68 const DETECT_CONTACTS = 4;
69 const DETECT_AP_ACTOR = 5;
70 const DETECT_AP_COLLECTION = 6;
72 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
74 // Implementation specific endpoints
75 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
76 const DETECT_FRIENDIKA = 10;
77 const DETECT_FRIENDICA = 11;
78 const DETECT_STATUSNET = 12;
79 const DETECT_GNUSOCIAL = 13;
80 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
81 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
82 const DETECT_MASTODON_API = 16;
83 const DETECT_STATUS_PHP = 17; // Nextcloud
84 const DETECT_V1_CONFIG = 18;
85 const DETECT_PUMPIO = 19; // Deprecated
86 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
88 // Standardized endpoints
89 const DETECT_STATISTICS_JSON = 100;
90 const DETECT_NODEINFO_1 = 101;
91 const DETECT_NODEINFO_2 = 102;
92 const DETECT_NODEINFO_210 = 103;
95 * Check for the existance of a server and adds it in the background if not existant
98 * @param boolean $only_nodeinfo
102 public static function add(string $url, bool $only_nodeinfo = false)
104 if (self::getID($url)) {
108 UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
112 * Get the ID for the given server URL
115 * @param boolean $no_check Don't check if the server hadn't been found
117 * @return int|null gserver id or NULL on empty URL or failed check
119 public static function getID(string $url, bool $no_check = false): ?int
121 $url = self::cleanURL($url);
127 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
128 if (DBA::isResult($gserver)) {
129 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
130 return $gserver['id'];
133 if ($no_check || !self::check($url)) {
137 return self::getID($url, true);
141 * Retrieves all the servers which base domain are matching the provided domain pattern
143 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
145 * @param string $pattern
151 public static function listByDomainPattern(string $pattern): array
153 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
155 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
156 // eventual server path and keep only the server domain which we're matching against the pattern.
157 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
159 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
160 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
161 AND NOT `gserver`.`failed`
162 GROUP BY `gserver`.`id`";
164 $stmt = DI::dba()->p($sql, $likePattern);
166 return DI::dba()->toArray($stmt);
170 * Checks if the given server array is unreachable for a long time now
172 * @param integer $gsid
175 private static function isDefunct(array $gserver): bool
177 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
178 ($gserver['last_contact'] >= $gserver['created']) &&
179 ($gserver['last_contact'] < $gserver['last_failure']) &&
180 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
184 * Checks if the given server id is unreachable for a long time now
186 * @param integer $gsid
189 public static function isDefunctById(int $gsid): bool
191 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
192 if (empty($gserver)) {
195 if (strtotime($gserver['next_contact']) < time()) {
196 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
199 return self::isDefunct($gserver);
204 * Checks if the given server id is reachable
206 * @param integer $gsid
209 public static function isReachableById(int $gsid): bool
211 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
212 if (empty($gserver)) {
215 if (strtotime($gserver['next_contact']) < time()) {
216 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
219 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
224 * Checks if the given server is reachable
226 * @param array $contact Contact that should be checked
228 * @return boolean 'true' if server seems vital
230 public static function reachable(array $contact): bool
232 if (!empty($contact['gsid'])) {
233 $gsid = $contact['gsid'];
234 } elseif (!empty($contact['baseurl'])) {
235 $server = $contact['baseurl'];
236 } elseif ($contact['network'] == Protocol::DIASPORA) {
237 $parts = parse_url($contact['url']);
238 unset($parts['path']);
239 $server = (string)Uri::fromParts($parts);
245 $condition = ['id' => $gsid];
247 $condition = ['nurl' => Strings::normaliseLink($server)];
250 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
251 if (empty($gserver)) {
254 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
255 $server = $gserver['url'];
258 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
259 UpdateGServer::add(Worker::PRIORITY_LOW, $server);
266 * Calculate the next update day
268 * @param bool $success
269 * @param string $created
270 * @param string $last_contact
271 * @param bool $undetected
277 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
279 // On successful contact process check again next week when it is a detected system.
280 // When we haven't detected the system, it could be a static website or a really old system.
282 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
285 $now = strtotime(DateTimeFormat::utcNow());
287 if ($created > $last_contact) {
288 $contact_time = strtotime($created);
290 $contact_time = strtotime($last_contact);
293 // If the last contact was less than 6 hours before then try again in 6 hours
294 if (($now - $contact_time) < (60 * 60 * 6)) {
295 return DateTimeFormat::utc('now +6 hour');
298 // If the last contact was less than 12 hours before then try again in 12 hours
299 if (($now - $contact_time) < (60 * 60 * 12)) {
300 return DateTimeFormat::utc('now +12 hour');
303 // If the last contact was less than 24 hours before then try tomorrow again
304 if (($now - $contact_time) < (60 * 60 * 24)) {
305 return DateTimeFormat::utc('now +1 day');
308 // If the last contact was less than a week before then try again in a week
309 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
310 return DateTimeFormat::utc('now +1 week');
313 // If the last contact was less than two weeks before then try again in two week
314 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
315 return DateTimeFormat::utc('now +2 week');
318 // If the last contact was less than a month before then try again in a month
319 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
320 return DateTimeFormat::utc('now +1 month');
323 // The system hadn't been successul contacted for more than a month, so try again in three months
324 return DateTimeFormat::utc('now +3 month');
328 * Checks the state of the given server.
330 * @param string $server_url URL of the given server
331 * @param string $network Network value that is used, when detection failed
332 * @param boolean $force Force an update.
333 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
335 * @return boolean 'true' if server seems vital
337 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
339 $server_url = self::cleanURL($server_url);
340 if ($server_url == '') {
344 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
345 if (DBA::isResult($gserver)) {
346 if ($gserver['created'] <= DBA::NULL_DATETIME) {
347 $fields = ['created' => DateTimeFormat::utcNow()];
348 $condition = ['nurl' => Strings::normaliseLink($server_url)];
349 self::update($fields, $condition);
352 if (!$force && (strtotime($gserver['next_contact']) > time())) {
353 Logger::info('No update needed', ['server' => $server_url]);
354 return (!$gserver['failed']);
356 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
358 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
361 return self::detect($server_url, $network, $only_nodeinfo);
365 * Reset failed server status by gserver id
368 * @param string $network
370 public static function setReachableById(int $gsid, string $network)
372 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
373 if (DBA::isResult($gserver) && $gserver['failed']) {
374 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow()];
375 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
376 $fields['network'] = $network;
378 self::update($fields, ['id' => $gsid]);
379 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
381 if (strtotime($gserver['next_contact']) < time()) {
382 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
388 * Set failed server status by gserver id
392 public static function setFailureById(int $gsid)
394 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
395 if (DBA::isResult($gserver) && !$gserver['failed']) {
396 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
397 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
399 if (strtotime($gserver['next_contact']) < time()) {
400 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
406 * Set failed server status
410 public static function setFailureByUrl(string $url)
412 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
413 if (DBA::isResult($gserver)) {
414 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
415 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
416 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
417 ['nurl' => Strings::normaliseLink($url)]);
418 Logger::info('Set failed status for existing server', ['url' => $url]);
419 if (self::isDefunct($gserver)) {
420 self::archiveContacts($gserver['id']);
424 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
425 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
426 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
427 Logger::info('Set failed status for new server', ['url' => $url]);
431 * Archive server related contacts and inboxes
433 * @param integer $gsid
436 private static function archiveContacts(int $gsid)
438 Contact::update(['archive' => true], ['gsid' => $gsid]);
439 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
443 * Remove unwanted content from the given URL
445 * @param string $dirtyUrl
447 * @return string cleaned URL
449 * @deprecated since 2023.03 Use cleanUri instead
451 public static function cleanURL(string $dirtyUrl): string
454 return (string)self::cleanUri(new Uri($dirtyUrl));
455 } catch (\Throwable $e) {
456 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
462 * Remove unwanted content from the given URI
464 * @param UriInterface $dirtyUri
466 * @return UriInterface cleaned URI
469 public static function cleanUri(UriInterface $dirtyUri): string
477 '#(?:^|/)index\.php#',
479 rtrim($dirtyUri->getPath(), '/')
485 * Detect server data (type, protocol, version number, ...)
486 * The detected data is then updated or inserted in the gserver table.
488 * @param string $url URL of the given server
489 * @param string $network Network value that is used, when detection failed
490 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
492 * @return boolean 'true' if server could be detected
494 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
496 Logger::info('Detect server type', ['server' => $url]);
498 $original_url = $url;
500 // Remove URL content that is not supposed to exist for a server url
501 $url = rtrim(self::cleanURL($url), '/');
503 Logger::notice('Empty URL.');
507 // If the URL missmatches, then we mark the old entry as failure
508 if (!Strings::compareLink($url, $original_url)) {
509 self::setFailureByUrl($original_url);
510 if (!self::getID($url, true)) {
511 self::detect($url, $network, $only_nodeinfo);
516 $valid_url = Network::isUrlValid($url);
518 self::setFailureByUrl($url);
521 $valid_url = rtrim($valid_url, '/');
524 if (!Strings::compareLink($url, $valid_url)) {
525 // We only follow redirects when the path stays the same or the target url has no path.
526 // Some systems have got redirects on their landing page to a single account page. This check handles it.
527 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))) ||
528 (((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)))) {
529 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
530 self::setFailureByUrl($url);
531 if (!self::getID($valid_url, true)) {
532 self::detect($valid_url, $network, $only_nodeinfo);
537 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)) &&
538 (parse_url($url, PHP_URL_PATH) == '')) {
539 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
540 $parts = parse_url($valid_url);
541 unset($parts['path']);
542 $valid_url = (string)Uri::fromParts($parts);
544 self::setFailureByUrl($url);
545 if (!self::getID($valid_url, true)) {
546 self::detect($valid_url, $network, $only_nodeinfo);
550 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
553 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
554 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
555 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
559 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
561 // When a nodeinfo is present, we don't need to dig further
562 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
563 if ($curlResult->isTimeout()) {
564 self::setFailureByUrl($url);
568 $serverdata = self::parseNodeinfo210($curlResult);
569 if (empty($serverdata)) {
570 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
571 $serverdata = self::fetchNodeinfo($url, $curlResult);
574 if ($only_nodeinfo && empty($serverdata)) {
575 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
576 self::setFailureByUrl($url);
578 } elseif (empty($serverdata)) {
579 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
582 // When there is no Nodeinfo, then use some protocol specific endpoints
583 if ($serverdata['network'] == Protocol::PHANTOM) {
585 // Fetch the landing page, possibly it reveals some data
586 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
587 $curlResult = DI::httpClient()->get($url, $accept);
588 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
589 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
590 $html_fetched = true;
592 $html_fetched = false;
595 if ($curlResult->isSuccess()) {
596 $json = json_decode($curlResult->getBody(), true);
597 if (!empty($json) && is_array($json)) {
598 $data = self::fetchDataFromSystemActor($json, $serverdata);
599 $serverdata = $data['server'];
600 $systemactor = $data['actor'];
601 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
602 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
604 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
605 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
608 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
609 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
610 $serverdata = self::analyseRootBody($curlResult, $serverdata);
614 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
615 self::setFailureByUrl($url);
619 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
620 $serverdata = self::detectMastodonAlikes($url, $serverdata);
624 // All following checks are done for systems that always have got a "host-meta" endpoint.
625 // With this check we don't have to waste time and ressources for dead systems.
626 // Also this hopefully prevents us from receiving abuse messages.
627 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
628 $validHostMeta = self::validHostMeta($url);
630 $validHostMeta = false;
633 if ($validHostMeta) {
634 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
635 $serverdata['detection-method'] = self::DETECT_HOST_META;
638 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
639 $serverdata = self::detectFriendica($url, $serverdata);
642 // The following systems have to be installed in the root directory.
644 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
645 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
646 $serverdata = self::fetchSiteinfo($url, $serverdata);
649 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
650 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
651 $serverdata = self::detectHubzilla($url, $serverdata);
654 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
655 $serverdata = self::detectPeertube($url, $serverdata);
658 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
659 $serverdata = self::detectGNUSocial($url, $serverdata);
662 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
663 $serverdata = self::detectFriendica($url, $serverdata);
666 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
667 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
670 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
671 // Since this endpoint is only rarely used, we query it at a later time
672 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
673 $serverdata = self::fetchStatistics($url, $serverdata);
677 // When we hadn't been able to detect the network type, we use the hint from the parameter
678 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
679 $serverdata['network'] = $network;
682 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
683 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
684 self::setFailureByUrl($url);
688 $serverdata['url'] = $url;
689 $serverdata['nurl'] = Strings::normaliseLink($url);
691 // We have to prevent an endless loop here.
692 // When a server is new, then there is no gserver entry yet.
693 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
694 // and this can call this function here as well.
695 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
696 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
697 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
700 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
701 self::setFailureByUrl($url);
705 // Detect the directory type
706 $serverdata['directory-type'] = self::DT_NONE;
708 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
709 $serverdata = self::checkMastodonDirectory($url, $serverdata);
711 if ($serverdata['directory-type'] == self::DT_NONE) {
712 $serverdata = self::checkPoCo($url, $serverdata);
716 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
717 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
720 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
722 // Numbers above a reasonable value (10 millions) are ignored
723 if ($serverdata['registered-users'] > 10000000) {
724 $serverdata['registered-users'] = 0;
727 // On an active server there has to be at least a single user
728 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
729 $serverdata['registered-users'] = 1;
730 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
731 $serverdata['registered-users'] = 0;
734 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
736 $serverdata['last_contact'] = DateTimeFormat::utcNow();
737 $serverdata['failed'] = false;
739 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
740 if (!DBA::isResult($gserver)) {
741 $serverdata['created'] = DateTimeFormat::utcNow();
742 $ret = self::insert($serverdata);
743 $id = DBA::lastInsertId();
745 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
746 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
747 if (DBA::isResult($gserver)) {
748 $id = $gserver['id'];
752 // Count the number of known contacts from this server
753 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
754 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
755 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
756 $max_users = max($apcontacts, $contacts);
757 if ($max_users > $serverdata['registered-users']) {
758 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
759 self::update(['registered-users' => $max_users], ['id' => $id]);
762 if (empty($serverdata['active-month-users'])) {
763 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
765 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
766 self::update(['active-month-users' => $contacts], ['id' => $id]);
770 if (empty($serverdata['active-halfyear-users'])) {
771 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
773 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
774 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
779 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
780 self::discoverRelay($url);
783 if (!empty($systemactor)) {
784 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
785 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
792 * Fetch relay data from a given server url
794 * @param string $server_url address of the server
798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
800 private static function discoverRelay(string $server_url)
802 Logger::info('Discover relay data', ['server' => $server_url]);
804 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
805 if (!$curlResult->isSuccess()) {
809 $data = json_decode($curlResult->getBody(), true);
810 if (!is_array($data)) {
814 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
815 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
817 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
819 $data['subscribe'] = false;
823 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
824 if (!DBA::isResult($gserver)) {
828 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
829 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
830 self::update($fields, ['id' => $gserver['id']]);
833 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
835 if ($data['scope'] == 'tags') {
838 foreach ($data['tags'] as $tag) {
839 $tag = mb_strtolower($tag);
840 if (strlen($tag) < 100) {
845 foreach ($tags as $tag) {
846 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
850 // Create or update the relay contact
852 if (isset($data['protocols'])) {
853 if (isset($data['protocols']['diaspora'])) {
854 $fields['network'] = Protocol::DIASPORA;
856 if (isset($data['protocols']['diaspora']['receive'])) {
857 $fields['batch'] = $data['protocols']['diaspora']['receive'];
858 } elseif (is_string($data['protocols']['diaspora'])) {
859 $fields['batch'] = $data['protocols']['diaspora'];
863 if (isset($data['protocols']['dfrn'])) {
864 $fields['network'] = Protocol::DFRN;
866 if (isset($data['protocols']['dfrn']['receive'])) {
867 $fields['batch'] = $data['protocols']['dfrn']['receive'];
868 } elseif (is_string($data['protocols']['dfrn'])) {
869 $fields['batch'] = $data['protocols']['dfrn'];
873 if (isset($data['protocols']['activitypub'])) {
874 $fields['network'] = Protocol::ACTIVITYPUB;
876 if (!empty($data['protocols']['activitypub']['actor'])) {
877 $fields['url'] = $data['protocols']['activitypub']['actor'];
879 if (!empty($data['protocols']['activitypub']['receive'])) {
880 $fields['batch'] = $data['protocols']['activitypub']['receive'];
885 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
887 Relay::updateContact($gserver, $fields);
891 * Fetch server data from '/statistics.json' on the given server
893 * @param string $url URL of the given server
895 * @return array server data
897 private static function fetchStatistics(string $url, array $serverdata): array
899 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
900 if (!$curlResult->isSuccess()) {
904 $data = json_decode($curlResult->getBody(), true);
909 // Some AP enabled systems return activity data that we don't expect here.
910 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
915 $old_serverdata = $serverdata;
917 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
919 if (!empty($data['version'])) {
921 $serverdata['version'] = $data['version'];
922 // Version numbers on statistics.json are presented with additional info, e.g.:
923 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
924 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
927 if (!empty($data['name'])) {
929 $serverdata['site_name'] = $data['name'];
932 if (!empty($data['network'])) {
934 $serverdata['platform'] = strtolower($data['network']);
936 if ($serverdata['platform'] == 'diaspora') {
937 $serverdata['network'] = Protocol::DIASPORA;
938 } elseif ($serverdata['platform'] == 'friendica') {
939 $serverdata['network'] = Protocol::DFRN;
940 } elseif ($serverdata['platform'] == 'hubzilla') {
941 $serverdata['network'] = Protocol::ZOT;
942 } elseif ($serverdata['platform'] == 'redmatrix') {
943 $serverdata['network'] = Protocol::ZOT;
947 if (!empty($data['total_users'])) {
949 $serverdata['registered-users'] = max($data['total_users'], 1);
952 if (!empty($data['active_users_monthly'])) {
954 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
957 if (!empty($data['active_users_halfyear'])) {
959 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
962 if (!empty($data['local_posts'])) {
964 $serverdata['local-posts'] = max($data['local_posts'], 0);
967 if (!empty($data['registrations_open'])) {
968 $serverdata['register_policy'] = Register::OPEN;
970 $serverdata['register_policy'] = Register::CLOSED;
974 return $old_serverdata;
981 * Detect server type by using the nodeinfo data
983 * @param string $url address of the server
984 * @param ICanHandleHttpResponses $httpResult
986 * @return array Server data
988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
990 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
992 if (!$httpResult->isSuccess()) {
996 $nodeinfo = json_decode($httpResult->getBody(), true);
998 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
1002 $nodeinfo1_url = '';
1003 $nodeinfo2_url = '';
1005 foreach ($nodeinfo['links'] as $link) {
1006 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
1007 Logger::info('Invalid nodeinfo format', ['url' => $url]);
1010 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
1011 $nodeinfo1_url = $link['href'];
1012 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
1013 $nodeinfo2_url = $link['href'];
1017 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1023 if (!empty($nodeinfo2_url)) {
1024 $server = self::parseNodeinfo2($nodeinfo2_url);
1027 if (empty($server) && !empty($nodeinfo1_url)) {
1028 $server = self::parseNodeinfo1($nodeinfo1_url);
1037 * @param string $nodeinfo_url address of the nodeinfo path
1039 * @return array Server data
1041 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 private static function parseNodeinfo1(string $nodeinfo_url): array
1045 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1046 if (!$curlResult->isSuccess()) {
1050 $nodeinfo = json_decode($curlResult->getBody(), true);
1052 if (!is_array($nodeinfo)) {
1056 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1057 'register_policy' => Register::CLOSED];
1059 if (!empty($nodeinfo['openRegistrations'])) {
1060 $server['register_policy'] = Register::OPEN;
1063 if (is_array($nodeinfo['software'])) {
1064 if (!empty($nodeinfo['software']['name'])) {
1065 $server['platform'] = strtolower($nodeinfo['software']['name']);
1068 if (!empty($nodeinfo['software']['version'])) {
1069 $server['version'] = $nodeinfo['software']['version'];
1070 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1071 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1072 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1076 if (!empty($nodeinfo['metadata']['nodeName'])) {
1077 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1080 if (!empty($nodeinfo['usage']['users']['total'])) {
1081 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1084 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1085 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1088 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1089 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1092 if (!empty($nodeinfo['usage']['localPosts'])) {
1093 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1096 if (!empty($nodeinfo['usage']['localComments'])) {
1097 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1100 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1102 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1103 $protocols[$protocol] = true;
1106 if (!empty($protocols['friendica'])) {
1107 $server['network'] = Protocol::DFRN;
1108 } elseif (!empty($protocols['activitypub'])) {
1109 $server['network'] = Protocol::ACTIVITYPUB;
1110 } elseif (!empty($protocols['diaspora'])) {
1111 $server['network'] = Protocol::DIASPORA;
1112 } elseif (!empty($protocols['ostatus'])) {
1113 $server['network'] = Protocol::OSTATUS;
1114 } elseif (!empty($protocols['gnusocial'])) {
1115 $server['network'] = Protocol::OSTATUS;
1116 } elseif (!empty($protocols['zot'])) {
1117 $server['network'] = Protocol::ZOT;
1121 if (empty($server)) {
1125 if (empty($server['network'])) {
1126 $server['network'] = Protocol::PHANTOM;
1135 * @see https://git.feneas.org/jaywink/nodeinfo2
1137 * @param string $nodeinfo_url address of the nodeinfo path
1139 * @return array Server data
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 private static function parseNodeinfo2(string $nodeinfo_url): array
1145 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1146 if (!$curlResult->isSuccess()) {
1150 $nodeinfo = json_decode($curlResult->getBody(), true);
1151 if (!is_array($nodeinfo)) {
1156 'detection-method' => self::DETECT_NODEINFO_2,
1157 'register_policy' => Register::CLOSED,
1158 'platform' => 'unknown',
1161 if (!empty($nodeinfo['openRegistrations'])) {
1162 $server['register_policy'] = Register::OPEN;
1165 if (!empty($nodeinfo['software'])) {
1166 if (isset($nodeinfo['software']['name'])) {
1167 $server['platform'] = strtolower($nodeinfo['software']['name']);
1170 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1171 $server['version'] = $nodeinfo['software']['version'];
1172 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1173 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1174 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1176 // qoto advertises itself as Mastodon
1177 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1178 $server['platform'] = 'qoto';
1183 if (!empty($nodeinfo['metadata']['nodeName'])) {
1184 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1187 if (!empty($nodeinfo['usage']['users']['total'])) {
1188 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1191 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1192 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1195 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1196 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1199 if (!empty($nodeinfo['usage']['localPosts'])) {
1200 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1203 if (!empty($nodeinfo['usage']['localComments'])) {
1204 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1207 if (!empty($nodeinfo['protocols'])) {
1209 foreach ($nodeinfo['protocols'] as $protocol) {
1210 if (is_string($protocol)) {
1211 $protocols[$protocol] = true;
1215 if (!empty($protocols['dfrn'])) {
1216 $server['network'] = Protocol::DFRN;
1217 } elseif (!empty($protocols['activitypub'])) {
1218 $server['network'] = Protocol::ACTIVITYPUB;
1219 } elseif (!empty($protocols['diaspora'])) {
1220 $server['network'] = Protocol::DIASPORA;
1221 } elseif (!empty($protocols['ostatus'])) {
1222 $server['network'] = Protocol::OSTATUS;
1223 } elseif (!empty($protocols['gnusocial'])) {
1224 $server['network'] = Protocol::OSTATUS;
1225 } elseif (!empty($protocols['zot'])) {
1226 $server['network'] = Protocol::ZOT;
1230 if (empty($server)) {
1234 if (empty($server['network'])) {
1235 $server['network'] = Protocol::PHANTOM;
1242 * Parses NodeInfo2 protocol 1.0
1244 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1246 * @param string $nodeinfo_url address of the nodeinfo path
1248 * @return array Server data
1250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1252 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1254 if (!$httpResult->isSuccess()) {
1258 $nodeinfo = json_decode($httpResult->getBody(), true);
1260 if (!is_array($nodeinfo)) {
1264 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1265 'register_policy' => Register::CLOSED];
1267 if (!empty($nodeinfo['openRegistrations'])) {
1268 $server['register_policy'] = Register::OPEN;
1271 if (!empty($nodeinfo['server'])) {
1272 if (!empty($nodeinfo['server']['software'])) {
1273 $server['platform'] = strtolower($nodeinfo['server']['software']);
1276 if (!empty($nodeinfo['server']['version'])) {
1277 $server['version'] = $nodeinfo['server']['version'];
1278 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1279 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1280 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1283 if (!empty($nodeinfo['server']['name'])) {
1284 $server['site_name'] = $nodeinfo['server']['name'];
1288 if (!empty($nodeinfo['usage']['users']['total'])) {
1289 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1292 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1293 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1296 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1297 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1300 if (!empty($nodeinfo['usage']['localPosts'])) {
1301 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1304 if (!empty($nodeinfo['usage']['localComments'])) {
1305 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1308 if (!empty($nodeinfo['protocols'])) {
1310 foreach ($nodeinfo['protocols'] as $protocol) {
1311 if (is_string($protocol)) {
1312 $protocols[$protocol] = true;
1316 if (!empty($protocols['dfrn'])) {
1317 $server['network'] = Protocol::DFRN;
1318 } elseif (!empty($protocols['activitypub'])) {
1319 $server['network'] = Protocol::ACTIVITYPUB;
1320 } elseif (!empty($protocols['diaspora'])) {
1321 $server['network'] = Protocol::DIASPORA;
1322 } elseif (!empty($protocols['ostatus'])) {
1323 $server['network'] = Protocol::OSTATUS;
1324 } elseif (!empty($protocols['gnusocial'])) {
1325 $server['network'] = Protocol::OSTATUS;
1326 } elseif (!empty($protocols['zot'])) {
1327 $server['network'] = Protocol::ZOT;
1331 if (empty($server) || empty($server['platform'])) {
1335 if (empty($server['network'])) {
1336 $server['network'] = Protocol::PHANTOM;
1343 * Fetch server information from a 'siteinfo.json' file on the given server
1345 * @param string $url URL of the given server
1346 * @param array $serverdata array with server data
1348 * @return array server data
1350 private static function fetchSiteinfo(string $url, array $serverdata): array
1352 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1353 if (!$curlResult->isSuccess()) {
1357 $data = json_decode($curlResult->getBody(), true);
1362 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1363 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1366 if (!empty($data['url'])) {
1367 $serverdata['platform'] = strtolower($data['platform']);
1368 $serverdata['version'] = $data['version'] ?? 'N/A';
1371 if (!empty($data['plugins'])) {
1372 if (in_array('pubcrawl', $data['plugins'])) {
1373 $serverdata['network'] = Protocol::ACTIVITYPUB;
1374 } elseif (in_array('diaspora', $data['plugins'])) {
1375 $serverdata['network'] = Protocol::DIASPORA;
1376 } elseif (in_array('gnusoc', $data['plugins'])) {
1377 $serverdata['network'] = Protocol::OSTATUS;
1379 $serverdata['network'] = Protocol::ZOT;
1383 if (!empty($data['site_name'])) {
1384 $serverdata['site_name'] = $data['site_name'];
1387 if (!empty($data['channels_total'])) {
1388 $serverdata['registered-users'] = max($data['channels_total'], 1);
1391 if (!empty($data['channels_active_monthly'])) {
1392 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1395 if (!empty($data['channels_active_halfyear'])) {
1396 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1399 if (!empty($data['local_posts'])) {
1400 $serverdata['local-posts'] = max($data['local_posts'], 0);
1403 if (!empty($data['local_comments'])) {
1404 $serverdata['local-comments'] = max($data['local_comments'], 0);
1407 if (!empty($data['register_policy'])) {
1408 switch ($data['register_policy']) {
1409 case 'REGISTER_OPEN':
1410 $serverdata['register_policy'] = Register::OPEN;
1413 case 'REGISTER_APPROVE':
1414 $serverdata['register_policy'] = Register::APPROVE;
1417 case 'REGISTER_CLOSED':
1419 $serverdata['register_policy'] = Register::CLOSED;
1428 * Fetches server data via an ActivityPub account with url of that server
1430 * @param string $url URL of the given server
1431 * @param array $serverdata array with server data
1433 * @return array server data
1437 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1440 return ['server' => $serverdata, 'actor' => ''];
1443 $actor = JsonLD::compact($data, false);
1444 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1445 $serverdata['network'] = Protocol::ACTIVITYPUB;
1446 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1447 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1448 if (!empty($actor['as:generator'])) {
1449 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1450 $serverdata['platform'] = strtolower(array_shift($generator));
1451 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1453 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1455 return ['server' => $serverdata, 'actor' => $actor['@id']];
1456 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1457 // By now only Ktistec seems to provide collections this way
1458 $serverdata['platform'] = 'ktistec';
1459 $serverdata['network'] = Protocol::ACTIVITYPUB;
1460 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1462 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1463 if (!empty($actors) && !empty($actors[0]['@id'])) {
1464 $actor_url = $actor['@id'] . $actors[0]['@id'];
1469 return ['server' => $serverdata, 'actor' => $actor_url];
1471 return ['server' => $serverdata, 'actor' => ''];
1475 * Checks if the server contains a valid host meta file
1477 * @param string $url URL of the given server
1479 * @return boolean 'true' if the server seems to be vital
1481 private static function validHostMeta(string $url): bool
1483 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1484 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1485 if (!$curlResult->isSuccess()) {
1489 $xrd = XML::parseString($curlResult->getBody(), true);
1490 if (!is_object($xrd)) {
1494 $elements = XML::elementToArray($xrd);
1495 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1500 foreach ($elements['xrd']['link'] as $link) {
1501 // When there is more than a single "link" element, the array looks slightly different
1502 if (!empty($link['@attributes'])) {
1503 $link = $link['@attributes'];
1506 if (empty($link['rel']) || empty($link['template'])) {
1510 if ($link['rel'] == 'lrdd') {
1511 // When the webfinger host is the same like the system host, it should be ok.
1512 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1520 * Detect the network of the given server via their known contacts
1522 * @param string $url URL of the given server
1523 * @param array $serverdata array with server data
1525 * @return array server data
1527 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1531 $nurl = Strings::normaliseLink($url);
1533 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1534 while ($apcontact = DBA::fetch($apcontacts)) {
1535 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1537 DBA::close($apcontacts);
1539 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1540 while ($pcontact = DBA::fetch($pcontacts)) {
1541 $contacts[$pcontact['nurl']] = $pcontact['url'];
1543 DBA::close($pcontacts);
1545 if (empty($contacts)) {
1550 foreach ($contacts as $contact) {
1551 // Endlosschleife verhindern wegen gsid!
1552 $data = Probe::uri($contact);
1553 if (in_array($data['network'], Protocol::FEDERATED)) {
1554 $serverdata['network'] = $data['network'];
1556 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1557 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1560 } elseif ((time() - $time) > 10) {
1561 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1570 * Checks if the given server does have a '/poco' endpoint.
1571 * This is used for the 'PortableContact' functionality,
1572 * which is used by both Friendica and Hubzilla.
1574 * @param string $url URL of the given server
1575 * @param array $serverdata array with server data
1577 * @return array server data
1579 private static function checkPoCo(string $url, array $serverdata): array
1581 $serverdata['poco'] = '';
1583 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1584 if (!$curlResult->isSuccess()) {
1588 $data = json_decode($curlResult->getBody(), true);
1593 if (!empty($data['totalResults'])) {
1594 $registeredUsers = $serverdata['registered-users'] ?? 0;
1595 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1596 $serverdata['directory-type'] = self::DT_POCO;
1597 $serverdata['poco'] = $url . '/poco';
1604 * Checks if the given server does have a Mastodon style directory endpoint.
1606 * @param string $url URL of the given server
1607 * @param array $serverdata array with server data
1609 * @return array server data
1611 public static function checkMastodonDirectory(string $url, array $serverdata): array
1613 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1614 if (!$curlResult->isSuccess()) {
1618 $data = json_decode($curlResult->getBody(), true);
1623 if (count($data) == 1) {
1624 $serverdata['directory-type'] = self::DT_MASTODON;
1631 * Detects Peertube via their known endpoint
1633 * @param string $url URL of the given server
1634 * @param array $serverdata array with server data
1636 * @return array server data
1638 private static function detectPeertube(string $url, array $serverdata): array
1640 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1641 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1645 $data = json_decode($curlResult->getBody(), true);
1650 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1651 $serverdata['platform'] = 'peertube';
1652 $serverdata['version'] = $data['serverVersion'];
1653 $serverdata['network'] = Protocol::ACTIVITYPUB;
1655 if (!empty($data['instance']['name'])) {
1656 $serverdata['site_name'] = $data['instance']['name'];
1659 if (!empty($data['instance']['shortDescription'])) {
1660 $serverdata['info'] = $data['instance']['shortDescription'];
1663 if (!empty($data['signup'])) {
1664 if (!empty($data['signup']['allowed'])) {
1665 $serverdata['register_policy'] = Register::OPEN;
1669 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1670 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1678 * Detects the version number of a given server when it was a NextCloud installation
1680 * @param string $url URL of the given server
1681 * @param array $serverdata array with server data
1682 * @param bool $validHostMeta
1684 * @return array server data
1686 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1688 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1689 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1693 $data = json_decode($curlResult->getBody(), true);
1698 if (!empty($data['version'])) {
1699 $serverdata['platform'] = 'nextcloud';
1700 $serverdata['version'] = $data['version'];
1702 if ($validHostMeta) {
1703 $serverdata['network'] = Protocol::ACTIVITYPUB;
1706 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1707 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1715 * Fetches weekly usage data
1717 * @param string $url URL of the given server
1718 * @param array $serverdata array with server data
1720 * @return array server data
1722 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1724 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1725 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1729 $data = json_decode($curlResult->getBody(), true);
1735 foreach ($data as $week) {
1736 // Use only data from a full week
1737 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1741 // Most likely the data is sorted correctly. But we better are safe than sorry
1742 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1743 $current_week = $week;
1747 if (!empty($current_week['logins'])) {
1748 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1755 * Detects data from a given server url if it was a mastodon alike system
1757 * @param string $url URL of the given server
1758 * @param array $serverdata array with server data
1760 * @return array server data
1762 private static function detectMastodonAlikes(string $url, array $serverdata): array
1764 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1765 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1769 $data = json_decode($curlResult->getBody(), true);
1776 if (!empty($data['version'])) {
1777 $serverdata['platform'] = 'mastodon';
1778 $serverdata['version'] = $data['version'] ?? '';
1779 $serverdata['network'] = Protocol::ACTIVITYPUB;
1783 if (!empty($data['title'])) {
1784 $serverdata['site_name'] = $data['title'];
1787 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1788 $serverdata['platform'] = 'mastodon';
1789 $serverdata['network'] = Protocol::ACTIVITYPUB;
1793 if (!empty($data['description'])) {
1794 $serverdata['info'] = trim($data['description']);
1797 if (!empty($data['stats']['user_count'])) {
1798 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1801 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1802 $serverdata['platform'] = strtolower($matches[1]);
1803 $serverdata['version'] = $matches[2];
1807 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1808 $serverdata['platform'] = 'pleroma';
1809 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1813 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1814 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1815 $serverdata['platform'] = 'pleroma';
1819 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1820 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1827 * Detects data from typical Hubzilla endpoints
1829 * @param string $url URL of the given server
1830 * @param array $serverdata array with server data
1832 * @return array server data
1834 private static function detectHubzilla(string $url, array $serverdata): array
1836 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1837 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1841 $data = json_decode($curlResult->getBody(), true);
1842 if (empty($data) || empty($data['site'])) {
1846 if (!empty($data['site']['name'])) {
1847 $serverdata['site_name'] = $data['site']['name'];
1850 if (!empty($data['site']['platform'])) {
1851 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1852 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1853 $serverdata['network'] = Protocol::ZOT;
1856 if (!empty($data['site']['hubzilla'])) {
1857 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1858 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1859 $serverdata['network'] = Protocol::ZOT;
1862 if (!empty($data['site']['redmatrix'])) {
1863 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1864 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1865 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1866 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1869 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1870 $serverdata['network'] = Protocol::ZOT;
1874 $inviteonly = false;
1877 if (!empty($data['site']['closed'])) {
1878 $closed = self::toBoolean($data['site']['closed']);
1881 if (!empty($data['site']['private'])) {
1882 $private = self::toBoolean($data['site']['private']);
1885 if (!empty($data['site']['inviteonly'])) {
1886 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1889 if (!$closed && !$private and $inviteonly) {
1890 $serverdata['register_policy'] = Register::APPROVE;
1891 } elseif (!$closed && !$private) {
1892 $serverdata['register_policy'] = Register::OPEN;
1894 $serverdata['register_policy'] = Register::CLOSED;
1897 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1898 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1905 * Converts input value to a boolean value
1907 * @param string|integer $val
1911 private static function toBoolean($val): bool
1913 if (($val == 'true') || ($val == 1)) {
1915 } elseif (($val == 'false') || ($val == 0)) {
1923 * Detect if the URL belongs to a GNU Social server
1925 * @param string $url URL of the given server
1926 * @param array $serverdata array with server data
1928 * @return array server data
1930 private static function detectGNUSocial(string $url, array $serverdata): array
1932 // Test for GNU Social
1933 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1934 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1935 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1936 $serverdata['platform'] = 'gnusocial';
1937 // Remove junk that some GNU Social servers return
1938 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1939 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1940 $serverdata['version'] = trim($serverdata['version'], '"');
1941 $serverdata['network'] = Protocol::OSTATUS;
1943 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1944 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1950 // Test for Statusnet
1951 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1952 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1953 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1955 // Remove junk that some GNU Social servers return
1956 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1957 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1958 $serverdata['version'] = trim($serverdata['version'], '"');
1960 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1961 $serverdata['platform'] = 'pleroma';
1962 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1963 $serverdata['network'] = Protocol::ACTIVITYPUB;
1965 $serverdata['platform'] = 'statusnet';
1966 $serverdata['network'] = Protocol::OSTATUS;
1969 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1970 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1978 * Detect if the URL belongs to a Friendica server
1980 * @param string $url URL of the given server
1981 * @param array $serverdata array with server data
1983 * @return array server data
1985 private static function detectFriendica(string $url, array $serverdata): array
1987 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1988 // Because of this me must not use ACCEPT_JSON here.
1989 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1990 if (!$curlResult->isSuccess()) {
1991 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1993 $platform = 'Friendika';
1996 $platform = 'Friendica';
1999 if (!$curlResult->isSuccess()) {
2003 $data = json_decode($curlResult->getBody(), true);
2004 if (empty($data) || empty($data['version'])) {
2008 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2009 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2012 $serverdata['network'] = Protocol::DFRN;
2013 $serverdata['version'] = $data['version'];
2015 if (!empty($data['no_scrape_url'])) {
2016 $serverdata['noscrape'] = $data['no_scrape_url'];
2019 if (!empty($data['site_name'])) {
2020 $serverdata['site_name'] = $data['site_name'];
2023 if (!empty($data['info'])) {
2024 $serverdata['info'] = trim($data['info']);
2027 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2028 switch ($register_policy) {
2029 case 'REGISTER_OPEN':
2030 $serverdata['register_policy'] = Register::OPEN;
2033 case 'REGISTER_APPROVE':
2034 $serverdata['register_policy'] = Register::APPROVE;
2037 case 'REGISTER_CLOSED':
2038 case 'REGISTER_INVITATION':
2039 $serverdata['register_policy'] = Register::CLOSED;
2042 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2043 $serverdata['register_policy'] = Register::CLOSED;
2047 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2053 * Analyses the landing page of a given server for hints about type and system of that server
2055 * @param object $curlResult result of curl execution
2056 * @param array $serverdata array with server data
2058 * @return array server data
2060 private static function analyseRootBody($curlResult, array $serverdata): array
2062 if (empty($curlResult->getBody())) {
2066 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2067 require __DIR__ . '/../../static/platforms.config.php';
2069 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2072 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2074 $doc = new DOMDocument();
2075 @$doc->loadHTML($curlResult->getBody());
2076 $xpath = new DOMXPath($doc);
2079 // We can only detect honk via some HTML element on their page
2080 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2081 $serverdata['platform'] = 'honk';
2082 $serverdata['network'] = Protocol::ACTIVITYPUB;
2086 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2087 if (!empty($title)) {
2088 $serverdata['site_name'] = $title;
2091 $list = $xpath->query('//meta[@name]');
2093 foreach ($list as $node) {
2095 if ($node->attributes->length) {
2096 foreach ($node->attributes as $attribute) {
2097 $value = trim($attribute->value);
2098 if (empty($value)) {
2102 $attr[$attribute->name] = $value;
2105 if (empty($attr['name']) || empty($attr['content'])) {
2110 if ($attr['name'] == 'description') {
2111 $serverdata['info'] = $attr['content'];
2114 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2115 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2116 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2117 $platform = str_replace('/', ' ', $platform);
2118 $platform_parts = explode(' ', $platform);
2119 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2120 $platform = $platform_parts[0];
2121 $serverdata['version'] = $platform_parts[1];
2123 if (in_array($platform, array_values($dfrn_platforms))) {
2124 $serverdata['network'] = Protocol::DFRN;
2125 } elseif (in_array($platform, array_values($ap_platforms))) {
2126 $serverdata['network'] = Protocol::ACTIVITYPUB;
2127 } elseif (in_array($platform, array_values($zap_platforms))) {
2128 $serverdata['network'] = Protocol::ZOT;
2130 if (in_array($platform, array_values($platforms))) {
2131 $serverdata['platform'] = $platform;
2137 $list = $xpath->query('//meta[@property]');
2139 foreach ($list as $node) {
2141 if ($node->attributes->length) {
2142 foreach ($node->attributes as $attribute) {
2143 $value = trim($attribute->value);
2144 if (empty($value)) {
2148 $attr[$attribute->name] = $value;
2151 if (empty($attr['property']) || empty($attr['content'])) {
2156 if ($attr['property'] == 'og:site_name') {
2157 $serverdata['site_name'] = $attr['content'];
2160 if ($attr['property'] == 'og:description') {
2161 $serverdata['info'] = $attr['content'];
2164 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2165 if (in_array($attr['content'], array_keys($platforms))) {
2166 $serverdata['platform'] = $platforms[$attr['content']];
2170 if (in_array($attr['content'], array_keys($ap_platforms))) {
2171 $serverdata['network'] = Protocol::ACTIVITYPUB;
2172 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2173 $serverdata['network'] = Protocol::ZOT;
2178 $list = $xpath->query('//link[@rel="me"]');
2179 foreach ($list as $node) {
2180 foreach ($node->attributes as $attribute) {
2181 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2182 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2183 $serverdata['platform'] = 'microblog';
2184 $serverdata['network'] = Protocol::ACTIVITYPUB;
2190 if ($serverdata['platform'] != 'microblog') {
2191 $list = $xpath->query('//link[@rel="micropub"]');
2192 foreach ($list as $node) {
2193 foreach ($node->attributes as $attribute) {
2194 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2195 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2196 $serverdata['platform'] = 'microblog';
2197 $serverdata['network'] = Protocol::ACTIVITYPUB;
2204 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2205 $serverdata['detection-method'] = self::DETECT_BODY;
2212 * Analyses the header data of a given server for hints about type and system of that server
2214 * @param object $curlResult result of curl execution
2215 * @param array $serverdata array with server data
2217 * @return array server data
2219 private static function analyseRootHeader($curlResult, array $serverdata): array
2221 if ($curlResult->getHeader('server') == 'Mastodon') {
2222 $serverdata['platform'] = 'mastodon';
2223 $serverdata['network'] = Protocol::ACTIVITYPUB;
2224 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2225 $serverdata['platform'] = 'diaspora';
2226 $serverdata['network'] = Protocol::DIASPORA;
2227 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2228 } elseif ($curlResult->inHeader('x-friendica-version')) {
2229 $serverdata['platform'] = 'friendica';
2230 $serverdata['network'] = Protocol::DFRN;
2231 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2236 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2237 $serverdata['detection-method'] = self::DETECT_HEADER;
2244 * Update GServer entries
2246 public static function discover()
2248 // Update the server list
2249 self::discoverFederation();
2253 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2255 if ($requery_days == 0) {
2259 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2261 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2262 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2263 ['order' => ['RAND()']]);
2265 while ($gserver = DBA::fetch($gservers)) {
2266 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2267 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2269 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2270 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2272 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2273 self::update($fields, ['nurl' => $gserver['nurl']]);
2275 if (--$no_of_queries == 0) {
2280 DBA::close($gservers);
2284 * Discover federated servers
2286 private static function discoverFederation()
2288 $last = DI::keyValue()->get('poco_last_federation_discovery');
2291 $next = $last + (24 * 60 * 60);
2293 if ($next > time()) {
2298 // Discover federated servers
2299 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2300 foreach ($protocols as $protocol) {
2301 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2302 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2303 if (!empty($curlResult)) {
2304 $data = json_decode($curlResult, true);
2305 if (!empty($data['data']['nodes'])) {
2306 foreach ($data['data']['nodes'] as $server) {
2307 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2308 self::add('https://' . $server['host'], true);
2314 // Disvover Mastodon servers
2315 $accesstoken = DI::config()->get('system', 'instances_social_key');
2317 if (!empty($accesstoken)) {
2318 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2319 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2320 if ($curlResult->isSuccess()) {
2321 $servers = json_decode($curlResult->getBody(), true);
2323 if (!empty($servers['instances'])) {
2324 foreach ($servers['instances'] as $server) {
2325 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2332 DI::keyValue()->set('poco_last_federation_discovery', time());
2336 * Set the protocol for the given server
2338 * @param int $gsid Server id
2339 * @param int $protocol Protocol id
2343 public static function setProtocol(int $gsid, int $protocol)
2349 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2350 if (!DBA::isResult($gserver)) {
2354 $old = $gserver['protocol'];
2356 if (!is_null($old)) {
2358 The priority for the protocols is:
2360 2. DFRN via Diaspora
2366 // We don't need to change it when nothing is to be changed
2367 if ($old == $protocol) {
2371 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2372 if ($protocol == Post\DeliveryData::OSTATUS) {
2376 // If the server is marked as ActivityPub then we won't change it to anything different
2377 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2381 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2382 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2386 // Don't change it to Diaspora when it is a legacy DFRN server
2387 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2392 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2393 self::update(['protocol' => $protocol], ['id' => $gsid]);
2397 * Fetch the protocol of the given server
2399 * @param int $gsid Server id
2401 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2405 public static function getProtocol(int $gsid): ?int
2411 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2412 if (DBA::isResult($gserver)) {
2413 return $gserver['protocol'];
2420 * Update rows in the gserver table.
2421 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2423 * @param array $fields
2424 * @param array $condition
2430 public static function update(array $fields, array $condition): bool
2432 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2434 return DBA::update('gserver', $fields, $condition);
2438 * Insert a row into the gserver table.
2439 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2441 * @param array $fields
2442 * @param int $duplicate_mode What to do on a duplicated entry
2448 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2450 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2452 return DBA::insert('gserver', $fields, $duplicate_mode);