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;
48 use Psr\Http\Message\UriInterface;
51 * This class handles GServer related functions
58 const DT_MASTODON = 2;
60 // Methods to detect server types
62 // Non endpoint specific methods
63 const DETECT_MANUAL = 0;
64 const DETECT_HEADER = 1;
65 const DETECT_BODY = 2;
66 const DETECT_HOST_META = 3;
67 const DETECT_CONTACTS = 4;
68 const DETECT_AP_ACTOR = 5;
69 const DETECT_AP_COLLECTION = 6;
71 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
73 // Implementation specific endpoints
74 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
75 const DETECT_FRIENDIKA = 10;
76 const DETECT_FRIENDICA = 11;
77 const DETECT_STATUSNET = 12;
78 const DETECT_GNUSOCIAL = 13;
79 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
80 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
81 const DETECT_MASTODON_API = 16;
82 const DETECT_STATUS_PHP = 17; // Nextcloud
83 const DETECT_V1_CONFIG = 18;
84 const DETECT_PUMPIO = 19; // Deprecated
85 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
87 // Standardized endpoints
88 const DETECT_STATISTICS_JSON = 100;
89 const DETECT_NODEINFO_1 = 101;
90 const DETECT_NODEINFO_2 = 102;
91 const DETECT_NODEINFO_210 = 103;
94 * Check for the existance of a server and adds it in the background if not existant
97 * @param boolean $only_nodeinfo
101 public static function add(string $url, bool $only_nodeinfo = false)
103 if (self::getID($url, false)) {
107 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
111 * Get the ID for the given server URL
114 * @param boolean $no_check Don't check if the server hadn't been found
116 * @return int|null gserver id or NULL on empty URL or failed check
118 public static function getID(string $url, bool $no_check = false): ?int
120 $url = self::cleanURL($url);
126 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
127 if (DBA::isResult($gserver)) {
128 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
129 return $gserver['id'];
132 if ($no_check || !self::check($url)) {
136 return self::getID($url, true);
140 * Retrieves all the servers which base domain are matching the provided domain pattern
142 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
144 * @param string $pattern
150 public static function listByDomainPattern(string $pattern): array
152 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
154 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
155 // eventual server path and keep only the server domain which we're matching against the pattern.
156 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
158 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
159 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
160 AND NOT `gserver`.`failed`
161 GROUP BY `gserver`.`id`";
163 $stmt = DI::dba()->p($sql, $likePattern);
165 return DI::dba()->toArray($stmt);
169 * Checks if the given server array is unreachable for a long time now
171 * @param integer $gsid
174 private static function isDefunct(array $gserver): bool
176 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
177 ($gserver['last_contact'] >= $gserver['created']) &&
178 ($gserver['last_contact'] < $gserver['last_failure']) &&
179 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
183 * Checks if the given server id is unreachable for a long time now
185 * @param integer $gsid
188 public static function isDefunctById(int $gsid): bool
190 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
191 if (empty($gserver)) {
194 if (strtotime($gserver['next_contact']) < time()) {
195 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
197 return self::isDefunct($gserver);
202 * Checks if the given server id is reachable
204 * @param integer $gsid
207 public static function isReachableById(int $gsid): bool
209 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
210 if (empty($gserver)) {
213 if (strtotime($gserver['next_contact']) < time()) {
214 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
216 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
221 * Checks if the given server is reachable
223 * @param array $contact Contact that should be checked
225 * @return boolean 'true' if server seems vital
227 public static function reachable(array $contact): bool
229 if (!empty($contact['gsid'])) {
230 $gsid = $contact['gsid'];
231 } elseif (!empty($contact['baseurl'])) {
232 $server = $contact['baseurl'];
233 } elseif ($contact['network'] == Protocol::DIASPORA) {
234 $parts = parse_url($contact['url']);
235 unset($parts['path']);
236 $server = (string)Uri::fromParts($parts);
242 $condition = ['id' => $gsid];
244 $condition = ['nurl' => Strings::normaliseLink($server)];
247 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
248 if (empty($gserver)) {
251 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
252 $server = $gserver['url'];
255 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
256 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $server, false);
263 * Calculate the next update day
265 * @param bool $success
266 * @param string $created
267 * @param string $last_contact
268 * @param bool $undetected
274 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
276 // On successful contact process check again next week when it is a detected system.
277 // When we haven't detected the system, it could be a static website or a really old system.
279 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
282 $now = strtotime(DateTimeFormat::utcNow());
284 if ($created > $last_contact) {
285 $contact_time = strtotime($created);
287 $contact_time = strtotime($last_contact);
290 // If the last contact was less than 6 hours before then try again in 6 hours
291 if (($now - $contact_time) < (60 * 60 * 6)) {
292 return DateTimeFormat::utc('now +6 hour');
295 // If the last contact was less than 12 hours before then try again in 12 hours
296 if (($now - $contact_time) < (60 * 60 * 12)) {
297 return DateTimeFormat::utc('now +12 hour');
300 // If the last contact was less than 24 hours before then try tomorrow again
301 if (($now - $contact_time) < (60 * 60 * 24)) {
302 return DateTimeFormat::utc('now +1 day');
305 // If the last contact was less than a week before then try again in a week
306 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
307 return DateTimeFormat::utc('now +1 week');
310 // If the last contact was less than two weeks before then try again in two week
311 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
312 return DateTimeFormat::utc('now +2 week');
315 // If the last contact was less than a month before then try again in a month
316 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
317 return DateTimeFormat::utc('now +1 month');
320 // The system hadn't been successul contacted for more than a month, so try again in three months
321 return DateTimeFormat::utc('now +3 month');
325 * Checks the state of the given server.
327 * @param string $server_url URL of the given server
328 * @param string $network Network value that is used, when detection failed
329 * @param boolean $force Force an update.
330 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
332 * @return boolean 'true' if server seems vital
334 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
336 $server_url = self::cleanURL($server_url);
337 if ($server_url == '') {
341 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
342 if (DBA::isResult($gserver)) {
343 if ($gserver['created'] <= DBA::NULL_DATETIME) {
344 $fields = ['created' => DateTimeFormat::utcNow()];
345 $condition = ['nurl' => Strings::normaliseLink($server_url)];
346 self::update($fields, $condition);
349 if (!$force && (strtotime($gserver['next_contact']) > time())) {
350 Logger::info('No update needed', ['server' => $server_url]);
351 return (!$gserver['failed']);
353 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
355 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
358 return self::detect($server_url, $network, $only_nodeinfo);
362 * Reset failed server status by gserver id
365 * @param string $network
367 public static function setReachableById(int $gsid, string $network)
369 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
370 if (DBA::isResult($gserver) && $gserver['failed']) {
371 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow()];
372 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
373 $fields['network'] = $network;
375 self::update($fields, ['id' => $gsid]);
376 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
378 if (strtotime($gserver['next_contact']) < time()) {
379 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
385 * Set failed server status by gserver id
389 public static function setFailureById(int $gsid)
391 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
392 if (DBA::isResult($gserver) && !$gserver['failed']) {
393 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
394 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
396 if (strtotime($gserver['next_contact']) < time()) {
397 Worker::add(Worker::PRIORITY_LOW, 'UpdateGServer', $gserver['url'], false);
403 * Set failed server status
407 public static function setFailureByUrl(string $url)
409 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
410 if (DBA::isResult($gserver)) {
411 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
412 self::update(['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
413 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
414 ['nurl' => Strings::normaliseLink($url)]);
415 Logger::info('Set failed status for existing server', ['url' => $url]);
416 if (self::isDefunct($gserver)) {
417 self::archiveContacts($gserver['id']);
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 * Archive server related contacts and inboxes
430 * @param integer $gsid
433 private static function archiveContacts(int $gsid)
435 Contact::update(['archive' => true], ['gsid' => $gsid]);
436 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
440 * Remove unwanted content from the given URL
442 * @param string $dirtyUrl
444 * @return string cleaned URL
446 * @deprecated since 2023.03 Use cleanUri instead
448 public static function cleanURL(string $dirtyUrl): string
451 return (string)self::cleanUri(new Uri($dirtyUrl));
452 } catch (\Throwable $e) {
453 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
459 * Remove unwanted content from the given URI
461 * @param UriInterface $dirtyUri
463 * @return UriInterface cleaned URI
466 public static function cleanUri(UriInterface $dirtyUri): string
474 '#(?:^|/)index\.php#',
476 rtrim($dirtyUri->getPath(), '/')
482 * Detect server data (type, protocol, version number, ...)
483 * The detected data is then updated or inserted in the gserver table.
485 * @param string $url URL of the given server
486 * @param string $network Network value that is used, when detection failed
487 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
489 * @return boolean 'true' if server could be detected
491 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
493 Logger::info('Detect server type', ['server' => $url]);
495 $original_url = $url;
497 // Remove URL content that is not supposed to exist for a server url
498 $url = rtrim(self::cleanURL($url), '/');
500 Logger::notice('Empty URL.');
504 // If the URL missmatches, then we mark the old entry as failure
505 if (!Strings::compareLink($url, $original_url)) {
506 self::setFailureByUrl($original_url);
507 if (!self::getID($url, true)) {
508 self::detect($url, $network, $only_nodeinfo);
513 $valid_url = Network::isUrlValid($url);
515 self::setFailureByUrl($url);
518 $valid_url = rtrim($valid_url, '/');
521 if (!Strings::compareLink($url, $valid_url)) {
522 // We only follow redirects when the path stays the same or the target url has no path.
523 // Some systems have got redirects on their landing page to a single account page. This check handles it.
524 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))) ||
525 (((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)))) {
526 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
527 self::setFailureByUrl($url);
528 if (!self::getID($valid_url, true)) {
529 self::detect($valid_url, $network, $only_nodeinfo);
534 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)) &&
535 (parse_url($url, PHP_URL_PATH) == '')) {
536 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
537 $parts = parse_url($valid_url);
538 unset($parts['path']);
539 $valid_url = (string)Uri::fromParts($parts);
541 self::setFailureByUrl($url);
542 if (!self::getID($valid_url, true)) {
543 self::detect($valid_url, $network, $only_nodeinfo);
547 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
550 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
551 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
552 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
556 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
558 // When a nodeinfo is present, we don't need to dig further
559 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
560 if ($curlResult->isTimeout()) {
561 self::setFailureByUrl($url);
565 $serverdata = self::parseNodeinfo210($curlResult);
566 if (empty($serverdata)) {
567 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
568 $serverdata = self::fetchNodeinfo($url, $curlResult);
571 if ($only_nodeinfo && empty($serverdata)) {
572 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
573 self::setFailureByUrl($url);
575 } elseif (empty($serverdata)) {
576 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
579 // When there is no Nodeinfo, then use some protocol specific endpoints
580 if ($serverdata['network'] == Protocol::PHANTOM) {
582 // Fetch the landing page, possibly it reveals some data
583 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
584 $curlResult = DI::httpClient()->get($url, $accept);
585 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
586 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
587 $html_fetched = true;
589 $html_fetched = false;
592 if ($curlResult->isSuccess()) {
593 $json = json_decode($curlResult->getBody(), true);
594 if (!empty($json) && is_array($json)) {
595 $data = self::fetchDataFromSystemActor($json, $serverdata);
596 $serverdata = $data['server'];
597 $systemactor = $data['actor'];
598 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
599 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
601 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
602 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
605 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
606 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
607 $serverdata = self::analyseRootBody($curlResult, $serverdata);
611 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
612 self::setFailureByUrl($url);
616 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
617 $serverdata = self::detectMastodonAlikes($url, $serverdata);
621 // All following checks are done for systems that always have got a "host-meta" endpoint.
622 // With this check we don't have to waste time and ressources for dead systems.
623 // Also this hopefully prevents us from receiving abuse messages.
624 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
625 $validHostMeta = self::validHostMeta($url);
627 $validHostMeta = false;
630 if ($validHostMeta) {
631 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
632 $serverdata['detection-method'] = self::DETECT_HOST_META;
635 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
636 $serverdata = self::detectFriendica($url, $serverdata);
639 // The following systems have to be installed in the root directory.
641 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
642 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
643 $serverdata = self::fetchSiteinfo($url, $serverdata);
646 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
647 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
648 $serverdata = self::detectHubzilla($url, $serverdata);
651 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
652 $serverdata = self::detectPeertube($url, $serverdata);
655 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
656 $serverdata = self::detectGNUSocial($url, $serverdata);
659 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
660 $serverdata = self::detectFriendica($url, $serverdata);
663 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
664 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
667 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
668 // Since this endpoint is only rarely used, we query it at a later time
669 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
670 $serverdata = self::fetchStatistics($url, $serverdata);
674 // When we hadn't been able to detect the network type, we use the hint from the parameter
675 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
676 $serverdata['network'] = $network;
679 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
680 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
681 self::setFailureByUrl($url);
685 $serverdata['url'] = $url;
686 $serverdata['nurl'] = Strings::normaliseLink($url);
688 // We have to prevent an endless loop here.
689 // When a server is new, then there is no gserver entry yet.
690 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
691 // and this can call this function here as well.
692 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
693 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
694 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
697 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
698 self::setFailureByUrl($url);
702 // Detect the directory type
703 $serverdata['directory-type'] = self::DT_NONE;
705 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
706 $serverdata = self::checkMastodonDirectory($url, $serverdata);
708 if ($serverdata['directory-type'] == self::DT_NONE) {
709 $serverdata = self::checkPoCo($url, $serverdata);
713 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
714 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
717 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
719 // Numbers above a reasonable value (10 millions) are ignored
720 if ($serverdata['registered-users'] > 10000000) {
721 $serverdata['registered-users'] = 0;
724 // On an active server there has to be at least a single user
725 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
726 $serverdata['registered-users'] = 1;
727 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
728 $serverdata['registered-users'] = 0;
731 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
733 $serverdata['last_contact'] = DateTimeFormat::utcNow();
734 $serverdata['failed'] = false;
736 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
737 if (!DBA::isResult($gserver)) {
738 $serverdata['created'] = DateTimeFormat::utcNow();
739 $ret = self::insert($serverdata);
740 $id = DBA::lastInsertId();
742 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
743 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
744 if (DBA::isResult($gserver)) {
745 $id = $gserver['id'];
749 // Count the number of known contacts from this server
750 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
751 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
752 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
753 $max_users = max($apcontacts, $contacts);
754 if ($max_users > $serverdata['registered-users']) {
755 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
756 self::update(['registered-users' => $max_users], ['id' => $id]);
759 if (empty($serverdata['active-month-users'])) {
760 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
762 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
763 self::update(['active-month-users' => $contacts], ['id' => $id]);
767 if (empty($serverdata['active-halfyear-users'])) {
768 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
770 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
771 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
776 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
777 self::discoverRelay($url);
780 if (!empty($systemactor)) {
781 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
782 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
789 * Fetch relay data from a given server url
791 * @param string $server_url address of the server
795 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
797 private static function discoverRelay(string $server_url)
799 Logger::info('Discover relay data', ['server' => $server_url]);
801 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
802 if (!$curlResult->isSuccess()) {
806 $data = json_decode($curlResult->getBody(), true);
807 if (!is_array($data)) {
811 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
812 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
814 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
816 $data['subscribe'] = false;
820 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
821 if (!DBA::isResult($gserver)) {
825 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
826 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
827 self::update($fields, ['id' => $gserver['id']]);
830 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
832 if ($data['scope'] == 'tags') {
835 foreach ($data['tags'] as $tag) {
836 $tag = mb_strtolower($tag);
837 if (strlen($tag) < 100) {
842 foreach ($tags as $tag) {
843 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
847 // Create or update the relay contact
849 if (isset($data['protocols'])) {
850 if (isset($data['protocols']['diaspora'])) {
851 $fields['network'] = Protocol::DIASPORA;
853 if (isset($data['protocols']['diaspora']['receive'])) {
854 $fields['batch'] = $data['protocols']['diaspora']['receive'];
855 } elseif (is_string($data['protocols']['diaspora'])) {
856 $fields['batch'] = $data['protocols']['diaspora'];
860 if (isset($data['protocols']['dfrn'])) {
861 $fields['network'] = Protocol::DFRN;
863 if (isset($data['protocols']['dfrn']['receive'])) {
864 $fields['batch'] = $data['protocols']['dfrn']['receive'];
865 } elseif (is_string($data['protocols']['dfrn'])) {
866 $fields['batch'] = $data['protocols']['dfrn'];
870 if (isset($data['protocols']['activitypub'])) {
871 $fields['network'] = Protocol::ACTIVITYPUB;
873 if (!empty($data['protocols']['activitypub']['actor'])) {
874 $fields['url'] = $data['protocols']['activitypub']['actor'];
876 if (!empty($data['protocols']['activitypub']['receive'])) {
877 $fields['batch'] = $data['protocols']['activitypub']['receive'];
882 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
884 Relay::updateContact($gserver, $fields);
888 * Fetch server data from '/statistics.json' on the given server
890 * @param string $url URL of the given server
892 * @return array server data
894 private static function fetchStatistics(string $url, array $serverdata): array
896 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
897 if (!$curlResult->isSuccess()) {
901 $data = json_decode($curlResult->getBody(), true);
906 // Some AP enabled systems return activity data that we don't expect here.
907 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
912 $old_serverdata = $serverdata;
914 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
916 if (!empty($data['version'])) {
918 $serverdata['version'] = $data['version'];
919 // Version numbers on statistics.json are presented with additional info, e.g.:
920 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
921 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
924 if (!empty($data['name'])) {
926 $serverdata['site_name'] = $data['name'];
929 if (!empty($data['network'])) {
931 $serverdata['platform'] = strtolower($data['network']);
933 if ($serverdata['platform'] == 'diaspora') {
934 $serverdata['network'] = Protocol::DIASPORA;
935 } elseif ($serverdata['platform'] == 'friendica') {
936 $serverdata['network'] = Protocol::DFRN;
937 } elseif ($serverdata['platform'] == 'hubzilla') {
938 $serverdata['network'] = Protocol::ZOT;
939 } elseif ($serverdata['platform'] == 'redmatrix') {
940 $serverdata['network'] = Protocol::ZOT;
944 if (!empty($data['total_users'])) {
946 $serverdata['registered-users'] = max($data['total_users'], 1);
949 if (!empty($data['active_users_monthly'])) {
951 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
954 if (!empty($data['active_users_halfyear'])) {
956 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
959 if (!empty($data['local_posts'])) {
961 $serverdata['local-posts'] = max($data['local_posts'], 0);
964 if (!empty($data['registrations_open'])) {
965 $serverdata['register_policy'] = Register::OPEN;
967 $serverdata['register_policy'] = Register::CLOSED;
971 return $old_serverdata;
978 * Detect server type by using the nodeinfo data
980 * @param string $url address of the server
981 * @param ICanHandleHttpResponses $httpResult
983 * @return array Server data
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
989 if (!$httpResult->isSuccess()) {
993 $nodeinfo = json_decode($httpResult->getBody(), true);
995 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
1000 $nodeinfo2_url = '';
1002 foreach ($nodeinfo['links'] as $link) {
1003 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
1004 Logger::info('Invalid nodeinfo format', ['url' => $url]);
1007 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
1008 $nodeinfo1_url = $link['href'];
1009 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
1010 $nodeinfo2_url = $link['href'];
1014 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1020 if (!empty($nodeinfo2_url)) {
1021 $server = self::parseNodeinfo2($nodeinfo2_url);
1024 if (empty($server) && !empty($nodeinfo1_url)) {
1025 $server = self::parseNodeinfo1($nodeinfo1_url);
1034 * @param string $nodeinfo_url address of the nodeinfo path
1036 * @return array Server data
1038 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1040 private static function parseNodeinfo1(string $nodeinfo_url): array
1042 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1043 if (!$curlResult->isSuccess()) {
1047 $nodeinfo = json_decode($curlResult->getBody(), true);
1049 if (!is_array($nodeinfo)) {
1053 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1054 'register_policy' => Register::CLOSED];
1056 if (!empty($nodeinfo['openRegistrations'])) {
1057 $server['register_policy'] = Register::OPEN;
1060 if (is_array($nodeinfo['software'])) {
1061 if (!empty($nodeinfo['software']['name'])) {
1062 $server['platform'] = strtolower($nodeinfo['software']['name']);
1065 if (!empty($nodeinfo['software']['version'])) {
1066 $server['version'] = $nodeinfo['software']['version'];
1067 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1068 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1069 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1073 if (!empty($nodeinfo['metadata']['nodeName'])) {
1074 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1077 if (!empty($nodeinfo['usage']['users']['total'])) {
1078 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1081 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1082 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1085 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1086 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1089 if (!empty($nodeinfo['usage']['localPosts'])) {
1090 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1093 if (!empty($nodeinfo['usage']['localComments'])) {
1094 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1097 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1099 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1100 $protocols[$protocol] = true;
1103 if (!empty($protocols['friendica'])) {
1104 $server['network'] = Protocol::DFRN;
1105 } elseif (!empty($protocols['activitypub'])) {
1106 $server['network'] = Protocol::ACTIVITYPUB;
1107 } elseif (!empty($protocols['diaspora'])) {
1108 $server['network'] = Protocol::DIASPORA;
1109 } elseif (!empty($protocols['ostatus'])) {
1110 $server['network'] = Protocol::OSTATUS;
1111 } elseif (!empty($protocols['gnusocial'])) {
1112 $server['network'] = Protocol::OSTATUS;
1113 } elseif (!empty($protocols['zot'])) {
1114 $server['network'] = Protocol::ZOT;
1118 if (empty($server)) {
1122 if (empty($server['network'])) {
1123 $server['network'] = Protocol::PHANTOM;
1132 * @see https://git.feneas.org/jaywink/nodeinfo2
1134 * @param string $nodeinfo_url address of the nodeinfo path
1136 * @return array Server data
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 private static function parseNodeinfo2(string $nodeinfo_url): array
1142 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1143 if (!$curlResult->isSuccess()) {
1147 $nodeinfo = json_decode($curlResult->getBody(), true);
1148 if (!is_array($nodeinfo)) {
1153 'detection-method' => self::DETECT_NODEINFO_2,
1154 'register_policy' => Register::CLOSED,
1155 'platform' => 'unknown',
1158 if (!empty($nodeinfo['openRegistrations'])) {
1159 $server['register_policy'] = Register::OPEN;
1162 if (!empty($nodeinfo['software'])) {
1163 if (isset($nodeinfo['software']['name'])) {
1164 $server['platform'] = strtolower($nodeinfo['software']['name']);
1167 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1168 $server['version'] = $nodeinfo['software']['version'];
1169 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1170 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1171 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1173 // qoto advertises itself as Mastodon
1174 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1175 $server['platform'] = 'qoto';
1180 if (!empty($nodeinfo['metadata']['nodeName'])) {
1181 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1184 if (!empty($nodeinfo['usage']['users']['total'])) {
1185 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1188 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1189 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1192 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1193 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1196 if (!empty($nodeinfo['usage']['localPosts'])) {
1197 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1200 if (!empty($nodeinfo['usage']['localComments'])) {
1201 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1204 if (!empty($nodeinfo['protocols'])) {
1206 foreach ($nodeinfo['protocols'] as $protocol) {
1207 if (is_string($protocol)) {
1208 $protocols[$protocol] = true;
1212 if (!empty($protocols['dfrn'])) {
1213 $server['network'] = Protocol::DFRN;
1214 } elseif (!empty($protocols['activitypub'])) {
1215 $server['network'] = Protocol::ACTIVITYPUB;
1216 } elseif (!empty($protocols['diaspora'])) {
1217 $server['network'] = Protocol::DIASPORA;
1218 } elseif (!empty($protocols['ostatus'])) {
1219 $server['network'] = Protocol::OSTATUS;
1220 } elseif (!empty($protocols['gnusocial'])) {
1221 $server['network'] = Protocol::OSTATUS;
1222 } elseif (!empty($protocols['zot'])) {
1223 $server['network'] = Protocol::ZOT;
1227 if (empty($server)) {
1231 if (empty($server['network'])) {
1232 $server['network'] = Protocol::PHANTOM;
1239 * Parses NodeInfo2 protocol 1.0
1241 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1243 * @param string $nodeinfo_url address of the nodeinfo path
1245 * @return array Server data
1247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1249 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1251 if (!$httpResult->isSuccess()) {
1255 $nodeinfo = json_decode($httpResult->getBody(), true);
1257 if (!is_array($nodeinfo)) {
1261 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1262 'register_policy' => Register::CLOSED];
1264 if (!empty($nodeinfo['openRegistrations'])) {
1265 $server['register_policy'] = Register::OPEN;
1268 if (!empty($nodeinfo['server'])) {
1269 if (!empty($nodeinfo['server']['software'])) {
1270 $server['platform'] = strtolower($nodeinfo['server']['software']);
1273 if (!empty($nodeinfo['server']['version'])) {
1274 $server['version'] = $nodeinfo['server']['version'];
1275 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1276 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1277 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1280 if (!empty($nodeinfo['server']['name'])) {
1281 $server['site_name'] = $nodeinfo['server']['name'];
1285 if (!empty($nodeinfo['usage']['users']['total'])) {
1286 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1289 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1290 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1293 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1294 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1297 if (!empty($nodeinfo['usage']['localPosts'])) {
1298 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1301 if (!empty($nodeinfo['usage']['localComments'])) {
1302 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1305 if (!empty($nodeinfo['protocols'])) {
1307 foreach ($nodeinfo['protocols'] as $protocol) {
1308 if (is_string($protocol)) {
1309 $protocols[$protocol] = true;
1313 if (!empty($protocols['dfrn'])) {
1314 $server['network'] = Protocol::DFRN;
1315 } elseif (!empty($protocols['activitypub'])) {
1316 $server['network'] = Protocol::ACTIVITYPUB;
1317 } elseif (!empty($protocols['diaspora'])) {
1318 $server['network'] = Protocol::DIASPORA;
1319 } elseif (!empty($protocols['ostatus'])) {
1320 $server['network'] = Protocol::OSTATUS;
1321 } elseif (!empty($protocols['gnusocial'])) {
1322 $server['network'] = Protocol::OSTATUS;
1323 } elseif (!empty($protocols['zot'])) {
1324 $server['network'] = Protocol::ZOT;
1328 if (empty($server) || empty($server['platform'])) {
1332 if (empty($server['network'])) {
1333 $server['network'] = Protocol::PHANTOM;
1340 * Fetch server information from a 'siteinfo.json' file on the given server
1342 * @param string $url URL of the given server
1343 * @param array $serverdata array with server data
1345 * @return array server data
1347 private static function fetchSiteinfo(string $url, array $serverdata): array
1349 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1350 if (!$curlResult->isSuccess()) {
1354 $data = json_decode($curlResult->getBody(), true);
1359 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1360 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1363 if (!empty($data['url'])) {
1364 $serverdata['platform'] = strtolower($data['platform']);
1365 $serverdata['version'] = $data['version'] ?? 'N/A';
1368 if (!empty($data['plugins'])) {
1369 if (in_array('pubcrawl', $data['plugins'])) {
1370 $serverdata['network'] = Protocol::ACTIVITYPUB;
1371 } elseif (in_array('diaspora', $data['plugins'])) {
1372 $serverdata['network'] = Protocol::DIASPORA;
1373 } elseif (in_array('gnusoc', $data['plugins'])) {
1374 $serverdata['network'] = Protocol::OSTATUS;
1376 $serverdata['network'] = Protocol::ZOT;
1380 if (!empty($data['site_name'])) {
1381 $serverdata['site_name'] = $data['site_name'];
1384 if (!empty($data['channels_total'])) {
1385 $serverdata['registered-users'] = max($data['channels_total'], 1);
1388 if (!empty($data['channels_active_monthly'])) {
1389 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1392 if (!empty($data['channels_active_halfyear'])) {
1393 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1396 if (!empty($data['local_posts'])) {
1397 $serverdata['local-posts'] = max($data['local_posts'], 0);
1400 if (!empty($data['local_comments'])) {
1401 $serverdata['local-comments'] = max($data['local_comments'], 0);
1404 if (!empty($data['register_policy'])) {
1405 switch ($data['register_policy']) {
1406 case 'REGISTER_OPEN':
1407 $serverdata['register_policy'] = Register::OPEN;
1410 case 'REGISTER_APPROVE':
1411 $serverdata['register_policy'] = Register::APPROVE;
1414 case 'REGISTER_CLOSED':
1416 $serverdata['register_policy'] = Register::CLOSED;
1425 * Fetches server data via an ActivityPub account with url of that server
1427 * @param string $url URL of the given server
1428 * @param array $serverdata array with server data
1430 * @return array server data
1434 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1437 return ['server' => $serverdata, 'actor' => ''];
1440 $actor = JsonLD::compact($data, false);
1441 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1442 $serverdata['network'] = Protocol::ACTIVITYPUB;
1443 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1444 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1445 if (!empty($actor['as:generator'])) {
1446 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1447 $serverdata['platform'] = strtolower(array_shift($generator));
1448 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1450 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1452 return ['server' => $serverdata, 'actor' => $actor['@id']];
1453 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1454 // By now only Ktistec seems to provide collections this way
1455 $serverdata['platform'] = 'ktistec';
1456 $serverdata['network'] = Protocol::ACTIVITYPUB;
1457 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1459 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1460 if (!empty($actors) && !empty($actors[0]['@id'])) {
1461 $actor_url = $actor['@id'] . $actors[0]['@id'];
1466 return ['server' => $serverdata, 'actor' => $actor_url];
1468 return ['server' => $serverdata, 'actor' => ''];
1472 * Checks if the server contains a valid host meta file
1474 * @param string $url URL of the given server
1476 * @return boolean 'true' if the server seems to be vital
1478 private static function validHostMeta(string $url): bool
1480 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1481 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1482 if (!$curlResult->isSuccess()) {
1486 $xrd = XML::parseString($curlResult->getBody(), true);
1487 if (!is_object($xrd)) {
1491 $elements = XML::elementToArray($xrd);
1492 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1497 foreach ($elements['xrd']['link'] as $link) {
1498 // When there is more than a single "link" element, the array looks slightly different
1499 if (!empty($link['@attributes'])) {
1500 $link = $link['@attributes'];
1503 if (empty($link['rel']) || empty($link['template'])) {
1507 if ($link['rel'] == 'lrdd') {
1508 // When the webfinger host is the same like the system host, it should be ok.
1509 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1517 * Detect the network of the given server via their known contacts
1519 * @param string $url URL of the given server
1520 * @param array $serverdata array with server data
1522 * @return array server data
1524 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1528 $nurl = Strings::normaliseLink($url);
1530 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1531 while ($apcontact = DBA::fetch($apcontacts)) {
1532 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1534 DBA::close($apcontacts);
1536 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1537 while ($pcontact = DBA::fetch($pcontacts)) {
1538 $contacts[$pcontact['nurl']] = $pcontact['url'];
1540 DBA::close($pcontacts);
1542 if (empty($contacts)) {
1547 foreach ($contacts as $contact) {
1548 // Endlosschleife verhindern wegen gsid!
1549 $data = Probe::uri($contact);
1550 if (in_array($data['network'], Protocol::FEDERATED)) {
1551 $serverdata['network'] = $data['network'];
1553 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1554 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1557 } elseif ((time() - $time) > 10) {
1558 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1567 * Checks if the given server does have a '/poco' endpoint.
1568 * This is used for the 'PortableContact' functionality,
1569 * which is used by both Friendica and Hubzilla.
1571 * @param string $url URL of the given server
1572 * @param array $serverdata array with server data
1574 * @return array server data
1576 private static function checkPoCo(string $url, array $serverdata): array
1578 $serverdata['poco'] = '';
1580 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1581 if (!$curlResult->isSuccess()) {
1585 $data = json_decode($curlResult->getBody(), true);
1590 if (!empty($data['totalResults'])) {
1591 $registeredUsers = $serverdata['registered-users'] ?? 0;
1592 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1593 $serverdata['directory-type'] = self::DT_POCO;
1594 $serverdata['poco'] = $url . '/poco';
1601 * Checks if the given server does have a Mastodon style directory endpoint.
1603 * @param string $url URL of the given server
1604 * @param array $serverdata array with server data
1606 * @return array server data
1608 public static function checkMastodonDirectory(string $url, array $serverdata): array
1610 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1611 if (!$curlResult->isSuccess()) {
1615 $data = json_decode($curlResult->getBody(), true);
1620 if (count($data) == 1) {
1621 $serverdata['directory-type'] = self::DT_MASTODON;
1628 * Detects Peertube via their known endpoint
1630 * @param string $url URL of the given server
1631 * @param array $serverdata array with server data
1633 * @return array server data
1635 private static function detectPeertube(string $url, array $serverdata): array
1637 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1638 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1642 $data = json_decode($curlResult->getBody(), true);
1647 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1648 $serverdata['platform'] = 'peertube';
1649 $serverdata['version'] = $data['serverVersion'];
1650 $serverdata['network'] = Protocol::ACTIVITYPUB;
1652 if (!empty($data['instance']['name'])) {
1653 $serverdata['site_name'] = $data['instance']['name'];
1656 if (!empty($data['instance']['shortDescription'])) {
1657 $serverdata['info'] = $data['instance']['shortDescription'];
1660 if (!empty($data['signup'])) {
1661 if (!empty($data['signup']['allowed'])) {
1662 $serverdata['register_policy'] = Register::OPEN;
1666 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1667 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1675 * Detects the version number of a given server when it was a NextCloud installation
1677 * @param string $url URL of the given server
1678 * @param array $serverdata array with server data
1679 * @param bool $validHostMeta
1681 * @return array server data
1683 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1685 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1686 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1690 $data = json_decode($curlResult->getBody(), true);
1695 if (!empty($data['version'])) {
1696 $serverdata['platform'] = 'nextcloud';
1697 $serverdata['version'] = $data['version'];
1699 if ($validHostMeta) {
1700 $serverdata['network'] = Protocol::ACTIVITYPUB;
1703 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1704 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1712 * Fetches weekly usage data
1714 * @param string $url URL of the given server
1715 * @param array $serverdata array with server data
1717 * @return array server data
1719 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1721 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1722 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1726 $data = json_decode($curlResult->getBody(), true);
1732 foreach ($data as $week) {
1733 // Use only data from a full week
1734 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1738 // Most likely the data is sorted correctly. But we better are safe than sorry
1739 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1740 $current_week = $week;
1744 if (!empty($current_week['logins'])) {
1745 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1752 * Detects data from a given server url if it was a mastodon alike system
1754 * @param string $url URL of the given server
1755 * @param array $serverdata array with server data
1757 * @return array server data
1759 private static function detectMastodonAlikes(string $url, array $serverdata): array
1761 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1762 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1766 $data = json_decode($curlResult->getBody(), true);
1773 if (!empty($data['version'])) {
1774 $serverdata['platform'] = 'mastodon';
1775 $serverdata['version'] = $data['version'] ?? '';
1776 $serverdata['network'] = Protocol::ACTIVITYPUB;
1780 if (!empty($data['title'])) {
1781 $serverdata['site_name'] = $data['title'];
1784 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1785 $serverdata['platform'] = 'mastodon';
1786 $serverdata['network'] = Protocol::ACTIVITYPUB;
1790 if (!empty($data['description'])) {
1791 $serverdata['info'] = trim($data['description']);
1794 if (!empty($data['stats']['user_count'])) {
1795 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1798 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1799 $serverdata['platform'] = strtolower($matches[1]);
1800 $serverdata['version'] = $matches[2];
1804 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1805 $serverdata['platform'] = 'pleroma';
1806 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1810 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1811 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1812 $serverdata['platform'] = 'pleroma';
1816 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1817 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1824 * Detects data from typical Hubzilla endpoints
1826 * @param string $url URL of the given server
1827 * @param array $serverdata array with server data
1829 * @return array server data
1831 private static function detectHubzilla(string $url, array $serverdata): array
1833 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1834 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1838 $data = json_decode($curlResult->getBody(), true);
1839 if (empty($data) || empty($data['site'])) {
1843 if (!empty($data['site']['name'])) {
1844 $serverdata['site_name'] = $data['site']['name'];
1847 if (!empty($data['site']['platform'])) {
1848 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1849 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1850 $serverdata['network'] = Protocol::ZOT;
1853 if (!empty($data['site']['hubzilla'])) {
1854 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1855 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1856 $serverdata['network'] = Protocol::ZOT;
1859 if (!empty($data['site']['redmatrix'])) {
1860 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1861 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1862 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1863 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1866 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1867 $serverdata['network'] = Protocol::ZOT;
1871 $inviteonly = false;
1874 if (!empty($data['site']['closed'])) {
1875 $closed = self::toBoolean($data['site']['closed']);
1878 if (!empty($data['site']['private'])) {
1879 $private = self::toBoolean($data['site']['private']);
1882 if (!empty($data['site']['inviteonly'])) {
1883 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1886 if (!$closed && !$private and $inviteonly) {
1887 $serverdata['register_policy'] = Register::APPROVE;
1888 } elseif (!$closed && !$private) {
1889 $serverdata['register_policy'] = Register::OPEN;
1891 $serverdata['register_policy'] = Register::CLOSED;
1894 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1895 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1902 * Converts input value to a boolean value
1904 * @param string|integer $val
1908 private static function toBoolean($val): bool
1910 if (($val == 'true') || ($val == 1)) {
1912 } elseif (($val == 'false') || ($val == 0)) {
1920 * Detect if the URL belongs to a GNU Social server
1922 * @param string $url URL of the given server
1923 * @param array $serverdata array with server data
1925 * @return array server data
1927 private static function detectGNUSocial(string $url, array $serverdata): array
1929 // Test for GNU Social
1930 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1931 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1932 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1933 $serverdata['platform'] = 'gnusocial';
1934 // Remove junk that some GNU Social servers return
1935 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1936 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1937 $serverdata['version'] = trim($serverdata['version'], '"');
1938 $serverdata['network'] = Protocol::OSTATUS;
1940 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1941 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1947 // Test for Statusnet
1948 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1949 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1950 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1952 // Remove junk that some GNU Social servers return
1953 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1954 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1955 $serverdata['version'] = trim($serverdata['version'], '"');
1957 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1958 $serverdata['platform'] = 'pleroma';
1959 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1960 $serverdata['network'] = Protocol::ACTIVITYPUB;
1962 $serverdata['platform'] = 'statusnet';
1963 $serverdata['network'] = Protocol::OSTATUS;
1966 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1967 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1975 * Detect if the URL belongs to a Friendica server
1977 * @param string $url URL of the given server
1978 * @param array $serverdata array with server data
1980 * @return array server data
1982 private static function detectFriendica(string $url, array $serverdata): array
1984 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1985 // Because of this me must not use ACCEPT_JSON here.
1986 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1987 if (!$curlResult->isSuccess()) {
1988 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1990 $platform = 'Friendika';
1993 $platform = 'Friendica';
1996 if (!$curlResult->isSuccess()) {
2000 $data = json_decode($curlResult->getBody(), true);
2001 if (empty($data) || empty($data['version'])) {
2005 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2006 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2009 $serverdata['network'] = Protocol::DFRN;
2010 $serverdata['version'] = $data['version'];
2012 if (!empty($data['no_scrape_url'])) {
2013 $serverdata['noscrape'] = $data['no_scrape_url'];
2016 if (!empty($data['site_name'])) {
2017 $serverdata['site_name'] = $data['site_name'];
2020 if (!empty($data['info'])) {
2021 $serverdata['info'] = trim($data['info']);
2024 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2025 switch ($register_policy) {
2026 case 'REGISTER_OPEN':
2027 $serverdata['register_policy'] = Register::OPEN;
2030 case 'REGISTER_APPROVE':
2031 $serverdata['register_policy'] = Register::APPROVE;
2034 case 'REGISTER_CLOSED':
2035 case 'REGISTER_INVITATION':
2036 $serverdata['register_policy'] = Register::CLOSED;
2039 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2040 $serverdata['register_policy'] = Register::CLOSED;
2044 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2050 * Analyses the landing page of a given server for hints about type and system of that server
2052 * @param object $curlResult result of curl execution
2053 * @param array $serverdata array with server data
2055 * @return array server data
2057 private static function analyseRootBody($curlResult, array $serverdata): array
2059 if (empty($curlResult->getBody())) {
2063 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2064 require __DIR__ . '/../../static/platforms.config.php';
2066 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2069 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2071 $doc = new DOMDocument();
2072 @$doc->loadHTML($curlResult->getBody());
2073 $xpath = new DOMXPath($doc);
2076 // We can only detect honk via some HTML element on their page
2077 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2078 $serverdata['platform'] = 'honk';
2079 $serverdata['network'] = Protocol::ACTIVITYPUB;
2083 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2084 if (!empty($title)) {
2085 $serverdata['site_name'] = $title;
2088 $list = $xpath->query('//meta[@name]');
2090 foreach ($list as $node) {
2092 if ($node->attributes->length) {
2093 foreach ($node->attributes as $attribute) {
2094 $value = trim($attribute->value);
2095 if (empty($value)) {
2099 $attr[$attribute->name] = $value;
2102 if (empty($attr['name']) || empty($attr['content'])) {
2107 if ($attr['name'] == 'description') {
2108 $serverdata['info'] = $attr['content'];
2111 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2112 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2113 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2114 $platform = str_replace('/', ' ', $platform);
2115 $platform_parts = explode(' ', $platform);
2116 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2117 $platform = $platform_parts[0];
2118 $serverdata['version'] = $platform_parts[1];
2120 if (in_array($platform, array_values($dfrn_platforms))) {
2121 $serverdata['network'] = Protocol::DFRN;
2122 } elseif (in_array($platform, array_values($ap_platforms))) {
2123 $serverdata['network'] = Protocol::ACTIVITYPUB;
2124 } elseif (in_array($platform, array_values($zap_platforms))) {
2125 $serverdata['network'] = Protocol::ZOT;
2127 if (in_array($platform, array_values($platforms))) {
2128 $serverdata['platform'] = $platform;
2134 $list = $xpath->query('//meta[@property]');
2136 foreach ($list as $node) {
2138 if ($node->attributes->length) {
2139 foreach ($node->attributes as $attribute) {
2140 $value = trim($attribute->value);
2141 if (empty($value)) {
2145 $attr[$attribute->name] = $value;
2148 if (empty($attr['property']) || empty($attr['content'])) {
2153 if ($attr['property'] == 'og:site_name') {
2154 $serverdata['site_name'] = $attr['content'];
2157 if ($attr['property'] == 'og:description') {
2158 $serverdata['info'] = $attr['content'];
2161 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2162 if (in_array($attr['content'], array_keys($platforms))) {
2163 $serverdata['platform'] = $platforms[$attr['content']];
2167 if (in_array($attr['content'], array_keys($ap_platforms))) {
2168 $serverdata['network'] = Protocol::ACTIVITYPUB;
2169 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2170 $serverdata['network'] = Protocol::ZOT;
2175 $list = $xpath->query('//link[@rel="me"]');
2176 foreach ($list as $node) {
2177 foreach ($node->attributes as $attribute) {
2178 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2179 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2180 $serverdata['platform'] = 'microblog';
2181 $serverdata['network'] = Protocol::ACTIVITYPUB;
2187 if ($serverdata['platform'] != 'microblog') {
2188 $list = $xpath->query('//link[@rel="micropub"]');
2189 foreach ($list as $node) {
2190 foreach ($node->attributes as $attribute) {
2191 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2192 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2193 $serverdata['platform'] = 'microblog';
2194 $serverdata['network'] = Protocol::ACTIVITYPUB;
2201 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2202 $serverdata['detection-method'] = self::DETECT_BODY;
2209 * Analyses the header data of a given server for hints about type and system of that server
2211 * @param object $curlResult result of curl execution
2212 * @param array $serverdata array with server data
2214 * @return array server data
2216 private static function analyseRootHeader($curlResult, array $serverdata): array
2218 if ($curlResult->getHeader('server') == 'Mastodon') {
2219 $serverdata['platform'] = 'mastodon';
2220 $serverdata['network'] = Protocol::ACTIVITYPUB;
2221 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2222 $serverdata['platform'] = 'diaspora';
2223 $serverdata['network'] = Protocol::DIASPORA;
2224 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2225 } elseif ($curlResult->inHeader('x-friendica-version')) {
2226 $serverdata['platform'] = 'friendica';
2227 $serverdata['network'] = Protocol::DFRN;
2228 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2233 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2234 $serverdata['detection-method'] = self::DETECT_HEADER;
2241 * Update GServer entries
2243 public static function discover()
2245 // Update the server list
2246 self::discoverFederation();
2250 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2252 if ($requery_days == 0) {
2256 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2258 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2259 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2260 ['order' => ['RAND()']]);
2262 while ($gserver = DBA::fetch($gservers)) {
2263 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2264 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2266 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2267 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2269 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2270 self::update($fields, ['nurl' => $gserver['nurl']]);
2272 if (--$no_of_queries == 0) {
2277 DBA::close($gservers);
2281 * Discover federated servers
2283 private static function discoverFederation()
2285 $last = DI::keyValue()->get('poco_last_federation_discovery');
2288 $next = $last + (24 * 60 * 60);
2290 if ($next > time()) {
2295 // Discover federated servers
2296 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2297 foreach ($protocols as $protocol) {
2298 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2299 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2300 if (!empty($curlResult)) {
2301 $data = json_decode($curlResult, true);
2302 if (!empty($data['data']['nodes'])) {
2303 foreach ($data['data']['nodes'] as $server) {
2304 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2305 self::add('https://' . $server['host'], true);
2311 // Disvover Mastodon servers
2312 $accesstoken = DI::config()->get('system', 'instances_social_key');
2314 if (!empty($accesstoken)) {
2315 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2316 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2317 if ($curlResult->isSuccess()) {
2318 $servers = json_decode($curlResult->getBody(), true);
2320 if (!empty($servers['instances'])) {
2321 foreach ($servers['instances'] as $server) {
2322 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2329 DI::keyValue()->set('poco_last_federation_discovery', time());
2333 * Set the protocol for the given server
2335 * @param int $gsid Server id
2336 * @param int $protocol Protocol id
2340 public static function setProtocol(int $gsid, int $protocol)
2346 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2347 if (!DBA::isResult($gserver)) {
2351 $old = $gserver['protocol'];
2353 if (!is_null($old)) {
2355 The priority for the protocols is:
2357 2. DFRN via Diaspora
2363 // We don't need to change it when nothing is to be changed
2364 if ($old == $protocol) {
2368 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2369 if ($protocol == Post\DeliveryData::OSTATUS) {
2373 // If the server is marked as ActivityPub then we won't change it to anything different
2374 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2378 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2379 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2383 // Don't change it to Diaspora when it is a legacy DFRN server
2384 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2389 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2390 self::update(['protocol' => $protocol], ['id' => $gsid]);
2394 * Fetch the protocol of the given server
2396 * @param int $gsid Server id
2398 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2402 public static function getProtocol(int $gsid): ?int
2408 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2409 if (DBA::isResult($gserver)) {
2410 return $gserver['protocol'];
2417 * Update rows in the gserver table.
2418 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2420 * @param array $fields
2421 * @param array $condition
2427 public static function update(array $fields, array $condition): bool
2429 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2431 return DBA::update('gserver', $fields, $condition);
2435 * Insert a row into the gserver table.
2436 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2438 * @param array $fields
2439 * @param int $duplicate_mode What to do on a duplicated entry
2445 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2447 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2449 return DBA::insert('gserver', $fields, $duplicate_mode);