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_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
86 // Standardized endpoints
87 const DETECT_STATISTICS_JSON = 100;
88 const DETECT_NODEINFO_1 = 101;
89 const DETECT_NODEINFO_2 = 102;
90 const DETECT_NODEINFO_210 = 103;
93 * Check for the existence of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
100 public static function add(string $url, bool $only_nodeinfo = false)
102 if (self::getID($url)) {
106 UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
110 * Get the ID for the given server URL
113 * @param boolean $no_check Don't check if the server hadn't been found
115 * @return int|null gserver id or NULL on empty URL or failed check
117 public static function getID(string $url, bool $no_check = false): ?int
119 $url = self::cleanURL($url);
125 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
126 if (DBA::isResult($gserver)) {
127 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url]);
129 if (Network::isUrlBlocked($url)) {
130 self::setBlockedById($gserver['id']);
132 self::setUnblockedById($gserver['id']);
135 return $gserver['id'];
138 if ($no_check || !self::check($url)) {
142 return self::getID($url, true);
146 * Retrieves all the servers which base domain are matching the provided domain pattern
148 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
150 * @param string $pattern
156 public static function listByDomainPattern(string $pattern): array
158 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
160 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
161 // eventual server path and keep only the server domain which we're matching against the pattern.
162 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
164 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
165 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
166 AND NOT `gserver`.`failed`
167 GROUP BY `gserver`.`id`";
169 $stmt = DI::dba()->p($sql, $likePattern);
171 return DI::dba()->toArray($stmt);
175 * Checks if the given server array is unreachable for a long time now
177 * @param integer $gsid
180 private static function isDefunct(array $gserver): bool
182 return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
183 ($gserver['last_contact'] >= $gserver['created']) &&
184 ($gserver['last_contact'] < $gserver['last_failure']) &&
185 ($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
189 * Checks if the given server id is unreachable for a long time now
191 * @param integer $gsid
194 public static function isDefunctById(int $gsid): bool
196 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
197 if (empty($gserver)) {
200 if (strtotime($gserver['next_contact']) < time()) {
201 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
204 return self::isDefunct($gserver);
209 * Checks if the given server id is reachable
211 * @param integer $gsid
214 public static function isReachableById(int $gsid): bool
216 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
217 if (empty($gserver)) {
220 if (strtotime($gserver['next_contact']) < time()) {
221 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
224 return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
229 * Checks if the given server is reachable
231 * @param array $contact Contact that should be checked
233 * @return boolean 'true' if server seems vital
235 public static function reachable(array $contact): bool
237 if (!empty($contact['gsid'])) {
238 $gsid = $contact['gsid'];
239 } elseif (!empty($contact['baseurl'])) {
240 $server = $contact['baseurl'];
241 } elseif ($contact['network'] == Protocol::DIASPORA) {
242 $parts = (array)parse_url($contact['url']);
243 unset($parts['path']);
244 $server = (string)Uri::fromParts($parts);
250 $condition = ['id' => $gsid];
252 $condition = ['nurl' => Strings::normaliseLink($server)];
255 $gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
256 if (empty($gserver)) {
259 $reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
260 $server = $gserver['url'];
263 if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
264 UpdateGServer::add(Worker::PRIORITY_LOW, $server);
271 * Calculate the next update day
273 * @param bool $success
274 * @param string $created
275 * @param string $last_contact
276 * @param bool $undetected
282 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
284 // On successful contact process check again next week when it is a detected system.
285 // When we haven't detected the system, it could be a static website or a really old system.
287 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
290 $now = strtotime(DateTimeFormat::utcNow());
292 if ($created > $last_contact) {
293 $contact_time = strtotime($created);
295 $contact_time = strtotime($last_contact);
298 // If the last contact was less than 6 hours before then try again in 6 hours
299 if (($now - $contact_time) < (60 * 60 * 6)) {
300 return DateTimeFormat::utc('now +6 hour');
303 // If the last contact was less than 12 hours before then try again in 12 hours
304 if (($now - $contact_time) < (60 * 60 * 12)) {
305 return DateTimeFormat::utc('now +12 hour');
308 // If the last contact was less than 24 hours before then try tomorrow again
309 if (($now - $contact_time) < (60 * 60 * 24)) {
310 return DateTimeFormat::utc('now +1 day');
313 // If the last contact was less than a week before then try again in a week
314 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
315 return DateTimeFormat::utc('now +1 week');
318 // If the last contact was less than two weeks before then try again in two week
319 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
320 return DateTimeFormat::utc('now +2 week');
323 // If the last contact was less than a month before then try again in a month
324 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
325 return DateTimeFormat::utc('now +1 month');
328 // The system hadn't been successful contacted for more than a month, so try again in three months
329 return DateTimeFormat::utc('now +3 month');
333 * Checks the state of the given server.
335 * @param string $server_url URL of the given server
336 * @param string $network Network value that is used, when detection failed
337 * @param boolean $force Force an update.
338 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
340 * @return boolean 'true' if server seems vital
342 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
344 $server_url = self::cleanURL($server_url);
345 if ($server_url == '') {
349 if (Network::isUrlBlocked($server_url)) {
350 Logger::info('Server is blocked', ['url' => $server_url]);
351 self::setBlockedByUrl($server_url);
355 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
356 if (DBA::isResult($gserver)) {
357 if ($gserver['created'] <= DBA::NULL_DATETIME) {
358 $fields = ['created' => DateTimeFormat::utcNow()];
359 $condition = ['nurl' => Strings::normaliseLink($server_url)];
360 self::update($fields, $condition);
363 if (!$force && (strtotime($gserver['next_contact']) > time())) {
364 Logger::info('No update needed', ['server' => $server_url]);
365 return (!$gserver['failed']);
367 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
369 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
372 return self::detect($server_url, $network, $only_nodeinfo);
376 * Reset failed server status by gserver id
379 * @param string $network
381 public static function setReachableById(int $gsid, string $network)
383 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
384 if (!DBA::isResult($gserver)) {
388 $blocked = Network::isUrlBlocked($gserver['url']);
389 if ($gserver['failed']) {
390 $fields = ['failed' => false, 'blocked' => $blocked, 'last_contact' => DateTimeFormat::utcNow()];
391 if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
392 $fields['network'] = $network;
394 self::update($fields, ['id' => $gsid]);
395 Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
397 if (strtotime($gserver['next_contact']) < time()) {
398 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
400 } elseif ($blocked) {
401 self::setBlockedById($gsid);
403 self::setUnblockedById($gsid);
408 * Set failed server status by gserver id
412 public static function setFailureById(int $gsid)
414 $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
415 if (DBA::isResult($gserver) && !$gserver['failed']) {
416 self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
417 Logger::info('Set failed status for server', ['url' => $gserver['url']]);
419 if (strtotime($gserver['next_contact']) < time()) {
420 UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
425 public static function setUnblockedById(int $gsid)
427 $gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
428 if (DBA::isResult($gserver)) {
429 self::update(['blocked' => false], ['id' => $gsid]);
430 Logger::info('Set unblocked status for server', ['url' => $gserver['url']]);
434 public static function setBlockedById(int $gsid)
436 $gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
437 if (DBA::isResult($gserver)) {
438 self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
439 Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
443 public static function setBlockedByUrl(string $url)
445 $gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
446 if (DBA::isResult($gserver)) {
447 self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
448 Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
453 * Set failed server status
458 public static function setFailureByUrl(string $url)
460 $nurl = Strings::normaliseLink($url);
462 $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
463 if (DBA::isResult($gserver)) {
464 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
465 self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
466 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
468 Logger::info('Set failed status for existing server', ['url' => $url]);
469 if (self::isDefunct($gserver)) {
470 self::archiveContacts($gserver['id']);
475 self::insert(['url' => $url, 'nurl' => $nurl,
476 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
477 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
478 Logger::info('Set failed status for new server', ['url' => $url]);
482 * Archive server related contacts and inboxes
484 * @param integer $gsid
487 private static function archiveContacts(int $gsid)
489 Contact::update(['archive' => true], ['gsid' => $gsid]);
490 DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
494 * Remove unwanted content from the given URL
496 * @param string $dirtyUrl
498 * @return string cleaned URL
500 * @deprecated since 2023.03 Use cleanUri instead
502 public static function cleanURL(string $dirtyUrl): string
505 return (string)self::cleanUri(new Uri($dirtyUrl));
506 } catch (\Throwable $e) {
507 Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
513 * Remove unwanted content from the given URI
515 * @param UriInterface $dirtyUri
517 * @return UriInterface cleaned URI
520 public static function cleanUri(UriInterface $dirtyUri): string
528 '#(?:^|/)index\.php#',
530 rtrim($dirtyUri->getPath(), '/')
536 * Detect server data (type, protocol, version number, ...)
537 * The detected data is then updated or inserted in the gserver table.
539 * @param string $url URL of the given server
540 * @param string $network Network value that is used, when detection failed
541 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
543 * @return boolean 'true' if server could be detected
545 private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
547 Logger::info('Detect server type', ['server' => $url]);
549 $original_url = $url;
551 // Remove URL content that is not supposed to exist for a server url
552 $url = rtrim(self::cleanURL($url), '/');
554 Logger::notice('Empty URL.');
558 // If the URL mismatches, then we mark the old entry as failure
559 if (!Strings::compareLink($url, $original_url)) {
560 self::setFailureByUrl($original_url);
561 if (!self::getID($url, true) && !Network::isUrlBlocked($url)) {
562 self::detect($url, $network, $only_nodeinfo);
567 $valid_url = Network::isUrlValid($url);
569 self::setFailureByUrl($url);
572 $valid_url = rtrim($valid_url, '/');
575 if (!Strings::compareLink($url, $valid_url)) {
576 // We only follow redirects when the path stays the same or the target url has no path.
577 // Some systems have got redirects on their landing page to a single account page. This check handles it.
578 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))) ||
579 (((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)))) {
580 Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
581 self::setFailureByUrl($url);
582 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
583 self::detect($valid_url, $network, $only_nodeinfo);
588 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)) &&
589 (parse_url($url, PHP_URL_PATH) == '')) {
590 Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
591 $parts = (array)parse_url($valid_url);
592 unset($parts['path']);
593 $valid_url = (string)Uri::fromParts($parts);
595 self::setFailureByUrl($url);
596 if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
597 self::detect($valid_url, $network, $only_nodeinfo);
601 Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
604 if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
605 (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
606 (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
610 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
612 // When a nodeinfo is present, we don't need to dig further
613 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
614 if ($curlResult->isTimeout()) {
615 self::setFailureByUrl($url);
619 if (!empty($network) && !in_array($network, Protocol::NATIVE_SUPPORT)) {
620 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => $network, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
622 $serverdata = self::parseNodeinfo210($curlResult);
623 if (empty($serverdata)) {
624 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
625 $serverdata = self::fetchNodeinfo($url, $curlResult);
629 if ($only_nodeinfo && empty($serverdata)) {
630 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
631 self::setFailureByUrl($url);
633 } elseif (empty($serverdata)) {
634 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
637 // When there is no Nodeinfo, then use some protocol specific endpoints
638 if ($serverdata['network'] == Protocol::PHANTOM) {
640 // Fetch the landing page, possibly it reveals some data
641 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
642 $curlResult = DI::httpClient()->get($url, $accept);
643 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
644 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
645 $html_fetched = true;
647 $html_fetched = false;
650 if ($curlResult->isSuccess()) {
651 $json = json_decode($curlResult->getBody(), true);
652 if (!empty($json) && is_array($json)) {
653 $data = self::fetchDataFromSystemActor($json, $serverdata);
654 $serverdata = $data['server'];
655 $systemactor = $data['actor'];
656 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
657 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
659 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
660 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
663 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
664 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
665 $serverdata = self::analyseRootBody($curlResult, $serverdata);
669 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
670 self::setFailureByUrl($url);
674 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
675 $serverdata = self::detectMastodonAlikes($url, $serverdata);
679 // All following checks are done for systems that always have got a "host-meta" endpoint.
680 // With this check we don't have to waste time and resources for dead systems.
681 // Also this hopefully prevents us from receiving abuse messages.
682 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
683 $validHostMeta = self::validHostMeta($url);
685 $validHostMeta = false;
688 if ($validHostMeta) {
689 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
690 $serverdata['detection-method'] = self::DETECT_HOST_META;
693 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
694 $serverdata = self::detectFriendica($url, $serverdata);
697 // The following systems have to be installed in the root directory.
699 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
700 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
701 $serverdata = self::fetchSiteinfo($url, $serverdata);
704 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
705 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
706 $serverdata = self::detectHubzilla($url, $serverdata);
709 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
710 $serverdata = self::detectPeertube($url, $serverdata);
713 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
714 $serverdata = self::detectGNUSocial($url, $serverdata);
717 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
718 $serverdata = self::detectFriendica($url, $serverdata);
721 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
722 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
725 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
726 // Since this endpoint is only rarely used, we query it at a later time
727 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
728 $serverdata = self::fetchStatistics($url, $serverdata);
732 // When we hadn't been able to detect the network type, we use the hint from the parameter
733 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
734 $serverdata['network'] = $network;
737 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
738 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
739 self::setFailureByUrl($url);
743 $serverdata['url'] = $url;
744 $serverdata['nurl'] = Strings::normaliseLink($url);
746 // We have to prevent an endless loop here.
747 // When a server is new, then there is no gserver entry yet.
748 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
749 // and this can call this function here as well.
750 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
751 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
752 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
755 if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
756 self::setFailureByUrl($url);
760 if (empty($serverdata['version']) && in_array($serverdata['platform'], ['osada']) && in_array($serverdata['detection-method'], [self::DETECT_CONTACTS, self::DETECT_BODY])) {
761 $serverdata['version'] = self::getNomadVersion($url);
764 // Detect the directory type
765 $serverdata['directory-type'] = self::DT_NONE;
767 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
768 $serverdata = self::checkMastodonDirectory($url, $serverdata);
770 if ($serverdata['directory-type'] == self::DT_NONE) {
771 $serverdata = self::checkPoCo($url, $serverdata);
775 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
776 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
779 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
781 // Numbers above a reasonable value (10 millions) are ignored
782 if ($serverdata['registered-users'] > 10000000) {
783 $serverdata['registered-users'] = 0;
786 // On an active server there has to be at least a single user
787 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
788 $serverdata['registered-users'] = 1;
789 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
790 $serverdata['registered-users'] = 0;
793 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
794 $serverdata['last_contact'] = DateTimeFormat::utcNow();
795 $serverdata['failed'] = false;
796 $serverdata['blocked'] = false;
798 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
799 if (!DBA::isResult($gserver)) {
800 $serverdata['created'] = DateTimeFormat::utcNow();
801 $ret = self::insert($serverdata);
802 $id = DBA::lastInsertId();
804 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
805 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
806 if (DBA::isResult($gserver)) {
807 $id = $gserver['id'];
811 // Count the number of known contacts from this server
812 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
813 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
814 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
815 $max_users = max($apcontacts, $contacts);
816 if ($max_users > $serverdata['registered-users']) {
817 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
818 self::update(['registered-users' => $max_users], ['id' => $id]);
821 if (empty($serverdata['active-month-users'])) {
822 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
824 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
825 self::update(['active-month-users' => $contacts], ['id' => $id]);
829 if (empty($serverdata['active-halfyear-users'])) {
830 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
832 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
833 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
838 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
839 self::discoverRelay($url);
842 if (!empty($systemactor)) {
843 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
844 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
851 * Fetch relay data from a given server url
853 * @param string $server_url address of the server
857 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859 private static function discoverRelay(string $server_url)
861 Logger::info('Discover relay data', ['server' => $server_url]);
863 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
864 if (!$curlResult->isSuccess()) {
868 $data = json_decode($curlResult->getBody(), true);
869 if (!is_array($data)) {
873 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
874 $data['subscribe'] = (bool)($data['subscribe'] ?? false);
876 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
878 $data['subscribe'] = false;
882 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
883 if (!DBA::isResult($gserver)) {
887 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
888 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
889 self::update($fields, ['id' => $gserver['id']]);
892 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
894 if ($data['scope'] == 'tags') {
897 foreach ($data['tags'] as $tag) {
898 $tag = mb_strtolower($tag);
899 if (strlen($tag) < 100) {
904 foreach ($tags as $tag) {
905 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
909 // Create or update the relay contact
911 if (isset($data['protocols'])) {
912 if (isset($data['protocols']['diaspora'])) {
913 $fields['network'] = Protocol::DIASPORA;
915 if (isset($data['protocols']['diaspora']['receive'])) {
916 $fields['batch'] = $data['protocols']['diaspora']['receive'];
917 } elseif (is_string($data['protocols']['diaspora'])) {
918 $fields['batch'] = $data['protocols']['diaspora'];
922 if (isset($data['protocols']['dfrn'])) {
923 $fields['network'] = Protocol::DFRN;
925 if (isset($data['protocols']['dfrn']['receive'])) {
926 $fields['batch'] = $data['protocols']['dfrn']['receive'];
927 } elseif (is_string($data['protocols']['dfrn'])) {
928 $fields['batch'] = $data['protocols']['dfrn'];
932 if (isset($data['protocols']['activitypub'])) {
933 $fields['network'] = Protocol::ACTIVITYPUB;
935 if (!empty($data['protocols']['activitypub']['actor'])) {
936 $fields['url'] = $data['protocols']['activitypub']['actor'];
938 if (!empty($data['protocols']['activitypub']['receive'])) {
939 $fields['batch'] = $data['protocols']['activitypub']['receive'];
944 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
946 Relay::updateContact($gserver, $fields);
950 * Fetch server data from '/statistics.json' on the given server
952 * @param string $url URL of the given server
954 * @return array server data
956 private static function fetchStatistics(string $url, array $serverdata): array
958 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
959 if (!$curlResult->isSuccess()) {
963 $data = json_decode($curlResult->getBody(), true);
968 // Some AP enabled systems return activity data that we don't expect here.
969 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
974 $old_serverdata = $serverdata;
976 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
978 if (!empty($data['version'])) {
980 $serverdata['version'] = $data['version'];
981 // Version numbers on statistics.json are presented with additional info, e.g.:
982 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
983 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
986 if (!empty($data['name'])) {
988 $serverdata['site_name'] = $data['name'];
991 if (!empty($data['network'])) {
993 $serverdata['platform'] = strtolower($data['network']);
995 if ($serverdata['platform'] == 'diaspora') {
996 $serverdata['network'] = Protocol::DIASPORA;
997 } elseif ($serverdata['platform'] == 'friendica') {
998 $serverdata['network'] = Protocol::DFRN;
999 } elseif ($serverdata['platform'] == 'hubzilla') {
1000 $serverdata['network'] = Protocol::ZOT;
1001 } elseif ($serverdata['platform'] == 'redmatrix') {
1002 $serverdata['network'] = Protocol::ZOT;
1006 if (!empty($data['total_users'])) {
1008 $serverdata['registered-users'] = max($data['total_users'], 1);
1011 if (!empty($data['active_users_monthly'])) {
1013 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
1016 if (!empty($data['active_users_halfyear'])) {
1018 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
1021 if (!empty($data['local_posts'])) {
1023 $serverdata['local-posts'] = max($data['local_posts'], 0);
1026 if (!empty($data['registrations_open'])) {
1027 $serverdata['register_policy'] = Register::OPEN;
1029 $serverdata['register_policy'] = Register::CLOSED;
1033 return $old_serverdata;
1040 * Detect server type by using the nodeinfo data
1042 * @param string $url address of the server
1043 * @param ICanHandleHttpResponses $httpResult
1045 * @return array Server data
1047 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1049 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
1051 if (!$httpResult->isSuccess()) {
1055 $nodeinfo = json_decode($httpResult->getBody(), true);
1057 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
1061 $nodeinfo1_url = '';
1062 $nodeinfo2_url = '';
1064 foreach ($nodeinfo['links'] as $link) {
1065 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
1066 Logger::info('Invalid nodeinfo format', ['url' => $url]);
1070 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
1071 $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1072 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
1073 $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl());
1077 if ($nodeinfo1_url . $nodeinfo2_url == '') {
1083 if (!empty($nodeinfo2_url)) {
1084 $server = self::parseNodeinfo2($nodeinfo2_url);
1087 if (empty($server) && !empty($nodeinfo1_url)) {
1088 $server = self::parseNodeinfo1($nodeinfo1_url);
1097 * @param string $nodeinfo_url address of the nodeinfo path
1099 * @return array Server data
1101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1103 private static function parseNodeinfo1(string $nodeinfo_url): array
1105 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1106 if (!$curlResult->isSuccess()) {
1110 $nodeinfo = json_decode($curlResult->getBody(), true);
1112 if (!is_array($nodeinfo)) {
1116 $server = ['detection-method' => self::DETECT_NODEINFO_1,
1117 'register_policy' => Register::CLOSED];
1119 if (!empty($nodeinfo['openRegistrations'])) {
1120 $server['register_policy'] = Register::OPEN;
1123 if (is_array($nodeinfo['software'])) {
1124 if (!empty($nodeinfo['software']['name'])) {
1125 $server['platform'] = strtolower($nodeinfo['software']['name']);
1128 if (!empty($nodeinfo['software']['version'])) {
1129 $server['version'] = $nodeinfo['software']['version'];
1130 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1131 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1132 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1136 if (!empty($nodeinfo['metadata']['nodeName'])) {
1137 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1140 if (!empty($nodeinfo['usage']['users']['total'])) {
1141 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1144 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1145 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1148 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1149 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1152 if (!empty($nodeinfo['usage']['localPosts'])) {
1153 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1156 if (!empty($nodeinfo['usage']['localComments'])) {
1157 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1160 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
1162 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
1163 $protocols[$protocol] = true;
1166 if (!empty($protocols['friendica'])) {
1167 $server['network'] = Protocol::DFRN;
1168 } elseif (!empty($protocols['activitypub'])) {
1169 $server['network'] = Protocol::ACTIVITYPUB;
1170 } elseif (!empty($protocols['diaspora'])) {
1171 $server['network'] = Protocol::DIASPORA;
1172 } elseif (!empty($protocols['ostatus'])) {
1173 $server['network'] = Protocol::OSTATUS;
1174 } elseif (!empty($protocols['gnusocial'])) {
1175 $server['network'] = Protocol::OSTATUS;
1176 } elseif (!empty($protocols['zot'])) {
1177 $server['network'] = Protocol::ZOT;
1181 if (empty($server)) {
1185 if (empty($server['network'])) {
1186 $server['network'] = Protocol::PHANTOM;
1195 * @see https://git.feneas.org/jaywink/nodeinfo2
1197 * @param string $nodeinfo_url address of the nodeinfo path
1199 * @return array Server data
1201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1203 private static function parseNodeinfo2(string $nodeinfo_url): array
1205 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
1206 if (!$curlResult->isSuccess()) {
1210 $nodeinfo = json_decode($curlResult->getBody(), true);
1211 if (!is_array($nodeinfo)) {
1216 'detection-method' => self::DETECT_NODEINFO_2,
1217 'register_policy' => Register::CLOSED,
1218 'platform' => 'unknown',
1221 if (!empty($nodeinfo['openRegistrations'])) {
1222 $server['register_policy'] = Register::OPEN;
1225 if (!empty($nodeinfo['software'])) {
1226 if (isset($nodeinfo['software']['name'])) {
1227 $server['platform'] = strtolower($nodeinfo['software']['name']);
1230 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
1231 $server['version'] = $nodeinfo['software']['version'];
1232 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1233 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1234 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1236 // qoto advertises itself as Mastodon
1237 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
1238 $server['platform'] = 'qoto';
1243 if (!empty($nodeinfo['metadata']['nodeName'])) {
1244 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
1247 if (!empty($nodeinfo['usage']['users']['total'])) {
1248 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1251 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1252 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1255 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1256 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1259 if (!empty($nodeinfo['usage']['localPosts'])) {
1260 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1263 if (!empty($nodeinfo['usage']['localComments'])) {
1264 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1267 if (!empty($nodeinfo['protocols'])) {
1269 foreach ($nodeinfo['protocols'] as $protocol) {
1270 if (is_string($protocol)) {
1271 $protocols[$protocol] = true;
1275 if (!empty($protocols['dfrn'])) {
1276 $server['network'] = Protocol::DFRN;
1277 } elseif (!empty($protocols['activitypub'])) {
1278 $server['network'] = Protocol::ACTIVITYPUB;
1279 } elseif (!empty($protocols['diaspora'])) {
1280 $server['network'] = Protocol::DIASPORA;
1281 } elseif (!empty($protocols['ostatus'])) {
1282 $server['network'] = Protocol::OSTATUS;
1283 } elseif (!empty($protocols['gnusocial'])) {
1284 $server['network'] = Protocol::OSTATUS;
1285 } elseif (!empty($protocols['zot'])) {
1286 $server['network'] = Protocol::ZOT;
1290 if (empty($server)) {
1294 if (empty($server['network'])) {
1295 $server['network'] = Protocol::PHANTOM;
1302 * Parses NodeInfo2 protocol 1.0
1304 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1306 * @param string $nodeinfo_url address of the nodeinfo path
1308 * @return array Server data
1310 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1312 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
1314 if (!$httpResult->isSuccess()) {
1318 $nodeinfo = json_decode($httpResult->getBody(), true);
1320 if (!is_array($nodeinfo)) {
1324 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1325 'register_policy' => Register::CLOSED];
1327 if (!empty($nodeinfo['openRegistrations'])) {
1328 $server['register_policy'] = Register::OPEN;
1331 if (!empty($nodeinfo['server'])) {
1332 if (!empty($nodeinfo['server']['software'])) {
1333 $server['platform'] = strtolower($nodeinfo['server']['software']);
1336 if (!empty($nodeinfo['server']['version'])) {
1337 $server['version'] = $nodeinfo['server']['version'];
1338 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1339 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1340 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1343 if (!empty($nodeinfo['server']['name'])) {
1344 $server['site_name'] = $nodeinfo['server']['name'];
1348 if (!empty($nodeinfo['usage']['users']['total'])) {
1349 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1352 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1353 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1356 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1357 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1360 if (!empty($nodeinfo['usage']['localPosts'])) {
1361 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1364 if (!empty($nodeinfo['usage']['localComments'])) {
1365 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1368 if (!empty($nodeinfo['protocols'])) {
1370 foreach ($nodeinfo['protocols'] as $protocol) {
1371 if (is_string($protocol)) {
1372 $protocols[$protocol] = true;
1376 if (!empty($protocols['dfrn'])) {
1377 $server['network'] = Protocol::DFRN;
1378 } elseif (!empty($protocols['activitypub'])) {
1379 $server['network'] = Protocol::ACTIVITYPUB;
1380 } elseif (!empty($protocols['diaspora'])) {
1381 $server['network'] = Protocol::DIASPORA;
1382 } elseif (!empty($protocols['ostatus'])) {
1383 $server['network'] = Protocol::OSTATUS;
1384 } elseif (!empty($protocols['gnusocial'])) {
1385 $server['network'] = Protocol::OSTATUS;
1386 } elseif (!empty($protocols['zot'])) {
1387 $server['network'] = Protocol::ZOT;
1391 if (empty($server) || empty($server['platform'])) {
1395 if (empty($server['network'])) {
1396 $server['network'] = Protocol::PHANTOM;
1403 * Fetch server information from a 'siteinfo.json' file on the given server
1405 * @param string $url URL of the given server
1406 * @param array $serverdata array with server data
1408 * @return array server data
1410 private static function fetchSiteinfo(string $url, array $serverdata): array
1412 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1413 if (!$curlResult->isSuccess()) {
1417 $data = json_decode($curlResult->getBody(), true);
1422 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1423 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1426 if (!empty($data['platform'])) {
1427 $serverdata['platform'] = strtolower($data['platform']);
1428 $serverdata['version'] = $data['version'] ?? 'N/A';
1431 if (!empty($data['plugins'])) {
1432 if (in_array('pubcrawl', $data['plugins'])) {
1433 $serverdata['network'] = Protocol::ACTIVITYPUB;
1434 } elseif (in_array('diaspora', $data['plugins'])) {
1435 $serverdata['network'] = Protocol::DIASPORA;
1436 } elseif (in_array('gnusoc', $data['plugins'])) {
1437 $serverdata['network'] = Protocol::OSTATUS;
1439 $serverdata['network'] = Protocol::ZOT;
1443 if (!empty($data['site_name'])) {
1444 $serverdata['site_name'] = $data['site_name'];
1447 if (!empty($data['channels_total'])) {
1448 $serverdata['registered-users'] = max($data['channels_total'], 1);
1451 if (!empty($data['channels_active_monthly'])) {
1452 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1455 if (!empty($data['channels_active_halfyear'])) {
1456 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1459 if (!empty($data['local_posts'])) {
1460 $serverdata['local-posts'] = max($data['local_posts'], 0);
1463 if (!empty($data['local_comments'])) {
1464 $serverdata['local-comments'] = max($data['local_comments'], 0);
1467 if (!empty($data['register_policy'])) {
1468 switch ($data['register_policy']) {
1469 case 'REGISTER_OPEN':
1470 $serverdata['register_policy'] = Register::OPEN;
1473 case 'REGISTER_APPROVE':
1474 $serverdata['register_policy'] = Register::APPROVE;
1477 case 'REGISTER_CLOSED':
1479 $serverdata['register_policy'] = Register::CLOSED;
1488 * Fetches server data via an ActivityPub account with url of that server
1490 * @param string $url URL of the given server
1491 * @param array $serverdata array with server data
1493 * @return array server data
1497 private static function fetchDataFromSystemActor(array $data, array $serverdata): array
1500 return ['server' => $serverdata, 'actor' => ''];
1503 $actor = JsonLD::compact($data, false);
1504 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1505 $serverdata['network'] = Protocol::ACTIVITYPUB;
1506 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1507 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1508 if (self::isNomad($actor)) {
1509 $serverdata['platform'] = self::getNomadName($actor['@id']);
1510 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1511 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1512 } elseif (!empty($actor['as:generator'])) {
1513 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1514 $serverdata['platform'] = strtolower(array_shift($generator));
1515 $serverdata['version'] = self::getNomadVersion($actor['@id']);
1516 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1518 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1520 return ['server' => $serverdata, 'actor' => $actor['@id']];
1521 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1522 // By now only Ktistec seems to provide collections this way
1523 $serverdata['platform'] = 'ktistec';
1524 $serverdata['network'] = Protocol::ACTIVITYPUB;
1525 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1527 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1528 if (!empty($actors) && !empty($actors[0]['@id'])) {
1529 $actor_url = $actor['@id'] . $actors[0]['@id'];
1534 return ['server' => $serverdata, 'actor' => $actor_url];
1536 return ['server' => $serverdata, 'actor' => ''];
1540 * Detect if the given actor is a nomad account
1542 * @param array $actor
1545 private static function isNomad(array $actor): bool
1547 $tags = JsonLD::fetchElementArray($actor, 'as:tag');
1552 foreach ($tags as $tag) {
1553 if ((($tag['as:name'] ?? '') == 'Protocol') && (($tag['sc:value'] ?? '') == 'nomad')) {
1561 * Fetch the name of Nomad implementation
1563 * @param string $url
1566 private static function getNomadName(string $url): string
1569 $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json');
1570 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1574 $data = json_decode($curlResult->getBody(), true);
1579 return $data['name'] ?? $name;
1583 * Fetch the version of the Nomad installation
1585 * @param string $url
1588 private static function getNomadVersion(string $url): string
1590 $curlResult = DI::httpClient()->get($url . '/api/z/1.0/version', HttpClientAccept::JSON);
1591 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1595 $data = json_decode($curlResult->getBody(), true);
1603 * Checks if the server contains a valid host meta file
1605 * @param string $url URL of the given server
1607 * @return boolean 'true' if the server seems to be vital
1609 private static function validHostMeta(string $url): bool
1611 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1612 $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1613 if (!$curlResult->isSuccess()) {
1617 $xrd = XML::parseString($curlResult->getBody(), true);
1618 if (!is_object($xrd)) {
1622 $elements = XML::elementToArray($xrd);
1623 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1628 foreach ($elements['xrd']['link'] as $link) {
1629 // When there is more than a single "link" element, the array looks slightly different
1630 if (!empty($link['@attributes'])) {
1631 $link = $link['@attributes'];
1634 if (empty($link['rel']) || empty($link['template'])) {
1638 if ($link['rel'] == 'lrdd') {
1639 // When the webfinger host is the same like the system host, it should be ok.
1640 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1648 * Detect the network of the given server via their known contacts
1650 * @param string $url URL of the given server
1651 * @param array $serverdata array with server data
1653 * @return array server data
1655 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1659 $nurl = Strings::normaliseLink($url);
1661 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1662 while ($apcontact = DBA::fetch($apcontacts)) {
1663 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1665 DBA::close($apcontacts);
1667 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1668 while ($pcontact = DBA::fetch($pcontacts)) {
1669 $contacts[$pcontact['nurl']] = $pcontact['url'];
1671 DBA::close($pcontacts);
1673 if (empty($contacts)) {
1678 foreach ($contacts as $contact) {
1679 // Endlosschleife verhindern wegen gsid!
1680 $data = Probe::uri($contact);
1681 if (in_array($data['network'], Protocol::FEDERATED)) {
1682 $serverdata['network'] = $data['network'];
1684 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1685 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1688 } elseif ((time() - $time) > 10) {
1689 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1698 * Checks if the given server does have a '/poco' endpoint.
1699 * This is used for the 'PortableContact' functionality,
1700 * which is used by both Friendica and Hubzilla.
1702 * @param string $url URL of the given server
1703 * @param array $serverdata array with server data
1705 * @return array server data
1707 private static function checkPoCo(string $url, array $serverdata): array
1709 $serverdata['poco'] = '';
1711 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1712 if (!$curlResult->isSuccess()) {
1716 $data = json_decode($curlResult->getBody(), true);
1721 if (!empty($data['totalResults'])) {
1722 $registeredUsers = $serverdata['registered-users'] ?? 0;
1723 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1724 $serverdata['directory-type'] = self::DT_POCO;
1725 $serverdata['poco'] = $url . '/poco';
1732 * Checks if the given server does have a Mastodon style directory endpoint.
1734 * @param string $url URL of the given server
1735 * @param array $serverdata array with server data
1737 * @return array server data
1739 public static function checkMastodonDirectory(string $url, array $serverdata): array
1741 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1742 if (!$curlResult->isSuccess()) {
1746 $data = json_decode($curlResult->getBody(), true);
1751 if (count($data) == 1) {
1752 $serverdata['directory-type'] = self::DT_MASTODON;
1759 * Detects Peertube via their known endpoint
1761 * @param string $url URL of the given server
1762 * @param array $serverdata array with server data
1764 * @return array server data
1766 private static function detectPeertube(string $url, array $serverdata): array
1768 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1769 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1773 $data = json_decode($curlResult->getBody(), true);
1778 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1779 $serverdata['platform'] = 'peertube';
1780 $serverdata['version'] = $data['serverVersion'];
1781 $serverdata['network'] = Protocol::ACTIVITYPUB;
1783 if (!empty($data['instance']['name'])) {
1784 $serverdata['site_name'] = $data['instance']['name'];
1787 if (!empty($data['instance']['shortDescription'])) {
1788 $serverdata['info'] = $data['instance']['shortDescription'];
1791 if (!empty($data['signup'])) {
1792 if (!empty($data['signup']['allowed'])) {
1793 $serverdata['register_policy'] = Register::OPEN;
1797 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1798 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1806 * Detects the version number of a given server when it was a NextCloud installation
1808 * @param string $url URL of the given server
1809 * @param array $serverdata array with server data
1810 * @param bool $validHostMeta
1812 * @return array server data
1814 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
1816 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1817 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1821 $data = json_decode($curlResult->getBody(), true);
1826 if (!empty($data['version'])) {
1827 $serverdata['platform'] = 'nextcloud';
1828 $serverdata['version'] = $data['version'];
1830 if ($validHostMeta) {
1831 $serverdata['network'] = Protocol::ACTIVITYPUB;
1834 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1835 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1843 * Fetches weekly usage data
1845 * @param string $url URL of the given server
1846 * @param array $serverdata array with server data
1848 * @return array server data
1850 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1852 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1853 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1857 $data = json_decode($curlResult->getBody(), true);
1863 foreach ($data as $week) {
1864 // Use only data from a full week
1865 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1869 // Most likely the data is sorted correctly. But we better are safe than sorry
1870 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1871 $current_week = $week;
1875 if (!empty($current_week['logins'])) {
1876 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1883 * Detects data from a given server url if it was a mastodon alike system
1885 * @param string $url URL of the given server
1886 * @param array $serverdata array with server data
1888 * @return array server data
1890 private static function detectMastodonAlikes(string $url, array $serverdata): array
1892 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1893 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1897 $data = json_decode($curlResult->getBody(), true);
1904 if (!empty($data['version'])) {
1905 $serverdata['platform'] = 'mastodon';
1906 $serverdata['version'] = $data['version'] ?? '';
1907 $serverdata['network'] = Protocol::ACTIVITYPUB;
1911 if (!empty($data['title'])) {
1912 $serverdata['site_name'] = $data['title'];
1915 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1916 $serverdata['platform'] = 'mastodon';
1917 $serverdata['network'] = Protocol::ACTIVITYPUB;
1921 if (!empty($data['description'])) {
1922 $serverdata['info'] = trim($data['description']);
1925 if (!empty($data['stats']['user_count'])) {
1926 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1929 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1930 $serverdata['platform'] = strtolower($matches[1]);
1931 $serverdata['version'] = $matches[2];
1935 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1936 $serverdata['platform'] = 'pleroma';
1937 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1941 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1942 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1943 $serverdata['platform'] = 'pleroma';
1947 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1948 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1955 * Detects data from typical Hubzilla endpoints
1957 * @param string $url URL of the given server
1958 * @param array $serverdata array with server data
1960 * @return array server data
1962 private static function detectHubzilla(string $url, array $serverdata): array
1964 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1965 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1969 $data = json_decode($curlResult->getBody(), true);
1970 if (empty($data) || empty($data['site'])) {
1974 if (!empty($data['site']['name'])) {
1975 $serverdata['site_name'] = $data['site']['name'];
1978 if (!empty($data['site']['platform'])) {
1979 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1980 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1981 $serverdata['network'] = Protocol::ZOT;
1984 if (!empty($data['site']['hubzilla'])) {
1985 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1986 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1987 $serverdata['network'] = Protocol::ZOT;
1990 if (!empty($data['site']['redmatrix'])) {
1991 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1992 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1993 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1994 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1997 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1998 $serverdata['network'] = Protocol::ZOT;
2002 $inviteonly = false;
2005 if (!empty($data['site']['closed'])) {
2006 $closed = self::toBoolean($data['site']['closed']);
2009 if (!empty($data['site']['private'])) {
2010 $private = self::toBoolean($data['site']['private']);
2013 if (!empty($data['site']['inviteonly'])) {
2014 $inviteonly = self::toBoolean($data['site']['inviteonly']);
2017 if (!$closed && !$private and $inviteonly) {
2018 $serverdata['register_policy'] = Register::APPROVE;
2019 } elseif (!$closed && !$private) {
2020 $serverdata['register_policy'] = Register::OPEN;
2022 $serverdata['register_policy'] = Register::CLOSED;
2025 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2026 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
2033 * Converts input value to a boolean value
2035 * @param string|integer $val
2039 private static function toBoolean($val): bool
2041 if (($val == 'true') || ($val == 1)) {
2043 } elseif (($val == 'false') || ($val == 0)) {
2051 * Detect if the URL belongs to a GNU Social server
2053 * @param string $url URL of the given server
2054 * @param array $serverdata array with server data
2056 * @return array server data
2058 private static function detectGNUSocial(string $url, array $serverdata): array
2060 // Test for GNU Social
2061 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
2062 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2063 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2064 $serverdata['platform'] = 'gnusocial';
2065 // Remove junk that some GNU Social servers return
2066 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
2067 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2068 $serverdata['version'] = trim($serverdata['version'], '"');
2069 $serverdata['network'] = Protocol::OSTATUS;
2071 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2072 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
2078 // Test for Statusnet
2079 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
2080 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
2081 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2083 // Remove junk that some GNU Social servers return
2084 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
2085 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2086 $serverdata['version'] = trim($serverdata['version'], '"');
2088 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
2089 $serverdata['platform'] = 'pleroma';
2090 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
2091 $serverdata['network'] = Protocol::ACTIVITYPUB;
2093 $serverdata['platform'] = 'statusnet';
2094 $serverdata['network'] = Protocol::OSTATUS;
2097 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2098 $serverdata['detection-method'] = self::DETECT_STATUSNET;
2106 * Detect if the URL belongs to a Friendica server
2108 * @param string $url URL of the given server
2109 * @param array $serverdata array with server data
2111 * @return array server data
2113 private static function detectFriendica(string $url, array $serverdata): array
2115 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
2116 // Because of this me must not use ACCEPT_JSON here.
2117 $curlResult = DI::httpClient()->get($url . '/friendica/json');
2118 if (!$curlResult->isSuccess()) {
2119 $curlResult = DI::httpClient()->get($url . '/friendika/json');
2121 $platform = 'Friendika';
2124 $platform = 'Friendica';
2127 if (!$curlResult->isSuccess()) {
2131 $data = json_decode($curlResult->getBody(), true);
2132 if (empty($data) || empty($data['version'])) {
2136 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
2137 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
2140 $serverdata['network'] = Protocol::DFRN;
2141 $serverdata['version'] = $data['version'];
2143 if (!empty($data['no_scrape_url'])) {
2144 $serverdata['noscrape'] = $data['no_scrape_url'];
2147 if (!empty($data['site_name'])) {
2148 $serverdata['site_name'] = $data['site_name'];
2151 if (!empty($data['info'])) {
2152 $serverdata['info'] = trim($data['info']);
2155 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2156 switch ($register_policy) {
2157 case 'REGISTER_OPEN':
2158 $serverdata['register_policy'] = Register::OPEN;
2161 case 'REGISTER_APPROVE':
2162 $serverdata['register_policy'] = Register::APPROVE;
2165 case 'REGISTER_CLOSED':
2166 case 'REGISTER_INVITATION':
2167 $serverdata['register_policy'] = Register::CLOSED;
2170 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
2171 $serverdata['register_policy'] = Register::CLOSED;
2175 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2181 * Analyses the landing page of a given server for hints about type and system of that server
2183 * @param object $curlResult result of curl execution
2184 * @param array $serverdata array with server data
2186 * @return array server data
2188 private static function analyseRootBody($curlResult, array $serverdata): array
2190 if (empty($curlResult->getBody())) {
2194 if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
2195 require __DIR__ . '/../../static/platforms.config.php';
2197 throw new HTTPException\InternalServerErrorException('Invalid platform file');
2200 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2202 $doc = new DOMDocument();
2203 @$doc->loadHTML($curlResult->getBody());
2204 $xpath = new DOMXPath($doc);
2207 // We can only detect honk via some HTML element on their page
2208 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
2209 $serverdata['platform'] = 'honk';
2210 $serverdata['network'] = Protocol::ACTIVITYPUB;
2214 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
2215 if (!empty($title)) {
2216 $serverdata['site_name'] = $title;
2219 $list = $xpath->query('//meta[@name]');
2221 foreach ($list as $node) {
2223 if ($node->attributes->length) {
2224 foreach ($node->attributes as $attribute) {
2225 $value = trim($attribute->value);
2226 if (empty($value)) {
2230 $attr[$attribute->name] = $value;
2233 if (empty($attr['name']) || empty($attr['content'])) {
2238 if ($attr['name'] == 'description') {
2239 $serverdata['info'] = $attr['content'];
2242 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2243 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2244 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
2245 $platform = str_replace('/', ' ', $platform);
2246 $platform_parts = explode(' ', $platform);
2247 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
2248 $platform = $platform_parts[0];
2249 $serverdata['version'] = $platform_parts[1];
2251 if (in_array($platform, array_values($dfrn_platforms))) {
2252 $serverdata['network'] = Protocol::DFRN;
2253 } elseif (in_array($platform, array_values($ap_platforms))) {
2254 $serverdata['network'] = Protocol::ACTIVITYPUB;
2255 } elseif (in_array($platform, array_values($zap_platforms))) {
2256 $serverdata['network'] = Protocol::ZOT;
2258 if (in_array($platform, array_values($platforms))) {
2259 $serverdata['platform'] = $platform;
2265 $list = $xpath->query('//meta[@property]');
2267 foreach ($list as $node) {
2269 if ($node->attributes->length) {
2270 foreach ($node->attributes as $attribute) {
2271 $value = trim($attribute->value);
2272 if (empty($value)) {
2276 $attr[$attribute->name] = $value;
2279 if (empty($attr['property']) || empty($attr['content'])) {
2284 if ($attr['property'] == 'og:site_name') {
2285 $serverdata['site_name'] = $attr['content'];
2288 if ($attr['property'] == 'og:description') {
2289 $serverdata['info'] = $attr['content'];
2292 if (in_array($attr['property'], ['og:platform', 'generator'])) {
2293 if (in_array($attr['content'], array_keys($platforms))) {
2294 $serverdata['platform'] = $platforms[$attr['content']];
2298 if (in_array($attr['content'], array_keys($ap_platforms))) {
2299 $serverdata['network'] = Protocol::ACTIVITYPUB;
2300 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
2301 $serverdata['network'] = Protocol::ZOT;
2306 $list = $xpath->query('//link[@rel="me"]');
2307 foreach ($list as $node) {
2308 foreach ($node->attributes as $attribute) {
2309 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
2310 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2311 $serverdata['platform'] = 'microblog';
2312 $serverdata['network'] = Protocol::ACTIVITYPUB;
2318 if ($serverdata['platform'] != 'microblog') {
2319 $list = $xpath->query('//link[@rel="micropub"]');
2320 foreach ($list as $node) {
2321 foreach ($node->attributes as $attribute) {
2322 if (trim($attribute->value) == 'https://micro.blog/micropub') {
2323 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
2324 $serverdata['platform'] = 'microblog';
2325 $serverdata['network'] = Protocol::ACTIVITYPUB;
2332 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
2333 $serverdata['detection-method'] = self::DETECT_BODY;
2340 * Analyses the header data of a given server for hints about type and system of that server
2342 * @param object $curlResult result of curl execution
2343 * @param array $serverdata array with server data
2345 * @return array server data
2347 private static function analyseRootHeader($curlResult, array $serverdata): array
2349 if ($curlResult->getHeader('server') == 'Mastodon') {
2350 $serverdata['platform'] = 'mastodon';
2351 $serverdata['network'] = Protocol::ACTIVITYPUB;
2352 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2353 $serverdata['platform'] = 'diaspora';
2354 $serverdata['network'] = Protocol::DIASPORA;
2355 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2356 } elseif ($curlResult->inHeader('x-friendica-version')) {
2357 $serverdata['platform'] = 'friendica';
2358 $serverdata['network'] = Protocol::DFRN;
2359 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2364 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2365 $serverdata['detection-method'] = self::DETECT_HEADER;
2372 * Update GServer entries
2374 public static function discover()
2376 // Update the server list
2377 self::discoverFederation();
2381 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2383 if ($requery_days == 0) {
2387 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2389 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2390 ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2391 ['order' => ['RAND()']]);
2393 while ($gserver = DBA::fetch($gservers)) {
2394 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2395 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2397 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2398 Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2400 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2401 self::update($fields, ['nurl' => $gserver['nurl']]);
2403 if (--$no_of_queries == 0) {
2408 DBA::close($gservers);
2412 * Discover federated servers
2414 private static function discoverFederation()
2416 $last = DI::keyValue()->get('poco_last_federation_discovery');
2419 $next = $last + (24 * 60 * 60);
2421 if ($next > time()) {
2426 // Discover federated servers
2427 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2428 foreach ($protocols as $protocol) {
2429 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2430 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2431 if (!empty($curlResult)) {
2432 $data = json_decode($curlResult, true);
2433 if (!empty($data['data']['nodes'])) {
2434 foreach ($data['data']['nodes'] as $server) {
2435 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2436 self::add('https://' . $server['host'], true);
2442 // Discover Mastodon servers
2443 $accesstoken = DI::config()->get('system', 'instances_social_key');
2445 if (!empty($accesstoken)) {
2446 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2447 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2448 if ($curlResult->isSuccess()) {
2449 $servers = json_decode($curlResult->getBody(), true);
2451 if (!empty($servers['instances'])) {
2452 foreach ($servers['instances'] as $server) {
2453 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2460 DI::keyValue()->set('poco_last_federation_discovery', time());
2464 * Set the protocol for the given server
2466 * @param int $gsid Server id
2467 * @param int $protocol Protocol id
2471 public static function setProtocol(int $gsid, int $protocol)
2477 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2478 if (!DBA::isResult($gserver)) {
2482 $old = $gserver['protocol'];
2484 if (!is_null($old)) {
2486 The priority for the protocols is:
2488 2. DFRN via Diaspora
2494 // We don't need to change it when nothing is to be changed
2495 if ($old == $protocol) {
2499 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2500 if ($protocol == Post\DeliveryData::OSTATUS) {
2504 // If the server is marked as ActivityPub then we won't change it to anything different
2505 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2509 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2510 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2514 // Don't change it to Diaspora when it is a legacy DFRN server
2515 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2520 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]);
2521 self::update(['protocol' => $protocol], ['id' => $gsid]);
2525 * Fetch the protocol of the given server
2527 * @param int $gsid Server id
2529 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2533 public static function getProtocol(int $gsid): ?int
2539 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2540 if (DBA::isResult($gserver)) {
2541 return $gserver['protocol'];
2548 * Update rows in the gserver table.
2549 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2551 * @param array $fields
2552 * @param array $condition
2558 public static function update(array $fields, array $condition): bool
2560 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2562 return DBA::update('gserver', $fields, $condition);
2566 * Insert a row into the gserver table.
2567 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2569 * @param array $fields
2570 * @param int $duplicate_mode What to do on a duplicated entry
2576 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
2578 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2580 return DBA::insert('gserver', $fields, $duplicate_mode);