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 Friendica\Worker\UpdateGServer;
48 use GuzzleHttp\Psr7\Uri;
49 use Psr\Http\Message\UriInterface;
52 * This class handles GServer related functions
59 const DT_MASTODON = 2;
61 // Methods to detect server types
63 // Non endpoint specific methods
64 const DETECT_MANUAL = 0;
65 const DETECT_HEADER = 1;
66 const DETECT_BODY = 2;
67 const DETECT_HOST_META = 3;
68 const DETECT_CONTACTS = 4;
69 const DETECT_AP_ACTOR = 5;
70 const DETECT_AP_COLLECTION = 6;
72 const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
74 // Implementation specific endpoints
75 // @todo Possibly add Lemmy detection via the endpoint /api/v3/site
76 const DETECT_FRIENDIKA = 10;
77 const DETECT_FRIENDICA = 11;
78 const DETECT_STATUSNET = 12;
79 const DETECT_GNUSOCIAL = 13;
80 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
81 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
82 const DETECT_MASTODON_API = 16;
83 const DETECT_STATUS_PHP = 17; // Nextcloud
84 const DETECT_V1_CONFIG = 18;
85 const DETECT_PUMPIO = 19; // Deprecated
86 const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
88 // Standardized endpoints
89 const DETECT_STATISTICS_JSON = 100;
90 const DETECT_NODEINFO_1 = 101;
91 const DETECT_NODEINFO_2 = 102;
92 const DETECT_NODEINFO_210 = 103;
95 * Check for the existance of a server and adds it in the background if not existant
98 * @param boolean $only_nodeinfo
102 public static function add(string $url, bool $only_nodeinfo = false)
104 if (self::getID($url)) {
108 UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
112 * Get the ID for the given server URL
115 * @param boolean $no_check Don't check if the server hadn't been found
117 * @return int|null gserver id or NULL on empty URL or failed check
119 public static function getID(string $url, bool $no_check = false): ?int
121 $url = self::cleanURL($url);
127 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
128 if (DBA::isResult($gserver)) {
129 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
131 if (Network::isUrlBlocked($url)) {
132 self::setBlockedById($gserver['id']);
134 self::setUnblockedById($gserver['id']);
137 return $gserver['id'];
140 if ($no_check || !self::check($url)) {
144 return self::getID($url, true);
148 * Retrieves all the servers which base domain are matching the provided domain pattern
150 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
152 * @param string $pattern
158 public static function listByDomainPattern(string $pattern): array
160 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
162 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
163 // eventual server path and keep only the server domain which we're matching against the pattern.
164 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
166 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
167 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
168 AND NOT `gserver`.`failed`
169 GROUP BY `gserver`.`id`";
171 $stmt = DI::dba()->p($sql, $likePattern);
173 return DI::dba()->toArray($stmt);
177 * Checks if the given server array is unreachable for a long time now
179 * @param integer $gsid
182 private static function isDefunct(array $gserver): bool
184 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
185 ($gserver['last_contact'] >= $gserver['created']) &&
186 ($gserver['last_contact'] < $gserver['last_failure']) &&
187 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
191 * Checks if the given server id is unreachable for a long time now
193 * @param integer $gsid
196 public static function isDefunctById(int $gsid): bool
198 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
199 if (empty($gserver)) {
202 if (strtotime($gserver['next_contact']) < time()) {
203 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
206 return self::isDefunct($gserver);
211 * Checks if the given server id is reachable
213 * @param integer $gsid
216 public static function isReachableById(int $gsid): bool
218 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
219 if (empty($gserver)) {
222 if (strtotime($gserver['next_contact']) < time()) {
223 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
226 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
231 * Checks if the given server is reachable
233 * @param array $contact Contact that should be checked
235 * @return boolean 'true' if server seems vital
237 public static function reachable(array $contact): bool
239 if (!empty($contact['gsid'])) {
240 $gsid = $contact['gsid'];
241 } elseif (!empty($contact['baseurl'])) {
242 $server = $contact['baseurl'];
243 } elseif ($contact['network'] == Protocol::DIASPORA) {
244 $parts = parse_url($contact['url']);
245 unset($parts['path']);
246 $server = (string)Uri::fromParts($parts);
252 $condition = ['id' => $gsid];
254 $condition = ['nurl' => Strings::normaliseLink($server)];
257 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
258 if (empty($gserver)) {
261 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
262 $server = $gserver['url'];
265 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
266 UpdateGServer::add(Worker::PRIORITY_LOW, $server);
273 * Calculate the next update day
275 * @param bool $success
276 * @param string $created
277 * @param string $last_contact
278 * @param bool $undetected
284 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
286 // On successful contact process check again next week when it is a detected system.
287 // When we haven't detected the system, it could be a static website or a really old system.
289 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
292 $now = strtotime(DateTimeFormat::utcNow());
294 if ($created > $last_contact) {
295 $contact_time = strtotime($created);
297 $contact_time = strtotime($last_contact);
300 // If the last contact was less than 6 hours before then try again in 6 hours
301 if (($now - $contact_time) < (60 * 60 * 6)) {
302 return DateTimeFormat::utc('now +6 hour');
305 // If the last contact was less than 12 hours before then try again in 12 hours
306 if (($now - $contact_time) < (60 * 60 * 12)) {
307 return DateTimeFormat::utc('now +12 hour');
310 // If the last contact was less than 24 hours before then try tomorrow again
311 if (($now - $contact_time) < (60 * 60 * 24)) {
312 return DateTimeFormat::utc('now +1 day');
315 // If the last contact was less than a week before then try again in a week
316 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
317 return DateTimeFormat::utc('now +1 week');
320 // If the last contact was less than two weeks before then try again in two week
321 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
322 return DateTimeFormat::utc('now +2 week');
325 // If the last contact was less than a month before then try again in a month
326 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
327 return DateTimeFormat::utc('now +1 month');
330 // The system hadn't been successul contacted for more than a month, so try again in three months
331 return DateTimeFormat::utc('now +3 month');
335 * Checks the state of the given server.
337 * @param string $server_url URL of the given server
338 * @param string $network Network value that is used, when detection failed
339 * @param boolean $force Force an update.
340 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
342 * @return boolean 'true' if server seems vital
344 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
346 $server_url = self::cleanURL($server_url);
347 if ($server_url == '') {
351 if (Network::isUrlBlocked($server_url)) {
352 Logger::info('Server is blocked', ['url' => $server_url]);
353 self::setBlockedByUrl($server_url);
357 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
358 if (DBA::isResult($gserver)) {
359 if ($gserver['created'] <= DBA::NULL_DATETIME) {
360 $fields = ['created' => DateTimeFormat::utcNow()];
361 $condition = ['nurl' => Strings::normaliseLink($server_url)];
362 self::update($fields, $condition);
365 if (!$force && (strtotime($gserver['next_contact']) > time())) {
366 Logger::info('No update needed', ['server' => $server_url]);
367 return (!$gserver['failed']);
369 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
371 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
374 return self::detect($server_url, $network, $only_nodeinfo);
378 * Reset failed server status by gserver id
381 * @param string $network
383 public static function setReachableById(int $gsid, string $network)
385 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
386 if (!DBA::isResult($gserver)) {
390 $blocked = Network::isUrlBlocked($gserver['url']);
391 if ($gserver['failed']) {
392 $fields = ['failed' => false, 'blocked' => $blocked, 'last_contact' => DateTimeFormat::utcNow()];
393 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
394 $fields['network'] = $network;
396 self::update($fields, ['id' => $gsid]);
397 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
399 if (strtotime($gserver['next_contact']) < time()) {
400 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
402 } elseif ($blocked) {
403 self::setBlockedById($gsid);
405 self::setUnblockedById($gsid);
410 * Set failed server status by gserver id
414 public static function setFailureById(int $gsid)
416 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
417 if (DBA::isResult($gserver) && !$gserver['failed']) {
418 self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
419 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
421 if (strtotime($gserver['next_contact']) < time()) {
422 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
427 public static function setUnblockedById(int $gsid)
429 $gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
430 if (DBA::isResult($gserver)) {
431 self::update(['blocked' => false], ['id' => $gsid]);
432 Logger::info('Set unblocked status for server', ['url' => $gserver['url']]);
436 public static function setBlockedById(int $gsid)
438 $gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
439 if (DBA::isResult($gserver)) {
440 self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
441 Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
445 public static function setBlockedByUrl(string $url)
447 $gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
448 if (DBA::isResult($gserver)) {
449 self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
450 Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
455 * Set failed server status
460 public static function setFailureByUrl(string $url)
462 $nurl = Strings::normaliseLink($url);
464 $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
465 if (DBA::isResult($gserver)) {
466 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
467 self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
468 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
470 Logger::info('Set failed status for existing server', ['url' => $url]);
471 if (self::isDefunct($gserver)) {
472 self::archiveContacts($gserver['id']);
477 self::insert(['url' => $url, 'nurl' => $nurl,
478 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
479 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
480 Logger::info('Set failed status for new server', ['url' => $url]);
484 * Archive server related contacts and inboxes
486 * @param integer $gsid
489 private static function archiveContacts(int $gsid)
491 Contact::update(['archive' => true], ['gsid' => $gsid]);
492 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
496 * Remove unwanted content from the given URL
498 * @param string $dirtyUrl
500 * @return string cleaned URL
502 * @deprecated since 2023.03 Use cleanUri instead
504 public static function cleanURL(string $dirtyUrl): string
507 return (string)self::cleanUri(new Uri($dirtyUrl));
508 } catch (\Throwable $e) {
509 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
515 * Remove unwanted content from the given URI
517 * @param UriInterface $dirtyUri
519 * @return UriInterface cleaned URI
522 public static function cleanUri(UriInterface $dirtyUri): string
530 '#(?:^|/)index\.php#',
532 rtrim($dirtyUri->getPath(), '/')
538 * Detect server data (type, protocol, version number, ...)
539 * The detected data is then updated or inserted in the gserver table.
541 * @param string $url URL of the given server
542 * @param string $network Network value that is used, when detection failed
543 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
545 * @return boolean 'true' if server could be detected
547 private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
549 Logger::info('Detect server type', ['server' => $url]);
551 $original_url = $url;
553 // Remove URL content that is not supposed to exist for a server url
554 $url = rtrim(self::cleanURL($url), '/');
556 Logger::notice('Empty URL.');
560 // If the URL missmatches, then we mark the old entry as failure
561 if (!Strings::compareLink($url, $original_url)) {
562 self::setFailureByUrl($original_url);
563 if (!self::getID($url, true) && !Network::isUrlBlocked($url)) {
564 self::detect($url, $network, $only_nodeinfo);
569 $valid_url = Network::isUrlValid($url);
571 self::setFailureByUrl($url);
574 $valid_url = rtrim($valid_url, '/');
577 if (!Strings::compareLink($url, $valid_url)) {
578 // We only follow redirects when the path stays the same or the target url has no path.
579 // Some systems have got redirects on their landing page to a single account page. This check handles it.
580 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))) ||
581 (((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)))) {
582 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
583 self::setFailureByUrl($url);
584 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
585 self::detect($valid_url, $network, $only_nodeinfo);
590 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)) &&
591 (parse_url($url, PHP_URL_PATH) == '')) {
592 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
593 $parts = parse_url($valid_url);
594 unset($parts['path']);
595 $valid_url = (string)Uri::fromParts($parts);
597 self::setFailureByUrl($url);
598 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
599 self::detect($valid_url, $network, $only_nodeinfo);
603 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
606 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
607 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
608 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
612 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
614 // When a nodeinfo is present, we don't need to dig further
615 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
616 if ($curlResult->isTimeout()) {
617 self::setFailureByUrl($url);
621 $serverdata = self::parseNodeinfo210($curlResult);
622 if (empty($serverdata)) {
623 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
624 $serverdata = self::fetchNodeinfo($url, $curlResult);
627 if ($only_nodeinfo && empty($serverdata)) {
628 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
629 self::setFailureByUrl($url);
631 } elseif (empty($serverdata)) {
632 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
635 // When there is no Nodeinfo, then use some protocol specific endpoints
636 if ($serverdata['network'] == Protocol::PHANTOM) {
638 // Fetch the landing page, possibly it reveals some data
639 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
640 $curlResult = DI::httpClient()->get($url, $accept);
641 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
642 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
643 $html_fetched = true;
645 $html_fetched = false;
648 if ($curlResult->isSuccess()) {
649 $json = json_decode($curlResult->getBody(), true);
650 if (!empty($json) && is_array($json)) {
651 $data = self::fetchDataFromSystemActor($json, $serverdata);
652 $serverdata = $data['server'];
653 $systemactor = $data['actor'];
654 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
655 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
657 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
658 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
661 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
662 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
663 $serverdata = self::analyseRootBody($curlResult, $serverdata);
667 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
668 self::setFailureByUrl($url);
672 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
673 $serverdata = self::detectMastodonAlikes($url, $serverdata);
677 // All following checks are done for systems that always have got a "host-meta" endpoint.
678 // With this check we don't have to waste time and ressources for dead systems.
679 // Also this hopefully prevents us from receiving abuse messages.
680 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
681 $validHostMeta = self::validHostMeta($url);
683 $validHostMeta = false;
686 if ($validHostMeta) {
687 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
688 $serverdata['detection-method'] = self::DETECT_HOST_META;
691 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
692 $serverdata = self::detectFriendica($url, $serverdata);
695 // The following systems have to be installed in the root directory.
697 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
698 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
699 $serverdata = self::fetchSiteinfo($url, $serverdata);
702 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
703 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
704 $serverdata = self::detectHubzilla($url, $serverdata);
707 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
708 $serverdata = self::detectPeertube($url, $serverdata);
711 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
712 $serverdata = self::detectGNUSocial($url, $serverdata);
715 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
716 $serverdata = self::detectFriendica($url, $serverdata);
719 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
720 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
723 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
724 // Since this endpoint is only rarely used, we query it at a later time
725 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
726 $serverdata = self::fetchStatistics($url, $serverdata);
730 // When we hadn't been able to detect the network type, we use the hint from the parameter
731 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
732 $serverdata['network'] = $network;
735 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
736 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
737 self::setFailureByUrl($url);
741 $serverdata['url'] = $url;
742 $serverdata['nurl'] = Strings::normaliseLink($url);
744 // We have to prevent an endless loop here.
745 // When a server is new, then there is no gserver entry yet.
746 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
747 // and this can call this function here as well.
748 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
749 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
750 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
753 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
754 self::setFailureByUrl($url);
758 // Detect the directory type
759 $serverdata['directory-type'] = self::DT_NONE;
761 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
762 $serverdata = self::checkMastodonDirectory($url, $serverdata);
764 if ($serverdata['directory-type'] == self::DT_NONE) {
765 $serverdata = self::checkPoCo($url, $serverdata);
769 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
770 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
773 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
775 // Numbers above a reasonable value (10 millions) are ignored
776 if ($serverdata['registered-users'] > 10000000) {
777 $serverdata['registered-users'] = 0;
780 // On an active server there has to be at least a single user
781 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
782 $serverdata['registered-users'] = 1;
783 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
784 $serverdata['registered-users'] = 0;
787 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
788 $serverdata['last_contact'] = DateTimeFormat::utcNow();
789 $serverdata['failed'] = false;
790 $serverdata['blocked'] = false;
792 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
793 if (!DBA::isResult($gserver)) {
794 $serverdata['created'] = DateTimeFormat::utcNow();
795 $ret = self::insert($serverdata);
796 $id = DBA::lastInsertId();
798 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
799 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
800 if (DBA::isResult($gserver)) {
801 $id = $gserver['id'];
805 // Count the number of known contacts from this server
806 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
807 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
808 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
809 $max_users = max($apcontacts, $contacts);
810 if ($max_users > $serverdata['registered-users']) {
811 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
812 self::update(['registered-users' => $max_users], ['id' => $id]);
815 if (empty($serverdata['active-month-users'])) {
816 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
818 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
819 self::update(['active-month-users' => $contacts], ['id' => $id]);
823 if (empty($serverdata['active-halfyear-users'])) {
824 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
826 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
827 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
832 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
833 self::discoverRelay($url);
836 if (!empty($systemactor)) {
837 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
838 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
845 * Fetch relay data from a given server url
847 * @param string $server_url address of the server
851 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
853 private static function discoverRelay(string $server_url)
855 Logger::info('Discover relay data', ['server' => $server_url]);
857 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
858 if (!$curlResult->isSuccess()) {
862 $data = json_decode($curlResult->getBody(), true);
863 if (!is_array($data)) {
867 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
868 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
870 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
872 $data['subscribe'] = false;
876 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
877 if (!DBA::isResult($gserver)) {
881 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
882 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
883 self::update($fields, ['id' => $gserver['id']]);
886 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
888 if ($data['scope'] == 'tags') {
891 foreach ($data['tags'] as $tag) {
892 $tag = mb_strtolower($tag);
893 if (strlen($tag) < 100) {
898 foreach ($tags as $tag) {
899 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
903 // Create or update the relay contact
905 if (isset($data['protocols'])) {
906 if (isset($data['protocols']['diaspora'])) {
907 $fields['network'] = Protocol::DIASPORA;
909 if (isset($data['protocols']['diaspora']['receive'])) {
910 $fields['batch'] = $data['protocols']['diaspora']['receive'];
911 } elseif (is_string($data['protocols']['diaspora'])) {
912 $fields['batch'] = $data['protocols']['diaspora'];
916 if (isset($data['protocols']['dfrn'])) {
917 $fields['network'] = Protocol::DFRN;
919 if (isset($data['protocols']['dfrn']['receive'])) {
920 $fields['batch'] = $data['protocols']['dfrn']['receive'];
921 } elseif (is_string($data['protocols']['dfrn'])) {
922 $fields['batch'] = $data['protocols']['dfrn'];
926 if (isset($data['protocols']['activitypub'])) {
927 $fields['network'] = Protocol::ACTIVITYPUB;
929 if (!empty($data['protocols']['activitypub']['actor'])) {
930 $fields['url'] = $data['protocols']['activitypub']['actor'];
932 if (!empty($data['protocols']['activitypub']['receive'])) {
933 $fields['batch'] = $data['protocols']['activitypub']['receive'];
938 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
940 Relay::updateContact($gserver, $fields);
944 * Fetch server data from '/statistics.json' on the given server
946 * @param string $url URL of the given server
948 * @return array server data
950 private static function fetchStatistics(string $url, array $serverdata): array
952 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
953 if (!$curlResult->isSuccess()) {
957 $data = json_decode($curlResult->getBody(), true);
962 // Some AP enabled systems return activity data that we don't expect here.
963 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
968 $old_serverdata = $serverdata;
970 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
972 if (!empty($data['version'])) {
974 $serverdata['version'] = $data['version'];
975 // Version numbers on statistics.json are presented with additional info, e.g.:
976 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
977 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
980 if (!empty($data['name'])) {
982 $serverdata['site_name'] = $data['name'];
985 if (!empty($data['network'])) {
987 $serverdata['platform'] = strtolower($data['network']);
989 if ($serverdata['platform'] == 'diaspora') {
990 $serverdata['network'] = Protocol::DIASPORA;
991 } elseif ($serverdata['platform'] == 'friendica') {
992 $serverdata['network'] = Protocol::DFRN;
993 } elseif ($serverdata['platform'] == 'hubzilla') {
994 $serverdata['network'] = Protocol::ZOT;
995 } elseif ($serverdata['platform'] == 'redmatrix') {
996 $serverdata['network'] = Protocol::ZOT;
1000 if (!empty($data['total_users'])) {
1002 $serverdata['registered-users'] = max($data['total_users'], 1);
1005 if (!empty($data['active_users_monthly'])) {
1007 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
1010 if (!empty($data['active_users_halfyear'])) {
1012 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
1015 if (!empty($data['local_posts'])) {
1017 $serverdata['local-posts'] = max($data['local_posts'], 0);
1020 if (!empty($data['registrations_open'])) {
1021 $serverdata['register_policy'] = Register::OPEN;
1023 $serverdata['register_policy'] = Register::CLOSED;
1027 return $old_serverdata;
1034 * Detect server type by using the nodeinfo data
1036 * @param string $url address of the server
1037 * @param ICanHandleHttpResponses $httpResult
1039 * @return array Server data
1041 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
1045 if (!$httpResult->isSuccess()) {
1049 $nodeinfo = json_decode($httpResult->getBody(), true);
1051 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
1055 $nodeinfo1_url = '';
1056 $nodeinfo2_url = '';
1058 foreach ($nodeinfo['links'] as $link) {
1059 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
1060 Logger::info('Invalid nodeinfo format', ['url' => $url]);
1064 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
1065 $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1066 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
1067 $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1071 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1077 if (!empty($nodeinfo2_url)) {
1078 $server = self::parseNodeinfo2($nodeinfo2_url);
1081 if (empty($server) && !empty($nodeinfo1_url)) {
1082 $server = self::parseNodeinfo1($nodeinfo1_url);
1091 * @param string $nodeinfo_url address of the nodeinfo path
1093 * @return array Server data
1095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1097 private static function parseNodeinfo1(string $nodeinfo_url): array
1099 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1100 if (!$curlResult->isSuccess()) {
1104 $nodeinfo = json_decode($curlResult->getBody(), true);
1106 if (!is_array($nodeinfo)) {
1110 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1111 'register_policy' => Register::CLOSED];
1113 if (!empty($nodeinfo['openRegistrations'])) {
1114 $server['register_policy'] = Register::OPEN;
1117 if (is_array($nodeinfo['software'])) {
1118 if (!empty($nodeinfo['software']['name'])) {
1119 $server['platform'] = strtolower($nodeinfo['software']['name']);
1122 if (!empty($nodeinfo['software']['version'])) {
1123 $server['version'] = $nodeinfo['software']['version'];
1124 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1125 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1126 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1130 if (!empty($nodeinfo['metadata']['nodeName'])) {
1131 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1134 if (!empty($nodeinfo['usage']['users']['total'])) {
1135 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1138 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1139 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1142 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1143 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1146 if (!empty($nodeinfo['usage']['localPosts'])) {
1147 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1150 if (!empty($nodeinfo['usage']['localComments'])) {
1151 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1154 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1156 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1157 $protocols[$protocol] = true;
1160 if (!empty($protocols['friendica'])) {
1161 $server['network'] = Protocol::DFRN;
1162 } elseif (!empty($protocols['activitypub'])) {
1163 $server['network'] = Protocol::ACTIVITYPUB;
1164 } elseif (!empty($protocols['diaspora'])) {
1165 $server['network'] = Protocol::DIASPORA;
1166 } elseif (!empty($protocols['ostatus'])) {
1167 $server['network'] = Protocol::OSTATUS;
1168 } elseif (!empty($protocols['gnusocial'])) {
1169 $server['network'] = Protocol::OSTATUS;
1170 } elseif (!empty($protocols['zot'])) {
1171 $server['network'] = Protocol::ZOT;
1175 if (empty($server)) {
1179 if (empty($server['network'])) {
1180 $server['network'] = Protocol::PHANTOM;
1189 * @see https://git.feneas.org/jaywink/nodeinfo2
1191 * @param string $nodeinfo_url address of the nodeinfo path
1193 * @return array Server data
1195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1197 private static function parseNodeinfo2(string $nodeinfo_url): array
1199 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1200 if (!$curlResult->isSuccess()) {
1204 $nodeinfo = json_decode($curlResult->getBody(), true);
1205 if (!is_array($nodeinfo)) {
1210 'detection-method' => self::DETECT_NODEINFO_2,
1211 'register_policy' => Register::CLOSED,
1212 'platform' => 'unknown',
1215 if (!empty($nodeinfo['openRegistrations'])) {
1216 $server['register_policy'] = Register::OPEN;
1219 if (!empty($nodeinfo['software'])) {
1220 if (isset($nodeinfo['software']['name'])) {
1221 $server['platform'] = strtolower($nodeinfo['software']['name']);
1224 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1225 $server['version'] = $nodeinfo['software']['version'];
1226 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1227 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1228 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1230 // qoto advertises itself as Mastodon
1231 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1232 $server['platform'] = 'qoto';
1237 if (!empty($nodeinfo['metadata']['nodeName'])) {
1238 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1241 if (!empty($nodeinfo['usage']['users']['total'])) {
1242 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1245 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1246 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1249 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1250 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1253 if (!empty($nodeinfo['usage']['localPosts'])) {
1254 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1257 if (!empty($nodeinfo['usage']['localComments'])) {
1258 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1261 if (!empty($nodeinfo['protocols'])) {
1263 foreach ($nodeinfo['protocols'] as $protocol) {
1264 if (is_string($protocol)) {
1265 $protocols[$protocol] = true;
1269 if (!empty($protocols['dfrn'])) {
1270 $server['network'] = Protocol::DFRN;
1271 } elseif (!empty($protocols['activitypub'])) {
1272 $server['network'] = Protocol::ACTIVITYPUB;
1273 } elseif (!empty($protocols['diaspora'])) {
1274 $server['network'] = Protocol::DIASPORA;
1275 } elseif (!empty($protocols['ostatus'])) {
1276 $server['network'] = Protocol::OSTATUS;
1277 } elseif (!empty($protocols['gnusocial'])) {
1278 $server['network'] = Protocol::OSTATUS;
1279 } elseif (!empty($protocols['zot'])) {
1280 $server['network'] = Protocol::ZOT;
1284 if (empty($server)) {
1288 if (empty($server['network'])) {
1289 $server['network'] = Protocol::PHANTOM;
1296 * Parses NodeInfo2 protocol 1.0
1298 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1300 * @param string $nodeinfo_url address of the nodeinfo path
1302 * @return array Server data
1304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1306 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1308 if (!$httpResult->isSuccess()) {
1312 $nodeinfo = json_decode($httpResult->getBody(), true);
1314 if (!is_array($nodeinfo)) {
1318 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1319 'register_policy' => Register::CLOSED];
1321 if (!empty($nodeinfo['openRegistrations'])) {
1322 $server['register_policy'] = Register::OPEN;
1325 if (!empty($nodeinfo['server'])) {
1326 if (!empty($nodeinfo['server']['software'])) {
1327 $server['platform'] = strtolower($nodeinfo['server']['software']);
1330 if (!empty($nodeinfo['server']['version'])) {
1331 $server['version'] = $nodeinfo['server']['version'];
1332 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1333 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1334 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1337 if (!empty($nodeinfo['server']['name'])) {
1338 $server['site_name'] = $nodeinfo['server']['name'];
1342 if (!empty($nodeinfo['usage']['users']['total'])) {
1343 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1346 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1347 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1350 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1351 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1354 if (!empty($nodeinfo['usage']['localPosts'])) {
1355 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1358 if (!empty($nodeinfo['usage']['localComments'])) {
1359 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1362 if (!empty($nodeinfo['protocols'])) {
1364 foreach ($nodeinfo['protocols'] as $protocol) {
1365 if (is_string($protocol)) {
1366 $protocols[$protocol] = true;
1370 if (!empty($protocols['dfrn'])) {
1371 $server['network'] = Protocol::DFRN;
1372 } elseif (!empty($protocols['activitypub'])) {
1373 $server['network'] = Protocol::ACTIVITYPUB;
1374 } elseif (!empty($protocols['diaspora'])) {
1375 $server['network'] = Protocol::DIASPORA;
1376 } elseif (!empty($protocols['ostatus'])) {
1377 $server['network'] = Protocol::OSTATUS;
1378 } elseif (!empty($protocols['gnusocial'])) {
1379 $server['network'] = Protocol::OSTATUS;
1380 } elseif (!empty($protocols['zot'])) {
1381 $server['network'] = Protocol::ZOT;
1385 if (empty($server) || empty($server['platform'])) {
1389 if (empty($server['network'])) {
1390 $server['network'] = Protocol::PHANTOM;
1397 * Fetch server information from a 'siteinfo.json' file on the given server
1399 * @param string $url URL of the given server
1400 * @param array $serverdata array with server data
1402 * @return array server data
1404 private static function fetchSiteinfo(string $url, array $serverdata): array
1406 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1407 if (!$curlResult->isSuccess()) {
1411 $data = json_decode($curlResult->getBody(), true);
1416 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1417 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1420 if (!empty($data['platform'])) {
1421 $serverdata['platform'] = strtolower($data['platform']);
1422 $serverdata['version'] = $data['version'] ?? 'N/A';
1425 if (!empty($data['plugins'])) {
1426 if (in_array('pubcrawl', $data['plugins'])) {
1427 $serverdata['network'] = Protocol::ACTIVITYPUB;
1428 } elseif (in_array('diaspora', $data['plugins'])) {
1429 $serverdata['network'] = Protocol::DIASPORA;
1430 } elseif (in_array('gnusoc', $data['plugins'])) {
1431 $serverdata['network'] = Protocol::OSTATUS;
1433 $serverdata['network'] = Protocol::ZOT;
1437 if (!empty($data['site_name'])) {
1438 $serverdata['site_name'] = $data['site_name'];
1441 if (!empty($data['channels_total'])) {
1442 $serverdata['registered-users'] = max($data['channels_total'], 1);
1445 if (!empty($data['channels_active_monthly'])) {
1446 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1449 if (!empty($data['channels_active_halfyear'])) {
1450 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1453 if (!empty($data['local_posts'])) {
1454 $serverdata['local-posts'] = max($data['local_posts'], 0);
1457 if (!empty($data['local_comments'])) {
1458 $serverdata['local-comments'] = max($data['local_comments'], 0);
1461 if (!empty($data['register_policy'])) {
1462 switch ($data['register_policy']) {
1463 case 'REGISTER_OPEN':
1464 $serverdata['register_policy'] = Register::OPEN;
1467 case 'REGISTER_APPROVE':
1468 $serverdata['register_policy'] = Register::APPROVE;
1471 case 'REGISTER_CLOSED':
1473 $serverdata['register_policy'] = Register::CLOSED;
1482 * Fetches server data via an ActivityPub account with url of that server
1484 * @param string $url URL of the given server
1485 * @param array $serverdata array with server data
1487 * @return array server data
1491 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1494 return ['server' => $serverdata, 'actor' => ''];
1497 $actor = JsonLD::compact($data, false);
1498 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1499 $serverdata['network'] = Protocol::ACTIVITYPUB;
1500 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1501 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1502 if (!empty($actor['as:generator'])) {
1503 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1504 $serverdata['platform'] = strtolower(array_shift($generator));
1505 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1506 if (self::isNomad($actor['@id'])) {
1507 $serverdata['version'] = $serverdata['platform'];
1508 $serverdata['platform'] = 'nomad';
1511 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1513 return ['server' => $serverdata, 'actor' => $actor['@id']];
1514 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1515 // By now only Ktistec seems to provide collections this way
1516 $serverdata['platform'] = 'ktistec';
1517 $serverdata['network'] = Protocol::ACTIVITYPUB;
1518 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1520 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1521 if (!empty($actors) && !empty($actors[0]['@id'])) {
1522 $actor_url = $actor['@id'] . $actors[0]['@id'];
1527 return ['server' => $serverdata, 'actor' => $actor_url];
1529 return ['server' => $serverdata, 'actor' => ''];
1533 * Detect if the given url belongs to a nomad account
1535 * @param string $url
1538 private static function isNomad(string $url): bool
1540 foreach (Probe::lrdd($url) as $attribute) {
1541 if ((($attribute['@attributes']['rel'] ?? '') == 'http://purl.org/nomad') && (($attribute['@attributes']['type'] ?? '') == 'application/x-nomad+json')) {
1549 * Checks if the server contains a valid host meta file
1551 * @param string $url URL of the given server
1553 * @return boolean 'true' if the server seems to be vital
1555 private static function validHostMeta(string $url): bool
1557 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1558 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1559 if (!$curlResult->isSuccess()) {
1563 $xrd = XML::parseString($curlResult->getBody(), true);
1564 if (!is_object($xrd)) {
1568 $elements = XML::elementToArray($xrd);
1569 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1574 foreach ($elements['xrd']['link'] as $link) {
1575 // When there is more than a single "link" element, the array looks slightly different
1576 if (!empty($link['@attributes'])) {
1577 $link = $link['@attributes'];
1580 if (empty($link['rel']) || empty($link['template'])) {
1584 if ($link['rel'] == 'lrdd') {
1585 // When the webfinger host is the same like the system host, it should be ok.
1586 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1594 * Detect the network of the given server via their known contacts
1596 * @param string $url URL of the given server
1597 * @param array $serverdata array with server data
1599 * @return array server data
1601 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1605 $nurl = Strings::normaliseLink($url);
1607 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1608 while ($apcontact = DBA::fetch($apcontacts)) {
1609 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1611 DBA::close($apcontacts);
1613 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1614 while ($pcontact = DBA::fetch($pcontacts)) {
1615 $contacts[$pcontact['nurl']] = $pcontact['url'];
1617 DBA::close($pcontacts);
1619 if (empty($contacts)) {
1624 foreach ($contacts as $contact) {
1625 // Endlosschleife verhindern wegen gsid!
1626 $data = Probe::uri($contact);
1627 if (in_array($data['network'], Protocol::FEDERATED)) {
1628 $serverdata['network'] = $data['network'];
1630 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1631 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1634 } elseif ((time() - $time) > 10) {
1635 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1644 * Checks if the given server does have a '/poco' endpoint.
1645 * This is used for the 'PortableContact' functionality,
1646 * which is used by both Friendica and Hubzilla.
1648 * @param string $url URL of the given server
1649 * @param array $serverdata array with server data
1651 * @return array server data
1653 private static function checkPoCo(string $url, array $serverdata): array
1655 $serverdata['poco'] = '';
1657 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1658 if (!$curlResult->isSuccess()) {
1662 $data = json_decode($curlResult->getBody(), true);
1667 if (!empty($data['totalResults'])) {
1668 $registeredUsers = $serverdata['registered-users'] ?? 0;
1669 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1670 $serverdata['directory-type'] = self::DT_POCO;
1671 $serverdata['poco'] = $url . '/poco';
1678 * Checks if the given server does have a Mastodon style directory endpoint.
1680 * @param string $url URL of the given server
1681 * @param array $serverdata array with server data
1683 * @return array server data
1685 public static function checkMastodonDirectory(string $url, array $serverdata): array
1687 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1688 if (!$curlResult->isSuccess()) {
1692 $data = json_decode($curlResult->getBody(), true);
1697 if (count($data) == 1) {
1698 $serverdata['directory-type'] = self::DT_MASTODON;
1705 * Detects Peertube via their known endpoint
1707 * @param string $url URL of the given server
1708 * @param array $serverdata array with server data
1710 * @return array server data
1712 private static function detectPeertube(string $url, array $serverdata): array
1714 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1715 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1719 $data = json_decode($curlResult->getBody(), true);
1724 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1725 $serverdata['platform'] = 'peertube';
1726 $serverdata['version'] = $data['serverVersion'];
1727 $serverdata['network'] = Protocol::ACTIVITYPUB;
1729 if (!empty($data['instance']['name'])) {
1730 $serverdata['site_name'] = $data['instance']['name'];
1733 if (!empty($data['instance']['shortDescription'])) {
1734 $serverdata['info'] = $data['instance']['shortDescription'];
1737 if (!empty($data['signup'])) {
1738 if (!empty($data['signup']['allowed'])) {
1739 $serverdata['register_policy'] = Register::OPEN;
1743 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1744 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1752 * Detects the version number of a given server when it was a NextCloud installation
1754 * @param string $url URL of the given server
1755 * @param array $serverdata array with server data
1756 * @param bool $validHostMeta
1758 * @return array server data
1760 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1762 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1763 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1767 $data = json_decode($curlResult->getBody(), true);
1772 if (!empty($data['version'])) {
1773 $serverdata['platform'] = 'nextcloud';
1774 $serverdata['version'] = $data['version'];
1776 if ($validHostMeta) {
1777 $serverdata['network'] = Protocol::ACTIVITYPUB;
1780 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1781 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1789 * Fetches weekly usage data
1791 * @param string $url URL of the given server
1792 * @param array $serverdata array with server data
1794 * @return array server data
1796 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1798 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1799 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1803 $data = json_decode($curlResult->getBody(), true);
1809 foreach ($data as $week) {
1810 // Use only data from a full week
1811 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1815 // Most likely the data is sorted correctly. But we better are safe than sorry
1816 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1817 $current_week = $week;
1821 if (!empty($current_week['logins'])) {
1822 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1829 * Detects data from a given server url if it was a mastodon alike system
1831 * @param string $url URL of the given server
1832 * @param array $serverdata array with server data
1834 * @return array server data
1836 private static function detectMastodonAlikes(string $url, array $serverdata): array
1838 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1839 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1843 $data = json_decode($curlResult->getBody(), true);
1850 if (!empty($data['version'])) {
1851 $serverdata['platform'] = 'mastodon';
1852 $serverdata['version'] = $data['version'] ?? '';
1853 $serverdata['network'] = Protocol::ACTIVITYPUB;
1857 if (!empty($data['title'])) {
1858 $serverdata['site_name'] = $data['title'];
1861 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1862 $serverdata['platform'] = 'mastodon';
1863 $serverdata['network'] = Protocol::ACTIVITYPUB;
1867 if (!empty($data['description'])) {
1868 $serverdata['info'] = trim($data['description']);
1871 if (!empty($data['stats']['user_count'])) {
1872 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1875 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1876 $serverdata['platform'] = strtolower($matches[1]);
1877 $serverdata['version'] = $matches[2];
1881 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1882 $serverdata['platform'] = 'pleroma';
1883 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1887 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1888 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1889 $serverdata['platform'] = 'pleroma';
1893 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1894 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1901 * Detects data from typical Hubzilla endpoints
1903 * @param string $url URL of the given server
1904 * @param array $serverdata array with server data
1906 * @return array server data
1908 private static function detectHubzilla(string $url, array $serverdata): array
1910 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1911 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1915 $data = json_decode($curlResult->getBody(), true);
1916 if (empty($data) || empty($data['site'])) {
1920 if (!empty($data['site']['name'])) {
1921 $serverdata['site_name'] = $data['site']['name'];
1924 if (!empty($data['site']['platform'])) {
1925 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1926 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1927 $serverdata['network'] = Protocol::ZOT;
1930 if (!empty($data['site']['hubzilla'])) {
1931 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1932 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1933 $serverdata['network'] = Protocol::ZOT;
1936 if (!empty($data['site']['redmatrix'])) {
1937 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1938 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1939 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1940 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1943 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1944 $serverdata['network'] = Protocol::ZOT;
1948 $inviteonly = false;
1951 if (!empty($data['site']['closed'])) {
1952 $closed = self::toBoolean($data['site']['closed']);
1955 if (!empty($data['site']['private'])) {
1956 $private = self::toBoolean($data['site']['private']);
1959 if (!empty($data['site']['inviteonly'])) {
1960 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1963 if (!$closed && !$private and $inviteonly) {
1964 $serverdata['register_policy'] = Register::APPROVE;
1965 } elseif (!$closed && !$private) {
1966 $serverdata['register_policy'] = Register::OPEN;
1968 $serverdata['register_policy'] = Register::CLOSED;
1971 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1972 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1979 * Converts input value to a boolean value
1981 * @param string|integer $val
1985 private static function toBoolean($val): bool
1987 if (($val == 'true') || ($val == 1)) {
1989 } elseif (($val == 'false') || ($val == 0)) {
1997 * Detect if the URL belongs to a GNU Social server
1999 * @param string $url URL of the given server
2000 * @param array $serverdata array with server data
2002 * @return array server data
2004 private static function detectGNUSocial(string $url, array $serverdata): array
2006 // Test for GNU Social
2007 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
2008 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2009 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2010 $serverdata['platform'] = 'gnusocial';
2011 // Remove junk that some GNU Social servers return
2012 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
2013 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2014 $serverdata['version'] = trim($serverdata['version'], '"');
2015 $serverdata['network'] = Protocol::OSTATUS;
2017 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2018 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
2024 // Test for Statusnet
2025 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
2026 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2027 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2029 // Remove junk that some GNU Social servers return
2030 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
2031 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2032 $serverdata['version'] = trim($serverdata['version'], '"');
2034 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
2035 $serverdata['platform'] = 'pleroma';
2036 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
2037 $serverdata['network'] = Protocol::ACTIVITYPUB;
2039 $serverdata['platform'] = 'statusnet';
2040 $serverdata['network'] = Protocol::OSTATUS;
2043 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2044 $serverdata['detection-method'] = self::DETECT_STATUSNET;
2052 * Detect if the URL belongs to a Friendica server
2054 * @param string $url URL of the given server
2055 * @param array $serverdata array with server data
2057 * @return array server data
2059 private static function detectFriendica(string $url, array $serverdata): array
2061 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
2062 // Because of this me must not use ACCEPT_JSON here.
2063 $curlResult = DI::httpClient()->get($url . '/friendica/json');
2064 if (!$curlResult->isSuccess()) {
2065 $curlResult = DI::httpClient()->get($url . '/friendika/json');
2067 $platform = 'Friendika';
2070 $platform = 'Friendica';
2073 if (!$curlResult->isSuccess()) {
2077 $data = json_decode($curlResult->getBody(), true);
2078 if (empty($data) || empty($data['version'])) {
2082 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2083 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2086 $serverdata['network'] = Protocol::DFRN;
2087 $serverdata['version'] = $data['version'];
2089 if (!empty($data['no_scrape_url'])) {
2090 $serverdata['noscrape'] = $data['no_scrape_url'];
2093 if (!empty($data['site_name'])) {
2094 $serverdata['site_name'] = $data['site_name'];
2097 if (!empty($data['info'])) {
2098 $serverdata['info'] = trim($data['info']);
2101 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2102 switch ($register_policy) {
2103 case 'REGISTER_OPEN':
2104 $serverdata['register_policy'] = Register::OPEN;
2107 case 'REGISTER_APPROVE':
2108 $serverdata['register_policy'] = Register::APPROVE;
2111 case 'REGISTER_CLOSED':
2112 case 'REGISTER_INVITATION':
2113 $serverdata['register_policy'] = Register::CLOSED;
2116 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2117 $serverdata['register_policy'] = Register::CLOSED;
2121 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2127 * Analyses the landing page of a given server for hints about type and system of that server
2129 * @param object $curlResult result of curl execution
2130 * @param array $serverdata array with server data
2132 * @return array server data
2134 private static function analyseRootBody($curlResult, array $serverdata): array
2136 if (empty($curlResult->getBody())) {
2140 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2141 require __DIR__ . '/../../static/platforms.config.php';
2143 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2146 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2148 $doc = new DOMDocument();
2149 @$doc->loadHTML($curlResult->getBody());
2150 $xpath = new DOMXPath($doc);
2153 // We can only detect honk via some HTML element on their page
2154 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2155 $serverdata['platform'] = 'honk';
2156 $serverdata['network'] = Protocol::ACTIVITYPUB;
2160 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2161 if (!empty($title)) {
2162 $serverdata['site_name'] = $title;
2165 $list = $xpath->query('//meta[@name]');
2167 foreach ($list as $node) {
2169 if ($node->attributes->length) {
2170 foreach ($node->attributes as $attribute) {
2171 $value = trim($attribute->value);
2172 if (empty($value)) {
2176 $attr[$attribute->name] = $value;
2179 if (empty($attr['name']) || empty($attr['content'])) {
2184 if ($attr['name'] == 'description') {
2185 $serverdata['info'] = $attr['content'];
2188 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2189 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2190 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2191 $platform = str_replace('/', ' ', $platform);
2192 $platform_parts = explode(' ', $platform);
2193 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2194 $platform = $platform_parts[0];
2195 $serverdata['version'] = $platform_parts[1];
2197 if (in_array($platform, array_values($dfrn_platforms))) {
2198 $serverdata['network'] = Protocol::DFRN;
2199 } elseif (in_array($platform, array_values($ap_platforms))) {
2200 $serverdata['network'] = Protocol::ACTIVITYPUB;
2201 } elseif (in_array($platform, array_values($zap_platforms))) {
2202 $serverdata['network'] = Protocol::ZOT;
2204 if (in_array($platform, array_values($platforms))) {
2205 $serverdata['platform'] = $platform;
2211 $list = $xpath->query('//meta[@property]');
2213 foreach ($list as $node) {
2215 if ($node->attributes->length) {
2216 foreach ($node->attributes as $attribute) {
2217 $value = trim($attribute->value);
2218 if (empty($value)) {
2222 $attr[$attribute->name] = $value;
2225 if (empty($attr['property']) || empty($attr['content'])) {
2230 if ($attr['property'] == 'og:site_name') {
2231 $serverdata['site_name'] = $attr['content'];
2234 if ($attr['property'] == 'og:description') {
2235 $serverdata['info'] = $attr['content'];
2238 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2239 if (in_array($attr['content'], array_keys($platforms))) {
2240 $serverdata['platform'] = $platforms[$attr['content']];
2244 if (in_array($attr['content'], array_keys($ap_platforms))) {
2245 $serverdata['network'] = Protocol::ACTIVITYPUB;
2246 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2247 $serverdata['network'] = Protocol::ZOT;
2252 $list = $xpath->query('//link[@rel="me"]');
2253 foreach ($list as $node) {
2254 foreach ($node->attributes as $attribute) {
2255 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2256 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2257 $serverdata['platform'] = 'microblog';
2258 $serverdata['network'] = Protocol::ACTIVITYPUB;
2264 if ($serverdata['platform'] != 'microblog') {
2265 $list = $xpath->query('//link[@rel="micropub"]');
2266 foreach ($list as $node) {
2267 foreach ($node->attributes as $attribute) {
2268 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2269 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2270 $serverdata['platform'] = 'microblog';
2271 $serverdata['network'] = Protocol::ACTIVITYPUB;
2278 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2279 $serverdata['detection-method'] = self::DETECT_BODY;
2286 * Analyses the header data of a given server for hints about type and system of that server
2288 * @param object $curlResult result of curl execution
2289 * @param array $serverdata array with server data
2291 * @return array server data
2293 private static function analyseRootHeader($curlResult, array $serverdata): array
2295 if ($curlResult->getHeader('server') == 'Mastodon') {
2296 $serverdata['platform'] = 'mastodon';
2297 $serverdata['network'] = Protocol::ACTIVITYPUB;
2298 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2299 $serverdata['platform'] = 'diaspora';
2300 $serverdata['network'] = Protocol::DIASPORA;
2301 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2302 } elseif ($curlResult->inHeader('x-friendica-version')) {
2303 $serverdata['platform'] = 'friendica';
2304 $serverdata['network'] = Protocol::DFRN;
2305 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2310 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2311 $serverdata['detection-method'] = self::DETECT_HEADER;
2318 * Update GServer entries
2320 public static function discover()
2322 // Update the server list
2323 self::discoverFederation();
2327 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2329 if ($requery_days == 0) {
2333 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2335 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2336 ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2337 ['order' => ['RAND()']]);
2339 while ($gserver = DBA::fetch($gservers)) {
2340 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2341 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2343 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2344 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2346 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2347 self::update($fields, ['nurl' => $gserver['nurl']]);
2349 if (--$no_of_queries == 0) {
2354 DBA::close($gservers);
2358 * Discover federated servers
2360 private static function discoverFederation()
2362 $last = DI::keyValue()->get('poco_last_federation_discovery');
2365 $next = $last + (24 * 60 * 60);
2367 if ($next > time()) {
2372 // Discover federated servers
2373 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2374 foreach ($protocols as $protocol) {
2375 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2376 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2377 if (!empty($curlResult)) {
2378 $data = json_decode($curlResult, true);
2379 if (!empty($data['data']['nodes'])) {
2380 foreach ($data['data']['nodes'] as $server) {
2381 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2382 self::add('https://' . $server['host'], true);
2388 // Disvover Mastodon servers
2389 $accesstoken = DI::config()->get('system', 'instances_social_key');
2391 if (!empty($accesstoken)) {
2392 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2393 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2394 if ($curlResult->isSuccess()) {
2395 $servers = json_decode($curlResult->getBody(), true);
2397 if (!empty($servers['instances'])) {
2398 foreach ($servers['instances'] as $server) {
2399 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2406 DI::keyValue()->set('poco_last_federation_discovery', time());
2410 * Set the protocol for the given server
2412 * @param int $gsid Server id
2413 * @param int $protocol Protocol id
2417 public static function setProtocol(int $gsid, int $protocol)
2423 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2424 if (!DBA::isResult($gserver)) {
2428 $old = $gserver['protocol'];
2430 if (!is_null($old)) {
2432 The priority for the protocols is:
2434 2. DFRN via Diaspora
2440 // We don't need to change it when nothing is to be changed
2441 if ($old == $protocol) {
2445 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2446 if ($protocol == Post\DeliveryData::OSTATUS) {
2450 // If the server is marked as ActivityPub then we won't change it to anything different
2451 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2455 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2456 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2460 // Don't change it to Diaspora when it is a legacy DFRN server
2461 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2466 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2467 self::update(['protocol' => $protocol], ['id' => $gsid]);
2471 * Fetch the protocol of the given server
2473 * @param int $gsid Server id
2475 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2479 public static function getProtocol(int $gsid): ?int
2485 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2486 if (DBA::isResult($gserver)) {
2487 return $gserver['protocol'];
2494 * Update rows in the gserver table.
2495 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2497 * @param array $fields
2498 * @param array $condition
2504 public static function update(array $fields, array $condition): bool
2506 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2508 return DBA::update('gserver', $fields, $condition);
2512 * Insert a row into the gserver table.
2513 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2515 * @param array $fields
2516 * @param int $duplicate_mode What to do on a duplicated entry
2522 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2524 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2526 return DBA::insert('gserver', $fields, $duplicate_mode);