3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Relay;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
46 use Friendica\Network\HTTPException;
47 use GuzzleHttp\Psr7\Uri;
50 * This class handles GServer related functions
57 const DT_MASTODON = 2;
59 // Methods to detect server types
61 // Non endpoint specific methods
62 const DETECT_MANUAL = 0;
63 const DETECT_HEADER = 1;
64 const DETECT_BODY = 2;
65 const DETECT_HOST_META = 3;
66 const DETECT_CONTACTS = 4;
67 const DETECT_AP_ACTOR = 5;
68 const DETECT_AP_COLLECTION = 6;
70 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
72 // Implementation specific endpoints
73 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
74 const DETECT_FRIENDIKA = 10;
75 const DETECT_FRIENDICA = 11;
76 const DETECT_STATUSNET = 12;
77 const DETECT_GNUSOCIAL = 13;
78 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
79 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
80 const DETECT_MASTODON_API = 16;
81 const DETECT_STATUS_PHP = 17; // Nextcloud
82 const DETECT_V1_CONFIG = 18;
83 const DETECT_PUMPIO = 19; // Deprecated
84 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
86 // Standardized endpoints
87 const DETECT_STATISTICS_JSON = 100;
88 const DETECT_NODEINFO_1 = 101;
89 const DETECT_NODEINFO_2 = 102;
90 const DETECT_NODEINFO_210 = 103;
93 * Check for the existance of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
100 public static function add(string $url, bool $only_nodeinfo = false)
102 if (self::getID($url, false)) {
106 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
110 * Get the ID for the given server URL
113 * @param boolean $no_check Don't check if the server hadn't been found
115 * @return int|null gserver id or NULL on empty URL or failed check
117 public static function getID(string $url, bool $no_check = false): ?int
119 $url = self::cleanURL($url);
125 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
126 if (DBA::isResult($gserver)) {
127 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
128 return $gserver['id'];
131 if ($no_check || !self::check($url)) {
135 return self::getID($url, true);
139 * Retrieves all the servers which base domain are matching the provided domain pattern
141 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
143 * @param string $pattern
149 public static function listByDomainPattern(string $pattern): array
151 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
153 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
154 // eventual server path and keep only the server domain which we're matching against the pattern.
155 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
157 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
158 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
159 AND NOT `gserver`.`failed`
160 GROUP BY `gserver`.`id`";
162 $stmt = DI::dba()->p($sql, $likePattern);
164 return DI::dba()->toArray($stmt);
168 * Checks if the given server 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
365 public static function setReachableById(int $gsid)
367 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
368 if (DBA::isResult($gserver) && $gserver['failed']) {
369 self::update(['failed' => false, 'last_contact' => DateTimeFormat::utcNow()], ['id' => $gsid]);
370 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
372 if (strtotime($gserver['next_contact']) < time()) {
373 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
379 * Set failed server status by gserver id
383 public static function setFailureById(int $gsid)
385 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
386 if (DBA::isResult($gserver) && !$gserver['failed']) {
387 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
388 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
390 if (strtotime($gserver['next_contact']) < time()) {
391 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
397 * Set failed server status
401 public static function setFailureByUrl(string $url)
403 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
404 if (DBA::isResult($gserver)) {
405 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
406 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
407 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
408 ['nurl' => Strings::normaliseLink($url)]);
409 Logger::info('Set failed status for existing server', ['url' => $url]);
410 if (self::isDefunct($gserver)) {
411 self::archiveContacts($gserver['id']);
415 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
416 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
417 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
418 Logger::info('Set failed status for new server', ['url' => $url]);
422 * Archive server related contacts and inboxes
424 * @param integer $gsid
427 private static function archiveContacts(int $gsid)
429 Contact::update(['archive' => true], ['gsid' => $gsid]);
430 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
434 * Remove unwanted content from the given URL
436 * @param string $dirtyUrl
438 * @return string cleaned URL
441 public static function cleanURL(string $dirtyUrl): string
444 $url = str_replace('/index.php', '', trim($dirtyUrl, '/'));
445 return (string)(new Uri($url))->withUserInfo('')->withQuery('')->withFragment('');
446 } catch (\Throwable $e) {
447 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl, 'url' => $url]);
453 * Detect server data (type, protocol, version number, ...)
454 * The detected data is then updated or inserted in the gserver table.
456 * @param string $url URL of the given server
457 * @param string $network Network value that is used, when detection failed
458 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
460 * @return boolean 'true' if server could be detected
462 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
464 Logger::info('Detect server type', ['server' => $url]);
466 $original_url = $url;
468 // Remove URL content that is not supposed to exist for a server url
469 $url = rtrim(self::cleanURL($url), '/');
471 Logger::notice('Empty URL.');
475 // If the URL missmatches, then we mark the old entry as failure
476 if (!Strings::compareLink($url, $original_url)) {
477 self::setFailureByUrl($original_url);
478 if (!self::getID($url, true)) {
479 self::detect($url, $network, $only_nodeinfo);
484 $valid_url = Network::isUrlValid($url);
486 self::setFailureByUrl($url);
489 $valid_url = rtrim($valid_url, '/');
492 if (!Strings::compareLink($url, $valid_url)) {
493 // We only follow redirects when the path stays the same or the target url has no path.
494 // Some systems have got redirects on their landing page to a single account page. This check handles it.
495 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))) ||
496 (((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)))) {
497 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
498 self::setFailureByUrl($url);
499 if (!self::getID($valid_url, true)) {
500 self::detect($valid_url, $network, $only_nodeinfo);
505 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)) &&
506 (parse_url($url, PHP_URL_PATH) == '')) {
507 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
508 $parts = parse_url($valid_url);
509 unset($parts['path']);
510 $valid_url = (string)Uri::fromParts($parts);
512 self::setFailureByUrl($url);
513 if (!self::getID($valid_url, true)) {
514 self::detect($valid_url, $network, $only_nodeinfo);
518 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
521 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
522 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
523 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
527 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
529 // When a nodeinfo is present, we don't need to dig further
530 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
531 if ($curlResult->isTimeout()) {
532 self::setFailureByUrl($url);
536 $serverdata = self::parseNodeinfo210($curlResult);
537 if (empty($serverdata)) {
538 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
539 $serverdata = self::fetchNodeinfo($url, $curlResult);
542 if ($only_nodeinfo && empty($serverdata)) {
543 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
544 self::setFailureByUrl($url);
546 } elseif (empty($serverdata)) {
547 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
550 // When there is no Nodeinfo, then use some protocol specific endpoints
551 if ($serverdata['network'] == Protocol::PHANTOM) {
553 // Fetch the landing page, possibly it reveals some data
554 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
555 $curlResult = DI::httpClient()->get($url, $accept);
556 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
557 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
558 $html_fetched = true;
560 $html_fetched = false;
563 if ($curlResult->isSuccess()) {
564 $json = json_decode($curlResult->getBody(), true);
565 if (!empty($json) && is_array($json)) {
566 $data = self::fetchDataFromSystemActor($json, $serverdata);
567 $serverdata = $data['server'];
568 $systemactor = $data['actor'];
569 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
570 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
572 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
573 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
576 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
577 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
578 $serverdata = self::analyseRootBody($curlResult, $serverdata);
582 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
583 self::setFailureByUrl($url);
587 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
588 $serverdata = self::detectMastodonAlikes($url, $serverdata);
592 // All following checks are done for systems that always have got a "host-meta" endpoint.
593 // With this check we don't have to waste time and ressources for dead systems.
594 // Also this hopefully prevents us from receiving abuse messages.
595 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
596 $validHostMeta = self::validHostMeta($url);
598 $validHostMeta = false;
601 if ($validHostMeta) {
602 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
603 $serverdata['detection-method'] = self::DETECT_HOST_META;
606 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
607 $serverdata = self::detectFriendica($url, $serverdata);
610 // The following systems have to be installed in the root directory.
612 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
613 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
614 $serverdata = self::fetchSiteinfo($url, $serverdata);
617 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
618 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
619 $serverdata = self::detectHubzilla($url, $serverdata);
622 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
623 $serverdata = self::detectPeertube($url, $serverdata);
626 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
627 $serverdata = self::detectGNUSocial($url, $serverdata);
630 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
631 $serverdata = self::detectFriendica($url, $serverdata);
634 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
635 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
638 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
639 // Since this endpoint is only rarely used, we query it at a later time
640 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
641 $serverdata = self::fetchStatistics($url, $serverdata);
645 // When we hadn't been able to detect the network type, we use the hint from the parameter
646 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
647 $serverdata['network'] = $network;
650 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
651 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
652 self::setFailureByUrl($url);
656 $serverdata['url'] = $url;
657 $serverdata['nurl'] = Strings::normaliseLink($url);
659 // We have to prevent an endless loop here.
660 // When a server is new, then there is no gserver entry yet.
661 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
662 // and this can call this function here as well.
663 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
664 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
665 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
668 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
669 self::setFailureByUrl($url);
673 // Detect the directory type
674 $serverdata['directory-type'] = self::DT_NONE;
676 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
677 $serverdata = self::checkMastodonDirectory($url, $serverdata);
679 if ($serverdata['directory-type'] == self::DT_NONE) {
680 $serverdata = self::checkPoCo($url, $serverdata);
684 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
685 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
688 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
690 // Numbers above a reasonable value (10 millions) are ignored
691 if ($serverdata['registered-users'] > 10000000) {
692 $serverdata['registered-users'] = 0;
695 // On an active server there has to be at least a single user
696 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
697 $serverdata['registered-users'] = 1;
698 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
699 $serverdata['registered-users'] = 0;
702 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
704 $serverdata['last_contact'] = DateTimeFormat::utcNow();
705 $serverdata['failed'] = false;
707 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
708 if (!DBA::isResult($gserver)) {
709 $serverdata['created'] = DateTimeFormat::utcNow();
710 $ret = self::insert($serverdata);
711 $id = DBA::lastInsertId();
713 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
714 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
715 if (DBA::isResult($gserver)) {
716 $id = $gserver['id'];
720 // Count the number of known contacts from this server
721 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
722 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
723 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
724 $max_users = max($apcontacts, $contacts);
725 if ($max_users > $serverdata['registered-users']) {
726 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
727 self::update(['registered-users' => $max_users], ['id' => $id]);
730 if (empty($serverdata['active-month-users'])) {
731 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
733 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
734 self::update(['active-month-users' => $contacts], ['id' => $id]);
738 if (empty($serverdata['active-halfyear-users'])) {
739 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
741 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
742 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
747 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
748 self::discoverRelay($url);
751 if (!empty($systemactor)) {
752 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
753 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
760 * Fetch relay data from a given server url
762 * @param string $server_url address of the server
766 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 private static function discoverRelay(string $server_url)
770 Logger::info('Discover relay data', ['server' => $server_url]);
772 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
773 if (!$curlResult->isSuccess()) {
777 $data = json_decode($curlResult->getBody(), true);
778 if (!is_array($data)) {
782 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
783 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
785 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
787 $data['subscribe'] = false;
791 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
792 if (!DBA::isResult($gserver)) {
796 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
797 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
798 self::update($fields, ['id' => $gserver['id']]);
801 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
803 if ($data['scope'] == 'tags') {
806 foreach ($data['tags'] as $tag) {
807 $tag = mb_strtolower($tag);
808 if (strlen($tag) < 100) {
813 foreach ($tags as $tag) {
814 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
818 // Create or update the relay contact
820 if (isset($data['protocols'])) {
821 if (isset($data['protocols']['diaspora'])) {
822 $fields['network'] = Protocol::DIASPORA;
824 if (isset($data['protocols']['diaspora']['receive'])) {
825 $fields['batch'] = $data['protocols']['diaspora']['receive'];
826 } elseif (is_string($data['protocols']['diaspora'])) {
827 $fields['batch'] = $data['protocols']['diaspora'];
831 if (isset($data['protocols']['dfrn'])) {
832 $fields['network'] = Protocol::DFRN;
834 if (isset($data['protocols']['dfrn']['receive'])) {
835 $fields['batch'] = $data['protocols']['dfrn']['receive'];
836 } elseif (is_string($data['protocols']['dfrn'])) {
837 $fields['batch'] = $data['protocols']['dfrn'];
841 if (isset($data['protocols']['activitypub'])) {
842 $fields['network'] = Protocol::ACTIVITYPUB;
844 if (!empty($data['protocols']['activitypub']['actor'])) {
845 $fields['url'] = $data['protocols']['activitypub']['actor'];
847 if (!empty($data['protocols']['activitypub']['receive'])) {
848 $fields['batch'] = $data['protocols']['activitypub']['receive'];
853 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
855 Relay::updateContact($gserver, $fields);
859 * Fetch server data from '/statistics.json' on the given server
861 * @param string $url URL of the given server
863 * @return array server data
865 private static function fetchStatistics(string $url, array $serverdata): array
867 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
868 if (!$curlResult->isSuccess()) {
872 $data = json_decode($curlResult->getBody(), true);
877 // Some AP enabled systems return activity data that we don't expect here.
878 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
883 $old_serverdata = $serverdata;
885 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
887 if (!empty($data['version'])) {
889 $serverdata['version'] = $data['version'];
890 // Version numbers on statistics.json are presented with additional info, e.g.:
891 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
892 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
895 if (!empty($data['name'])) {
897 $serverdata['site_name'] = $data['name'];
900 if (!empty($data['network'])) {
902 $serverdata['platform'] = strtolower($data['network']);
904 if ($serverdata['platform'] == 'diaspora') {
905 $serverdata['network'] = Protocol::DIASPORA;
906 } elseif ($serverdata['platform'] == 'friendica') {
907 $serverdata['network'] = Protocol::DFRN;
908 } elseif ($serverdata['platform'] == 'hubzilla') {
909 $serverdata['network'] = Protocol::ZOT;
910 } elseif ($serverdata['platform'] == 'redmatrix') {
911 $serverdata['network'] = Protocol::ZOT;
915 if (!empty($data['total_users'])) {
917 $serverdata['registered-users'] = max($data['total_users'], 1);
920 if (!empty($data['active_users_monthly'])) {
922 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
925 if (!empty($data['active_users_halfyear'])) {
927 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
930 if (!empty($data['local_posts'])) {
932 $serverdata['local-posts'] = max($data['local_posts'], 0);
935 if (!empty($data['registrations_open'])) {
936 $serverdata['register_policy'] = Register::OPEN;
938 $serverdata['register_policy'] = Register::CLOSED;
942 return $old_serverdata;
949 * Detect server type by using the nodeinfo data
951 * @param string $url address of the server
952 * @param ICanHandleHttpResponses $httpResult
954 * @return array Server data
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
958 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
960 if (!$httpResult->isSuccess()) {
964 $nodeinfo = json_decode($httpResult->getBody(), true);
966 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
973 foreach ($nodeinfo['links'] as $link) {
974 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
975 Logger::info('Invalid nodeinfo format', ['url' => $url]);
978 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
979 $nodeinfo1_url = $link['href'];
980 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
981 $nodeinfo2_url = $link['href'];
985 if ($nodeinfo1_url . $nodeinfo2_url == '') {
991 if (!empty($nodeinfo2_url)) {
992 $server = self::parseNodeinfo2($nodeinfo2_url);
995 if (empty($server) && !empty($nodeinfo1_url)) {
996 $server = self::parseNodeinfo1($nodeinfo1_url);
1005 * @param string $nodeinfo_url address of the nodeinfo path
1007 * @return array Server data
1009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1011 private static function parseNodeinfo1(string $nodeinfo_url): array
1013 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1014 if (!$curlResult->isSuccess()) {
1018 $nodeinfo = json_decode($curlResult->getBody(), true);
1020 if (!is_array($nodeinfo)) {
1024 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1025 'register_policy' => Register::CLOSED];
1027 if (!empty($nodeinfo['openRegistrations'])) {
1028 $server['register_policy'] = Register::OPEN;
1031 if (is_array($nodeinfo['software'])) {
1032 if (!empty($nodeinfo['software']['name'])) {
1033 $server['platform'] = strtolower($nodeinfo['software']['name']);
1036 if (!empty($nodeinfo['software']['version'])) {
1037 $server['version'] = $nodeinfo['software']['version'];
1038 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1039 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1040 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1044 if (!empty($nodeinfo['metadata']['nodeName'])) {
1045 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1048 if (!empty($nodeinfo['usage']['users']['total'])) {
1049 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1052 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1053 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1056 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1057 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1060 if (!empty($nodeinfo['usage']['localPosts'])) {
1061 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1064 if (!empty($nodeinfo['usage']['localComments'])) {
1065 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1068 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1070 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1071 $protocols[$protocol] = true;
1074 if (!empty($protocols['friendica'])) {
1075 $server['network'] = Protocol::DFRN;
1076 } elseif (!empty($protocols['activitypub'])) {
1077 $server['network'] = Protocol::ACTIVITYPUB;
1078 } elseif (!empty($protocols['diaspora'])) {
1079 $server['network'] = Protocol::DIASPORA;
1080 } elseif (!empty($protocols['ostatus'])) {
1081 $server['network'] = Protocol::OSTATUS;
1082 } elseif (!empty($protocols['gnusocial'])) {
1083 $server['network'] = Protocol::OSTATUS;
1084 } elseif (!empty($protocols['zot'])) {
1085 $server['network'] = Protocol::ZOT;
1089 if (empty($server)) {
1093 if (empty($server['network'])) {
1094 $server['network'] = Protocol::PHANTOM;
1103 * @see https://git.feneas.org/jaywink/nodeinfo2
1105 * @param string $nodeinfo_url address of the nodeinfo path
1107 * @return array Server data
1109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1111 private static function parseNodeinfo2(string $nodeinfo_url): array
1113 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1114 if (!$curlResult->isSuccess()) {
1118 $nodeinfo = json_decode($curlResult->getBody(), true);
1119 if (!is_array($nodeinfo)) {
1124 'detection-method' => self::DETECT_NODEINFO_2,
1125 'register_policy' => Register::CLOSED,
1126 'platform' => 'unknown',
1129 if (!empty($nodeinfo['openRegistrations'])) {
1130 $server['register_policy'] = Register::OPEN;
1133 if (!empty($nodeinfo['software'])) {
1134 if (isset($nodeinfo['software']['name'])) {
1135 $server['platform'] = strtolower($nodeinfo['software']['name']);
1138 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1139 $server['version'] = $nodeinfo['software']['version'];
1140 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1141 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1142 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1144 // qoto advertises itself as Mastodon
1145 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1146 $server['platform'] = 'qoto';
1151 if (!empty($nodeinfo['metadata']['nodeName'])) {
1152 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1155 if (!empty($nodeinfo['usage']['users']['total'])) {
1156 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1159 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1160 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1163 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1164 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1167 if (!empty($nodeinfo['usage']['localPosts'])) {
1168 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1171 if (!empty($nodeinfo['usage']['localComments'])) {
1172 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1175 if (!empty($nodeinfo['protocols'])) {
1177 foreach ($nodeinfo['protocols'] as $protocol) {
1178 if (is_string($protocol)) {
1179 $protocols[$protocol] = true;
1183 if (!empty($protocols['dfrn'])) {
1184 $server['network'] = Protocol::DFRN;
1185 } elseif (!empty($protocols['activitypub'])) {
1186 $server['network'] = Protocol::ACTIVITYPUB;
1187 } elseif (!empty($protocols['diaspora'])) {
1188 $server['network'] = Protocol::DIASPORA;
1189 } elseif (!empty($protocols['ostatus'])) {
1190 $server['network'] = Protocol::OSTATUS;
1191 } elseif (!empty($protocols['gnusocial'])) {
1192 $server['network'] = Protocol::OSTATUS;
1193 } elseif (!empty($protocols['zot'])) {
1194 $server['network'] = Protocol::ZOT;
1198 if (empty($server)) {
1202 if (empty($server['network'])) {
1203 $server['network'] = Protocol::PHANTOM;
1210 * Parses NodeInfo2 protocol 1.0
1212 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1214 * @param string $nodeinfo_url address of the nodeinfo path
1216 * @return array Server data
1218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1220 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1222 if (!$httpResult->isSuccess()) {
1226 $nodeinfo = json_decode($httpResult->getBody(), true);
1228 if (!is_array($nodeinfo)) {
1232 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1233 'register_policy' => Register::CLOSED];
1235 if (!empty($nodeinfo['openRegistrations'])) {
1236 $server['register_policy'] = Register::OPEN;
1239 if (!empty($nodeinfo['server'])) {
1240 if (!empty($nodeinfo['server']['software'])) {
1241 $server['platform'] = strtolower($nodeinfo['server']['software']);
1244 if (!empty($nodeinfo['server']['version'])) {
1245 $server['version'] = $nodeinfo['server']['version'];
1246 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1247 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1248 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1251 if (!empty($nodeinfo['server']['name'])) {
1252 $server['site_name'] = $nodeinfo['server']['name'];
1256 if (!empty($nodeinfo['usage']['users']['total'])) {
1257 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1260 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1261 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1264 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1265 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1268 if (!empty($nodeinfo['usage']['localPosts'])) {
1269 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1272 if (!empty($nodeinfo['usage']['localComments'])) {
1273 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1276 if (!empty($nodeinfo['protocols'])) {
1278 foreach ($nodeinfo['protocols'] as $protocol) {
1279 if (is_string($protocol)) {
1280 $protocols[$protocol] = true;
1284 if (!empty($protocols['dfrn'])) {
1285 $server['network'] = Protocol::DFRN;
1286 } elseif (!empty($protocols['activitypub'])) {
1287 $server['network'] = Protocol::ACTIVITYPUB;
1288 } elseif (!empty($protocols['diaspora'])) {
1289 $server['network'] = Protocol::DIASPORA;
1290 } elseif (!empty($protocols['ostatus'])) {
1291 $server['network'] = Protocol::OSTATUS;
1292 } elseif (!empty($protocols['gnusocial'])) {
1293 $server['network'] = Protocol::OSTATUS;
1294 } elseif (!empty($protocols['zot'])) {
1295 $server['network'] = Protocol::ZOT;
1299 if (empty($server) || empty($server['platform'])) {
1303 if (empty($server['network'])) {
1304 $server['network'] = Protocol::PHANTOM;
1311 * Fetch server information from a 'siteinfo.json' file on the given server
1313 * @param string $url URL of the given server
1314 * @param array $serverdata array with server data
1316 * @return array server data
1318 private static function fetchSiteinfo(string $url, array $serverdata): array
1320 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1321 if (!$curlResult->isSuccess()) {
1325 $data = json_decode($curlResult->getBody(), true);
1330 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1331 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1334 if (!empty($data['url'])) {
1335 $serverdata['platform'] = strtolower($data['platform']);
1336 $serverdata['version'] = $data['version'] ?? 'N/A';
1339 if (!empty($data['plugins'])) {
1340 if (in_array('pubcrawl', $data['plugins'])) {
1341 $serverdata['network'] = Protocol::ACTIVITYPUB;
1342 } elseif (in_array('diaspora', $data['plugins'])) {
1343 $serverdata['network'] = Protocol::DIASPORA;
1344 } elseif (in_array('gnusoc', $data['plugins'])) {
1345 $serverdata['network'] = Protocol::OSTATUS;
1347 $serverdata['network'] = Protocol::ZOT;
1351 if (!empty($data['site_name'])) {
1352 $serverdata['site_name'] = $data['site_name'];
1355 if (!empty($data['channels_total'])) {
1356 $serverdata['registered-users'] = max($data['channels_total'], 1);
1359 if (!empty($data['channels_active_monthly'])) {
1360 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1363 if (!empty($data['channels_active_halfyear'])) {
1364 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1367 if (!empty($data['local_posts'])) {
1368 $serverdata['local-posts'] = max($data['local_posts'], 0);
1371 if (!empty($data['local_comments'])) {
1372 $serverdata['local-comments'] = max($data['local_comments'], 0);
1375 if (!empty($data['register_policy'])) {
1376 switch ($data['register_policy']) {
1377 case 'REGISTER_OPEN':
1378 $serverdata['register_policy'] = Register::OPEN;
1381 case 'REGISTER_APPROVE':
1382 $serverdata['register_policy'] = Register::APPROVE;
1385 case 'REGISTER_CLOSED':
1387 $serverdata['register_policy'] = Register::CLOSED;
1396 * Fetches server data via an ActivityPub account with url of that server
1398 * @param string $url URL of the given server
1399 * @param array $serverdata array with server data
1401 * @return array server data
1405 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1408 return ['server' => $serverdata, 'actor' => ''];
1411 $actor = JsonLD::compact($data, false);
1412 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1413 $serverdata['network'] = Protocol::ACTIVITYPUB;
1414 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1415 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1416 if (!empty($actor['as:generator'])) {
1417 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1418 $serverdata['platform'] = strtolower(array_shift($generator));
1419 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1421 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1423 return ['server' => $serverdata, 'actor' => $actor['@id']];
1424 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1425 // By now only Ktistec seems to provide collections this way
1426 $serverdata['platform'] = 'ktistec';
1427 $serverdata['network'] = Protocol::ACTIVITYPUB;
1428 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1430 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1431 if (!empty($actors) && !empty($actors[0]['@id'])) {
1432 $actor_url = $actor['@id'] . $actors[0]['@id'];
1437 return ['server' => $serverdata, 'actor' => $actor_url];
1439 return ['server' => $serverdata, 'actor' => ''];
1443 * Checks if the server contains a valid host meta file
1445 * @param string $url URL of the given server
1447 * @return boolean 'true' if the server seems to be vital
1449 private static function validHostMeta(string $url): bool
1451 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1452 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1453 if (!$curlResult->isSuccess()) {
1457 $xrd = XML::parseString($curlResult->getBody(), true);
1458 if (!is_object($xrd)) {
1462 $elements = XML::elementToArray($xrd);
1463 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1468 foreach ($elements['xrd']['link'] as $link) {
1469 // When there is more than a single "link" element, the array looks slightly different
1470 if (!empty($link['@attributes'])) {
1471 $link = $link['@attributes'];
1474 if (empty($link['rel']) || empty($link['template'])) {
1478 if ($link['rel'] == 'lrdd') {
1479 // When the webfinger host is the same like the system host, it should be ok.
1480 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1488 * Detect the network of the given server via their known contacts
1490 * @param string $url URL of the given server
1491 * @param array $serverdata array with server data
1493 * @return array server data
1495 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1499 $nurl = Strings::normaliseLink($url);
1501 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1502 while ($apcontact = DBA::fetch($apcontacts)) {
1503 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1505 DBA::close($apcontacts);
1507 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1508 while ($pcontact = DBA::fetch($pcontacts)) {
1509 $contacts[$pcontact['nurl']] = $pcontact['url'];
1511 DBA::close($pcontacts);
1513 if (empty($contacts)) {
1518 foreach ($contacts as $contact) {
1519 // Endlosschleife verhindern wegen gsid!
1520 $data = Probe::uri($contact);
1521 if (in_array($data['network'], Protocol::FEDERATED)) {
1522 $serverdata['network'] = $data['network'];
1524 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1525 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1528 } elseif ((time() - $time) > 10) {
1529 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1538 * Checks if the given server does have a '/poco' endpoint.
1539 * This is used for the 'PortableContact' functionality,
1540 * which is used by both Friendica and Hubzilla.
1542 * @param string $url URL of the given server
1543 * @param array $serverdata array with server data
1545 * @return array server data
1547 private static function checkPoCo(string $url, array $serverdata): array
1549 $serverdata['poco'] = '';
1551 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1552 if (!$curlResult->isSuccess()) {
1556 $data = json_decode($curlResult->getBody(), true);
1561 if (!empty($data['totalResults'])) {
1562 $registeredUsers = $serverdata['registered-users'] ?? 0;
1563 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1564 $serverdata['directory-type'] = self::DT_POCO;
1565 $serverdata['poco'] = $url . '/poco';
1572 * Checks if the given server does have a Mastodon style directory endpoint.
1574 * @param string $url URL of the given server
1575 * @param array $serverdata array with server data
1577 * @return array server data
1579 public static function checkMastodonDirectory(string $url, array $serverdata): array
1581 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1582 if (!$curlResult->isSuccess()) {
1586 $data = json_decode($curlResult->getBody(), true);
1591 if (count($data) == 1) {
1592 $serverdata['directory-type'] = self::DT_MASTODON;
1599 * Detects Peertube via their known endpoint
1601 * @param string $url URL of the given server
1602 * @param array $serverdata array with server data
1604 * @return array server data
1606 private static function detectPeertube(string $url, array $serverdata): array
1608 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1609 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1613 $data = json_decode($curlResult->getBody(), true);
1618 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1619 $serverdata['platform'] = 'peertube';
1620 $serverdata['version'] = $data['serverVersion'];
1621 $serverdata['network'] = Protocol::ACTIVITYPUB;
1623 if (!empty($data['instance']['name'])) {
1624 $serverdata['site_name'] = $data['instance']['name'];
1627 if (!empty($data['instance']['shortDescription'])) {
1628 $serverdata['info'] = $data['instance']['shortDescription'];
1631 if (!empty($data['signup'])) {
1632 if (!empty($data['signup']['allowed'])) {
1633 $serverdata['register_policy'] = Register::OPEN;
1637 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1638 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1646 * Detects the version number of a given server when it was a NextCloud installation
1648 * @param string $url URL of the given server
1649 * @param array $serverdata array with server data
1650 * @param bool $validHostMeta
1652 * @return array server data
1654 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1656 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1657 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1661 $data = json_decode($curlResult->getBody(), true);
1666 if (!empty($data['version'])) {
1667 $serverdata['platform'] = 'nextcloud';
1668 $serverdata['version'] = $data['version'];
1670 if ($validHostMeta) {
1671 $serverdata['network'] = Protocol::ACTIVITYPUB;
1674 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1675 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1683 * Fetches weekly usage data
1685 * @param string $url URL of the given server
1686 * @param array $serverdata array with server data
1688 * @return array server data
1690 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1692 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1693 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1697 $data = json_decode($curlResult->getBody(), true);
1703 foreach ($data as $week) {
1704 // Use only data from a full week
1705 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1709 // Most likely the data is sorted correctly. But we better are safe than sorry
1710 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1711 $current_week = $week;
1715 if (!empty($current_week['logins'])) {
1716 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1723 * Detects data from a given server url if it was a mastodon alike system
1725 * @param string $url URL of the given server
1726 * @param array $serverdata array with server data
1728 * @return array server data
1730 private static function detectMastodonAlikes(string $url, array $serverdata): array
1732 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1733 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1737 $data = json_decode($curlResult->getBody(), true);
1744 if (!empty($data['version'])) {
1745 $serverdata['platform'] = 'mastodon';
1746 $serverdata['version'] = $data['version'] ?? '';
1747 $serverdata['network'] = Protocol::ACTIVITYPUB;
1751 if (!empty($data['title'])) {
1752 $serverdata['site_name'] = $data['title'];
1755 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1756 $serverdata['platform'] = 'mastodon';
1757 $serverdata['network'] = Protocol::ACTIVITYPUB;
1761 if (!empty($data['description'])) {
1762 $serverdata['info'] = trim($data['description']);
1765 if (!empty($data['stats']['user_count'])) {
1766 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1769 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1770 $serverdata['platform'] = strtolower($matches[1]);
1771 $serverdata['version'] = $matches[2];
1775 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1776 $serverdata['platform'] = 'pleroma';
1777 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1781 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1782 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1783 $serverdata['platform'] = 'pleroma';
1787 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1788 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1795 * Detects data from typical Hubzilla endpoints
1797 * @param string $url URL of the given server
1798 * @param array $serverdata array with server data
1800 * @return array server data
1802 private static function detectHubzilla(string $url, array $serverdata): array
1804 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1805 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1809 $data = json_decode($curlResult->getBody(), true);
1810 if (empty($data) || empty($data['site'])) {
1814 if (!empty($data['site']['name'])) {
1815 $serverdata['site_name'] = $data['site']['name'];
1818 if (!empty($data['site']['platform'])) {
1819 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1820 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1821 $serverdata['network'] = Protocol::ZOT;
1824 if (!empty($data['site']['hubzilla'])) {
1825 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1826 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1827 $serverdata['network'] = Protocol::ZOT;
1830 if (!empty($data['site']['redmatrix'])) {
1831 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1832 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1833 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1834 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1837 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1838 $serverdata['network'] = Protocol::ZOT;
1842 $inviteonly = false;
1845 if (!empty($data['site']['closed'])) {
1846 $closed = self::toBoolean($data['site']['closed']);
1849 if (!empty($data['site']['private'])) {
1850 $private = self::toBoolean($data['site']['private']);
1853 if (!empty($data['site']['inviteonly'])) {
1854 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1857 if (!$closed && !$private and $inviteonly) {
1858 $serverdata['register_policy'] = Register::APPROVE;
1859 } elseif (!$closed && !$private) {
1860 $serverdata['register_policy'] = Register::OPEN;
1862 $serverdata['register_policy'] = Register::CLOSED;
1865 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1866 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1873 * Converts input value to a boolean value
1875 * @param string|integer $val
1879 private static function toBoolean($val): bool
1881 if (($val == 'true') || ($val == 1)) {
1883 } elseif (($val == 'false') || ($val == 0)) {
1891 * Detect if the URL belongs to a GNU Social server
1893 * @param string $url URL of the given server
1894 * @param array $serverdata array with server data
1896 * @return array server data
1898 private static function detectGNUSocial(string $url, array $serverdata): array
1900 // Test for GNU Social
1901 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1902 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1903 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1904 $serverdata['platform'] = 'gnusocial';
1905 // Remove junk that some GNU Social servers return
1906 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1907 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1908 $serverdata['version'] = trim($serverdata['version'], '"');
1909 $serverdata['network'] = Protocol::OSTATUS;
1911 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1912 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1918 // Test for Statusnet
1919 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1920 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1921 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1923 // Remove junk that some GNU Social servers return
1924 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1925 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1926 $serverdata['version'] = trim($serverdata['version'], '"');
1928 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1929 $serverdata['platform'] = 'pleroma';
1930 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1931 $serverdata['network'] = Protocol::ACTIVITYPUB;
1933 $serverdata['platform'] = 'statusnet';
1934 $serverdata['network'] = Protocol::OSTATUS;
1937 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1938 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1946 * Detect if the URL belongs to a Friendica server
1948 * @param string $url URL of the given server
1949 * @param array $serverdata array with server data
1951 * @return array server data
1953 private static function detectFriendica(string $url, array $serverdata): array
1955 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1956 // Because of this me must not use ACCEPT_JSON here.
1957 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1958 if (!$curlResult->isSuccess()) {
1959 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1961 $platform = 'Friendika';
1964 $platform = 'Friendica';
1967 if (!$curlResult->isSuccess()) {
1971 $data = json_decode($curlResult->getBody(), true);
1972 if (empty($data) || empty($data['version'])) {
1976 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1977 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1980 $serverdata['network'] = Protocol::DFRN;
1981 $serverdata['version'] = $data['version'];
1983 if (!empty($data['no_scrape_url'])) {
1984 $serverdata['noscrape'] = $data['no_scrape_url'];
1987 if (!empty($data['site_name'])) {
1988 $serverdata['site_name'] = $data['site_name'];
1991 if (!empty($data['info'])) {
1992 $serverdata['info'] = trim($data['info']);
1995 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1996 switch ($register_policy) {
1997 case 'REGISTER_OPEN':
1998 $serverdata['register_policy'] = Register::OPEN;
2001 case 'REGISTER_APPROVE':
2002 $serverdata['register_policy'] = Register::APPROVE;
2005 case 'REGISTER_CLOSED':
2006 case 'REGISTER_INVITATION':
2007 $serverdata['register_policy'] = Register::CLOSED;
2010 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2011 $serverdata['register_policy'] = Register::CLOSED;
2015 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2021 * Analyses the landing page of a given server for hints about type and system of that server
2023 * @param object $curlResult result of curl execution
2024 * @param array $serverdata array with server data
2026 * @return array server data
2028 private static function analyseRootBody($curlResult, array $serverdata): array
2030 if (empty($curlResult->getBody())) {
2034 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2035 require __DIR__ . '/../../static/platforms.config.php';
2037 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2040 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2042 $doc = new DOMDocument();
2043 @$doc->loadHTML($curlResult->getBody());
2044 $xpath = new DOMXPath($doc);
2047 // We can only detect honk via some HTML element on their page
2048 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2049 $serverdata['platform'] = 'honk';
2050 $serverdata['network'] = Protocol::ACTIVITYPUB;
2054 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2055 if (!empty($title)) {
2056 $serverdata['site_name'] = $title;
2059 $list = $xpath->query('//meta[@name]');
2061 foreach ($list as $node) {
2063 if ($node->attributes->length) {
2064 foreach ($node->attributes as $attribute) {
2065 $value = trim($attribute->value);
2066 if (empty($value)) {
2070 $attr[$attribute->name] = $value;
2073 if (empty($attr['name']) || empty($attr['content'])) {
2078 if ($attr['name'] == 'description') {
2079 $serverdata['info'] = $attr['content'];
2082 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2083 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2084 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2085 $platform = str_replace('/', ' ', $platform);
2086 $platform_parts = explode(' ', $platform);
2087 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2088 $platform = $platform_parts[0];
2089 $serverdata['version'] = $platform_parts[1];
2091 if (in_array($platform, array_values($dfrn_platforms))) {
2092 $serverdata['network'] = Protocol::DFRN;
2093 } elseif (in_array($platform, array_values($ap_platforms))) {
2094 $serverdata['network'] = Protocol::ACTIVITYPUB;
2095 } elseif (in_array($platform, array_values($zap_platforms))) {
2096 $serverdata['network'] = Protocol::ZOT;
2098 if (in_array($platform, array_values($platforms))) {
2099 $serverdata['platform'] = $platform;
2105 $list = $xpath->query('//meta[@property]');
2107 foreach ($list as $node) {
2109 if ($node->attributes->length) {
2110 foreach ($node->attributes as $attribute) {
2111 $value = trim($attribute->value);
2112 if (empty($value)) {
2116 $attr[$attribute->name] = $value;
2119 if (empty($attr['property']) || empty($attr['content'])) {
2124 if ($attr['property'] == 'og:site_name') {
2125 $serverdata['site_name'] = $attr['content'];
2128 if ($attr['property'] == 'og:description') {
2129 $serverdata['info'] = $attr['content'];
2132 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2133 if (in_array($attr['content'], array_keys($platforms))) {
2134 $serverdata['platform'] = $platforms[$attr['content']];
2138 if (in_array($attr['content'], array_keys($ap_platforms))) {
2139 $serverdata['network'] = Protocol::ACTIVITYPUB;
2140 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2141 $serverdata['network'] = Protocol::ZOT;
2146 $list = $xpath->query('//link[@rel="me"]');
2147 foreach ($list as $node) {
2148 foreach ($node->attributes as $attribute) {
2149 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2150 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2151 $serverdata['platform'] = 'microblog';
2152 $serverdata['network'] = Protocol::ACTIVITYPUB;
2158 if ($serverdata['platform'] != 'microblog') {
2159 $list = $xpath->query('//link[@rel="micropub"]');
2160 foreach ($list as $node) {
2161 foreach ($node->attributes as $attribute) {
2162 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2163 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2164 $serverdata['platform'] = 'microblog';
2165 $serverdata['network'] = Protocol::ACTIVITYPUB;
2172 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2173 $serverdata['detection-method'] = self::DETECT_BODY;
2180 * Analyses the header data of a given server for hints about type and system of that server
2182 * @param object $curlResult result of curl execution
2183 * @param array $serverdata array with server data
2185 * @return array server data
2187 private static function analyseRootHeader($curlResult, array $serverdata): array
2189 if ($curlResult->getHeader('server') == 'Mastodon') {
2190 $serverdata['platform'] = 'mastodon';
2191 $serverdata['network'] = Protocol::ACTIVITYPUB;
2192 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2193 $serverdata['platform'] = 'diaspora';
2194 $serverdata['network'] = Protocol::DIASPORA;
2195 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2196 } elseif ($curlResult->inHeader('x-friendica-version')) {
2197 $serverdata['platform'] = 'friendica';
2198 $serverdata['network'] = Protocol::DFRN;
2199 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2204 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2205 $serverdata['detection-method'] = self::DETECT_HEADER;
2212 * Update GServer entries
2214 public static function discover()
2216 // Update the server list
2217 self::discoverFederation();
2221 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2223 if ($requery_days == 0) {
2227 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2229 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2230 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2231 ['order' => ['RAND()']]);
2233 while ($gserver = DBA::fetch($gservers)) {
2234 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2235 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2237 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2238 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2240 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2241 self::update($fields, ['nurl' => $gserver['nurl']]);
2243 if (--$no_of_queries == 0) {
2248 DBA::close($gservers);
2252 * Discover federated servers
2254 private static function discoverFederation()
2256 $last = DI::keyValue()->get('poco_last_federation_discovery');
2259 $next = $last + (24 * 60 * 60);
2261 if ($next > time()) {
2266 // Discover federated servers
2267 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2268 foreach ($protocols as $protocol) {
2269 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2270 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2271 if (!empty($curlResult)) {
2272 $data = json_decode($curlResult, true);
2273 if (!empty($data['data']['nodes'])) {
2274 foreach ($data['data']['nodes'] as $server) {
2275 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2276 self::add('https://' . $server['host'], true);
2282 // Disvover Mastodon servers
2283 $accesstoken = DI::config()->get('system', 'instances_social_key');
2285 if (!empty($accesstoken)) {
2286 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2287 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2288 if ($curlResult->isSuccess()) {
2289 $servers = json_decode($curlResult->getBody(), true);
2291 if (!empty($servers['instances'])) {
2292 foreach ($servers['instances'] as $server) {
2293 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2300 DI::keyValue()->set('poco_last_federation_discovery', time());
2304 * Set the protocol for the given server
2306 * @param int $gsid Server id
2307 * @param int $protocol Protocol id
2311 public static function setProtocol(int $gsid, int $protocol)
2317 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2318 if (!DBA::isResult($gserver)) {
2322 $old = $gserver['protocol'];
2324 if (!is_null($old)) {
2326 The priority for the protocols is:
2328 2. DFRN via Diaspora
2334 // We don't need to change it when nothing is to be changed
2335 if ($old == $protocol) {
2339 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2340 if ($protocol == Post\DeliveryData::OSTATUS) {
2344 // If the server is marked as ActivityPub then we won't change it to anything different
2345 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2349 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2350 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2354 // Don't change it to Diaspora when it is a legacy DFRN server
2355 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2360 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2361 self::update(['protocol' => $protocol], ['id' => $gsid]);
2365 * Fetch the protocol of the given server
2367 * @param int $gsid Server id
2369 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2373 public static function getProtocol(int $gsid): ?int
2379 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2380 if (DBA::isResult($gserver)) {
2381 return $gserver['protocol'];
2388 * Update rows in the gserver table.
2389 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2391 * @param array $fields
2392 * @param array $condition
2398 public static function update(array $fields, array $condition): bool
2400 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2402 return DBA::update('gserver', $fields, $condition);
2406 * Insert a row into the gserver table.
2407 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2409 * @param array $fields
2410 * @param int $duplicate_mode What to do on a duplicated entry
2416 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2418 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2420 return DBA::insert('gserver', $fields, $duplicate_mode);