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\Worker;
30 use Friendica\Database\Database;
31 use Friendica\Database\DBA;
33 use Friendica\Module\Register;
34 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
37 use Friendica\Network\Probe;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Relay;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\JsonLD;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
45 use Friendica\Network\HTTPException;
46 use Friendica\Worker\UpdateGServer;
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 existence 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)) {
107 UpdateGServer::add(Worker::PRIORITY_LOW, $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]);
130 if (Network::isUrlBlocked($url)) {
131 self::setBlockedById($gserver['id']);
133 self::setUnblockedById($gserver['id']);
136 return $gserver['id'];
139 if ($no_check || !self::check($url)) {
143 return self::getID($url, true);
147 * Retrieves all the servers which base domain are matching the provided domain pattern
149 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
151 * @param string $pattern
157 public static function listByDomainPattern(string $pattern): array
159 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
161 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
162 // eventual server path and keep only the server domain which we're matching against the pattern.
163 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
165 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
166 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
167 AND NOT `gserver`.`failed`
168 GROUP BY `gserver`.`id`";
170 $stmt = DI::dba()->p($sql, $likePattern);
172 return DI::dba()->toArray($stmt);
176 * Checks if the given server array is unreachable for a long time now
178 * @param integer $gsid
181 private static function isDefunct(array $gserver): bool
183 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
184 ($gserver['last_contact'] >= $gserver['created']) &&
185 ($gserver['last_contact'] < $gserver['last_failure']) &&
186 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
190 * Checks if the given server id is unreachable for a long time now
192 * @param integer $gsid
195 public static function isDefunctById(int $gsid): bool
197 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
198 if (empty($gserver)) {
201 if (strtotime($gserver['next_contact']) < time()) {
202 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
205 return self::isDefunct($gserver);
210 * Checks if the given server id is reachable
212 * @param integer $gsid
215 public static function isReachableById(int $gsid): bool
217 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
218 if (empty($gserver)) {
221 if (strtotime($gserver['next_contact']) < time()) {
222 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
225 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
230 * Checks if the given server is reachable
232 * @param array $contact Contact that should be checked
234 * @return boolean 'true' if server seems vital
236 public static function reachable(array $contact): bool
238 if (!empty($contact['gsid'])) {
239 $gsid = $contact['gsid'];
240 } elseif (!empty($contact['baseurl'])) {
241 $server = $contact['baseurl'];
242 } elseif ($contact['network'] == Protocol::DIASPORA) {
243 $parts = parse_url($contact['url']);
244 unset($parts['path']);
245 $server = (string)Uri::fromParts($parts);
251 $condition = ['id' => $gsid];
253 $condition = ['nurl' => Strings::normaliseLink($server)];
256 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
257 if (empty($gserver)) {
260 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
261 $server = $gserver['url'];
264 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
265 UpdateGServer::add(Worker::PRIORITY_LOW, $server);
272 * Calculate the next update day
274 * @param bool $success
275 * @param string $created
276 * @param string $last_contact
277 * @param bool $undetected
283 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
285 // On successful contact process check again next week when it is a detected system.
286 // When we haven't detected the system, it could be a static website or a really old system.
288 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
291 $now = strtotime(DateTimeFormat::utcNow());
293 if ($created > $last_contact) {
294 $contact_time = strtotime($created);
296 $contact_time = strtotime($last_contact);
299 // If the last contact was less than 6 hours before then try again in 6 hours
300 if (($now - $contact_time) < (60 * 60 * 6)) {
301 return DateTimeFormat::utc('now +6 hour');
304 // If the last contact was less than 12 hours before then try again in 12 hours
305 if (($now - $contact_time) < (60 * 60 * 12)) {
306 return DateTimeFormat::utc('now +12 hour');
309 // If the last contact was less than 24 hours before then try tomorrow again
310 if (($now - $contact_time) < (60 * 60 * 24)) {
311 return DateTimeFormat::utc('now +1 day');
314 // If the last contact was less than a week before then try again in a week
315 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
316 return DateTimeFormat::utc('now +1 week');
319 // If the last contact was less than two weeks before then try again in two week
320 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
321 return DateTimeFormat::utc('now +2 week');
324 // If the last contact was less than a month before then try again in a month
325 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
326 return DateTimeFormat::utc('now +1 month');
329 // The system hadn't been successful contacted for more than a month, so try again in three months
330 return DateTimeFormat::utc('now +3 month');
334 * Checks the state of the given server.
336 * @param string $server_url URL of the given server
337 * @param string $network Network value that is used, when detection failed
338 * @param boolean $force Force an update.
339 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
341 * @return boolean 'true' if server seems vital
343 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
345 $server_url = self::cleanURL($server_url);
346 if ($server_url == '') {
350 if (Network::isUrlBlocked($server_url)) {
351 Logger::info('Server is blocked', ['url' => $server_url]);
352 self::setBlockedByUrl($server_url);
356 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
357 if (DBA::isResult($gserver)) {
358 if ($gserver['created'] <= DBA::NULL_DATETIME) {
359 $fields = ['created' => DateTimeFormat::utcNow()];
360 $condition = ['nurl' => Strings::normaliseLink($server_url)];
361 self::update($fields, $condition);
364 if (!$force && (strtotime($gserver['next_contact']) > time())) {
365 Logger::info('No update needed', ['server' => $server_url]);
366 return (!$gserver['failed']);
368 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
370 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
373 return self::detect($server_url, $network, $only_nodeinfo);
377 * Reset failed server status by gserver id
380 * @param string $network
382 public static function setReachableById(int $gsid, string $network)
384 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
385 if (!DBA::isResult($gserver)) {
389 $blocked = Network::isUrlBlocked($gserver['url']);
390 if ($gserver['failed']) {
391 $fields = ['failed' => false, 'blocked' => $blocked, 'last_contact' => DateTimeFormat::utcNow()];
392 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
393 $fields['network'] = $network;
395 self::update($fields, ['id' => $gsid]);
396 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
398 if (strtotime($gserver['next_contact']) < time()) {
399 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
401 } elseif ($blocked) {
402 self::setBlockedById($gsid);
404 self::setUnblockedById($gsid);
409 * Set failed server status by gserver id
413 public static function setFailureById(int $gsid)
415 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
416 if (DBA::isResult($gserver) && !$gserver['failed']) {
417 self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
418 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
420 if (strtotime($gserver['next_contact']) < time()) {
421 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
426 public static function setUnblockedById(int $gsid)
428 $gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
429 if (DBA::isResult($gserver)) {
430 self::update(['blocked' => false], ['id' => $gsid]);
431 Logger::info('Set unblocked status for server', ['url' => $gserver['url']]);
435 public static function setBlockedById(int $gsid)
437 $gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
438 if (DBA::isResult($gserver)) {
439 self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
440 Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
444 public static function setBlockedByUrl(string $url)
446 $gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
447 if (DBA::isResult($gserver)) {
448 self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
449 Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
454 * Set failed server status
459 public static function setFailureByUrl(string $url)
461 $nurl = Strings::normaliseLink($url);
463 $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
464 if (DBA::isResult($gserver)) {
465 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
466 self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
467 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
469 Logger::info('Set failed status for existing server', ['url' => $url]);
470 if (self::isDefunct($gserver)) {
471 self::archiveContacts($gserver['id']);
476 self::insert(['url' => $url, 'nurl' => $nurl,
477 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
478 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
479 Logger::info('Set failed status for new server', ['url' => $url]);
483 * Archive server related contacts and inboxes
485 * @param integer $gsid
488 private static function archiveContacts(int $gsid)
490 Contact::update(['archive' => true], ['gsid' => $gsid]);
491 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
495 * Remove unwanted content from the given URL
497 * @param string $dirtyUrl
499 * @return string cleaned URL
501 * @deprecated since 2023.03 Use cleanUri instead
503 public static function cleanURL(string $dirtyUrl): string
506 return (string)self::cleanUri(new Uri($dirtyUrl));
507 } catch (\Throwable $e) {
508 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
514 * Remove unwanted content from the given URI
516 * @param UriInterface $dirtyUri
518 * @return UriInterface cleaned URI
521 public static function cleanUri(UriInterface $dirtyUri): string
529 '#(?:^|/)index\.php#',
531 rtrim($dirtyUri->getPath(), '/')
537 * Detect server data (type, protocol, version number, ...)
538 * The detected data is then updated or inserted in the gserver table.
540 * @param string $url URL of the given server
541 * @param string $network Network value that is used, when detection failed
542 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
544 * @return boolean 'true' if server could be detected
546 private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
548 Logger::info('Detect server type', ['server' => $url]);
550 $original_url = $url;
552 // Remove URL content that is not supposed to exist for a server url
553 $url = rtrim(self::cleanURL($url), '/');
555 Logger::notice('Empty URL.');
559 // If the URL mismatches, then we mark the old entry as failure
560 if (!Strings::compareLink($url, $original_url)) {
561 self::setFailureByUrl($original_url);
562 if (!self::getID($url, true) && !Network::isUrlBlocked($url)) {
563 self::detect($url, $network, $only_nodeinfo);
568 $valid_url = Network::isUrlValid($url);
570 self::setFailureByUrl($url);
573 $valid_url = rtrim($valid_url, '/');
576 if (!Strings::compareLink($url, $valid_url)) {
577 // We only follow redirects when the path stays the same or the target url has no path.
578 // Some systems have got redirects on their landing page to a single account page. This check handles it.
579 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))) ||
580 (((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)))) {
581 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
582 self::setFailureByUrl($url);
583 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
584 self::detect($valid_url, $network, $only_nodeinfo);
589 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)) &&
590 (parse_url($url, PHP_URL_PATH) == '')) {
591 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
592 $parts = parse_url($valid_url);
593 unset($parts['path']);
594 $valid_url = (string)Uri::fromParts($parts);
596 self::setFailureByUrl($url);
597 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
598 self::detect($valid_url, $network, $only_nodeinfo);
602 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
605 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
606 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
607 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
611 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
613 // When a nodeinfo is present, we don't need to dig further
614 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
615 if ($curlResult->isTimeout()) {
616 self::setFailureByUrl($url);
620 $serverdata = self::parseNodeinfo210($curlResult);
621 if (empty($serverdata)) {
622 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
623 $serverdata = self::fetchNodeinfo($url, $curlResult);
626 if ($only_nodeinfo && empty($serverdata)) {
627 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
628 self::setFailureByUrl($url);
630 } elseif (empty($serverdata)) {
631 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
634 // When there is no Nodeinfo, then use some protocol specific endpoints
635 if ($serverdata['network'] == Protocol::PHANTOM) {
637 // Fetch the landing page, possibly it reveals some data
638 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
639 $curlResult = DI::httpClient()->get($url, $accept);
640 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
641 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
642 $html_fetched = true;
644 $html_fetched = false;
647 if ($curlResult->isSuccess()) {
648 $json = json_decode($curlResult->getBody(), true);
649 if (!empty($json) && is_array($json)) {
650 $data = self::fetchDataFromSystemActor($json, $serverdata);
651 $serverdata = $data['server'];
652 $systemactor = $data['actor'];
653 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
654 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
656 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
657 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
660 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
661 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
662 $serverdata = self::analyseRootBody($curlResult, $serverdata);
666 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
667 self::setFailureByUrl($url);
671 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
672 $serverdata = self::detectMastodonAlikes($url, $serverdata);
676 // All following checks are done for systems that always have got a "host-meta" endpoint.
677 // With this check we don't have to waste time and resources for dead systems.
678 // Also this hopefully prevents us from receiving abuse messages.
679 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
680 $validHostMeta = self::validHostMeta($url);
682 $validHostMeta = false;
685 if ($validHostMeta) {
686 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
687 $serverdata['detection-method'] = self::DETECT_HOST_META;
690 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
691 $serverdata = self::detectFriendica($url, $serverdata);
694 // The following systems have to be installed in the root directory.
696 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
697 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
698 $serverdata = self::fetchSiteinfo($url, $serverdata);
701 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
702 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
703 $serverdata = self::detectHubzilla($url, $serverdata);
706 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
707 $serverdata = self::detectPeertube($url, $serverdata);
710 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
711 $serverdata = self::detectGNUSocial($url, $serverdata);
714 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
715 $serverdata = self::detectFriendica($url, $serverdata);
718 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
719 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
722 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
723 // Since this endpoint is only rarely used, we query it at a later time
724 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
725 $serverdata = self::fetchStatistics($url, $serverdata);
729 // When we hadn't been able to detect the network type, we use the hint from the parameter
730 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
731 $serverdata['network'] = $network;
734 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
735 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
736 self::setFailureByUrl($url);
740 $serverdata['url'] = $url;
741 $serverdata['nurl'] = Strings::normaliseLink($url);
743 // We have to prevent an endless loop here.
744 // When a server is new, then there is no gserver entry yet.
745 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
746 // and this can call this function here as well.
747 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
748 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
749 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
752 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
753 self::setFailureByUrl($url);
757 if (empty($serverdata['version']) && in_array($serverdata['platform'], ['osada']) && in_array($serverdata['detection-method'], [self::DETECT_CONTACTS, self::DETECT_BODY])) {
758 $serverdata['version'] = self::getNomadVersion($url);
761 // Detect the directory type
762 $serverdata['directory-type'] = self::DT_NONE;
764 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
765 $serverdata = self::checkMastodonDirectory($url, $serverdata);
767 if ($serverdata['directory-type'] == self::DT_NONE) {
768 $serverdata = self::checkPoCo($url, $serverdata);
772 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
773 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
776 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
778 // Numbers above a reasonable value (10 millions) are ignored
779 if ($serverdata['registered-users'] > 10000000) {
780 $serverdata['registered-users'] = 0;
783 // On an active server there has to be at least a single user
784 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
785 $serverdata['registered-users'] = 1;
786 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
787 $serverdata['registered-users'] = 0;
790 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
791 $serverdata['last_contact'] = DateTimeFormat::utcNow();
792 $serverdata['failed'] = false;
793 $serverdata['blocked'] = false;
795 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
796 if (!DBA::isResult($gserver)) {
797 $serverdata['created'] = DateTimeFormat::utcNow();
798 $ret = self::insert($serverdata);
799 $id = DBA::lastInsertId();
801 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
802 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
803 if (DBA::isResult($gserver)) {
804 $id = $gserver['id'];
808 // Count the number of known contacts from this server
809 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
810 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
811 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
812 $max_users = max($apcontacts, $contacts);
813 if ($max_users > $serverdata['registered-users']) {
814 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
815 self::update(['registered-users' => $max_users], ['id' => $id]);
818 if (empty($serverdata['active-month-users'])) {
819 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
821 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
822 self::update(['active-month-users' => $contacts], ['id' => $id]);
826 if (empty($serverdata['active-halfyear-users'])) {
827 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
829 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
830 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
835 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
836 self::discoverRelay($url);
839 if (!empty($systemactor)) {
840 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
841 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
848 * Fetch relay data from a given server url
850 * @param string $server_url address of the server
854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
856 private static function discoverRelay(string $server_url)
858 Logger::info('Discover relay data', ['server' => $server_url]);
860 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
861 if (!$curlResult->isSuccess()) {
865 $data = json_decode($curlResult->getBody(), true);
866 if (!is_array($data)) {
870 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
871 $data['subscribe'] = (bool)($data['subscribe'] ?? false);
873 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
875 $data['subscribe'] = false;
879 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
880 if (!DBA::isResult($gserver)) {
884 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
885 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
886 self::update($fields, ['id' => $gserver['id']]);
889 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
891 if ($data['scope'] == 'tags') {
894 foreach ($data['tags'] as $tag) {
895 $tag = mb_strtolower($tag);
896 if (strlen($tag) < 100) {
901 foreach ($tags as $tag) {
902 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
906 // Create or update the relay contact
908 if (isset($data['protocols'])) {
909 if (isset($data['protocols']['diaspora'])) {
910 $fields['network'] = Protocol::DIASPORA;
912 if (isset($data['protocols']['diaspora']['receive'])) {
913 $fields['batch'] = $data['protocols']['diaspora']['receive'];
914 } elseif (is_string($data['protocols']['diaspora'])) {
915 $fields['batch'] = $data['protocols']['diaspora'];
919 if (isset($data['protocols']['dfrn'])) {
920 $fields['network'] = Protocol::DFRN;
922 if (isset($data['protocols']['dfrn']['receive'])) {
923 $fields['batch'] = $data['protocols']['dfrn']['receive'];
924 } elseif (is_string($data['protocols']['dfrn'])) {
925 $fields['batch'] = $data['protocols']['dfrn'];
929 if (isset($data['protocols']['activitypub'])) {
930 $fields['network'] = Protocol::ACTIVITYPUB;
932 if (!empty($data['protocols']['activitypub']['actor'])) {
933 $fields['url'] = $data['protocols']['activitypub']['actor'];
935 if (!empty($data['protocols']['activitypub']['receive'])) {
936 $fields['batch'] = $data['protocols']['activitypub']['receive'];
941 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
943 Relay::updateContact($gserver, $fields);
947 * Fetch server data from '/statistics.json' on the given server
949 * @param string $url URL of the given server
951 * @return array server data
953 private static function fetchStatistics(string $url, array $serverdata): array
955 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
956 if (!$curlResult->isSuccess()) {
960 $data = json_decode($curlResult->getBody(), true);
965 // Some AP enabled systems return activity data that we don't expect here.
966 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
971 $old_serverdata = $serverdata;
973 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
975 if (!empty($data['version'])) {
977 $serverdata['version'] = $data['version'];
978 // Version numbers on statistics.json are presented with additional info, e.g.:
979 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
980 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
983 if (!empty($data['name'])) {
985 $serverdata['site_name'] = $data['name'];
988 if (!empty($data['network'])) {
990 $serverdata['platform'] = strtolower($data['network']);
992 if ($serverdata['platform'] == 'diaspora') {
993 $serverdata['network'] = Protocol::DIASPORA;
994 } elseif ($serverdata['platform'] == 'friendica') {
995 $serverdata['network'] = Protocol::DFRN;
996 } elseif ($serverdata['platform'] == 'hubzilla') {
997 $serverdata['network'] = Protocol::ZOT;
998 } elseif ($serverdata['platform'] == 'redmatrix') {
999 $serverdata['network'] = Protocol::ZOT;
1003 if (!empty($data['total_users'])) {
1005 $serverdata['registered-users'] = max($data['total_users'], 1);
1008 if (!empty($data['active_users_monthly'])) {
1010 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
1013 if (!empty($data['active_users_halfyear'])) {
1015 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
1018 if (!empty($data['local_posts'])) {
1020 $serverdata['local-posts'] = max($data['local_posts'], 0);
1023 if (!empty($data['registrations_open'])) {
1024 $serverdata['register_policy'] = Register::OPEN;
1026 $serverdata['register_policy'] = Register::CLOSED;
1030 return $old_serverdata;
1037 * Detect server type by using the nodeinfo data
1039 * @param string $url address of the server
1040 * @param ICanHandleHttpResponses $httpResult
1042 * @return array Server data
1044 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
1048 if (!$httpResult->isSuccess()) {
1052 $nodeinfo = json_decode($httpResult->getBody(), true);
1054 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
1058 $nodeinfo1_url = '';
1059 $nodeinfo2_url = '';
1061 foreach ($nodeinfo['links'] as $link) {
1062 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
1063 Logger::info('Invalid nodeinfo format', ['url' => $url]);
1067 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
1068 $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1069 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
1070 $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1074 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1080 if (!empty($nodeinfo2_url)) {
1081 $server = self::parseNodeinfo2($nodeinfo2_url);
1084 if (empty($server) && !empty($nodeinfo1_url)) {
1085 $server = self::parseNodeinfo1($nodeinfo1_url);
1094 * @param string $nodeinfo_url address of the nodeinfo path
1096 * @return array Server data
1098 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 private static function parseNodeinfo1(string $nodeinfo_url): array
1102 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1103 if (!$curlResult->isSuccess()) {
1107 $nodeinfo = json_decode($curlResult->getBody(), true);
1109 if (!is_array($nodeinfo)) {
1113 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1114 'register_policy' => Register::CLOSED];
1116 if (!empty($nodeinfo['openRegistrations'])) {
1117 $server['register_policy'] = Register::OPEN;
1120 if (is_array($nodeinfo['software'])) {
1121 if (!empty($nodeinfo['software']['name'])) {
1122 $server['platform'] = strtolower($nodeinfo['software']['name']);
1125 if (!empty($nodeinfo['software']['version'])) {
1126 $server['version'] = $nodeinfo['software']['version'];
1127 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1128 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1129 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1133 if (!empty($nodeinfo['metadata']['nodeName'])) {
1134 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1137 if (!empty($nodeinfo['usage']['users']['total'])) {
1138 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1141 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1142 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1145 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1146 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1149 if (!empty($nodeinfo['usage']['localPosts'])) {
1150 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1153 if (!empty($nodeinfo['usage']['localComments'])) {
1154 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1157 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1159 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1160 $protocols[$protocol] = true;
1163 if (!empty($protocols['friendica'])) {
1164 $server['network'] = Protocol::DFRN;
1165 } elseif (!empty($protocols['activitypub'])) {
1166 $server['network'] = Protocol::ACTIVITYPUB;
1167 } elseif (!empty($protocols['diaspora'])) {
1168 $server['network'] = Protocol::DIASPORA;
1169 } elseif (!empty($protocols['ostatus'])) {
1170 $server['network'] = Protocol::OSTATUS;
1171 } elseif (!empty($protocols['gnusocial'])) {
1172 $server['network'] = Protocol::OSTATUS;
1173 } elseif (!empty($protocols['zot'])) {
1174 $server['network'] = Protocol::ZOT;
1178 if (empty($server)) {
1182 if (empty($server['network'])) {
1183 $server['network'] = Protocol::PHANTOM;
1192 * @see https://git.feneas.org/jaywink/nodeinfo2
1194 * @param string $nodeinfo_url address of the nodeinfo path
1196 * @return array Server data
1198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1200 private static function parseNodeinfo2(string $nodeinfo_url): array
1202 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1203 if (!$curlResult->isSuccess()) {
1207 $nodeinfo = json_decode($curlResult->getBody(), true);
1208 if (!is_array($nodeinfo)) {
1213 'detection-method' => self::DETECT_NODEINFO_2,
1214 'register_policy' => Register::CLOSED,
1215 'platform' => 'unknown',
1218 if (!empty($nodeinfo['openRegistrations'])) {
1219 $server['register_policy'] = Register::OPEN;
1222 if (!empty($nodeinfo['software'])) {
1223 if (isset($nodeinfo['software']['name'])) {
1224 $server['platform'] = strtolower($nodeinfo['software']['name']);
1227 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1228 $server['version'] = $nodeinfo['software']['version'];
1229 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1230 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1231 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1233 // qoto advertises itself as Mastodon
1234 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1235 $server['platform'] = 'qoto';
1240 if (!empty($nodeinfo['metadata']['nodeName'])) {
1241 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1244 if (!empty($nodeinfo['usage']['users']['total'])) {
1245 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1248 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1249 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1252 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1253 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1256 if (!empty($nodeinfo['usage']['localPosts'])) {
1257 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1260 if (!empty($nodeinfo['usage']['localComments'])) {
1261 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1264 if (!empty($nodeinfo['protocols'])) {
1266 foreach ($nodeinfo['protocols'] as $protocol) {
1267 if (is_string($protocol)) {
1268 $protocols[$protocol] = true;
1272 if (!empty($protocols['dfrn'])) {
1273 $server['network'] = Protocol::DFRN;
1274 } elseif (!empty($protocols['activitypub'])) {
1275 $server['network'] = Protocol::ACTIVITYPUB;
1276 } elseif (!empty($protocols['diaspora'])) {
1277 $server['network'] = Protocol::DIASPORA;
1278 } elseif (!empty($protocols['ostatus'])) {
1279 $server['network'] = Protocol::OSTATUS;
1280 } elseif (!empty($protocols['gnusocial'])) {
1281 $server['network'] = Protocol::OSTATUS;
1282 } elseif (!empty($protocols['zot'])) {
1283 $server['network'] = Protocol::ZOT;
1287 if (empty($server)) {
1291 if (empty($server['network'])) {
1292 $server['network'] = Protocol::PHANTOM;
1299 * Parses NodeInfo2 protocol 1.0
1301 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1303 * @param string $nodeinfo_url address of the nodeinfo path
1305 * @return array Server data
1307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1309 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1311 if (!$httpResult->isSuccess()) {
1315 $nodeinfo = json_decode($httpResult->getBody(), true);
1317 if (!is_array($nodeinfo)) {
1321 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1322 'register_policy' => Register::CLOSED];
1324 if (!empty($nodeinfo['openRegistrations'])) {
1325 $server['register_policy'] = Register::OPEN;
1328 if (!empty($nodeinfo['server'])) {
1329 if (!empty($nodeinfo['server']['software'])) {
1330 $server['platform'] = strtolower($nodeinfo['server']['software']);
1333 if (!empty($nodeinfo['server']['version'])) {
1334 $server['version'] = $nodeinfo['server']['version'];
1335 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1336 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1337 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1340 if (!empty($nodeinfo['server']['name'])) {
1341 $server['site_name'] = $nodeinfo['server']['name'];
1345 if (!empty($nodeinfo['usage']['users']['total'])) {
1346 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1349 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1350 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1353 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1354 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1357 if (!empty($nodeinfo['usage']['localPosts'])) {
1358 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1361 if (!empty($nodeinfo['usage']['localComments'])) {
1362 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1365 if (!empty($nodeinfo['protocols'])) {
1367 foreach ($nodeinfo['protocols'] as $protocol) {
1368 if (is_string($protocol)) {
1369 $protocols[$protocol] = true;
1373 if (!empty($protocols['dfrn'])) {
1374 $server['network'] = Protocol::DFRN;
1375 } elseif (!empty($protocols['activitypub'])) {
1376 $server['network'] = Protocol::ACTIVITYPUB;
1377 } elseif (!empty($protocols['diaspora'])) {
1378 $server['network'] = Protocol::DIASPORA;
1379 } elseif (!empty($protocols['ostatus'])) {
1380 $server['network'] = Protocol::OSTATUS;
1381 } elseif (!empty($protocols['gnusocial'])) {
1382 $server['network'] = Protocol::OSTATUS;
1383 } elseif (!empty($protocols['zot'])) {
1384 $server['network'] = Protocol::ZOT;
1388 if (empty($server) || empty($server['platform'])) {
1392 if (empty($server['network'])) {
1393 $server['network'] = Protocol::PHANTOM;
1400 * Fetch server information from a 'siteinfo.json' file on the given server
1402 * @param string $url URL of the given server
1403 * @param array $serverdata array with server data
1405 * @return array server data
1407 private static function fetchSiteinfo(string $url, array $serverdata): array
1409 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1410 if (!$curlResult->isSuccess()) {
1414 $data = json_decode($curlResult->getBody(), true);
1419 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1420 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1423 if (!empty($data['platform'])) {
1424 $serverdata['platform'] = strtolower($data['platform']);
1425 $serverdata['version'] = $data['version'] ?? 'N/A';
1428 if (!empty($data['plugins'])) {
1429 if (in_array('pubcrawl', $data['plugins'])) {
1430 $serverdata['network'] = Protocol::ACTIVITYPUB;
1431 } elseif (in_array('diaspora', $data['plugins'])) {
1432 $serverdata['network'] = Protocol::DIASPORA;
1433 } elseif (in_array('gnusoc', $data['plugins'])) {
1434 $serverdata['network'] = Protocol::OSTATUS;
1436 $serverdata['network'] = Protocol::ZOT;
1440 if (!empty($data['site_name'])) {
1441 $serverdata['site_name'] = $data['site_name'];
1444 if (!empty($data['channels_total'])) {
1445 $serverdata['registered-users'] = max($data['channels_total'], 1);
1448 if (!empty($data['channels_active_monthly'])) {
1449 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1452 if (!empty($data['channels_active_halfyear'])) {
1453 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1456 if (!empty($data['local_posts'])) {
1457 $serverdata['local-posts'] = max($data['local_posts'], 0);
1460 if (!empty($data['local_comments'])) {
1461 $serverdata['local-comments'] = max($data['local_comments'], 0);
1464 if (!empty($data['register_policy'])) {
1465 switch ($data['register_policy']) {
1466 case 'REGISTER_OPEN':
1467 $serverdata['register_policy'] = Register::OPEN;
1470 case 'REGISTER_APPROVE':
1471 $serverdata['register_policy'] = Register::APPROVE;
1474 case 'REGISTER_CLOSED':
1476 $serverdata['register_policy'] = Register::CLOSED;
1485 * Fetches server data via an ActivityPub account with url of that server
1487 * @param string $url URL of the given server
1488 * @param array $serverdata array with server data
1490 * @return array server data
1494 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1497 return ['server' => $serverdata, 'actor' => ''];
1500 $actor = JsonLD::compact($data, false);
1501 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1502 $serverdata['network'] = Protocol::ACTIVITYPUB;
1503 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1504 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1505 if (self::isNomad($actor)) {
1506 $serverdata['platform'] = self::getNomadName($actor['@id']);
1507 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1508 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1509 } elseif (!empty($actor['as:generator'])) {
1510 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1511 $serverdata['platform'] = strtolower(array_shift($generator));
1512 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1513 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1515 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1517 return ['server' => $serverdata, 'actor' => $actor['@id']];
1518 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1519 // By now only Ktistec seems to provide collections this way
1520 $serverdata['platform'] = 'ktistec';
1521 $serverdata['network'] = Protocol::ACTIVITYPUB;
1522 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1524 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1525 if (!empty($actors) && !empty($actors[0]['@id'])) {
1526 $actor_url = $actor['@id'] . $actors[0]['@id'];
1531 return ['server' => $serverdata, 'actor' => $actor_url];
1533 return ['server' => $serverdata, 'actor' => ''];
1537 * Detect if the given actor is a nomad account
1539 * @param array $actor
1542 private static function isNomad(array $actor): bool
1544 $tags = JsonLD::fetchElementArray($actor, 'as:tag');
1549 foreach ($tags as $tag) {
1550 if ((($tag['as:name'] ?? '') == 'Protocol') && (($tag['sc:value'] ?? '') == 'nomad')) {
1558 * Fetch the name of Nomad implementation
1560 * @param string $url
1563 private static function getNomadName(string $url): string
1566 $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json');
1567 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1571 $data = json_decode($curlResult->getBody(), true);
1576 return $data['name'] ?? $name;
1580 * Fetch the version of the Nomad installation
1582 * @param string $url
1585 private static function getNomadVersion(string $url): string
1587 $curlResult = DI::httpClient()->get($url . '/api/z/1.0/version', HttpClientAccept::JSON);
1588 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1592 $data = json_decode($curlResult->getBody(), true);
1600 * Checks if the server contains a valid host meta file
1602 * @param string $url URL of the given server
1604 * @return boolean 'true' if the server seems to be vital
1606 private static function validHostMeta(string $url): bool
1608 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1609 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1610 if (!$curlResult->isSuccess()) {
1614 $xrd = XML::parseString($curlResult->getBody(), true);
1615 if (!is_object($xrd)) {
1619 $elements = XML::elementToArray($xrd);
1620 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1625 foreach ($elements['xrd']['link'] as $link) {
1626 // When there is more than a single "link" element, the array looks slightly different
1627 if (!empty($link['@attributes'])) {
1628 $link = $link['@attributes'];
1631 if (empty($link['rel']) || empty($link['template'])) {
1635 if ($link['rel'] == 'lrdd') {
1636 // When the webfinger host is the same like the system host, it should be ok.
1637 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1645 * Detect the network of the given server via their known contacts
1647 * @param string $url URL of the given server
1648 * @param array $serverdata array with server data
1650 * @return array server data
1652 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1656 $nurl = Strings::normaliseLink($url);
1658 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1659 while ($apcontact = DBA::fetch($apcontacts)) {
1660 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1662 DBA::close($apcontacts);
1664 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1665 while ($pcontact = DBA::fetch($pcontacts)) {
1666 $contacts[$pcontact['nurl']] = $pcontact['url'];
1668 DBA::close($pcontacts);
1670 if (empty($contacts)) {
1675 foreach ($contacts as $contact) {
1676 // Endlosschleife verhindern wegen gsid!
1677 $data = Probe::uri($contact);
1678 if (in_array($data['network'], Protocol::FEDERATED)) {
1679 $serverdata['network'] = $data['network'];
1681 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1682 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1685 } elseif ((time() - $time) > 10) {
1686 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1695 * Checks if the given server does have a '/poco' endpoint.
1696 * This is used for the 'PortableContact' functionality,
1697 * which is used by both Friendica and Hubzilla.
1699 * @param string $url URL of the given server
1700 * @param array $serverdata array with server data
1702 * @return array server data
1704 private static function checkPoCo(string $url, array $serverdata): array
1706 $serverdata['poco'] = '';
1708 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1709 if (!$curlResult->isSuccess()) {
1713 $data = json_decode($curlResult->getBody(), true);
1718 if (!empty($data['totalResults'])) {
1719 $registeredUsers = $serverdata['registered-users'] ?? 0;
1720 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1721 $serverdata['directory-type'] = self::DT_POCO;
1722 $serverdata['poco'] = $url . '/poco';
1729 * Checks if the given server does have a Mastodon style directory endpoint.
1731 * @param string $url URL of the given server
1732 * @param array $serverdata array with server data
1734 * @return array server data
1736 public static function checkMastodonDirectory(string $url, array $serverdata): array
1738 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1739 if (!$curlResult->isSuccess()) {
1743 $data = json_decode($curlResult->getBody(), true);
1748 if (count($data) == 1) {
1749 $serverdata['directory-type'] = self::DT_MASTODON;
1756 * Detects Peertube via their known endpoint
1758 * @param string $url URL of the given server
1759 * @param array $serverdata array with server data
1761 * @return array server data
1763 private static function detectPeertube(string $url, array $serverdata): array
1765 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1766 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1770 $data = json_decode($curlResult->getBody(), true);
1775 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1776 $serverdata['platform'] = 'peertube';
1777 $serverdata['version'] = $data['serverVersion'];
1778 $serverdata['network'] = Protocol::ACTIVITYPUB;
1780 if (!empty($data['instance']['name'])) {
1781 $serverdata['site_name'] = $data['instance']['name'];
1784 if (!empty($data['instance']['shortDescription'])) {
1785 $serverdata['info'] = $data['instance']['shortDescription'];
1788 if (!empty($data['signup'])) {
1789 if (!empty($data['signup']['allowed'])) {
1790 $serverdata['register_policy'] = Register::OPEN;
1794 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1795 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1803 * Detects the version number of a given server when it was a NextCloud installation
1805 * @param string $url URL of the given server
1806 * @param array $serverdata array with server data
1807 * @param bool $validHostMeta
1809 * @return array server data
1811 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1813 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1814 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1818 $data = json_decode($curlResult->getBody(), true);
1823 if (!empty($data['version'])) {
1824 $serverdata['platform'] = 'nextcloud';
1825 $serverdata['version'] = $data['version'];
1827 if ($validHostMeta) {
1828 $serverdata['network'] = Protocol::ACTIVITYPUB;
1831 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1832 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1840 * Fetches weekly usage data
1842 * @param string $url URL of the given server
1843 * @param array $serverdata array with server data
1845 * @return array server data
1847 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1849 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1850 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1854 $data = json_decode($curlResult->getBody(), true);
1860 foreach ($data as $week) {
1861 // Use only data from a full week
1862 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1866 // Most likely the data is sorted correctly. But we better are safe than sorry
1867 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1868 $current_week = $week;
1872 if (!empty($current_week['logins'])) {
1873 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1880 * Detects data from a given server url if it was a mastodon alike system
1882 * @param string $url URL of the given server
1883 * @param array $serverdata array with server data
1885 * @return array server data
1887 private static function detectMastodonAlikes(string $url, array $serverdata): array
1889 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1890 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1894 $data = json_decode($curlResult->getBody(), true);
1901 if (!empty($data['version'])) {
1902 $serverdata['platform'] = 'mastodon';
1903 $serverdata['version'] = $data['version'] ?? '';
1904 $serverdata['network'] = Protocol::ACTIVITYPUB;
1908 if (!empty($data['title'])) {
1909 $serverdata['site_name'] = $data['title'];
1912 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1913 $serverdata['platform'] = 'mastodon';
1914 $serverdata['network'] = Protocol::ACTIVITYPUB;
1918 if (!empty($data['description'])) {
1919 $serverdata['info'] = trim($data['description']);
1922 if (!empty($data['stats']['user_count'])) {
1923 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1926 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1927 $serverdata['platform'] = strtolower($matches[1]);
1928 $serverdata['version'] = $matches[2];
1932 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1933 $serverdata['platform'] = 'pleroma';
1934 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1938 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1939 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1940 $serverdata['platform'] = 'pleroma';
1944 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1945 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1952 * Detects data from typical Hubzilla endpoints
1954 * @param string $url URL of the given server
1955 * @param array $serverdata array with server data
1957 * @return array server data
1959 private static function detectHubzilla(string $url, array $serverdata): array
1961 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1962 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1966 $data = json_decode($curlResult->getBody(), true);
1967 if (empty($data) || empty($data['site'])) {
1971 if (!empty($data['site']['name'])) {
1972 $serverdata['site_name'] = $data['site']['name'];
1975 if (!empty($data['site']['platform'])) {
1976 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1977 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1978 $serverdata['network'] = Protocol::ZOT;
1981 if (!empty($data['site']['hubzilla'])) {
1982 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1983 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1984 $serverdata['network'] = Protocol::ZOT;
1987 if (!empty($data['site']['redmatrix'])) {
1988 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1989 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1990 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1991 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1994 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1995 $serverdata['network'] = Protocol::ZOT;
1999 $inviteonly = false;
2002 if (!empty($data['site']['closed'])) {
2003 $closed = self::toBoolean($data['site']['closed']);
2006 if (!empty($data['site']['private'])) {
2007 $private = self::toBoolean($data['site']['private']);
2010 if (!empty($data['site']['inviteonly'])) {
2011 $inviteonly = self::toBoolean($data['site']['inviteonly']);
2014 if (!$closed && !$private and $inviteonly) {
2015 $serverdata['register_policy'] = Register::APPROVE;
2016 } elseif (!$closed && !$private) {
2017 $serverdata['register_policy'] = Register::OPEN;
2019 $serverdata['register_policy'] = Register::CLOSED;
2022 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2023 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
2030 * Converts input value to a boolean value
2032 * @param string|integer $val
2036 private static function toBoolean($val): bool
2038 if (($val == 'true') || ($val == 1)) {
2040 } elseif (($val == 'false') || ($val == 0)) {
2048 * Detect if the URL belongs to a GNU Social server
2050 * @param string $url URL of the given server
2051 * @param array $serverdata array with server data
2053 * @return array server data
2055 private static function detectGNUSocial(string $url, array $serverdata): array
2057 // Test for GNU Social
2058 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
2059 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2060 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2061 $serverdata['platform'] = 'gnusocial';
2062 // Remove junk that some GNU Social servers return
2063 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
2064 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2065 $serverdata['version'] = trim($serverdata['version'], '"');
2066 $serverdata['network'] = Protocol::OSTATUS;
2068 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2069 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
2075 // Test for Statusnet
2076 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
2077 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2078 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2080 // Remove junk that some GNU Social servers return
2081 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
2082 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2083 $serverdata['version'] = trim($serverdata['version'], '"');
2085 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
2086 $serverdata['platform'] = 'pleroma';
2087 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
2088 $serverdata['network'] = Protocol::ACTIVITYPUB;
2090 $serverdata['platform'] = 'statusnet';
2091 $serverdata['network'] = Protocol::OSTATUS;
2094 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2095 $serverdata['detection-method'] = self::DETECT_STATUSNET;
2103 * Detect if the URL belongs to a Friendica server
2105 * @param string $url URL of the given server
2106 * @param array $serverdata array with server data
2108 * @return array server data
2110 private static function detectFriendica(string $url, array $serverdata): array
2112 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
2113 // Because of this me must not use ACCEPT_JSON here.
2114 $curlResult = DI::httpClient()->get($url . '/friendica/json');
2115 if (!$curlResult->isSuccess()) {
2116 $curlResult = DI::httpClient()->get($url . '/friendika/json');
2118 $platform = 'Friendika';
2121 $platform = 'Friendica';
2124 if (!$curlResult->isSuccess()) {
2128 $data = json_decode($curlResult->getBody(), true);
2129 if (empty($data) || empty($data['version'])) {
2133 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2134 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2137 $serverdata['network'] = Protocol::DFRN;
2138 $serverdata['version'] = $data['version'];
2140 if (!empty($data['no_scrape_url'])) {
2141 $serverdata['noscrape'] = $data['no_scrape_url'];
2144 if (!empty($data['site_name'])) {
2145 $serverdata['site_name'] = $data['site_name'];
2148 if (!empty($data['info'])) {
2149 $serverdata['info'] = trim($data['info']);
2152 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2153 switch ($register_policy) {
2154 case 'REGISTER_OPEN':
2155 $serverdata['register_policy'] = Register::OPEN;
2158 case 'REGISTER_APPROVE':
2159 $serverdata['register_policy'] = Register::APPROVE;
2162 case 'REGISTER_CLOSED':
2163 case 'REGISTER_INVITATION':
2164 $serverdata['register_policy'] = Register::CLOSED;
2167 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2168 $serverdata['register_policy'] = Register::CLOSED;
2172 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2178 * Analyses the landing page of a given server for hints about type and system of that server
2180 * @param object $curlResult result of curl execution
2181 * @param array $serverdata array with server data
2183 * @return array server data
2185 private static function analyseRootBody($curlResult, array $serverdata): array
2187 if (empty($curlResult->getBody())) {
2191 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2192 require __DIR__ . '/../../static/platforms.config.php';
2194 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2197 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2199 $doc = new DOMDocument();
2200 @$doc->loadHTML($curlResult->getBody());
2201 $xpath = new DOMXPath($doc);
2204 // We can only detect honk via some HTML element on their page
2205 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2206 $serverdata['platform'] = 'honk';
2207 $serverdata['network'] = Protocol::ACTIVITYPUB;
2211 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2212 if (!empty($title)) {
2213 $serverdata['site_name'] = $title;
2216 $list = $xpath->query('//meta[@name]');
2218 foreach ($list as $node) {
2220 if ($node->attributes->length) {
2221 foreach ($node->attributes as $attribute) {
2222 $value = trim($attribute->value);
2223 if (empty($value)) {
2227 $attr[$attribute->name] = $value;
2230 if (empty($attr['name']) || empty($attr['content'])) {
2235 if ($attr['name'] == 'description') {
2236 $serverdata['info'] = $attr['content'];
2239 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2240 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2241 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2242 $platform = str_replace('/', ' ', $platform);
2243 $platform_parts = explode(' ', $platform);
2244 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2245 $platform = $platform_parts[0];
2246 $serverdata['version'] = $platform_parts[1];
2248 if (in_array($platform, array_values($dfrn_platforms))) {
2249 $serverdata['network'] = Protocol::DFRN;
2250 } elseif (in_array($platform, array_values($ap_platforms))) {
2251 $serverdata['network'] = Protocol::ACTIVITYPUB;
2252 } elseif (in_array($platform, array_values($zap_platforms))) {
2253 $serverdata['network'] = Protocol::ZOT;
2255 if (in_array($platform, array_values($platforms))) {
2256 $serverdata['platform'] = $platform;
2262 $list = $xpath->query('//meta[@property]');
2264 foreach ($list as $node) {
2266 if ($node->attributes->length) {
2267 foreach ($node->attributes as $attribute) {
2268 $value = trim($attribute->value);
2269 if (empty($value)) {
2273 $attr[$attribute->name] = $value;
2276 if (empty($attr['property']) || empty($attr['content'])) {
2281 if ($attr['property'] == 'og:site_name') {
2282 $serverdata['site_name'] = $attr['content'];
2285 if ($attr['property'] == 'og:description') {
2286 $serverdata['info'] = $attr['content'];
2289 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2290 if (in_array($attr['content'], array_keys($platforms))) {
2291 $serverdata['platform'] = $platforms[$attr['content']];
2295 if (in_array($attr['content'], array_keys($ap_platforms))) {
2296 $serverdata['network'] = Protocol::ACTIVITYPUB;
2297 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2298 $serverdata['network'] = Protocol::ZOT;
2303 $list = $xpath->query('//link[@rel="me"]');
2304 foreach ($list as $node) {
2305 foreach ($node->attributes as $attribute) {
2306 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2307 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2308 $serverdata['platform'] = 'microblog';
2309 $serverdata['network'] = Protocol::ACTIVITYPUB;
2315 if ($serverdata['platform'] != 'microblog') {
2316 $list = $xpath->query('//link[@rel="micropub"]');
2317 foreach ($list as $node) {
2318 foreach ($node->attributes as $attribute) {
2319 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2320 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2321 $serverdata['platform'] = 'microblog';
2322 $serverdata['network'] = Protocol::ACTIVITYPUB;
2329 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2330 $serverdata['detection-method'] = self::DETECT_BODY;
2337 * Analyses the header data of a given server for hints about type and system of that server
2339 * @param object $curlResult result of curl execution
2340 * @param array $serverdata array with server data
2342 * @return array server data
2344 private static function analyseRootHeader($curlResult, array $serverdata): array
2346 if ($curlResult->getHeader('server') == 'Mastodon') {
2347 $serverdata['platform'] = 'mastodon';
2348 $serverdata['network'] = Protocol::ACTIVITYPUB;
2349 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2350 $serverdata['platform'] = 'diaspora';
2351 $serverdata['network'] = Protocol::DIASPORA;
2352 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2353 } elseif ($curlResult->inHeader('x-friendica-version')) {
2354 $serverdata['platform'] = 'friendica';
2355 $serverdata['network'] = Protocol::DFRN;
2356 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2361 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2362 $serverdata['detection-method'] = self::DETECT_HEADER;
2369 * Update GServer entries
2371 public static function discover()
2373 // Update the server list
2374 self::discoverFederation();
2378 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2380 if ($requery_days == 0) {
2384 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2386 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2387 ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2388 ['order' => ['RAND()']]);
2390 while ($gserver = DBA::fetch($gservers)) {
2391 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2392 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2394 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2395 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2397 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2398 self::update($fields, ['nurl' => $gserver['nurl']]);
2400 if (--$no_of_queries == 0) {
2405 DBA::close($gservers);
2409 * Discover federated servers
2411 private static function discoverFederation()
2413 $last = DI::keyValue()->get('poco_last_federation_discovery');
2416 $next = $last + (24 * 60 * 60);
2418 if ($next > time()) {
2423 // Discover federated servers
2424 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2425 foreach ($protocols as $protocol) {
2426 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2427 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2428 if (!empty($curlResult)) {
2429 $data = json_decode($curlResult, true);
2430 if (!empty($data['data']['nodes'])) {
2431 foreach ($data['data']['nodes'] as $server) {
2432 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2433 self::add('https://' . $server['host'], true);
2439 // Discover Mastodon servers
2440 $accesstoken = DI::config()->get('system', 'instances_social_key');
2442 if (!empty($accesstoken)) {
2443 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2444 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2445 if ($curlResult->isSuccess()) {
2446 $servers = json_decode($curlResult->getBody(), true);
2448 if (!empty($servers['instances'])) {
2449 foreach ($servers['instances'] as $server) {
2450 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2457 DI::keyValue()->set('poco_last_federation_discovery', time());
2461 * Set the protocol for the given server
2463 * @param int $gsid Server id
2464 * @param int $protocol Protocol id
2468 public static function setProtocol(int $gsid, int $protocol)
2474 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2475 if (!DBA::isResult($gserver)) {
2479 $old = $gserver['protocol'];
2481 if (!is_null($old)) {
2483 The priority for the protocols is:
2485 2. DFRN via Diaspora
2491 // We don't need to change it when nothing is to be changed
2492 if ($old == $protocol) {
2496 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2497 if ($protocol == Post\DeliveryData::OSTATUS) {
2501 // If the server is marked as ActivityPub then we won't change it to anything different
2502 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2506 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2507 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2511 // Don't change it to Diaspora when it is a legacy DFRN server
2512 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2517 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]);
2518 self::update(['protocol' => $protocol], ['id' => $gsid]);
2522 * Fetch the protocol of the given server
2524 * @param int $gsid Server id
2526 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2530 public static function getProtocol(int $gsid): ?int
2536 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2537 if (DBA::isResult($gserver)) {
2538 return $gserver['protocol'];
2545 * Update rows in the gserver table.
2546 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2548 * @param array $fields
2549 * @param array $condition
2555 public static function update(array $fields, array $condition): bool
2557 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2559 return DBA::update('gserver', $fields, $condition);
2563 * Insert a row into the gserver table.
2564 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2566 * @param array $fields
2567 * @param int $duplicate_mode What to do on a duplicated entry
2573 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2575 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2577 return DBA::insert('gserver', $fields, $duplicate_mode);