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 Friendica\Worker\UpdateGServer;
48 use GuzzleHttp\Psr7\Uri;
49 use Psr\Http\Message\UriInterface;
52 * This class handles GServer related functions
59 const DT_MASTODON = 2;
61 // Methods to detect server types
63 // Non endpoint specific methods
64 const DETECT_MANUAL = 0;
65 const DETECT_HEADER = 1;
66 const DETECT_BODY = 2;
67 const DETECT_HOST_META = 3;
68 const DETECT_CONTACTS = 4;
69 const DETECT_AP_ACTOR = 5;
70 const DETECT_AP_COLLECTION = 6;
72 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
74 // Implementation specific endpoints
75 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
76 const DETECT_FRIENDIKA = 10;
77 const DETECT_FRIENDICA = 11;
78 const DETECT_STATUSNET = 12;
79 const DETECT_GNUSOCIAL = 13;
80 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
81 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
82 const DETECT_MASTODON_API = 16;
83 const DETECT_STATUS_PHP = 17; // Nextcloud
84 const DETECT_V1_CONFIG = 18;
85 const DETECT_PUMPIO = 19; // Deprecated
86 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
88 // Standardized endpoints
89 const DETECT_STATISTICS_JSON = 100;
90 const DETECT_NODEINFO_1 = 101;
91 const DETECT_NODEINFO_2 = 102;
92 const DETECT_NODEINFO_210 = 103;
95 * Check for the existance of a server and adds it in the background if not existant
98 * @param boolean $only_nodeinfo
102 public static function add(string $url, bool $only_nodeinfo = false)
104 if (self::getID($url)) {
108 UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
112 * Get the ID for the given server URL
115 * @param boolean $no_check Don't check if the server hadn't been found
117 * @return int|null gserver id or NULL on empty URL or failed check
119 public static function getID(string $url, bool $no_check = false): ?int
121 $url = self::cleanURL($url);
127 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
128 if (DBA::isResult($gserver)) {
129 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
130 return $gserver['id'];
133 if ($no_check || !self::check($url)) {
137 return self::getID($url, true);
141 * Retrieves all the servers which base domain are matching the provided domain pattern
143 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
145 * @param string $pattern
151 public static function listByDomainPattern(string $pattern): array
153 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
155 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
156 // eventual server path and keep only the server domain which we're matching against the pattern.
157 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
159 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
160 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
161 AND NOT `gserver`.`failed`
162 GROUP BY `gserver`.`id`";
164 $stmt = DI::dba()->p($sql, $likePattern);
166 return DI::dba()->toArray($stmt);
170 * Checks if the given server array is unreachable for a long time now
172 * @param integer $gsid
175 private static function isDefunct(array $gserver): bool
177 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
178 ($gserver['last_contact'] >= $gserver['created']) &&
179 ($gserver['last_contact'] < $gserver['last_failure']) &&
180 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
184 * Checks if the given server id is unreachable for a long time now
186 * @param integer $gsid
189 public static function isDefunctById(int $gsid): bool
191 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
192 if (empty($gserver)) {
195 if (strtotime($gserver['next_contact']) < time()) {
196 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
199 return self::isDefunct($gserver);
204 * Checks if the given server id is reachable
206 * @param integer $gsid
209 public static function isReachableById(int $gsid): bool
211 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
212 if (empty($gserver)) {
215 if (strtotime($gserver['next_contact']) < time()) {
216 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
219 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
224 * Checks if the given server is reachable
226 * @param array $contact Contact that should be checked
228 * @return boolean 'true' if server seems vital
230 public static function reachable(array $contact): bool
232 if (!empty($contact['gsid'])) {
233 $gsid = $contact['gsid'];
234 } elseif (!empty($contact['baseurl'])) {
235 $server = $contact['baseurl'];
236 } elseif ($contact['network'] == Protocol::DIASPORA) {
237 $parts = parse_url($contact['url']);
238 unset($parts['path']);
239 $server = (string)Uri::fromParts($parts);
245 $condition = ['id' => $gsid];
247 $condition = ['nurl' => Strings::normaliseLink($server)];
250 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed'], $condition);
251 if (empty($gserver)) {
254 $reachable = !$gserver['failed'];
255 $server = $gserver['url'];
258 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
259 UpdateGServer::add(Worker::PRIORITY_LOW, $server);
266 * Calculate the next update day
268 * @param bool $success
269 * @param string $created
270 * @param string $last_contact
271 * @param bool $undetected
277 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
279 // On successful contact process check again next week when it is a detected system.
280 // When we haven't detected the system, it could be a static website or a really old system.
282 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
285 $now = strtotime(DateTimeFormat::utcNow());
287 if ($created > $last_contact) {
288 $contact_time = strtotime($created);
290 $contact_time = strtotime($last_contact);
293 // If the last contact was less than 6 hours before then try again in 6 hours
294 if (($now - $contact_time) < (60 * 60 * 6)) {
295 return DateTimeFormat::utc('now +6 hour');
298 // If the last contact was less than 12 hours before then try again in 12 hours
299 if (($now - $contact_time) < (60 * 60 * 12)) {
300 return DateTimeFormat::utc('now +12 hour');
303 // If the last contact was less than 24 hours before then try tomorrow again
304 if (($now - $contact_time) < (60 * 60 * 24)) {
305 return DateTimeFormat::utc('now +1 day');
308 // If the last contact was less than a week before then try again in a week
309 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
310 return DateTimeFormat::utc('now +1 week');
313 // If the last contact was less than two weeks before then try again in two week
314 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
315 return DateTimeFormat::utc('now +2 week');
318 // If the last contact was less than a month before then try again in a month
319 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
320 return DateTimeFormat::utc('now +1 month');
323 // The system hadn't been successul contacted for more than a month, so try again in three months
324 return DateTimeFormat::utc('now +3 month');
328 * Checks the state of the given server.
330 * @param string $server_url URL of the given server
331 * @param string $network Network value that is used, when detection failed
332 * @param boolean $force Force an update.
333 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
335 * @return boolean 'true' if server seems vital
337 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
339 $server_url = self::cleanURL($server_url);
340 if ($server_url == '') {
344 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
345 if (DBA::isResult($gserver)) {
346 if ($gserver['created'] <= DBA::NULL_DATETIME) {
347 $fields = ['created' => DateTimeFormat::utcNow()];
348 $condition = ['nurl' => Strings::normaliseLink($server_url)];
349 self::update($fields, $condition);
352 if (!$force && (strtotime($gserver['next_contact']) > time())) {
353 Logger::info('No update needed', ['server' => $server_url]);
354 return (!$gserver['failed']);
356 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
358 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
361 return self::detect($server_url, $network, $only_nodeinfo);
365 * Reset failed server status by gserver id
368 * @param string $network
370 public static function setReachableById(int $gsid, string $network)
372 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
373 if (DBA::isResult($gserver) && $gserver['failed']) {
374 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow()];
375 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
376 $fields['network'] = $network;
378 self::update($fields, ['id' => $gsid]);
379 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
381 if (strtotime($gserver['next_contact']) < time()) {
382 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
388 * Set failed server status by gserver id
392 public static function setFailureById(int $gsid)
394 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
395 if (DBA::isResult($gserver) && !$gserver['failed']) {
396 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
397 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
399 if (strtotime($gserver['next_contact']) < time()) {
400 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
406 * Set failed server status
410 public static function setFailure(string $url)
412 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
413 if (DBA::isResult($gserver)) {
414 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
415 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
416 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
417 ['nurl' => Strings::normaliseLink($url)]);
418 Logger::info('Set failed status for existing server', ['url' => $url]);
421 self::insert(['url' => $url, 'nurl' => Strings::normaliseLink($url),
422 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
423 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
424 Logger::info('Set failed status for new server', ['url' => $url]);
428 * Remove unwanted content from the given URL
430 * @param string $dirtyUrl
432 * @return string cleaned URL
434 * @deprecated since 2023.03 Use cleanUri instead
436 public static function cleanURL(string $dirtyUrl): string
439 return (string)self::cleanUri(new Uri($dirtyUrl));
440 } catch (\Throwable $e) {
441 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
447 * Remove unwanted content from the given URI
449 * @param UriInterface $dirtyUri
451 * @return UriInterface cleaned URI
454 public static function cleanUri(UriInterface $dirtyUri): string
462 '#(?:^|/)index\.php#',
464 rtrim($dirtyUri->getPath(), '/')
470 * Detect server data (type, protocol, version number, ...)
471 * The detected data is then updated or inserted in the gserver table.
473 * @param string $url URL of the given server
474 * @param string $network Network value that is used, when detection failed
475 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
477 * @return boolean 'true' if server could be detected
479 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
481 Logger::info('Detect server type', ['server' => $url]);
483 $original_url = $url;
485 // Remove URL content that is not supposed to exist for a server url
486 $url = rtrim(self::cleanURL($url), '/');
488 Logger::notice('Empty URL.');
492 // If the URL missmatches, then we mark the old entry as failure
493 if (!Strings::compareLink($url, $original_url)) {
494 self::setFailure($original_url);
495 if (!self::getID($url, true)) {
496 self::detect($url, $network, $only_nodeinfo);
501 $valid_url = Network::isUrlValid($url);
503 self::setFailure($url);
506 $valid_url = rtrim($valid_url, '/');
509 if (!Strings::compareLink($url, $valid_url)) {
510 // We only follow redirects when the path stays the same or the target url has no path.
511 // Some systems have got redirects on their landing page to a single account page. This check handles it.
512 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))) ||
513 (((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)))) {
514 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
515 self::setFailure($url);
516 if (!self::getID($valid_url, true)) {
517 self::detect($valid_url, $network, $only_nodeinfo);
522 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)) &&
523 (parse_url($url, PHP_URL_PATH) == '')) {
524 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
525 $parts = parse_url($valid_url);
526 unset($parts['path']);
527 $valid_url = (string)Uri::fromParts($parts);
529 self::setFailure($url);
530 if (!self::getID($valid_url, true)) {
531 self::detect($valid_url, $network, $only_nodeinfo);
535 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
538 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
539 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
540 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
544 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
546 // When a nodeinfo is present, we don't need to dig further
547 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
548 if ($curlResult->isTimeout()) {
549 self::setFailure($url);
553 $serverdata = self::parseNodeinfo210($curlResult);
554 if (empty($serverdata)) {
555 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
556 $serverdata = self::fetchNodeinfo($url, $curlResult);
559 if ($only_nodeinfo && empty($serverdata)) {
560 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
561 self::setFailure($url);
563 } elseif (empty($serverdata)) {
564 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
567 // When there is no Nodeinfo, then use some protocol specific endpoints
568 if ($serverdata['network'] == Protocol::PHANTOM) {
570 // Fetch the landing page, possibly it reveals some data
571 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
572 $curlResult = DI::httpClient()->get($url, $accept);
573 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
574 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
575 $html_fetched = true;
577 $html_fetched = false;
580 if ($curlResult->isSuccess()) {
581 $json = json_decode($curlResult->getBody(), true);
582 if (!empty($json) && is_array($json)) {
583 $data = self::fetchDataFromSystemActor($json, $serverdata);
584 $serverdata = $data['server'];
585 $systemactor = $data['actor'];
586 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
587 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
589 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
590 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
593 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
594 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
595 $serverdata = self::analyseRootBody($curlResult, $serverdata);
599 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
600 self::setFailure($url);
604 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
605 $serverdata = self::detectMastodonAlikes($url, $serverdata);
609 // All following checks are done for systems that always have got a "host-meta" endpoint.
610 // With this check we don't have to waste time and ressources for dead systems.
611 // Also this hopefully prevents us from receiving abuse messages.
612 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
613 $validHostMeta = self::validHostMeta($url);
615 $validHostMeta = false;
618 if ($validHostMeta) {
619 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
620 $serverdata['detection-method'] = self::DETECT_HOST_META;
623 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
624 $serverdata = self::detectFriendica($url, $serverdata);
627 // The following systems have to be installed in the root directory.
629 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
630 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
631 $serverdata = self::fetchSiteinfo($url, $serverdata);
634 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
635 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
636 $serverdata = self::detectHubzilla($url, $serverdata);
639 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
640 $serverdata = self::detectPeertube($url, $serverdata);
643 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
644 $serverdata = self::detectGNUSocial($url, $serverdata);
647 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
648 $serverdata = self::detectFriendica($url, $serverdata);
651 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
652 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
655 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
656 // Since this endpoint is only rarely used, we query it at a later time
657 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
658 $serverdata = self::fetchStatistics($url, $serverdata);
662 // When we hadn't been able to detect the network type, we use the hint from the parameter
663 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
664 $serverdata['network'] = $network;
667 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
668 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
669 self::setFailure($url);
673 $serverdata['url'] = $url;
674 $serverdata['nurl'] = Strings::normaliseLink($url);
676 // We have to prevent an endless loop here.
677 // When a server is new, then there is no gserver entry yet.
678 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
679 // and this can call this function here as well.
680 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
681 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
682 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
685 // Detect the directory type
686 $serverdata['directory-type'] = self::DT_NONE;
688 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
689 $serverdata = self::checkMastodonDirectory($url, $serverdata);
691 if ($serverdata['directory-type'] == self::DT_NONE) {
692 $serverdata = self::checkPoCo($url, $serverdata);
696 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
697 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
700 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
702 // Numbers above a reasonable value (10 millions) are ignored
703 if ($serverdata['registered-users'] > 10000000) {
704 $serverdata['registered-users'] = 0;
707 // On an active server there has to be at least a single user
708 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
709 $serverdata['registered-users'] = 1;
710 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
711 $serverdata['registered-users'] = 0;
714 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
716 $serverdata['last_contact'] = DateTimeFormat::utcNow();
717 $serverdata['failed'] = false;
719 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
720 if (!DBA::isResult($gserver)) {
721 $serverdata['created'] = DateTimeFormat::utcNow();
722 $ret = self::insert($serverdata);
723 $id = DBA::lastInsertId();
725 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
726 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
727 if (DBA::isResult($gserver)) {
728 $id = $gserver['id'];
732 // Count the number of known contacts from this server
733 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
734 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
735 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
736 $max_users = max($apcontacts, $contacts);
737 if ($max_users > $serverdata['registered-users']) {
738 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
739 self::update(['registered-users' => $max_users], ['id' => $id]);
742 if (empty($serverdata['active-month-users'])) {
743 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
745 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
746 self::update(['active-month-users' => $contacts], ['id' => $id]);
750 if (empty($serverdata['active-halfyear-users'])) {
751 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
753 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
754 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
759 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
760 self::discoverRelay($url);
763 if (!empty($systemactor)) {
764 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
765 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
772 * Fetch relay data from a given server url
774 * @param string $server_url address of the server
778 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
780 private static function discoverRelay(string $server_url)
782 Logger::info('Discover relay data', ['server' => $server_url]);
784 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
785 if (!$curlResult->isSuccess()) {
789 $data = json_decode($curlResult->getBody(), true);
790 if (!is_array($data)) {
794 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
795 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
797 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
799 $data['subscribe'] = false;
803 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
804 if (!DBA::isResult($gserver)) {
808 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
809 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
810 self::update($fields, ['id' => $gserver['id']]);
813 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
815 if ($data['scope'] == 'tags') {
818 foreach ($data['tags'] as $tag) {
819 $tag = mb_strtolower($tag);
820 if (strlen($tag) < 100) {
825 foreach ($tags as $tag) {
826 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
830 // Create or update the relay contact
832 if (isset($data['protocols'])) {
833 if (isset($data['protocols']['diaspora'])) {
834 $fields['network'] = Protocol::DIASPORA;
836 if (isset($data['protocols']['diaspora']['receive'])) {
837 $fields['batch'] = $data['protocols']['diaspora']['receive'];
838 } elseif (is_string($data['protocols']['diaspora'])) {
839 $fields['batch'] = $data['protocols']['diaspora'];
843 if (isset($data['protocols']['dfrn'])) {
844 $fields['network'] = Protocol::DFRN;
846 if (isset($data['protocols']['dfrn']['receive'])) {
847 $fields['batch'] = $data['protocols']['dfrn']['receive'];
848 } elseif (is_string($data['protocols']['dfrn'])) {
849 $fields['batch'] = $data['protocols']['dfrn'];
853 if (isset($data['protocols']['activitypub'])) {
854 $fields['network'] = Protocol::ACTIVITYPUB;
856 if (!empty($data['protocols']['activitypub']['actor'])) {
857 $fields['url'] = $data['protocols']['activitypub']['actor'];
859 if (!empty($data['protocols']['activitypub']['receive'])) {
860 $fields['batch'] = $data['protocols']['activitypub']['receive'];
865 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
867 Relay::updateContact($gserver, $fields);
871 * Fetch server data from '/statistics.json' on the given server
873 * @param string $url URL of the given server
875 * @return array server data
877 private static function fetchStatistics(string $url, array $serverdata): array
879 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
880 if (!$curlResult->isSuccess()) {
884 $data = json_decode($curlResult->getBody(), true);
889 // Some AP enabled systems return activity data that we don't expect here.
890 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
895 $old_serverdata = $serverdata;
897 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
899 if (!empty($data['version'])) {
901 $serverdata['version'] = $data['version'];
902 // Version numbers on statistics.json are presented with additional info, e.g.:
903 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
904 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
907 if (!empty($data['name'])) {
909 $serverdata['site_name'] = $data['name'];
912 if (!empty($data['network'])) {
914 $serverdata['platform'] = strtolower($data['network']);
916 if ($serverdata['platform'] == 'diaspora') {
917 $serverdata['network'] = Protocol::DIASPORA;
918 } elseif ($serverdata['platform'] == 'friendica') {
919 $serverdata['network'] = Protocol::DFRN;
920 } elseif ($serverdata['platform'] == 'hubzilla') {
921 $serverdata['network'] = Protocol::ZOT;
922 } elseif ($serverdata['platform'] == 'redmatrix') {
923 $serverdata['network'] = Protocol::ZOT;
927 if (!empty($data['total_users'])) {
929 $serverdata['registered-users'] = max($data['total_users'], 1);
932 if (!empty($data['active_users_monthly'])) {
934 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
937 if (!empty($data['active_users_halfyear'])) {
939 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
942 if (!empty($data['local_posts'])) {
944 $serverdata['local-posts'] = max($data['local_posts'], 0);
947 if (!empty($data['registrations_open'])) {
948 $serverdata['register_policy'] = Register::OPEN;
950 $serverdata['register_policy'] = Register::CLOSED;
954 return $old_serverdata;
961 * Detect server type by using the nodeinfo data
963 * @param string $url address of the server
964 * @param ICanHandleHttpResponses $httpResult
966 * @return array Server data
968 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
972 if (!$httpResult->isSuccess()) {
976 $nodeinfo = json_decode($httpResult->getBody(), true);
978 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
985 foreach ($nodeinfo['links'] as $link) {
986 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
987 Logger::info('Invalid nodeinfo format', ['url' => $url]);
990 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
991 $nodeinfo1_url = $link['href'];
992 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
993 $nodeinfo2_url = $link['href'];
997 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1003 if (!empty($nodeinfo2_url)) {
1004 $server = self::parseNodeinfo2($nodeinfo2_url);
1007 if (empty($server) && !empty($nodeinfo1_url)) {
1008 $server = self::parseNodeinfo1($nodeinfo1_url);
1017 * @param string $nodeinfo_url address of the nodeinfo path
1019 * @return array Server data
1021 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1023 private static function parseNodeinfo1(string $nodeinfo_url): array
1025 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1026 if (!$curlResult->isSuccess()) {
1030 $nodeinfo = json_decode($curlResult->getBody(), true);
1032 if (!is_array($nodeinfo)) {
1036 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1037 'register_policy' => Register::CLOSED];
1039 if (!empty($nodeinfo['openRegistrations'])) {
1040 $server['register_policy'] = Register::OPEN;
1043 if (is_array($nodeinfo['software'])) {
1044 if (!empty($nodeinfo['software']['name'])) {
1045 $server['platform'] = strtolower($nodeinfo['software']['name']);
1048 if (!empty($nodeinfo['software']['version'])) {
1049 $server['version'] = $nodeinfo['software']['version'];
1050 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1051 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1052 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1056 if (!empty($nodeinfo['metadata']['nodeName'])) {
1057 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1060 if (!empty($nodeinfo['usage']['users']['total'])) {
1061 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1064 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1065 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1068 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1069 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1072 if (!empty($nodeinfo['usage']['localPosts'])) {
1073 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1076 if (!empty($nodeinfo['usage']['localComments'])) {
1077 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1080 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1082 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1083 $protocols[$protocol] = true;
1086 if (!empty($protocols['friendica'])) {
1087 $server['network'] = Protocol::DFRN;
1088 } elseif (!empty($protocols['activitypub'])) {
1089 $server['network'] = Protocol::ACTIVITYPUB;
1090 } elseif (!empty($protocols['diaspora'])) {
1091 $server['network'] = Protocol::DIASPORA;
1092 } elseif (!empty($protocols['ostatus'])) {
1093 $server['network'] = Protocol::OSTATUS;
1094 } elseif (!empty($protocols['gnusocial'])) {
1095 $server['network'] = Protocol::OSTATUS;
1096 } elseif (!empty($protocols['zot'])) {
1097 $server['network'] = Protocol::ZOT;
1101 if (empty($server)) {
1105 if (empty($server['network'])) {
1106 $server['network'] = Protocol::PHANTOM;
1115 * @see https://git.feneas.org/jaywink/nodeinfo2
1117 * @param string $nodeinfo_url address of the nodeinfo path
1119 * @return array Server data
1121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1123 private static function parseNodeinfo2(string $nodeinfo_url): array
1125 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1126 if (!$curlResult->isSuccess()) {
1130 $nodeinfo = json_decode($curlResult->getBody(), true);
1131 if (!is_array($nodeinfo)) {
1136 'detection-method' => self::DETECT_NODEINFO_2,
1137 'register_policy' => Register::CLOSED,
1138 'platform' => 'unknown',
1141 if (!empty($nodeinfo['openRegistrations'])) {
1142 $server['register_policy'] = Register::OPEN;
1145 if (!empty($nodeinfo['software'])) {
1146 if (isset($nodeinfo['software']['name'])) {
1147 $server['platform'] = strtolower($nodeinfo['software']['name']);
1150 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1151 $server['version'] = $nodeinfo['software']['version'];
1152 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1153 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1154 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1156 // qoto advertises itself as Mastodon
1157 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1158 $server['platform'] = 'qoto';
1163 if (!empty($nodeinfo['metadata']['nodeName'])) {
1164 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1167 if (!empty($nodeinfo['usage']['users']['total'])) {
1168 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1171 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1172 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1175 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1176 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1179 if (!empty($nodeinfo['usage']['localPosts'])) {
1180 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1183 if (!empty($nodeinfo['usage']['localComments'])) {
1184 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1187 if (!empty($nodeinfo['protocols'])) {
1189 foreach ($nodeinfo['protocols'] as $protocol) {
1190 if (is_string($protocol)) {
1191 $protocols[$protocol] = true;
1195 if (!empty($protocols['dfrn'])) {
1196 $server['network'] = Protocol::DFRN;
1197 } elseif (!empty($protocols['activitypub'])) {
1198 $server['network'] = Protocol::ACTIVITYPUB;
1199 } elseif (!empty($protocols['diaspora'])) {
1200 $server['network'] = Protocol::DIASPORA;
1201 } elseif (!empty($protocols['ostatus'])) {
1202 $server['network'] = Protocol::OSTATUS;
1203 } elseif (!empty($protocols['gnusocial'])) {
1204 $server['network'] = Protocol::OSTATUS;
1205 } elseif (!empty($protocols['zot'])) {
1206 $server['network'] = Protocol::ZOT;
1210 if (empty($server)) {
1214 if (empty($server['network'])) {
1215 $server['network'] = Protocol::PHANTOM;
1222 * Parses NodeInfo2 protocol 1.0
1224 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1226 * @param string $nodeinfo_url address of the nodeinfo path
1228 * @return array Server data
1230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1232 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1234 if (!$httpResult->isSuccess()) {
1238 $nodeinfo = json_decode($httpResult->getBody(), true);
1240 if (!is_array($nodeinfo)) {
1244 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1245 'register_policy' => Register::CLOSED];
1247 if (!empty($nodeinfo['openRegistrations'])) {
1248 $server['register_policy'] = Register::OPEN;
1251 if (!empty($nodeinfo['server'])) {
1252 if (!empty($nodeinfo['server']['software'])) {
1253 $server['platform'] = strtolower($nodeinfo['server']['software']);
1256 if (!empty($nodeinfo['server']['version'])) {
1257 $server['version'] = $nodeinfo['server']['version'];
1258 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1259 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1260 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1263 if (!empty($nodeinfo['server']['name'])) {
1264 $server['site_name'] = $nodeinfo['server']['name'];
1268 if (!empty($nodeinfo['usage']['users']['total'])) {
1269 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1272 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1273 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1276 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1277 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1280 if (!empty($nodeinfo['usage']['localPosts'])) {
1281 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1284 if (!empty($nodeinfo['usage']['localComments'])) {
1285 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1288 if (!empty($nodeinfo['protocols'])) {
1290 foreach ($nodeinfo['protocols'] as $protocol) {
1291 if (is_string($protocol)) {
1292 $protocols[$protocol] = true;
1296 if (!empty($protocols['dfrn'])) {
1297 $server['network'] = Protocol::DFRN;
1298 } elseif (!empty($protocols['activitypub'])) {
1299 $server['network'] = Protocol::ACTIVITYPUB;
1300 } elseif (!empty($protocols['diaspora'])) {
1301 $server['network'] = Protocol::DIASPORA;
1302 } elseif (!empty($protocols['ostatus'])) {
1303 $server['network'] = Protocol::OSTATUS;
1304 } elseif (!empty($protocols['gnusocial'])) {
1305 $server['network'] = Protocol::OSTATUS;
1306 } elseif (!empty($protocols['zot'])) {
1307 $server['network'] = Protocol::ZOT;
1311 if (empty($server) || empty($server['platform'])) {
1315 if (empty($server['network'])) {
1316 $server['network'] = Protocol::PHANTOM;
1323 * Fetch server information from a 'siteinfo.json' file on the given server
1325 * @param string $url URL of the given server
1326 * @param array $serverdata array with server data
1328 * @return array server data
1330 private static function fetchSiteinfo(string $url, array $serverdata): array
1332 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1333 if (!$curlResult->isSuccess()) {
1337 $data = json_decode($curlResult->getBody(), true);
1342 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1343 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1346 if (!empty($data['url'])) {
1347 $serverdata['platform'] = strtolower($data['platform']);
1348 $serverdata['version'] = $data['version'] ?? 'N/A';
1351 if (!empty($data['plugins'])) {
1352 if (in_array('pubcrawl', $data['plugins'])) {
1353 $serverdata['network'] = Protocol::ACTIVITYPUB;
1354 } elseif (in_array('diaspora', $data['plugins'])) {
1355 $serverdata['network'] = Protocol::DIASPORA;
1356 } elseif (in_array('gnusoc', $data['plugins'])) {
1357 $serverdata['network'] = Protocol::OSTATUS;
1359 $serverdata['network'] = Protocol::ZOT;
1363 if (!empty($data['site_name'])) {
1364 $serverdata['site_name'] = $data['site_name'];
1367 if (!empty($data['channels_total'])) {
1368 $serverdata['registered-users'] = max($data['channels_total'], 1);
1371 if (!empty($data['channels_active_monthly'])) {
1372 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1375 if (!empty($data['channels_active_halfyear'])) {
1376 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1379 if (!empty($data['local_posts'])) {
1380 $serverdata['local-posts'] = max($data['local_posts'], 0);
1383 if (!empty($data['local_comments'])) {
1384 $serverdata['local-comments'] = max($data['local_comments'], 0);
1387 if (!empty($data['register_policy'])) {
1388 switch ($data['register_policy']) {
1389 case 'REGISTER_OPEN':
1390 $serverdata['register_policy'] = Register::OPEN;
1393 case 'REGISTER_APPROVE':
1394 $serverdata['register_policy'] = Register::APPROVE;
1397 case 'REGISTER_CLOSED':
1399 $serverdata['register_policy'] = Register::CLOSED;
1408 * Fetches server data via an ActivityPub account with url of that server
1410 * @param string $url URL of the given server
1411 * @param array $serverdata array with server data
1413 * @return array server data
1417 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1420 return ['server' => $serverdata, 'actor' => ''];
1423 $actor = JsonLD::compact($data, false);
1424 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1425 $serverdata['network'] = Protocol::ACTIVITYPUB;
1426 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1427 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1428 if (!empty($actor['as:generator'])) {
1429 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1430 $serverdata['platform'] = strtolower(array_shift($generator));
1431 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1433 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1435 return ['server' => $serverdata, 'actor' => $actor['@id']];
1436 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1437 // By now only Ktistec seems to provide collections this way
1438 $serverdata['platform'] = 'ktistec';
1439 $serverdata['network'] = Protocol::ACTIVITYPUB;
1440 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1442 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1443 if (!empty($actors) && !empty($actors[0]['@id'])) {
1444 $actor_url = $actor['@id'] . $actors[0]['@id'];
1449 return ['server' => $serverdata, 'actor' => $actor_url];
1451 return ['server' => $serverdata, 'actor' => ''];
1455 * Checks if the server contains a valid host meta file
1457 * @param string $url URL of the given server
1459 * @return boolean 'true' if the server seems to be vital
1461 private static function validHostMeta(string $url): bool
1463 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1464 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1465 if (!$curlResult->isSuccess()) {
1469 $xrd = XML::parseString($curlResult->getBody(), true);
1470 if (!is_object($xrd)) {
1474 $elements = XML::elementToArray($xrd);
1475 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1480 foreach ($elements['xrd']['link'] as $link) {
1481 // When there is more than a single "link" element, the array looks slightly different
1482 if (!empty($link['@attributes'])) {
1483 $link = $link['@attributes'];
1486 if (empty($link['rel']) || empty($link['template'])) {
1490 if ($link['rel'] == 'lrdd') {
1491 // When the webfinger host is the same like the system host, it should be ok.
1492 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1500 * Detect the network of the given server via their known contacts
1502 * @param string $url URL of the given server
1503 * @param array $serverdata array with server data
1505 * @return array server data
1507 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1511 $nurl = Strings::normaliseLink($url);
1513 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1514 while ($apcontact = DBA::fetch($apcontacts)) {
1515 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1517 DBA::close($apcontacts);
1519 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1520 while ($pcontact = DBA::fetch($pcontacts)) {
1521 $contacts[$pcontact['nurl']] = $pcontact['url'];
1523 DBA::close($pcontacts);
1525 if (empty($contacts)) {
1530 foreach ($contacts as $contact) {
1531 // Endlosschleife verhindern wegen gsid!
1532 $data = Probe::uri($contact);
1533 if (in_array($data['network'], Protocol::FEDERATED)) {
1534 $serverdata['network'] = $data['network'];
1536 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1537 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1540 } elseif ((time() - $time) > 10) {
1541 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1550 * Checks if the given server does have a '/poco' endpoint.
1551 * This is used for the 'PortableContact' functionality,
1552 * which is used by both Friendica and Hubzilla.
1554 * @param string $url URL of the given server
1555 * @param array $serverdata array with server data
1557 * @return array server data
1559 private static function checkPoCo(string $url, array $serverdata): array
1561 $serverdata['poco'] = '';
1563 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1564 if (!$curlResult->isSuccess()) {
1568 $data = json_decode($curlResult->getBody(), true);
1573 if (!empty($data['totalResults'])) {
1574 $registeredUsers = $serverdata['registered-users'] ?? 0;
1575 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1576 $serverdata['directory-type'] = self::DT_POCO;
1577 $serverdata['poco'] = $url . '/poco';
1584 * Checks if the given server does have a Mastodon style directory endpoint.
1586 * @param string $url URL of the given server
1587 * @param array $serverdata array with server data
1589 * @return array server data
1591 public static function checkMastodonDirectory(string $url, array $serverdata): array
1593 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1594 if (!$curlResult->isSuccess()) {
1598 $data = json_decode($curlResult->getBody(), true);
1603 if (count($data) == 1) {
1604 $serverdata['directory-type'] = self::DT_MASTODON;
1611 * Detects Peertube via their known endpoint
1613 * @param string $url URL of the given server
1614 * @param array $serverdata array with server data
1616 * @return array server data
1618 private static function detectPeertube(string $url, array $serverdata): array
1620 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1621 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1625 $data = json_decode($curlResult->getBody(), true);
1630 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1631 $serverdata['platform'] = 'peertube';
1632 $serverdata['version'] = $data['serverVersion'];
1633 $serverdata['network'] = Protocol::ACTIVITYPUB;
1635 if (!empty($data['instance']['name'])) {
1636 $serverdata['site_name'] = $data['instance']['name'];
1639 if (!empty($data['instance']['shortDescription'])) {
1640 $serverdata['info'] = $data['instance']['shortDescription'];
1643 if (!empty($data['signup'])) {
1644 if (!empty($data['signup']['allowed'])) {
1645 $serverdata['register_policy'] = Register::OPEN;
1649 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1650 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1658 * Detects the version number of a given server when it was a NextCloud installation
1660 * @param string $url URL of the given server
1661 * @param array $serverdata array with server data
1662 * @param bool $validHostMeta
1664 * @return array server data
1666 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1668 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1669 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1673 $data = json_decode($curlResult->getBody(), true);
1678 if (!empty($data['version'])) {
1679 $serverdata['platform'] = 'nextcloud';
1680 $serverdata['version'] = $data['version'];
1682 if ($validHostMeta) {
1683 $serverdata['network'] = Protocol::ACTIVITYPUB;
1686 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1687 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1695 * Fetches weekly usage data
1697 * @param string $url URL of the given server
1698 * @param array $serverdata array with server data
1700 * @return array server data
1702 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1704 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1705 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1709 $data = json_decode($curlResult->getBody(), true);
1715 foreach ($data as $week) {
1716 // Use only data from a full week
1717 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1721 // Most likely the data is sorted correctly. But we better are safe than sorry
1722 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1723 $current_week = $week;
1727 if (!empty($current_week['logins'])) {
1728 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1735 * Detects data from a given server url if it was a mastodon alike system
1737 * @param string $url URL of the given server
1738 * @param array $serverdata array with server data
1740 * @return array server data
1742 private static function detectMastodonAlikes(string $url, array $serverdata): array
1744 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1745 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1749 $data = json_decode($curlResult->getBody(), true);
1756 if (!empty($data['version'])) {
1757 $serverdata['platform'] = 'mastodon';
1758 $serverdata['version'] = $data['version'] ?? '';
1759 $serverdata['network'] = Protocol::ACTIVITYPUB;
1763 if (!empty($data['title'])) {
1764 $serverdata['site_name'] = $data['title'];
1767 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1768 $serverdata['platform'] = 'mastodon';
1769 $serverdata['network'] = Protocol::ACTIVITYPUB;
1773 if (!empty($data['description'])) {
1774 $serverdata['info'] = trim($data['description']);
1777 if (!empty($data['stats']['user_count'])) {
1778 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1781 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1782 $serverdata['platform'] = strtolower($matches[1]);
1783 $serverdata['version'] = $matches[2];
1787 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1788 $serverdata['platform'] = 'pleroma';
1789 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1793 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1794 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1795 $serverdata['platform'] = 'pleroma';
1799 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1800 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1807 * Detects data from typical Hubzilla endpoints
1809 * @param string $url URL of the given server
1810 * @param array $serverdata array with server data
1812 * @return array server data
1814 private static function detectHubzilla(string $url, array $serverdata): array
1816 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1817 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1821 $data = json_decode($curlResult->getBody(), true);
1822 if (empty($data) || empty($data['site'])) {
1826 if (!empty($data['site']['name'])) {
1827 $serverdata['site_name'] = $data['site']['name'];
1830 if (!empty($data['site']['platform'])) {
1831 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1832 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1833 $serverdata['network'] = Protocol::ZOT;
1836 if (!empty($data['site']['hubzilla'])) {
1837 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1838 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1839 $serverdata['network'] = Protocol::ZOT;
1842 if (!empty($data['site']['redmatrix'])) {
1843 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1844 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1845 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1846 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1849 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1850 $serverdata['network'] = Protocol::ZOT;
1854 $inviteonly = false;
1857 if (!empty($data['site']['closed'])) {
1858 $closed = self::toBoolean($data['site']['closed']);
1861 if (!empty($data['site']['private'])) {
1862 $private = self::toBoolean($data['site']['private']);
1865 if (!empty($data['site']['inviteonly'])) {
1866 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1869 if (!$closed && !$private and $inviteonly) {
1870 $serverdata['register_policy'] = Register::APPROVE;
1871 } elseif (!$closed && !$private) {
1872 $serverdata['register_policy'] = Register::OPEN;
1874 $serverdata['register_policy'] = Register::CLOSED;
1877 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1878 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1885 * Converts input value to a boolean value
1887 * @param string|integer $val
1891 private static function toBoolean($val): bool
1893 if (($val == 'true') || ($val == 1)) {
1895 } elseif (($val == 'false') || ($val == 0)) {
1903 * Detect if the URL belongs to a GNU Social server
1905 * @param string $url URL of the given server
1906 * @param array $serverdata array with server data
1908 * @return array server data
1910 private static function detectGNUSocial(string $url, array $serverdata): array
1912 // Test for GNU Social
1913 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1914 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1915 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1916 $serverdata['platform'] = 'gnusocial';
1917 // Remove junk that some GNU Social servers return
1918 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1919 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1920 $serverdata['version'] = trim($serverdata['version'], '"');
1921 $serverdata['network'] = Protocol::OSTATUS;
1923 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1924 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1930 // Test for Statusnet
1931 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1932 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1933 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1935 // Remove junk that some GNU Social servers return
1936 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1937 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1938 $serverdata['version'] = trim($serverdata['version'], '"');
1940 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1941 $serverdata['platform'] = 'pleroma';
1942 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1943 $serverdata['network'] = Protocol::ACTIVITYPUB;
1945 $serverdata['platform'] = 'statusnet';
1946 $serverdata['network'] = Protocol::OSTATUS;
1949 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1950 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1958 * Detect if the URL belongs to a Friendica server
1960 * @param string $url URL of the given server
1961 * @param array $serverdata array with server data
1963 * @return array server data
1965 private static function detectFriendica(string $url, array $serverdata): array
1967 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1968 // Because of this me must not use ACCEPT_JSON here.
1969 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1970 if (!$curlResult->isSuccess()) {
1971 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1973 $platform = 'Friendika';
1976 $platform = 'Friendica';
1979 if (!$curlResult->isSuccess()) {
1983 $data = json_decode($curlResult->getBody(), true);
1984 if (empty($data) || empty($data['version'])) {
1988 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1989 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1992 $serverdata['network'] = Protocol::DFRN;
1993 $serverdata['version'] = $data['version'];
1995 if (!empty($data['no_scrape_url'])) {
1996 $serverdata['noscrape'] = $data['no_scrape_url'];
1999 if (!empty($data['site_name'])) {
2000 $serverdata['site_name'] = $data['site_name'];
2003 if (!empty($data['info'])) {
2004 $serverdata['info'] = trim($data['info']);
2007 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2008 switch ($register_policy) {
2009 case 'REGISTER_OPEN':
2010 $serverdata['register_policy'] = Register::OPEN;
2013 case 'REGISTER_APPROVE':
2014 $serverdata['register_policy'] = Register::APPROVE;
2017 case 'REGISTER_CLOSED':
2018 case 'REGISTER_INVITATION':
2019 $serverdata['register_policy'] = Register::CLOSED;
2022 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2023 $serverdata['register_policy'] = Register::CLOSED;
2027 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2033 * Analyses the landing page of a given server for hints about type and system of that server
2035 * @param object $curlResult result of curl execution
2036 * @param array $serverdata array with server data
2038 * @return array server data
2040 private static function analyseRootBody($curlResult, array $serverdata): array
2042 if (empty($curlResult->getBody())) {
2046 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2047 require __DIR__ . '/../../static/platforms.config.php';
2049 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2052 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2054 $doc = new DOMDocument();
2055 @$doc->loadHTML($curlResult->getBody());
2056 $xpath = new DOMXPath($doc);
2059 // We can only detect honk via some HTML element on their page
2060 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2061 $serverdata['platform'] = 'honk';
2062 $serverdata['network'] = Protocol::ACTIVITYPUB;
2066 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2067 if (!empty($title)) {
2068 $serverdata['site_name'] = $title;
2071 $list = $xpath->query('//meta[@name]');
2073 foreach ($list as $node) {
2075 if ($node->attributes->length) {
2076 foreach ($node->attributes as $attribute) {
2077 $value = trim($attribute->value);
2078 if (empty($value)) {
2082 $attr[$attribute->name] = $value;
2085 if (empty($attr['name']) || empty($attr['content'])) {
2090 if ($attr['name'] == 'description') {
2091 $serverdata['info'] = $attr['content'];
2094 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2095 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2096 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2097 $platform = str_replace('/', ' ', $platform);
2098 $platform_parts = explode(' ', $platform);
2099 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2100 $platform = $platform_parts[0];
2101 $serverdata['version'] = $platform_parts[1];
2103 if (in_array($platform, array_values($dfrn_platforms))) {
2104 $serverdata['network'] = Protocol::DFRN;
2105 } elseif (in_array($platform, array_values($ap_platforms))) {
2106 $serverdata['network'] = Protocol::ACTIVITYPUB;
2107 } elseif (in_array($platform, array_values($zap_platforms))) {
2108 $serverdata['network'] = Protocol::ZOT;
2110 if (in_array($platform, array_values($platforms))) {
2111 $serverdata['platform'] = $platform;
2117 $list = $xpath->query('//meta[@property]');
2119 foreach ($list as $node) {
2121 if ($node->attributes->length) {
2122 foreach ($node->attributes as $attribute) {
2123 $value = trim($attribute->value);
2124 if (empty($value)) {
2128 $attr[$attribute->name] = $value;
2131 if (empty($attr['property']) || empty($attr['content'])) {
2136 if ($attr['property'] == 'og:site_name') {
2137 $serverdata['site_name'] = $attr['content'];
2140 if ($attr['property'] == 'og:description') {
2141 $serverdata['info'] = $attr['content'];
2144 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2145 if (in_array($attr['content'], array_keys($platforms))) {
2146 $serverdata['platform'] = $platforms[$attr['content']];
2150 if (in_array($attr['content'], array_keys($ap_platforms))) {
2151 $serverdata['network'] = Protocol::ACTIVITYPUB;
2152 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2153 $serverdata['network'] = Protocol::ZOT;
2158 $list = $xpath->query('//link[@rel="me"]');
2159 foreach ($list as $node) {
2160 foreach ($node->attributes as $attribute) {
2161 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2162 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2163 $serverdata['platform'] = 'microblog';
2164 $serverdata['network'] = Protocol::ACTIVITYPUB;
2170 if ($serverdata['platform'] != 'microblog') {
2171 $list = $xpath->query('//link[@rel="micropub"]');
2172 foreach ($list as $node) {
2173 foreach ($node->attributes as $attribute) {
2174 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2175 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2176 $serverdata['platform'] = 'microblog';
2177 $serverdata['network'] = Protocol::ACTIVITYPUB;
2184 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2185 $serverdata['detection-method'] = self::DETECT_BODY;
2192 * Analyses the header data of a given server for hints about type and system of that server
2194 * @param object $curlResult result of curl execution
2195 * @param array $serverdata array with server data
2197 * @return array server data
2199 private static function analyseRootHeader($curlResult, array $serverdata): array
2201 if ($curlResult->getHeader('server') == 'Mastodon') {
2202 $serverdata['platform'] = 'mastodon';
2203 $serverdata['network'] = Protocol::ACTIVITYPUB;
2204 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2205 $serverdata['platform'] = 'diaspora';
2206 $serverdata['network'] = Protocol::DIASPORA;
2207 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2208 } elseif ($curlResult->inHeader('x-friendica-version')) {
2209 $serverdata['platform'] = 'friendica';
2210 $serverdata['network'] = Protocol::DFRN;
2211 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2216 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2217 $serverdata['detection-method'] = self::DETECT_HEADER;
2224 * Update GServer entries
2226 public static function discover()
2228 // Update the server list
2229 self::discoverFederation();
2233 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2235 if ($requery_days == 0) {
2239 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2241 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2242 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2243 ['order' => ['RAND()']]);
2245 while ($gserver = DBA::fetch($gservers)) {
2246 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2247 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2249 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2250 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2252 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2253 self::update($fields, ['nurl' => $gserver['nurl']]);
2255 if (--$no_of_queries == 0) {
2260 DBA::close($gservers);
2264 * Discover federated servers
2266 private static function discoverFederation()
2268 $last = DI::config()->get('poco', 'last_federation_discovery');
2271 $next = $last + (24 * 60 * 60);
2273 if ($next > time()) {
2278 // Discover federated servers
2279 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2280 foreach ($protocols as $protocol) {
2281 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2282 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2283 if (!empty($curlResult)) {
2284 $data = json_decode($curlResult, true);
2285 if (!empty($data['data']['nodes'])) {
2286 foreach ($data['data']['nodes'] as $server) {
2287 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2288 self::add('https://' . $server['host'], true);
2294 // Disvover Mastodon servers
2295 $accesstoken = DI::config()->get('system', 'instances_social_key');
2297 if (!empty($accesstoken)) {
2298 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2299 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2300 if ($curlResult->isSuccess()) {
2301 $servers = json_decode($curlResult->getBody(), true);
2303 if (!empty($servers['instances'])) {
2304 foreach ($servers['instances'] as $server) {
2305 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2312 DI::config()->set('poco', 'last_federation_discovery', time());
2316 * Set the protocol for the given server
2318 * @param int $gsid Server id
2319 * @param int $protocol Protocol id
2323 public static function setProtocol(int $gsid, int $protocol)
2329 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2330 if (!DBA::isResult($gserver)) {
2334 $old = $gserver['protocol'];
2336 if (!is_null($old)) {
2338 The priority for the protocols is:
2340 2. DFRN via Diaspora
2346 // We don't need to change it when nothing is to be changed
2347 if ($old == $protocol) {
2351 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2352 if ($protocol == Post\DeliveryData::OSTATUS) {
2356 // If the server is marked as ActivityPub then we won't change it to anything different
2357 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2361 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2362 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2366 // Don't change it to Diaspora when it is a legacy DFRN server
2367 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2372 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2373 self::update(['protocol' => $protocol], ['id' => $gsid]);
2377 * Fetch the protocol of the given server
2379 * @param int $gsid Server id
2381 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2385 public static function getProtocol(int $gsid): ?int
2391 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2392 if (DBA::isResult($gserver)) {
2393 return $gserver['protocol'];
2400 * Update rows in the gserver table.
2401 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2403 * @param array $fields
2404 * @param array $condition
2410 public static function update(array $fields, array $condition): bool
2412 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2414 return DBA::update('gserver', $fields, $condition);
2418 * Insert a row into the gserver table.
2419 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2421 * @param array $fields
2422 * @param int $duplicate_mode What to do on a duplicated entry
2428 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2430 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2432 return DBA::insert('gserver', $fields, $duplicate_mode);