3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Relay;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
46 use Friendica\Network\HTTPException;
47 use GuzzleHttp\Psr7\Uri;
50 * This class handles GServer related functions
57 const DT_MASTODON = 2;
59 // Methods to detect server types
61 // Non endpoint specific methods
62 const DETECT_MANUAL = 0;
63 const DETECT_HEADER = 1;
64 const DETECT_BODY = 2;
65 const DETECT_HOST_META = 3;
66 const DETECT_CONTACTS = 4;
67 const DETECT_AP_ACTOR = 5;
68 const DETECT_AP_COLLECTION = 6;
70 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
72 // Implementation specific endpoints
73 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
74 const DETECT_FRIENDIKA = 10;
75 const DETECT_FRIENDICA = 11;
76 const DETECT_STATUSNET = 12;
77 const DETECT_GNUSOCIAL = 13;
78 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
79 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
80 const DETECT_MASTODON_API = 16;
81 const DETECT_STATUS_PHP = 17; // Nextcloud
82 const DETECT_V1_CONFIG = 18;
83 const DETECT_PUMPIO = 19; // Deprecated
84 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
86 // Standardized endpoints
87 const DETECT_STATISTICS_JSON = 100;
88 const DETECT_NODEINFO_1 = 101;
89 const DETECT_NODEINFO_2 = 102;
90 const DETECT_NODEINFO_210 = 103;
93 * Check for the existance of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
100 public static function add(string $url, bool $only_nodeinfo = false)
102 if (self::getID($url, false)) {
106 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
110 * Get the ID for the given server URL
113 * @param boolean $no_check Don't check if the server hadn't been found
115 * @return int|null gserver id or NULL on empty URL or failed check
117 public static function getID(string $url, bool $no_check = false): ?int
119 $url = self::cleanURL($url);
125 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
126 if (DBA::isResult($gserver)) {
127 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
128 return $gserver['id'];
131 if ($no_check || !self::check($url)) {
135 return self::getID($url, true);
139 * Retrieves all the servers which base domain are matching the provided domain pattern
141 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
143 * @param string $pattern
149 public static function listByDomainPattern(string $pattern): array
151 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
153 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
154 // eventual server path and keep only the server domain which we're matching against the pattern.
155 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
157 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
158 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
159 AND NOT `gserver`.`failed`
160 GROUP BY `gserver`.`id`";
162 $stmt = DI::dba()->p($sql, $likePattern);
164 return DI::dba()->toArray($stmt);
168 * Checks if the given server array is unreachable for a long time now
170 * @param integer $gsid
173 private static function isDefunct(array $gserver): bool
175 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
176 ($gserver['last_contact'] >= $gserver['created']) &&
177 ($gserver['last_contact'] < $gserver['last_failure']) &&
178 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
182 * Checks if the given server id is unreachable for a long time now
184 * @param integer $gsid
187 public static function isDefunctById(int $gsid): bool
189 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
190 if (empty($gserver)) {
193 if (strtotime($gserver['next_contact']) < time()) {
194 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
196 return self::isDefunct($gserver);
201 * Checks if the given server id is reachable
203 * @param integer $gsid
206 public static function isReachableById(int $gsid): bool
208 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
209 if (empty($gserver)) {
212 if (strtotime($gserver['next_contact']) < time()) {
213 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
215 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
220 * Checks if the given server is reachable
222 * @param array $contact Contact that should be checked
224 * @return boolean 'true' if server seems vital
226 public static function reachable(array $contact): bool
228 if (!empty($contact['gsid'])) {
229 $gsid = $contact['gsid'];
230 } elseif (!empty($contact['baseurl'])) {
231 $server = $contact['baseurl'];
232 } elseif ($contact['network'] == Protocol::DIASPORA) {
233 $parts = parse_url($contact['url']);
234 unset($parts['path']);
235 $server = (string)Uri::fromParts($parts);
241 $condition = ['id' => $gsid];
243 $condition = ['nurl' => Strings::normaliseLink($server)];
246 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
247 if (empty($gserver)) {
250 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
251 $server = $gserver['url'];
254 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
255 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $server, false);
262 * Calculate the next update day
264 * @param bool $success
265 * @param string $created
266 * @param string $last_contact
267 * @param bool $undetected
273 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
275 // On successful contact process check again next week when it is a detected system.
276 // When we haven't detected the system, it could be a static website or a really old system.
278 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
281 $now = strtotime(DateTimeFormat::utcNow());
283 if ($created > $last_contact) {
284 $contact_time = strtotime($created);
286 $contact_time = strtotime($last_contact);
289 // If the last contact was less than 6 hours before then try again in 6 hours
290 if (($now - $contact_time) < (60 * 60 * 6)) {
291 return DateTimeFormat::utc('now +6 hour');
294 // If the last contact was less than 12 hours before then try again in 12 hours
295 if (($now - $contact_time) < (60 * 60 * 12)) {
296 return DateTimeFormat::utc('now +12 hour');
299 // If the last contact was less than 24 hours before then try tomorrow again
300 if (($now - $contact_time) < (60 * 60 * 24)) {
301 return DateTimeFormat::utc('now +1 day');
304 // If the last contact was less than a week before then try again in a week
305 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
306 return DateTimeFormat::utc('now +1 week');
309 // If the last contact was less than two weeks before then try again in two week
310 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
311 return DateTimeFormat::utc('now +2 week');
314 // If the last contact was less than a month before then try again in a month
315 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
316 return DateTimeFormat::utc('now +1 month');
319 // The system hadn't been successul contacted for more than a month, so try again in three months
320 return DateTimeFormat::utc('now +3 month');
324 * Checks the state of the given server.
326 * @param string $server_url URL of the given server
327 * @param string $network Network value that is used, when detection failed
328 * @param boolean $force Force an update.
329 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
331 * @return boolean 'true' if server seems vital
333 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
335 $server_url = self::cleanURL($server_url);
336 if ($server_url == '') {
340 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
341 if (DBA::isResult($gserver)) {
342 if ($gserver['created'] <= DBA::NULL_DATETIME) {
343 $fields = ['created' => DateTimeFormat::utcNow()];
344 $condition = ['nurl' => Strings::normaliseLink($server_url)];
345 self::update($fields, $condition);
348 if (!$force && (strtotime($gserver['next_contact']) > time())) {
349 Logger::info('No update needed', ['server' => $server_url]);
350 return (!$gserver['failed']);
352 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
354 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
357 return self::detect($server_url, $network, $only_nodeinfo);
361 * Reset failed server status by gserver id
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 Contact::update(['archive' => true], ['gsid' => $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 * Remove unwanted content from the given URL
424 * @param string $dirtyUrl
426 * @return string cleaned URL
429 public static function cleanURL(string $dirtyUrl): string
432 $url = str_replace('/index.php', '', trim($dirtyUrl, '/'));
433 return (string)(new Uri($url))->withUserInfo('')->withQuery('')->withFragment('');
434 } catch (\Throwable $e) {
435 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl, 'url' => $url]);
441 * Detect server data (type, protocol, version number, ...)
442 * The detected data is then updated or inserted in the gserver table.
444 * @param string $url URL of the given server
445 * @param string $network Network value that is used, when detection failed
446 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
448 * @return boolean 'true' if server could be detected
450 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
452 Logger::info('Detect server type', ['server' => $url]);
454 $original_url = $url;
456 // Remove URL content that is not supposed to exist for a server url
457 $url = rtrim(self::cleanURL($url), '/');
459 Logger::notice('Empty URL.');
463 // If the URL missmatches, then we mark the old entry as failure
464 if (!Strings::compareLink($url, $original_url)) {
465 self::setFailureByUrl($original_url);
466 if (!self::getID($url, true)) {
467 self::detect($url, $network, $only_nodeinfo);
472 $valid_url = Network::isUrlValid($url);
474 self::setFailureByUrl($url);
477 $valid_url = rtrim($valid_url, '/');
480 if (!Strings::compareLink($url, $valid_url)) {
481 // We only follow redirects when the path stays the same or the target url has no path.
482 // Some systems have got redirects on their landing page to a single account page. This check handles it.
483 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))) ||
484 (((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)))) {
485 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
486 self::setFailureByUrl($url);
487 if (!self::getID($valid_url, true)) {
488 self::detect($valid_url, $network, $only_nodeinfo);
493 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)) &&
494 (parse_url($url, PHP_URL_PATH) == '')) {
495 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
496 $parts = parse_url($valid_url);
497 unset($parts['path']);
498 $valid_url = (string)Uri::fromParts($parts);
500 self::setFailureByUrl($url);
501 if (!self::getID($valid_url, true)) {
502 self::detect($valid_url, $network, $only_nodeinfo);
506 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
509 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
510 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
511 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
515 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
517 // When a nodeinfo is present, we don't need to dig further
518 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
519 if ($curlResult->isTimeout()) {
520 self::setFailureByUrl($url);
524 $serverdata = self::parseNodeinfo210($curlResult);
525 if (empty($serverdata)) {
526 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
527 $serverdata = self::fetchNodeinfo($url, $curlResult);
530 if ($only_nodeinfo && empty($serverdata)) {
531 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
532 self::setFailureByUrl($url);
534 } elseif (empty($serverdata)) {
535 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
538 // When there is no Nodeinfo, then use some protocol specific endpoints
539 if ($serverdata['network'] == Protocol::PHANTOM) {
541 // Fetch the landing page, possibly it reveals some data
542 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
543 $curlResult = DI::httpClient()->get($url, $accept);
544 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
545 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
546 $html_fetched = true;
548 $html_fetched = false;
551 if ($curlResult->isSuccess()) {
552 $json = json_decode($curlResult->getBody(), true);
553 if (!empty($json) && is_array($json)) {
554 $data = self::fetchDataFromSystemActor($json, $serverdata);
555 $serverdata = $data['server'];
556 $systemactor = $data['actor'];
557 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
558 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
560 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
561 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
564 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
565 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
566 $serverdata = self::analyseRootBody($curlResult, $serverdata);
570 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
571 self::setFailureByUrl($url);
575 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
576 $serverdata = self::detectMastodonAlikes($url, $serverdata);
580 // All following checks are done for systems that always have got a "host-meta" endpoint.
581 // With this check we don't have to waste time and ressources for dead systems.
582 // Also this hopefully prevents us from receiving abuse messages.
583 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
584 $validHostMeta = self::validHostMeta($url);
586 $validHostMeta = false;
589 if ($validHostMeta) {
590 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
591 $serverdata['detection-method'] = self::DETECT_HOST_META;
594 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
595 $serverdata = self::detectFriendica($url, $serverdata);
598 // The following systems have to be installed in the root directory.
600 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
601 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
602 $serverdata = self::fetchSiteinfo($url, $serverdata);
605 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
606 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
607 $serverdata = self::detectHubzilla($url, $serverdata);
610 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
611 $serverdata = self::detectPeertube($url, $serverdata);
614 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
615 $serverdata = self::detectGNUSocial($url, $serverdata);
618 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
619 $serverdata = self::detectFriendica($url, $serverdata);
622 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
623 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
626 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
627 // Since this endpoint is only rarely used, we query it at a later time
628 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
629 $serverdata = self::fetchStatistics($url, $serverdata);
633 // When we hadn't been able to detect the network type, we use the hint from the parameter
634 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
635 $serverdata['network'] = $network;
638 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
639 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
640 self::setFailureByUrl($url);
644 $serverdata['url'] = $url;
645 $serverdata['nurl'] = Strings::normaliseLink($url);
647 // We have to prevent an endless loop here.
648 // When a server is new, then there is no gserver entry yet.
649 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
650 // and this can call this function here as well.
651 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
652 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
653 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
656 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
657 self::setFailureByUrl($url);
661 // Detect the directory type
662 $serverdata['directory-type'] = self::DT_NONE;
664 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
665 $serverdata = self::checkMastodonDirectory($url, $serverdata);
667 if ($serverdata['directory-type'] == self::DT_NONE) {
668 $serverdata = self::checkPoCo($url, $serverdata);
672 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
673 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
676 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
678 // Numbers above a reasonable value (10 millions) are ignored
679 if ($serverdata['registered-users'] > 10000000) {
680 $serverdata['registered-users'] = 0;
683 // On an active server there has to be at least a single user
684 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
685 $serverdata['registered-users'] = 1;
686 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
687 $serverdata['registered-users'] = 0;
690 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
692 $serverdata['last_contact'] = DateTimeFormat::utcNow();
693 $serverdata['failed'] = false;
695 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
696 if (!DBA::isResult($gserver)) {
697 $serverdata['created'] = DateTimeFormat::utcNow();
698 $ret = self::insert($serverdata);
699 $id = DBA::lastInsertId();
701 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
702 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
703 if (DBA::isResult($gserver)) {
704 $id = $gserver['id'];
708 // Count the number of known contacts from this server
709 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
710 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
711 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
712 $max_users = max($apcontacts, $contacts);
713 if ($max_users > $serverdata['registered-users']) {
714 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
715 self::update(['registered-users' => $max_users], ['id' => $id]);
718 if (empty($serverdata['active-month-users'])) {
719 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
721 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
722 self::update(['active-month-users' => $contacts], ['id' => $id]);
726 if (empty($serverdata['active-halfyear-users'])) {
727 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
729 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
730 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
735 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
736 self::discoverRelay($url);
739 if (!empty($systemactor)) {
740 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
741 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
748 * Fetch relay data from a given server url
750 * @param string $server_url address of the server
754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
756 private static function discoverRelay(string $server_url)
758 Logger::info('Discover relay data', ['server' => $server_url]);
760 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
761 if (!$curlResult->isSuccess()) {
765 $data = json_decode($curlResult->getBody(), true);
766 if (!is_array($data)) {
770 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
771 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
773 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
775 $data['subscribe'] = false;
779 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
780 if (!DBA::isResult($gserver)) {
784 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
785 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
786 self::update($fields, ['id' => $gserver['id']]);
789 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
791 if ($data['scope'] == 'tags') {
794 foreach ($data['tags'] as $tag) {
795 $tag = mb_strtolower($tag);
796 if (strlen($tag) < 100) {
801 foreach ($tags as $tag) {
802 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
806 // Create or update the relay contact
808 if (isset($data['protocols'])) {
809 if (isset($data['protocols']['diaspora'])) {
810 $fields['network'] = Protocol::DIASPORA;
812 if (isset($data['protocols']['diaspora']['receive'])) {
813 $fields['batch'] = $data['protocols']['diaspora']['receive'];
814 } elseif (is_string($data['protocols']['diaspora'])) {
815 $fields['batch'] = $data['protocols']['diaspora'];
819 if (isset($data['protocols']['dfrn'])) {
820 $fields['network'] = Protocol::DFRN;
822 if (isset($data['protocols']['dfrn']['receive'])) {
823 $fields['batch'] = $data['protocols']['dfrn']['receive'];
824 } elseif (is_string($data['protocols']['dfrn'])) {
825 $fields['batch'] = $data['protocols']['dfrn'];
829 if (isset($data['protocols']['activitypub'])) {
830 $fields['network'] = Protocol::ACTIVITYPUB;
832 if (!empty($data['protocols']['activitypub']['actor'])) {
833 $fields['url'] = $data['protocols']['activitypub']['actor'];
835 if (!empty($data['protocols']['activitypub']['receive'])) {
836 $fields['batch'] = $data['protocols']['activitypub']['receive'];
841 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
843 Relay::updateContact($gserver, $fields);
847 * Fetch server data from '/statistics.json' on the given server
849 * @param string $url URL of the given server
851 * @return array server data
853 private static function fetchStatistics(string $url, array $serverdata): array
855 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
856 if (!$curlResult->isSuccess()) {
860 $data = json_decode($curlResult->getBody(), true);
865 // Some AP enabled systems return activity data that we don't expect here.
866 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
871 $old_serverdata = $serverdata;
873 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
875 if (!empty($data['version'])) {
877 $serverdata['version'] = $data['version'];
878 // Version numbers on statistics.json are presented with additional info, e.g.:
879 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
880 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
883 if (!empty($data['name'])) {
885 $serverdata['site_name'] = $data['name'];
888 if (!empty($data['network'])) {
890 $serverdata['platform'] = strtolower($data['network']);
892 if ($serverdata['platform'] == 'diaspora') {
893 $serverdata['network'] = Protocol::DIASPORA;
894 } elseif ($serverdata['platform'] == 'friendica') {
895 $serverdata['network'] = Protocol::DFRN;
896 } elseif ($serverdata['platform'] == 'hubzilla') {
897 $serverdata['network'] = Protocol::ZOT;
898 } elseif ($serverdata['platform'] == 'redmatrix') {
899 $serverdata['network'] = Protocol::ZOT;
903 if (!empty($data['total_users'])) {
905 $serverdata['registered-users'] = max($data['total_users'], 1);
908 if (!empty($data['active_users_monthly'])) {
910 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
913 if (!empty($data['active_users_halfyear'])) {
915 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
918 if (!empty($data['local_posts'])) {
920 $serverdata['local-posts'] = max($data['local_posts'], 0);
923 if (!empty($data['registrations_open'])) {
924 $serverdata['register_policy'] = Register::OPEN;
926 $serverdata['register_policy'] = Register::CLOSED;
930 return $old_serverdata;
937 * Detect server type by using the nodeinfo data
939 * @param string $url address of the server
940 * @param ICanHandleHttpResponses $httpResult
942 * @return array Server data
944 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
946 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
948 if (!$httpResult->isSuccess()) {
952 $nodeinfo = json_decode($httpResult->getBody(), true);
954 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
961 foreach ($nodeinfo['links'] as $link) {
962 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
963 Logger::info('Invalid nodeinfo format', ['url' => $url]);
966 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
967 $nodeinfo1_url = $link['href'];
968 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
969 $nodeinfo2_url = $link['href'];
973 if ($nodeinfo1_url . $nodeinfo2_url == '') {
979 if (!empty($nodeinfo2_url)) {
980 $server = self::parseNodeinfo2($nodeinfo2_url);
983 if (empty($server) && !empty($nodeinfo1_url)) {
984 $server = self::parseNodeinfo1($nodeinfo1_url);
993 * @param string $nodeinfo_url address of the nodeinfo path
995 * @return array Server data
997 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
999 private static function parseNodeinfo1(string $nodeinfo_url): array
1001 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1002 if (!$curlResult->isSuccess()) {
1006 $nodeinfo = json_decode($curlResult->getBody(), true);
1008 if (!is_array($nodeinfo)) {
1012 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1013 'register_policy' => Register::CLOSED];
1015 if (!empty($nodeinfo['openRegistrations'])) {
1016 $server['register_policy'] = Register::OPEN;
1019 if (is_array($nodeinfo['software'])) {
1020 if (!empty($nodeinfo['software']['name'])) {
1021 $server['platform'] = strtolower($nodeinfo['software']['name']);
1024 if (!empty($nodeinfo['software']['version'])) {
1025 $server['version'] = $nodeinfo['software']['version'];
1026 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1027 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1028 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1032 if (!empty($nodeinfo['metadata']['nodeName'])) {
1033 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1036 if (!empty($nodeinfo['usage']['users']['total'])) {
1037 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1040 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1041 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1044 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1045 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1048 if (!empty($nodeinfo['usage']['localPosts'])) {
1049 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1052 if (!empty($nodeinfo['usage']['localComments'])) {
1053 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1056 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1058 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1059 $protocols[$protocol] = true;
1062 if (!empty($protocols['friendica'])) {
1063 $server['network'] = Protocol::DFRN;
1064 } elseif (!empty($protocols['activitypub'])) {
1065 $server['network'] = Protocol::ACTIVITYPUB;
1066 } elseif (!empty($protocols['diaspora'])) {
1067 $server['network'] = Protocol::DIASPORA;
1068 } elseif (!empty($protocols['ostatus'])) {
1069 $server['network'] = Protocol::OSTATUS;
1070 } elseif (!empty($protocols['gnusocial'])) {
1071 $server['network'] = Protocol::OSTATUS;
1072 } elseif (!empty($protocols['zot'])) {
1073 $server['network'] = Protocol::ZOT;
1077 if (empty($server)) {
1081 if (empty($server['network'])) {
1082 $server['network'] = Protocol::PHANTOM;
1091 * @see https://git.feneas.org/jaywink/nodeinfo2
1093 * @param string $nodeinfo_url address of the nodeinfo path
1095 * @return array Server data
1097 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1099 private static function parseNodeinfo2(string $nodeinfo_url): array
1101 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1102 if (!$curlResult->isSuccess()) {
1106 $nodeinfo = json_decode($curlResult->getBody(), true);
1107 if (!is_array($nodeinfo)) {
1112 'detection-method' => self::DETECT_NODEINFO_2,
1113 'register_policy' => Register::CLOSED,
1114 'platform' => 'unknown',
1117 if (!empty($nodeinfo['openRegistrations'])) {
1118 $server['register_policy'] = Register::OPEN;
1121 if (!empty($nodeinfo['software'])) {
1122 if (isset($nodeinfo['software']['name'])) {
1123 $server['platform'] = strtolower($nodeinfo['software']['name']);
1126 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1127 $server['version'] = $nodeinfo['software']['version'];
1128 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1129 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1130 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1132 // qoto advertises itself as Mastodon
1133 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1134 $server['platform'] = 'qoto';
1139 if (!empty($nodeinfo['metadata']['nodeName'])) {
1140 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1143 if (!empty($nodeinfo['usage']['users']['total'])) {
1144 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1147 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1148 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1151 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1152 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1155 if (!empty($nodeinfo['usage']['localPosts'])) {
1156 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1159 if (!empty($nodeinfo['usage']['localComments'])) {
1160 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1163 if (!empty($nodeinfo['protocols'])) {
1165 foreach ($nodeinfo['protocols'] as $protocol) {
1166 if (is_string($protocol)) {
1167 $protocols[$protocol] = true;
1171 if (!empty($protocols['dfrn'])) {
1172 $server['network'] = Protocol::DFRN;
1173 } elseif (!empty($protocols['activitypub'])) {
1174 $server['network'] = Protocol::ACTIVITYPUB;
1175 } elseif (!empty($protocols['diaspora'])) {
1176 $server['network'] = Protocol::DIASPORA;
1177 } elseif (!empty($protocols['ostatus'])) {
1178 $server['network'] = Protocol::OSTATUS;
1179 } elseif (!empty($protocols['gnusocial'])) {
1180 $server['network'] = Protocol::OSTATUS;
1181 } elseif (!empty($protocols['zot'])) {
1182 $server['network'] = Protocol::ZOT;
1186 if (empty($server)) {
1190 if (empty($server['network'])) {
1191 $server['network'] = Protocol::PHANTOM;
1198 * Parses NodeInfo2 protocol 1.0
1200 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1202 * @param string $nodeinfo_url address of the nodeinfo path
1204 * @return array Server data
1206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1208 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1210 if (!$httpResult->isSuccess()) {
1214 $nodeinfo = json_decode($httpResult->getBody(), true);
1216 if (!is_array($nodeinfo)) {
1220 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1221 'register_policy' => Register::CLOSED];
1223 if (!empty($nodeinfo['openRegistrations'])) {
1224 $server['register_policy'] = Register::OPEN;
1227 if (!empty($nodeinfo['server'])) {
1228 if (!empty($nodeinfo['server']['software'])) {
1229 $server['platform'] = strtolower($nodeinfo['server']['software']);
1232 if (!empty($nodeinfo['server']['version'])) {
1233 $server['version'] = $nodeinfo['server']['version'];
1234 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1235 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1236 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1239 if (!empty($nodeinfo['server']['name'])) {
1240 $server['site_name'] = $nodeinfo['server']['name'];
1244 if (!empty($nodeinfo['usage']['users']['total'])) {
1245 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1248 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1249 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1252 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1253 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1256 if (!empty($nodeinfo['usage']['localPosts'])) {
1257 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1260 if (!empty($nodeinfo['usage']['localComments'])) {
1261 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1264 if (!empty($nodeinfo['protocols'])) {
1266 foreach ($nodeinfo['protocols'] as $protocol) {
1267 if (is_string($protocol)) {
1268 $protocols[$protocol] = true;
1272 if (!empty($protocols['dfrn'])) {
1273 $server['network'] = Protocol::DFRN;
1274 } elseif (!empty($protocols['activitypub'])) {
1275 $server['network'] = Protocol::ACTIVITYPUB;
1276 } elseif (!empty($protocols['diaspora'])) {
1277 $server['network'] = Protocol::DIASPORA;
1278 } elseif (!empty($protocols['ostatus'])) {
1279 $server['network'] = Protocol::OSTATUS;
1280 } elseif (!empty($protocols['gnusocial'])) {
1281 $server['network'] = Protocol::OSTATUS;
1282 } elseif (!empty($protocols['zot'])) {
1283 $server['network'] = Protocol::ZOT;
1287 if (empty($server) || empty($server['platform'])) {
1291 if (empty($server['network'])) {
1292 $server['network'] = Protocol::PHANTOM;
1299 * Fetch server information from a 'siteinfo.json' file on the given server
1301 * @param string $url URL of the given server
1302 * @param array $serverdata array with server data
1304 * @return array server data
1306 private static function fetchSiteinfo(string $url, array $serverdata): array
1308 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1309 if (!$curlResult->isSuccess()) {
1313 $data = json_decode($curlResult->getBody(), true);
1318 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1319 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1322 if (!empty($data['url'])) {
1323 $serverdata['platform'] = strtolower($data['platform']);
1324 $serverdata['version'] = $data['version'] ?? 'N/A';
1327 if (!empty($data['plugins'])) {
1328 if (in_array('pubcrawl', $data['plugins'])) {
1329 $serverdata['network'] = Protocol::ACTIVITYPUB;
1330 } elseif (in_array('diaspora', $data['plugins'])) {
1331 $serverdata['network'] = Protocol::DIASPORA;
1332 } elseif (in_array('gnusoc', $data['plugins'])) {
1333 $serverdata['network'] = Protocol::OSTATUS;
1335 $serverdata['network'] = Protocol::ZOT;
1339 if (!empty($data['site_name'])) {
1340 $serverdata['site_name'] = $data['site_name'];
1343 if (!empty($data['channels_total'])) {
1344 $serverdata['registered-users'] = max($data['channels_total'], 1);
1347 if (!empty($data['channels_active_monthly'])) {
1348 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1351 if (!empty($data['channels_active_halfyear'])) {
1352 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1355 if (!empty($data['local_posts'])) {
1356 $serverdata['local-posts'] = max($data['local_posts'], 0);
1359 if (!empty($data['local_comments'])) {
1360 $serverdata['local-comments'] = max($data['local_comments'], 0);
1363 if (!empty($data['register_policy'])) {
1364 switch ($data['register_policy']) {
1365 case 'REGISTER_OPEN':
1366 $serverdata['register_policy'] = Register::OPEN;
1369 case 'REGISTER_APPROVE':
1370 $serverdata['register_policy'] = Register::APPROVE;
1373 case 'REGISTER_CLOSED':
1375 $serverdata['register_policy'] = Register::CLOSED;
1384 * Fetches server data via an ActivityPub account with url of that server
1386 * @param string $url URL of the given server
1387 * @param array $serverdata array with server data
1389 * @return array server data
1393 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1396 return ['server' => $serverdata, 'actor' => ''];
1399 $actor = JsonLD::compact($data, false);
1400 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1401 $serverdata['network'] = Protocol::ACTIVITYPUB;
1402 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1403 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1404 if (!empty($actor['as:generator'])) {
1405 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1406 $serverdata['platform'] = strtolower(array_shift($generator));
1407 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1409 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1411 return ['server' => $serverdata, 'actor' => $actor['@id']];
1412 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1413 // By now only Ktistec seems to provide collections this way
1414 $serverdata['platform'] = 'ktistec';
1415 $serverdata['network'] = Protocol::ACTIVITYPUB;
1416 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1418 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1419 if (!empty($actors) && !empty($actors[0]['@id'])) {
1420 $actor_url = $actor['@id'] . $actors[0]['@id'];
1425 return ['server' => $serverdata, 'actor' => $actor_url];
1427 return ['server' => $serverdata, 'actor' => ''];
1431 * Checks if the server contains a valid host meta file
1433 * @param string $url URL of the given server
1435 * @return boolean 'true' if the server seems to be vital
1437 private static function validHostMeta(string $url): bool
1439 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1440 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1441 if (!$curlResult->isSuccess()) {
1445 $xrd = XML::parseString($curlResult->getBody(), true);
1446 if (!is_object($xrd)) {
1450 $elements = XML::elementToArray($xrd);
1451 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1456 foreach ($elements['xrd']['link'] as $link) {
1457 // When there is more than a single "link" element, the array looks slightly different
1458 if (!empty($link['@attributes'])) {
1459 $link = $link['@attributes'];
1462 if (empty($link['rel']) || empty($link['template'])) {
1466 if ($link['rel'] == 'lrdd') {
1467 // When the webfinger host is the same like the system host, it should be ok.
1468 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1476 * Detect the network of the given server via their known contacts
1478 * @param string $url URL of the given server
1479 * @param array $serverdata array with server data
1481 * @return array server data
1483 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1487 $nurl = Strings::normaliseLink($url);
1489 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1490 while ($apcontact = DBA::fetch($apcontacts)) {
1491 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1493 DBA::close($apcontacts);
1495 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1496 while ($pcontact = DBA::fetch($pcontacts)) {
1497 $contacts[$pcontact['nurl']] = $pcontact['url'];
1499 DBA::close($pcontacts);
1501 if (empty($contacts)) {
1506 foreach ($contacts as $contact) {
1507 // Endlosschleife verhindern wegen gsid!
1508 $data = Probe::uri($contact);
1509 if (in_array($data['network'], Protocol::FEDERATED)) {
1510 $serverdata['network'] = $data['network'];
1512 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1513 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1516 } elseif ((time() - $time) > 10) {
1517 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1526 * Checks if the given server does have a '/poco' endpoint.
1527 * This is used for the 'PortableContact' functionality,
1528 * which is used by both Friendica and Hubzilla.
1530 * @param string $url URL of the given server
1531 * @param array $serverdata array with server data
1533 * @return array server data
1535 private static function checkPoCo(string $url, array $serverdata): array
1537 $serverdata['poco'] = '';
1539 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1540 if (!$curlResult->isSuccess()) {
1544 $data = json_decode($curlResult->getBody(), true);
1549 if (!empty($data['totalResults'])) {
1550 $registeredUsers = $serverdata['registered-users'] ?? 0;
1551 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1552 $serverdata['directory-type'] = self::DT_POCO;
1553 $serverdata['poco'] = $url . '/poco';
1560 * Checks if the given server does have a Mastodon style directory endpoint.
1562 * @param string $url URL of the given server
1563 * @param array $serverdata array with server data
1565 * @return array server data
1567 public static function checkMastodonDirectory(string $url, array $serverdata): array
1569 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1570 if (!$curlResult->isSuccess()) {
1574 $data = json_decode($curlResult->getBody(), true);
1579 if (count($data) == 1) {
1580 $serverdata['directory-type'] = self::DT_MASTODON;
1587 * Detects Peertube via their known endpoint
1589 * @param string $url URL of the given server
1590 * @param array $serverdata array with server data
1592 * @return array server data
1594 private static function detectPeertube(string $url, array $serverdata): array
1596 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1597 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1601 $data = json_decode($curlResult->getBody(), true);
1606 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1607 $serverdata['platform'] = 'peertube';
1608 $serverdata['version'] = $data['serverVersion'];
1609 $serverdata['network'] = Protocol::ACTIVITYPUB;
1611 if (!empty($data['instance']['name'])) {
1612 $serverdata['site_name'] = $data['instance']['name'];
1615 if (!empty($data['instance']['shortDescription'])) {
1616 $serverdata['info'] = $data['instance']['shortDescription'];
1619 if (!empty($data['signup'])) {
1620 if (!empty($data['signup']['allowed'])) {
1621 $serverdata['register_policy'] = Register::OPEN;
1625 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1626 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1634 * Detects the version number of a given server when it was a NextCloud installation
1636 * @param string $url URL of the given server
1637 * @param array $serverdata array with server data
1638 * @param bool $validHostMeta
1640 * @return array server data
1642 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1644 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1645 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1649 $data = json_decode($curlResult->getBody(), true);
1654 if (!empty($data['version'])) {
1655 $serverdata['platform'] = 'nextcloud';
1656 $serverdata['version'] = $data['version'];
1658 if ($validHostMeta) {
1659 $serverdata['network'] = Protocol::ACTIVITYPUB;
1662 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1663 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1671 * Fetches weekly usage data
1673 * @param string $url URL of the given server
1674 * @param array $serverdata array with server data
1676 * @return array server data
1678 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1680 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1681 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1685 $data = json_decode($curlResult->getBody(), true);
1691 foreach ($data as $week) {
1692 // Use only data from a full week
1693 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1697 // Most likely the data is sorted correctly. But we better are safe than sorry
1698 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1699 $current_week = $week;
1703 if (!empty($current_week['logins'])) {
1704 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1711 * Detects data from a given server url if it was a mastodon alike system
1713 * @param string $url URL of the given server
1714 * @param array $serverdata array with server data
1716 * @return array server data
1718 private static function detectMastodonAlikes(string $url, array $serverdata): array
1720 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1721 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1725 $data = json_decode($curlResult->getBody(), true);
1732 if (!empty($data['version'])) {
1733 $serverdata['platform'] = 'mastodon';
1734 $serverdata['version'] = $data['version'] ?? '';
1735 $serverdata['network'] = Protocol::ACTIVITYPUB;
1739 if (!empty($data['title'])) {
1740 $serverdata['site_name'] = $data['title'];
1743 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1744 $serverdata['platform'] = 'mastodon';
1745 $serverdata['network'] = Protocol::ACTIVITYPUB;
1749 if (!empty($data['description'])) {
1750 $serverdata['info'] = trim($data['description']);
1753 if (!empty($data['stats']['user_count'])) {
1754 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1757 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1758 $serverdata['platform'] = strtolower($matches[1]);
1759 $serverdata['version'] = $matches[2];
1763 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1764 $serverdata['platform'] = 'pleroma';
1765 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1769 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1770 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1771 $serverdata['platform'] = 'pleroma';
1775 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1776 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1783 * Detects data from typical Hubzilla endpoints
1785 * @param string $url URL of the given server
1786 * @param array $serverdata array with server data
1788 * @return array server data
1790 private static function detectHubzilla(string $url, array $serverdata): array
1792 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1793 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1797 $data = json_decode($curlResult->getBody(), true);
1798 if (empty($data) || empty($data['site'])) {
1802 if (!empty($data['site']['name'])) {
1803 $serverdata['site_name'] = $data['site']['name'];
1806 if (!empty($data['site']['platform'])) {
1807 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1808 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1809 $serverdata['network'] = Protocol::ZOT;
1812 if (!empty($data['site']['hubzilla'])) {
1813 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1814 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1815 $serverdata['network'] = Protocol::ZOT;
1818 if (!empty($data['site']['redmatrix'])) {
1819 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1820 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1821 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1822 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1825 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1826 $serverdata['network'] = Protocol::ZOT;
1830 $inviteonly = false;
1833 if (!empty($data['site']['closed'])) {
1834 $closed = self::toBoolean($data['site']['closed']);
1837 if (!empty($data['site']['private'])) {
1838 $private = self::toBoolean($data['site']['private']);
1841 if (!empty($data['site']['inviteonly'])) {
1842 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1845 if (!$closed && !$private and $inviteonly) {
1846 $serverdata['register_policy'] = Register::APPROVE;
1847 } elseif (!$closed && !$private) {
1848 $serverdata['register_policy'] = Register::OPEN;
1850 $serverdata['register_policy'] = Register::CLOSED;
1853 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1854 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1861 * Converts input value to a boolean value
1863 * @param string|integer $val
1867 private static function toBoolean($val): bool
1869 if (($val == 'true') || ($val == 1)) {
1871 } elseif (($val == 'false') || ($val == 0)) {
1879 * Detect if the URL belongs to a GNU Social server
1881 * @param string $url URL of the given server
1882 * @param array $serverdata array with server data
1884 * @return array server data
1886 private static function detectGNUSocial(string $url, array $serverdata): array
1888 // Test for GNU Social
1889 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1890 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1891 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1892 $serverdata['platform'] = 'gnusocial';
1893 // Remove junk that some GNU Social servers return
1894 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1895 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1896 $serverdata['version'] = trim($serverdata['version'], '"');
1897 $serverdata['network'] = Protocol::OSTATUS;
1899 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1900 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1906 // Test for Statusnet
1907 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1908 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1909 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1911 // Remove junk that some GNU Social servers return
1912 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1913 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1914 $serverdata['version'] = trim($serverdata['version'], '"');
1916 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1917 $serverdata['platform'] = 'pleroma';
1918 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1919 $serverdata['network'] = Protocol::ACTIVITYPUB;
1921 $serverdata['platform'] = 'statusnet';
1922 $serverdata['network'] = Protocol::OSTATUS;
1925 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1926 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1934 * Detect if the URL belongs to a Friendica server
1936 * @param string $url URL of the given server
1937 * @param array $serverdata array with server data
1939 * @return array server data
1941 private static function detectFriendica(string $url, array $serverdata): array
1943 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1944 // Because of this me must not use ACCEPT_JSON here.
1945 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1946 if (!$curlResult->isSuccess()) {
1947 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1949 $platform = 'Friendika';
1952 $platform = 'Friendica';
1955 if (!$curlResult->isSuccess()) {
1959 $data = json_decode($curlResult->getBody(), true);
1960 if (empty($data) || empty($data['version'])) {
1964 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1965 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1968 $serverdata['network'] = Protocol::DFRN;
1969 $serverdata['version'] = $data['version'];
1971 if (!empty($data['no_scrape_url'])) {
1972 $serverdata['noscrape'] = $data['no_scrape_url'];
1975 if (!empty($data['site_name'])) {
1976 $serverdata['site_name'] = $data['site_name'];
1979 if (!empty($data['info'])) {
1980 $serverdata['info'] = trim($data['info']);
1983 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1984 switch ($register_policy) {
1985 case 'REGISTER_OPEN':
1986 $serverdata['register_policy'] = Register::OPEN;
1989 case 'REGISTER_APPROVE':
1990 $serverdata['register_policy'] = Register::APPROVE;
1993 case 'REGISTER_CLOSED':
1994 case 'REGISTER_INVITATION':
1995 $serverdata['register_policy'] = Register::CLOSED;
1998 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1999 $serverdata['register_policy'] = Register::CLOSED;
2003 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2009 * Analyses the landing page of a given server for hints about type and system of that server
2011 * @param object $curlResult result of curl execution
2012 * @param array $serverdata array with server data
2014 * @return array server data
2016 private static function analyseRootBody($curlResult, array $serverdata): array
2018 if (empty($curlResult->getBody())) {
2022 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2023 require __DIR__ . '/../../static/platforms.config.php';
2025 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2028 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2030 $doc = new DOMDocument();
2031 @$doc->loadHTML($curlResult->getBody());
2032 $xpath = new DOMXPath($doc);
2035 // We can only detect honk via some HTML element on their page
2036 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2037 $serverdata['platform'] = 'honk';
2038 $serverdata['network'] = Protocol::ACTIVITYPUB;
2042 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2043 if (!empty($title)) {
2044 $serverdata['site_name'] = $title;
2047 $list = $xpath->query('//meta[@name]');
2049 foreach ($list as $node) {
2051 if ($node->attributes->length) {
2052 foreach ($node->attributes as $attribute) {
2053 $value = trim($attribute->value);
2054 if (empty($value)) {
2058 $attr[$attribute->name] = $value;
2061 if (empty($attr['name']) || empty($attr['content'])) {
2066 if ($attr['name'] == 'description') {
2067 $serverdata['info'] = $attr['content'];
2070 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2071 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2072 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2073 $platform = str_replace('/', ' ', $platform);
2074 $platform_parts = explode(' ', $platform);
2075 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2076 $platform = $platform_parts[0];
2077 $serverdata['version'] = $platform_parts[1];
2079 if (in_array($platform, array_values($dfrn_platforms))) {
2080 $serverdata['network'] = Protocol::DFRN;
2081 } elseif (in_array($platform, array_values($ap_platforms))) {
2082 $serverdata['network'] = Protocol::ACTIVITYPUB;
2083 } elseif (in_array($platform, array_values($zap_platforms))) {
2084 $serverdata['network'] = Protocol::ZOT;
2086 if (in_array($platform, array_values($platforms))) {
2087 $serverdata['platform'] = $platform;
2093 $list = $xpath->query('//meta[@property]');
2095 foreach ($list as $node) {
2097 if ($node->attributes->length) {
2098 foreach ($node->attributes as $attribute) {
2099 $value = trim($attribute->value);
2100 if (empty($value)) {
2104 $attr[$attribute->name] = $value;
2107 if (empty($attr['property']) || empty($attr['content'])) {
2112 if ($attr['property'] == 'og:site_name') {
2113 $serverdata['site_name'] = $attr['content'];
2116 if ($attr['property'] == 'og:description') {
2117 $serverdata['info'] = $attr['content'];
2120 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2121 if (in_array($attr['content'], array_keys($platforms))) {
2122 $serverdata['platform'] = $platforms[$attr['content']];
2126 if (in_array($attr['content'], array_keys($ap_platforms))) {
2127 $serverdata['network'] = Protocol::ACTIVITYPUB;
2128 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2129 $serverdata['network'] = Protocol::ZOT;
2134 $list = $xpath->query('//link[@rel="me"]');
2135 foreach ($list as $node) {
2136 foreach ($node->attributes as $attribute) {
2137 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2138 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2139 $serverdata['platform'] = 'microblog';
2140 $serverdata['network'] = Protocol::ACTIVITYPUB;
2146 if ($serverdata['platform'] != 'microblog') {
2147 $list = $xpath->query('//link[@rel="micropub"]');
2148 foreach ($list as $node) {
2149 foreach ($node->attributes as $attribute) {
2150 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2151 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2152 $serverdata['platform'] = 'microblog';
2153 $serverdata['network'] = Protocol::ACTIVITYPUB;
2160 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2161 $serverdata['detection-method'] = self::DETECT_BODY;
2168 * Analyses the header data of a given server for hints about type and system of that server
2170 * @param object $curlResult result of curl execution
2171 * @param array $serverdata array with server data
2173 * @return array server data
2175 private static function analyseRootHeader($curlResult, array $serverdata): array
2177 if ($curlResult->getHeader('server') == 'Mastodon') {
2178 $serverdata['platform'] = 'mastodon';
2179 $serverdata['network'] = Protocol::ACTIVITYPUB;
2180 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2181 $serverdata['platform'] = 'diaspora';
2182 $serverdata['network'] = Protocol::DIASPORA;
2183 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2184 } elseif ($curlResult->inHeader('x-friendica-version')) {
2185 $serverdata['platform'] = 'friendica';
2186 $serverdata['network'] = Protocol::DFRN;
2187 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2192 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2193 $serverdata['detection-method'] = self::DETECT_HEADER;
2200 * Update GServer entries
2202 public static function discover()
2204 // Update the server list
2205 self::discoverFederation();
2209 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2211 if ($requery_days == 0) {
2215 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2217 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2218 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2219 ['order' => ['RAND()']]);
2221 while ($gserver = DBA::fetch($gservers)) {
2222 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2223 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2225 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2226 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2228 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2229 self::update($fields, ['nurl' => $gserver['nurl']]);
2231 if (--$no_of_queries == 0) {
2236 DBA::close($gservers);
2240 * Discover federated servers
2242 private static function discoverFederation()
2244 $last = DI::keyValue()->get('poco_last_federation_discovery');
2247 $next = $last + (24 * 60 * 60);
2249 if ($next > time()) {
2254 // Discover federated servers
2255 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2256 foreach ($protocols as $protocol) {
2257 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2258 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2259 if (!empty($curlResult)) {
2260 $data = json_decode($curlResult, true);
2261 if (!empty($data['data']['nodes'])) {
2262 foreach ($data['data']['nodes'] as $server) {
2263 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2264 self::add('https://' . $server['host'], true);
2270 // Disvover Mastodon servers
2271 $accesstoken = DI::config()->get('system', 'instances_social_key');
2273 if (!empty($accesstoken)) {
2274 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2275 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2276 if ($curlResult->isSuccess()) {
2277 $servers = json_decode($curlResult->getBody(), true);
2279 if (!empty($servers['instances'])) {
2280 foreach ($servers['instances'] as $server) {
2281 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2288 DI::keyValue()->set('poco_last_federation_discovery', time());
2292 * Set the protocol for the given server
2294 * @param int $gsid Server id
2295 * @param int $protocol Protocol id
2299 public static function setProtocol(int $gsid, int $protocol)
2305 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2306 if (!DBA::isResult($gserver)) {
2310 $old = $gserver['protocol'];
2312 if (!is_null($old)) {
2314 The priority for the protocols is:
2316 2. DFRN via Diaspora
2322 // We don't need to change it when nothing is to be changed
2323 if ($old == $protocol) {
2327 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2328 if ($protocol == Post\DeliveryData::OSTATUS) {
2332 // If the server is marked as ActivityPub then we won't change it to anything different
2333 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2337 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2338 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2342 // Don't change it to Diaspora when it is a legacy DFRN server
2343 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2348 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2349 self::update(['protocol' => $protocol], ['id' => $gsid]);
2353 * Fetch the protocol of the given server
2355 * @param int $gsid Server id
2357 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2361 public static function getProtocol(int $gsid): ?int
2367 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2368 if (DBA::isResult($gserver)) {
2369 return $gserver['protocol'];
2376 * Update rows in the gserver table.
2377 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2379 * @param array $fields
2380 * @param array $condition
2386 public static function update(array $fields, array $condition): bool
2388 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2390 return DBA::update('gserver', $fields, $condition);
2394 * Insert a row into the gserver table.
2395 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2397 * @param array $fields
2398 * @param int $duplicate_mode What to do on a duplicated entry
2404 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2406 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2408 return DBA::insert('gserver', $fields, $duplicate_mode);