3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
33 use Friendica\Database\DBStructure;
35 use Friendica\Module\Register;
36 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
37 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
38 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
39 use Friendica\Network\Probe;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Relay;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\Network;
45 use Friendica\Util\Strings;
46 use Friendica\Util\XML;
47 use GuzzleHttp\Exception\TransferException;
48 use Friendica\Network\HTTPException;
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 const DETECT_FRIENDIKA = 10;
75 const DETECT_FRIENDICA = 11;
76 const DETECT_STATUSNET = 12;
77 const DETECT_GNUSOCIAL = 13;
78 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
79 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
80 const DETECT_MASTODON_API = 16;
81 const DETECT_STATUS_PHP = 17; // Nextcloud
82 const DETECT_V1_CONFIG = 18;
83 const DETECT_PUMPIO = 19; // Deprecated
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 existance of a server and adds it in the background if not existant
96 * @param boolean $only_nodeinfo
99 public static function add(string $url, bool $only_nodeinfo = false)
101 if (self::getID($url, false)) {
105 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
109 * Get the ID for the given server URL
112 * @param boolean $no_check Don't check if the server hadn't been found
113 * @return int gserver id
115 public static function getID(string $url, bool $no_check = false)
121 $url = self::cleanURL($url);
123 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
124 if (DBA::isResult($gserver)) {
125 Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
126 return $gserver['id'];
129 if ($no_check || !self::check($url)) {
133 return self::getID($url, true);
137 * Retrieves all the servers which base domain are matching the provided domain pattern
139 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
141 * @param string $pattern
145 public static function listByDomainPattern(string $pattern): array
147 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
149 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
150 // eventual server path and keep only the server domain which we're matching against the pattern.
151 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
153 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
154 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
155 AND NOT `gserver`.`failed`
156 GROUP BY `gserver`.`id`";
158 $stmt = DI::dba()->p($sql, $likePattern);
160 return DI::dba()->toArray($stmt);
164 * Checks if the given server is reachable
166 * @param string $profile URL of the given profile
167 * @param string $server URL of the given server (If empty, taken from profile)
168 * @param string $network Network value that is used, when detection failed
169 * @param boolean $force Force an update.
171 * @return boolean 'true' if server seems vital
173 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
176 $contact = Contact::getByURL($profile, null, ['baseurl']);
177 if (!empty($contact['baseurl'])) {
178 $server = $contact['baseurl'];
186 return self::check($server, $network, $force);
189 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false)
191 // On successful contact process check again next week when it is a detected system.
192 // When we haven't detected the system, it could be a static website or a really old system.
194 return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
197 $now = strtotime(DateTimeFormat::utcNow());
199 if ($created > $last_contact) {
200 $contact_time = strtotime($created);
202 $contact_time = strtotime($last_contact);
205 // If the last contact was less than 6 hours before then try again in 6 hours
206 if (($now - $contact_time) < (60 * 60 * 6)) {
207 return DateTimeFormat::utc('now +6 hour');
210 // If the last contact was less than 12 hours before then try again in 12 hours
211 if (($now - $contact_time) < (60 * 60 * 12)) {
212 return DateTimeFormat::utc('now +12 hour');
215 // If the last contact was less than 24 hours before then try tomorrow again
216 if (($now - $contact_time) < (60 * 60 * 24)) {
217 return DateTimeFormat::utc('now +1 day');
220 // If the last contact was less than a week before then try again in a week
221 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
222 return DateTimeFormat::utc('now +1 week');
225 // If the last contact was less than two weeks before then try again in two week
226 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
227 return DateTimeFormat::utc('now +2 week');
230 // If the last contact was less than a month before then try again in a month
231 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
232 return DateTimeFormat::utc('now +1 month');
235 // The system hadn't been successul contacted for more than a month, so try again in three months
236 return DateTimeFormat::utc('now +3 month');
240 * Checks the state of the given server.
242 * @param string $server_url URL of the given server
243 * @param string $network Network value that is used, when detection failed
244 * @param boolean $force Force an update.
245 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
247 * @return boolean 'true' if server seems vital
249 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
251 $server_url = self::cleanURL($server_url);
252 if ($server_url == '') {
256 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
257 if (DBA::isResult($gserver)) {
258 if ($gserver['created'] <= DBA::NULL_DATETIME) {
259 $fields = ['created' => DateTimeFormat::utcNow()];
260 $condition = ['nurl' => Strings::normaliseLink($server_url)];
261 DBA::update('gserver', $fields, $condition);
264 if (!$force && (strtotime($gserver['next_contact']) > time())) {
265 Logger::info('No update needed', ['server' => $server_url]);
266 return (!$gserver['failed']);
268 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
270 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
273 return self::detect($server_url, $network, $only_nodeinfo);
277 * Set failed server status
281 public static function setFailure(string $url)
283 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
284 if (DBA::isResult($gserver)) {
285 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
286 DBA::update('gserver', ['url' => $url, 'failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
287 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
288 ['nurl' => Strings::normaliseLink($url)]);
289 Logger::info('Set failed status for existing server', ['url' => $url]);
292 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
293 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
294 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
295 Logger::info('Set failed status for new server', ['url' => $url]);
299 * Remove unwanted content from the given URL
302 * @return string cleaned URL
304 public static function cleanURL(string $url)
306 $url = trim($url, '/');
307 $url = str_replace('/index.php', '', $url);
309 $urlparts = parse_url($url);
310 unset($urlparts['user']);
311 unset($urlparts['pass']);
312 unset($urlparts['query']);
313 unset($urlparts['fragment']);
314 return Network::unparseURL($urlparts);
318 * Detect server data (type, protocol, version number, ...)
319 * The detected data is then updated or inserted in the gserver table.
321 * @param string $url URL of the given server
322 * @param string $network Network value that is used, when detection failed
323 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
325 * @return boolean 'true' if server could be detected
327 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
329 Logger::info('Detect server type', ['server' => $url]);
331 $original_url = $url;
333 // Remove URL content that is not supposed to exist for a server url
334 $url = rtrim(self::cleanURL($url), '/');
336 Logger::notice('Empty URL.');
340 if (!Network::isUrlValid($url)) {
341 self::setFailure($url);
345 // If the URL missmatches, then we mark the old entry as failure
346 if (Strings::normaliseLink($url) != Strings::normaliseLink($original_url)) {
347 self::setFailure($original_url);
348 self::detect($url, $network, $only_nodeinfo);
352 // On a redirect follow the new host but mark the old one as failure
354 $finalurl = rtrim(DI::httpClient()->finalUrl($url), '/');
355 } catch (TransferException $exception) {
356 Logger::notice('Error fetching final URL.', ['url' => $url, 'exception' => $exception]);
357 self::setFailure($url);
361 if (empty($finalurl)) {
362 Logger::notice('Empty redirected URL.', ['url' => $url]);
366 // We only follow redirects when the path stays the same or the target url has no path.
367 // Some systems have got redirects on their landing page to a single account page. This check handles it.
368 if (((parse_url($url, PHP_URL_HOST) != parse_url($finalurl, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) == parse_url($finalurl, PHP_URL_PATH))) ||
369 (((parse_url($url, PHP_URL_HOST) != parse_url($finalurl, PHP_URL_HOST)) || (parse_url($url, PHP_URL_PATH) != parse_url($finalurl, PHP_URL_PATH))) && empty(parse_url($finalurl, PHP_URL_PATH)))) {
370 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $finalurl]);
371 self::setFailure($url);
372 self::detect($finalurl, $network, $only_nodeinfo);
376 if ((parse_url($url, PHP_URL_HOST) == parse_url($finalurl, PHP_URL_HOST)) &&
377 (parse_url($url, PHP_URL_PATH) == parse_url($finalurl, PHP_URL_PATH)) &&
378 (parse_url($url, PHP_URL_SCHEME) != parse_url($finalurl, PHP_URL_SCHEME))) {
379 if (!Network::isUrlValid($finalurl)) {
380 self::setFailure($finalurl);
386 $in_webroot = empty(parse_url($url, PHP_URL_PATH));
388 // When a nodeinfo is present, we don't need to dig further
389 $curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
390 if ($curlResult->isTimeout()) {
391 self::setFailure($url);
395 $serverdata = self::parseNodeinfo210($curlResult);
396 if (empty($serverdata)) {
397 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
398 $serverdata = self::fetchNodeinfo($url, $curlResult);
401 if ($only_nodeinfo && empty($serverdata)) {
402 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
403 self::setFailure($url);
405 } elseif (empty($serverdata)) {
406 $serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
409 // When there is no Nodeinfo, then use some protocol specific endpoints
410 if ($serverdata['network'] == Protocol::PHANTOM) {
412 // Fetch the landing page, possibly it reveals some data
413 $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
414 $curlResult = DI::httpClient()->get($url, $accept);
415 if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
416 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
417 $html_fetched = true;
419 $html_fetched = false;
422 if ($curlResult->isSuccess()) {
423 $json = json_decode($curlResult->getBody(), true);
424 if (!empty($json) && is_array($json)) {
425 $data = self::fetchDataFromSystemActor($json, $serverdata);
426 $serverdata = $data['server'];
427 $systemactor = $data['actor'];
428 if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
429 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
431 } elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
432 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
435 if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
436 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
437 $serverdata = self::analyseRootBody($curlResult, $serverdata);
441 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
442 self::setFailure($url);
446 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
447 $serverdata = self::detectMastodonAlikes($url, $serverdata);
451 // All following checks are done for systems that always have got a "host-meta" endpoint.
452 // With this check we don't have to waste time and ressources for dead systems.
453 // Also this hopefully prevents us from receiving abuse messages.
454 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
455 $validHostMeta = self::validHostMeta($url);
457 $validHostMeta = false;
460 if ($validHostMeta) {
461 if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
462 $serverdata['detection-method'] = self::DETECT_HOST_META;
465 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
466 $serverdata = self::detectFriendica($url, $serverdata);
469 // The following systems have to be installed in the root directory.
471 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
472 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
473 $serverdata = self::fetchSiteinfo($url, $serverdata);
476 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
477 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
478 $serverdata = self::detectHubzilla($url, $serverdata);
481 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
482 $serverdata = self::detectPeertube($url, $serverdata);
485 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
486 $serverdata = self::detectGNUSocial($url, $serverdata);
489 } elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
490 $serverdata = self::detectFriendica($url, $serverdata);
493 if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
494 $serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
497 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
498 // Since this endpoint is only rarely used, we query it at a later time
499 if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
500 $serverdata = self::fetchStatistics($url, $serverdata);
504 // When we hadn't been able to detect the network type, we use the hint from the parameter
505 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
506 $serverdata['network'] = $network;
509 // Most servers aren't installed in a subdirectory, so we declare this entry as failed
510 if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
511 self::setFailure($url);
515 $serverdata['url'] = $url;
516 $serverdata['nurl'] = Strings::normaliseLink($url);
518 // We have to prevent an endless loop here.
519 // When a server is new, then there is no gserver entry yet.
520 // But in "detectNetworkViaContacts" it could happen that a contact is updated,
521 // and this can call this function here as well.
522 if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
523 in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
524 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
527 // Detect the directory type
528 $serverdata['directory-type'] = self::DT_NONE;
530 if (in_array($serverdata['network'], Protocol::FEDERATED)) {
531 $serverdata = self::checkMastodonDirectory($url, $serverdata);
533 if ($serverdata['directory-type'] == self::DT_NONE) {
534 $serverdata = self::checkPoCo($url, $serverdata);
538 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
539 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
542 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
544 // On an active server there has to be at least a single user
545 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
546 $serverdata['registered-users'] = 1;
547 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
548 $serverdata['registered-users'] = 0;
551 $serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
553 $serverdata['last_contact'] = DateTimeFormat::utcNow();
554 $serverdata['failed'] = false;
556 // Limit the length on incoming fields
557 $serverdata = DBStructure::getFieldsForTable('gserver', $serverdata);
559 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
560 if (!DBA::isResult($gserver)) {
561 $serverdata['created'] = DateTimeFormat::utcNow();
562 $ret = DBA::insert('gserver', $serverdata);
563 $id = DBA::lastInsertId();
565 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
566 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
567 if (DBA::isResult($gserver)) {
568 $id = $gserver['id'];
572 // Count the number of known contacts from this server
573 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
574 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
575 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
576 $max_users = max($apcontacts, $contacts);
577 if ($max_users > $serverdata['registered-users']) {
578 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
579 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
582 if (empty($serverdata['active-month-users'])) {
583 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
585 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
586 DBA::update('gserver', ['active-month-users' => $contacts], ['id' => $id]);
590 if (empty($serverdata['active-halfyear-users'])) {
591 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
593 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
594 DBA::update('gserver', ['active-halfyear-users' => $contacts], ['id' => $id]);
599 if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
600 self::discoverRelay($url);
603 if (!empty($systemactor)) {
604 $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
605 Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
612 * Fetch relay data from a given server url
614 * @param string $server_url address of the server
615 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
617 private static function discoverRelay(string $server_url)
619 Logger::info('Discover relay data', ['server' => $server_url]);
621 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
622 if (!$curlResult->isSuccess()) {
626 $data = json_decode($curlResult->getBody(), true);
627 if (!is_array($data)) {
631 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
632 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
634 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
636 $data['subscribe'] = false;
640 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
641 if (!DBA::isResult($gserver)) {
645 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
646 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
647 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
650 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
652 if ($data['scope'] == 'tags') {
655 foreach ($data['tags'] as $tag) {
656 $tag = mb_strtolower($tag);
657 if (strlen($tag) < 100) {
662 foreach ($tags as $tag) {
663 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
667 // Create or update the relay contact
669 if (isset($data['protocols'])) {
670 if (isset($data['protocols']['diaspora'])) {
671 $fields['network'] = Protocol::DIASPORA;
673 if (isset($data['protocols']['diaspora']['receive'])) {
674 $fields['batch'] = $data['protocols']['diaspora']['receive'];
675 } elseif (is_string($data['protocols']['diaspora'])) {
676 $fields['batch'] = $data['protocols']['diaspora'];
680 if (isset($data['protocols']['dfrn'])) {
681 $fields['network'] = Protocol::DFRN;
683 if (isset($data['protocols']['dfrn']['receive'])) {
684 $fields['batch'] = $data['protocols']['dfrn']['receive'];
685 } elseif (is_string($data['protocols']['dfrn'])) {
686 $fields['batch'] = $data['protocols']['dfrn'];
690 if (isset($data['protocols']['activitypub'])) {
691 $fields['network'] = Protocol::ACTIVITYPUB;
693 if (!empty($data['protocols']['activitypub']['actor'])) {
694 $fields['url'] = $data['protocols']['activitypub']['actor'];
696 if (!empty($data['protocols']['activitypub']['receive'])) {
697 $fields['batch'] = $data['protocols']['activitypub']['receive'];
702 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
704 Relay::updateContact($gserver, $fields);
708 * Fetch server data from '/statistics.json' on the given server
710 * @param string $url URL of the given server
712 * @return array server data
714 private static function fetchStatistics(string $url, array $serverdata)
716 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
717 if (!$curlResult->isSuccess()) {
721 $data = json_decode($curlResult->getBody(), true);
726 // Some AP enabled systems return activity data that we don't expect here.
727 if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
732 $old_serverdata = $serverdata;
734 $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
736 if (!empty($data['version'])) {
738 $serverdata['version'] = $data['version'];
739 // Version numbers on statistics.json are presented with additional info, e.g.:
740 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
741 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
744 if (!empty($data['name'])) {
746 $serverdata['site_name'] = $data['name'];
749 if (!empty($data['network'])) {
751 $serverdata['platform'] = strtolower($data['network']);
753 if ($serverdata['platform'] == 'diaspora') {
754 $serverdata['network'] = Protocol::DIASPORA;
755 } elseif ($serverdata['platform'] == 'friendica') {
756 $serverdata['network'] = Protocol::DFRN;
757 } elseif ($serverdata['platform'] == 'hubzilla') {
758 $serverdata['network'] = Protocol::ZOT;
759 } elseif ($serverdata['platform'] == 'redmatrix') {
760 $serverdata['network'] = Protocol::ZOT;
764 if (!empty($data['total_users'])) {
766 $serverdata['registered-users'] = max($data['total_users'], 1);
769 if (!empty($data['active_users_monthly'])) {
771 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
774 if (!empty($data['active_users_halfyear'])) {
776 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
779 if (!empty($data['local_posts'])) {
781 $serverdata['local-posts'] = max($data['local_posts'], 0);
784 if (!empty($data['registrations_open'])) {
785 $serverdata['register_policy'] = Register::OPEN;
787 $serverdata['register_policy'] = Register::CLOSED;
791 return $old_serverdata;
798 * Detect server type by using the nodeinfo data
800 * @param string $url address of the server
801 * @param ICanHandleHttpResponses $httpResult
803 * @return array Server data
804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
808 if (!$httpResult->isSuccess()) {
812 $nodeinfo = json_decode($httpResult->getBody(), true);
814 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
821 foreach ($nodeinfo['links'] as $link) {
822 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
823 Logger::info('Invalid nodeinfo format', ['url' => $url]);
826 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
827 $nodeinfo1_url = $link['href'];
828 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
829 $nodeinfo2_url = $link['href'];
833 if ($nodeinfo1_url . $nodeinfo2_url == '') {
839 if (!empty($nodeinfo2_url)) {
840 $server = self::parseNodeinfo2($nodeinfo2_url);
843 if (empty($server) && !empty($nodeinfo1_url)) {
844 $server = self::parseNodeinfo1($nodeinfo1_url);
853 * @param string $nodeinfo_url address of the nodeinfo path
854 * @return array Server data
855 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
857 private static function parseNodeinfo1(string $nodeinfo_url)
859 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
860 if (!$curlResult->isSuccess()) {
864 $nodeinfo = json_decode($curlResult->getBody(), true);
866 if (!is_array($nodeinfo)) {
870 $server = ['detection-method' => self::DETECT_NODEINFO_1,
871 'register_policy' => Register::CLOSED];
873 if (!empty($nodeinfo['openRegistrations'])) {
874 $server['register_policy'] = Register::OPEN;
877 if (is_array($nodeinfo['software'])) {
878 if (!empty($nodeinfo['software']['name'])) {
879 $server['platform'] = strtolower($nodeinfo['software']['name']);
882 if (!empty($nodeinfo['software']['version'])) {
883 $server['version'] = $nodeinfo['software']['version'];
884 // Version numbers on Nodeinfo are presented with additional info, e.g.:
885 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
886 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
890 if (!empty($nodeinfo['metadata']['nodeName'])) {
891 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
894 if (!empty($nodeinfo['usage']['users']['total'])) {
895 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
898 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
899 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
902 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
903 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
906 if (!empty($nodeinfo['usage']['localPosts'])) {
907 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
910 if (!empty($nodeinfo['usage']['localComments'])) {
911 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
914 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
916 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
917 $protocols[$protocol] = true;
920 if (!empty($protocols['friendica'])) {
921 $server['network'] = Protocol::DFRN;
922 } elseif (!empty($protocols['activitypub'])) {
923 $server['network'] = Protocol::ACTIVITYPUB;
924 } elseif (!empty($protocols['diaspora'])) {
925 $server['network'] = Protocol::DIASPORA;
926 } elseif (!empty($protocols['ostatus'])) {
927 $server['network'] = Protocol::OSTATUS;
928 } elseif (!empty($protocols['gnusocial'])) {
929 $server['network'] = Protocol::OSTATUS;
930 } elseif (!empty($protocols['zot'])) {
931 $server['network'] = Protocol::ZOT;
935 if (empty($server)) {
939 if (empty($server['network'])) {
940 $server['network'] = Protocol::PHANTOM;
949 * @see https://git.feneas.org/jaywink/nodeinfo2
950 * @param string $nodeinfo_url address of the nodeinfo path
951 * @return array Server data
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 private static function parseNodeinfo2(string $nodeinfo_url)
956 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
957 if (!$curlResult->isSuccess()) {
961 $nodeinfo = json_decode($curlResult->getBody(), true);
962 if (!is_array($nodeinfo)) {
966 $server = ['detection-method' => self::DETECT_NODEINFO_2,
967 'register_policy' => Register::CLOSED];
969 if (!empty($nodeinfo['openRegistrations'])) {
970 $server['register_policy'] = Register::OPEN;
973 if (!empty($nodeinfo['software'])) {
974 if (isset($nodeinfo['software']['name'])) {
975 $server['platform'] = strtolower($nodeinfo['software']['name']);
978 if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
979 $server['version'] = $nodeinfo['software']['version'];
980 // Version numbers on Nodeinfo are presented with additional info, e.g.:
981 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
982 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
984 // qoto advertises itself as Mastodon
985 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
986 $server['platform'] = 'qoto';
991 if (!empty($nodeinfo['metadata']['nodeName'])) {
992 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
995 if (!empty($nodeinfo['usage']['users']['total'])) {
996 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
999 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1000 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1003 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1004 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1007 if (!empty($nodeinfo['usage']['localPosts'])) {
1008 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1011 if (!empty($nodeinfo['usage']['localComments'])) {
1012 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1015 if (!empty($nodeinfo['protocols'])) {
1017 foreach ($nodeinfo['protocols'] as $protocol) {
1018 if (is_string($protocol)) {
1019 $protocols[$protocol] = true;
1023 if (!empty($protocols['dfrn'])) {
1024 $server['network'] = Protocol::DFRN;
1025 } elseif (!empty($protocols['activitypub'])) {
1026 $server['network'] = Protocol::ACTIVITYPUB;
1027 } elseif (!empty($protocols['diaspora'])) {
1028 $server['network'] = Protocol::DIASPORA;
1029 } elseif (!empty($protocols['ostatus'])) {
1030 $server['network'] = Protocol::OSTATUS;
1031 } elseif (!empty($protocols['gnusocial'])) {
1032 $server['network'] = Protocol::OSTATUS;
1033 } elseif (!empty($protocols['zot'])) {
1034 $server['network'] = Protocol::ZOT;
1038 if (empty($server)) {
1042 if (empty($server['network'])) {
1043 $server['network'] = Protocol::PHANTOM;
1050 * Parses NodeInfo2 protocol 1.0
1052 * @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
1053 * @param string $nodeinfo_url address of the nodeinfo path
1054 * @return array Server data
1055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1057 private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult)
1059 if (!$httpResult->isSuccess()) {
1063 $nodeinfo = json_decode($httpResult->getBody(), true);
1065 if (!is_array($nodeinfo)) {
1069 $server = ['detection-method' => self::DETECT_NODEINFO_210,
1070 'register_policy' => Register::CLOSED];
1072 if (!empty($nodeinfo['openRegistrations'])) {
1073 $server['register_policy'] = Register::OPEN;
1076 if (!empty($nodeinfo['server'])) {
1077 if (!empty($nodeinfo['server']['software'])) {
1078 $server['platform'] = strtolower($nodeinfo['server']['software']);
1081 if (!empty($nodeinfo['server']['version'])) {
1082 $server['version'] = $nodeinfo['server']['version'];
1083 // Version numbers on Nodeinfo are presented with additional info, e.g.:
1084 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1085 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
1088 if (!empty($nodeinfo['server']['name'])) {
1089 $server['site_name'] = $nodeinfo['server']['name'];
1093 if (!empty($nodeinfo['usage']['users']['total'])) {
1094 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
1097 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
1098 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
1101 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
1102 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
1105 if (!empty($nodeinfo['usage']['localPosts'])) {
1106 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
1109 if (!empty($nodeinfo['usage']['localComments'])) {
1110 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
1113 if (!empty($nodeinfo['protocols'])) {
1115 foreach ($nodeinfo['protocols'] as $protocol) {
1116 if (is_string($protocol)) {
1117 $protocols[$protocol] = true;
1121 if (!empty($protocols['dfrn'])) {
1122 $server['network'] = Protocol::DFRN;
1123 } elseif (!empty($protocols['activitypub'])) {
1124 $server['network'] = Protocol::ACTIVITYPUB;
1125 } elseif (!empty($protocols['diaspora'])) {
1126 $server['network'] = Protocol::DIASPORA;
1127 } elseif (!empty($protocols['ostatus'])) {
1128 $server['network'] = Protocol::OSTATUS;
1129 } elseif (!empty($protocols['gnusocial'])) {
1130 $server['network'] = Protocol::OSTATUS;
1131 } elseif (!empty($protocols['zot'])) {
1132 $server['network'] = Protocol::ZOT;
1136 if (empty($server) || empty($server['platform'])) {
1140 if (empty($server['network'])) {
1141 $server['network'] = Protocol::PHANTOM;
1148 * Fetch server information from a 'siteinfo.json' file on the given server
1150 * @param string $url URL of the given server
1151 * @param array $serverdata array with server data
1153 * @return array server data
1155 private static function fetchSiteinfo(string $url, array $serverdata)
1157 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1158 if (!$curlResult->isSuccess()) {
1162 $data = json_decode($curlResult->getBody(), true);
1167 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1168 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1171 if (!empty($data['url'])) {
1172 $serverdata['platform'] = strtolower($data['platform']);
1173 $serverdata['version'] = $data['version'];
1176 if (!empty($data['plugins'])) {
1177 if (in_array('pubcrawl', $data['plugins'])) {
1178 $serverdata['network'] = Protocol::ACTIVITYPUB;
1179 } elseif (in_array('diaspora', $data['plugins'])) {
1180 $serverdata['network'] = Protocol::DIASPORA;
1181 } elseif (in_array('gnusoc', $data['plugins'])) {
1182 $serverdata['network'] = Protocol::OSTATUS;
1184 $serverdata['network'] = Protocol::ZOT;
1188 if (!empty($data['site_name'])) {
1189 $serverdata['site_name'] = $data['site_name'];
1192 if (!empty($data['channels_total'])) {
1193 $serverdata['registered-users'] = max($data['channels_total'], 1);
1196 if (!empty($data['channels_active_monthly'])) {
1197 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1200 if (!empty($data['channels_active_halfyear'])) {
1201 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1204 if (!empty($data['local_posts'])) {
1205 $serverdata['local-posts'] = max($data['local_posts'], 0);
1208 if (!empty($data['local_comments'])) {
1209 $serverdata['local-comments'] = max($data['local_comments'], 0);
1212 if (!empty($data['register_policy'])) {
1213 switch ($data['register_policy']) {
1214 case 'REGISTER_OPEN':
1215 $serverdata['register_policy'] = Register::OPEN;
1218 case 'REGISTER_APPROVE':
1219 $serverdata['register_policy'] = Register::APPROVE;
1222 case 'REGISTER_CLOSED':
1224 $serverdata['register_policy'] = Register::CLOSED;
1232 private static function fetchDataFromSystemActor(array $data, array $serverdata)
1235 return ['server' => $serverdata, 'actor' => ''];
1238 $actor = JsonLD::compact($data, false);
1239 if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
1240 $serverdata['network'] = Protocol::ACTIVITYPUB;
1241 $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
1242 $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
1243 if (!empty($actor['as:generator'])) {
1244 $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
1245 $serverdata['platform'] = strtolower(array_shift($generator));
1246 $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
1248 $serverdata['detection-method'] = self::DETECT_AP_ACTOR;
1250 return ['server' => $serverdata, 'actor' => $actor['@id']];
1251 } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
1252 // By now only Ktistec seems to provide collections this way
1253 $serverdata['platform'] = 'ktistec';
1254 $serverdata['network'] = Protocol::ACTIVITYPUB;
1255 $serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
1257 $actors = JsonLD::fetchElementArray($actor, 'as:items');
1258 if (!empty($actors) && !empty($actors[0]['@id'])) {
1259 $actor_url = $actor['@id'] . $actors[0]['@id'];
1264 return ['server' => $serverdata, 'actor' => $actor_url];
1266 return ['server' => $serverdata, 'actor' => ''];
1270 * Checks if the server contains a valid host meta file
1272 * @param string $url URL of the given server
1274 * @return boolean 'true' if the server seems to be vital
1276 private static function validHostMeta(string $url)
1278 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1279 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1280 if (!$curlResult->isSuccess()) {
1284 $xrd = XML::parseString($curlResult->getBody());
1285 if (!is_object($xrd)) {
1289 $elements = XML::elementToArray($xrd);
1290 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1295 foreach ($elements['xrd']['link'] as $link) {
1296 // When there is more than a single "link" element, the array looks slightly different
1297 if (!empty($link['@attributes'])) {
1298 $link = $link['@attributes'];
1301 if (empty($link['rel']) || empty($link['template'])) {
1305 if ($link['rel'] == 'lrdd') {
1306 // When the webfinger host is the same like the system host, it should be ok.
1307 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1315 * Detect the network of the given server via their known contacts
1317 * @param string $url URL of the given server
1318 * @param array $serverdata array with server data
1320 * @return array server data
1322 private static function detectNetworkViaContacts(string $url, array $serverdata)
1326 $nurl = Strings::normaliseLink($url);
1328 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
1329 while ($apcontact = DBA::fetch($apcontacts)) {
1330 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1332 DBA::close($apcontacts);
1334 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
1335 while ($pcontact = DBA::fetch($pcontacts)) {
1336 $contacts[$pcontact['nurl']] = $pcontact['url'];
1338 DBA::close($pcontacts);
1340 if (empty($contacts)) {
1345 foreach ($contacts as $contact) {
1346 // Endlosschleife verhindern wegen gsid!
1347 $data = Probe::uri($contact);
1348 if (in_array($data['network'], Protocol::FEDERATED)) {
1349 $serverdata['network'] = $data['network'];
1351 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1352 $serverdata['detection-method'] = self::DETECT_CONTACTS;
1355 } elseif ((time() - $time) > 10) {
1356 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1365 * Checks if the given server does have a '/poco' endpoint.
1366 * This is used for the 'PortableContact' functionality,
1367 * which is used by both Friendica and Hubzilla.
1369 * @param string $url URL of the given server
1370 * @param array $serverdata array with server data
1372 * @return array server data
1374 private static function checkPoCo(string $url, array $serverdata)
1376 $serverdata['poco'] = '';
1378 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1379 if (!$curlResult->isSuccess()) {
1383 $data = json_decode($curlResult->getBody(), true);
1388 if (!empty($data['totalResults'])) {
1389 $registeredUsers = $serverdata['registered-users'] ?? 0;
1390 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1391 $serverdata['directory-type'] = self::DT_POCO;
1392 $serverdata['poco'] = $url . '/poco';
1399 * Checks if the given server does have a Mastodon style directory endpoint.
1401 * @param string $url URL of the given server
1402 * @param array $serverdata array with server data
1404 * @return array server data
1406 public static function checkMastodonDirectory(string $url, array $serverdata)
1408 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1409 if (!$curlResult->isSuccess()) {
1413 $data = json_decode($curlResult->getBody(), true);
1418 if (count($data) == 1) {
1419 $serverdata['directory-type'] = self::DT_MASTODON;
1426 * Detects Peertube via their known endpoint
1428 * @param string $url URL of the given server
1429 * @param array $serverdata array with server data
1431 * @return array server data
1433 private static function detectPeertube(string $url, array $serverdata)
1435 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1436 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1440 $data = json_decode($curlResult->getBody(), true);
1445 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1446 $serverdata['platform'] = 'peertube';
1447 $serverdata['version'] = $data['serverVersion'];
1448 $serverdata['network'] = Protocol::ACTIVITYPUB;
1450 if (!empty($data['instance']['name'])) {
1451 $serverdata['site_name'] = $data['instance']['name'];
1454 if (!empty($data['instance']['shortDescription'])) {
1455 $serverdata['info'] = $data['instance']['shortDescription'];
1458 if (!empty($data['signup'])) {
1459 if (!empty($data['signup']['allowed'])) {
1460 $serverdata['register_policy'] = Register::OPEN;
1464 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1465 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1473 * Detects the version number of a given server when it was a NextCloud installation
1475 * @param string $url URL of the given server
1476 * @param array $serverdata array with server data
1477 * @param bool $validHostMeta
1479 * @return array server data
1481 private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta)
1483 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1484 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1488 $data = json_decode($curlResult->getBody(), true);
1493 if (!empty($data['version'])) {
1494 $serverdata['platform'] = 'nextcloud';
1495 $serverdata['version'] = $data['version'];
1497 if ($validHostMeta) {
1498 $serverdata['network'] = Protocol::ACTIVITYPUB;
1501 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1502 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1509 private static function fetchWeeklyUsage(string $url, array $serverdata) {
1510 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1511 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1515 $data = json_decode($curlResult->getBody(), true);
1521 foreach ($data as $week) {
1522 // Use only data from a full week
1523 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1527 // Most likely the data is sorted correctly. But we better are safe than sorry
1528 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1529 $current_week = $week;
1533 if (!empty($current_week['logins'])) {
1534 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1541 * Detects data from a given server url if it was a mastodon alike system
1543 * @param string $url URL of the given server
1544 * @param array $serverdata array with server data
1546 * @return array server data
1548 private static function detectMastodonAlikes(string $url, array $serverdata)
1550 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1551 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1555 $data = json_decode($curlResult->getBody(), true);
1562 if (!empty($data['version'])) {
1563 $serverdata['platform'] = 'mastodon';
1564 $serverdata['version'] = $data['version'] ?? '';
1565 $serverdata['network'] = Protocol::ACTIVITYPUB;
1569 if (!empty($data['title'])) {
1570 $serverdata['site_name'] = $data['title'];
1573 if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
1574 $serverdata['platform'] = 'mastodon';
1575 $serverdata['network'] = Protocol::ACTIVITYPUB;
1579 if (!empty($data['description'])) {
1580 $serverdata['info'] = trim($data['description']);
1583 if (!empty($data['stats']['user_count'])) {
1584 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1587 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1588 $serverdata['platform'] = strtolower($matches[1]);
1589 $serverdata['version'] = $matches[2];
1593 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1594 $serverdata['platform'] = 'pleroma';
1595 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1599 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1600 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1601 $serverdata['platform'] = 'pleroma';
1605 if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1606 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1613 * Detects data from typical Hubzilla endpoints
1615 * @param string $url URL of the given server
1616 * @param array $serverdata array with server data
1618 * @return array server data
1620 private static function detectHubzilla(string $url, array $serverdata)
1622 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1623 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1627 $data = json_decode($curlResult->getBody(), true);
1628 if (empty($data) || empty($data['site'])) {
1632 if (!empty($data['site']['name'])) {
1633 $serverdata['site_name'] = $data['site']['name'];
1636 if (!empty($data['site']['platform'])) {
1637 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1638 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1639 $serverdata['network'] = Protocol::ZOT;
1642 if (!empty($data['site']['hubzilla'])) {
1643 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1644 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1645 $serverdata['network'] = Protocol::ZOT;
1648 if (!empty($data['site']['redmatrix'])) {
1649 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1650 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1651 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1652 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1655 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1656 $serverdata['network'] = Protocol::ZOT;
1660 $inviteonly = false;
1663 if (!empty($data['site']['closed'])) {
1664 $closed = self::toBoolean($data['site']['closed']);
1667 if (!empty($data['site']['private'])) {
1668 $private = self::toBoolean($data['site']['private']);
1671 if (!empty($data['site']['inviteonly'])) {
1672 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1675 if (!$closed && !$private and $inviteonly) {
1676 $serverdata['register_policy'] = Register::APPROVE;
1677 } elseif (!$closed && !$private) {
1678 $serverdata['register_policy'] = Register::OPEN;
1680 $serverdata['register_policy'] = Register::CLOSED;
1683 if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1684 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1691 * Converts input value to a boolean value
1693 * @param string|integer $val
1697 private static function toBoolean($val)
1699 if (($val == 'true') || ($val == 1)) {
1701 } elseif (($val == 'false') || ($val == 0)) {
1709 * Detect if the URL belongs to a GNU Social server
1711 * @param string $url URL of the given server
1712 * @param array $serverdata array with server data
1714 * @return array server data
1716 private static function detectGNUSocial(string $url, array $serverdata)
1718 // Test for GNU Social
1719 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1720 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1721 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1722 $serverdata['platform'] = 'gnusocial';
1723 // Remove junk that some GNU Social servers return
1724 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1725 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1726 $serverdata['version'] = trim($serverdata['version'], '"');
1727 $serverdata['network'] = Protocol::OSTATUS;
1729 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1730 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1736 // Test for Statusnet
1737 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1738 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1739 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1741 // Remove junk that some GNU Social servers return
1742 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1743 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1744 $serverdata['version'] = trim($serverdata['version'], '"');
1746 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1747 $serverdata['platform'] = 'pleroma';
1748 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1749 $serverdata['network'] = Protocol::ACTIVITYPUB;
1751 $serverdata['platform'] = 'statusnet';
1752 $serverdata['network'] = Protocol::OSTATUS;
1755 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1756 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1764 * Detect if the URL belongs to a Friendica server
1766 * @param string $url URL of the given server
1767 * @param array $serverdata array with server data
1769 * @return array server data
1771 private static function detectFriendica(string $url, array $serverdata)
1773 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1774 // Because of this me must not use ACCEPT_JSON here.
1775 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1776 if (!$curlResult->isSuccess()) {
1777 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1779 $platform = 'Friendika';
1782 $platform = 'Friendica';
1785 if (!$curlResult->isSuccess()) {
1789 $data = json_decode($curlResult->getBody(), true);
1790 if (empty($data) || empty($data['version'])) {
1794 if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
1795 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1798 $serverdata['network'] = Protocol::DFRN;
1799 $serverdata['version'] = $data['version'];
1801 if (!empty($data['no_scrape_url'])) {
1802 $serverdata['noscrape'] = $data['no_scrape_url'];
1805 if (!empty($data['site_name'])) {
1806 $serverdata['site_name'] = $data['site_name'];
1809 if (!empty($data['info'])) {
1810 $serverdata['info'] = trim($data['info']);
1813 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1814 switch ($register_policy) {
1815 case 'REGISTER_OPEN':
1816 $serverdata['register_policy'] = Register::OPEN;
1819 case 'REGISTER_APPROVE':
1820 $serverdata['register_policy'] = Register::APPROVE;
1823 case 'REGISTER_CLOSED':
1824 case 'REGISTER_INVITATION':
1825 $serverdata['register_policy'] = Register::CLOSED;
1828 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1829 $serverdata['register_policy'] = Register::CLOSED;
1833 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1839 * Analyses the landing page of a given server for hints about type and system of that server
1841 * @param object $curlResult result of curl execution
1842 * @param array $serverdata array with server data
1844 * @return array server data
1846 private static function analyseRootBody($curlResult, array $serverdata)
1848 if (empty($curlResult->getBody())) {
1852 if (file_exists(__DIR__ . '/../../static/generator.config.php')) {
1853 require __DIR__ . '/../../static/generator.config.php';
1855 throw new HTTPException\InternalServerErrorException('Invalid generator file');
1858 $platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
1860 $doc = new DOMDocument();
1861 @$doc->loadHTML($curlResult->getBody());
1862 $xpath = new DOMXPath($doc);
1865 // We can only detect honk via some HTML element on their page
1866 if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
1867 $serverdata['platform'] = 'honk';
1868 $serverdata['network'] = Protocol::ACTIVITYPUB;
1872 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1873 if (!empty($title)) {
1874 $serverdata['site_name'] = $title;
1877 $list = $xpath->query('//meta[@name]');
1879 foreach ($list as $node) {
1881 if ($node->attributes->length) {
1882 foreach ($node->attributes as $attribute) {
1883 $value = trim($attribute->value);
1884 if (empty($value)) {
1888 $attr[$attribute->name] = $value;
1891 if (empty($attr['name']) || empty($attr['content'])) {
1896 if ($attr['name'] == 'description') {
1897 $serverdata['info'] = $attr['content'];
1900 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1901 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
1902 $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
1903 $platform = str_replace('/', ' ', $platform);
1904 $platform_parts = explode(' ', $platform);
1905 if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
1906 $platform = $platform_parts[0];
1907 $serverdata['version'] = $platform_parts[1];
1909 if (in_array($platform, array_values($dfrn_platforms))) {
1910 $serverdata['network'] = Protocol::DFRN;
1911 } elseif (in_array($platform, array_values($ap_platforms))) {
1912 $serverdata['network'] = Protocol::ACTIVITYPUB;
1913 } elseif (in_array($platform, array_values($zap_platforms))) {
1914 $serverdata['network'] = Protocol::ZOT;
1916 if (in_array($platform, array_values($platforms))) {
1917 $serverdata['platform'] = $platform;
1923 $list = $xpath->query('//meta[@property]');
1925 foreach ($list as $node) {
1927 if ($node->attributes->length) {
1928 foreach ($node->attributes as $attribute) {
1929 $value = trim($attribute->value);
1930 if (empty($value)) {
1934 $attr[$attribute->name] = $value;
1937 if (empty($attr['property']) || empty($attr['content'])) {
1942 if ($attr['property'] == 'og:site_name') {
1943 $serverdata['site_name'] = $attr['content'];
1946 if ($attr['property'] == 'og:description') {
1947 $serverdata['info'] = $attr['content'];
1950 if (in_array($attr['property'], ['og:platform', 'generator'])) {
1951 if (in_array($attr['content'], array_keys($platforms))) {
1952 $serverdata['platform'] = $platforms[$attr['content']];
1956 if (in_array($attr['content'], array_keys($ap_platforms))) {
1957 $serverdata['network'] = Protocol::ACTIVITYPUB;
1958 } elseif (in_array($attr['content'], array_values($zap_platforms))) {
1959 $serverdata['network'] = Protocol::ZOT;
1964 $list = $xpath->query('//link[@rel="me"]');
1965 foreach ($list as $node) {
1966 foreach ($node->attributes as $attribute) {
1967 if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
1968 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
1969 $serverdata['platform'] = 'microblog';
1970 $serverdata['network'] = Protocol::ACTIVITYPUB;
1976 if ($serverdata['platform'] != 'microblog') {
1977 $list = $xpath->query('//link[@rel="micropub"]');
1978 foreach ($list as $node) {
1979 foreach ($node->attributes as $attribute) {
1980 if (trim($attribute->value) == 'https://micro.blog/micropub') {
1981 $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
1982 $serverdata['platform'] = 'microblog';
1983 $serverdata['network'] = Protocol::ACTIVITYPUB;
1990 if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
1991 $serverdata['detection-method'] = self::DETECT_BODY;
1998 * Analyses the header data of a given server for hints about type and system of that server
2000 * @param object $curlResult result of curl execution
2001 * @param array $serverdata array with server data
2003 * @return array server data
2005 private static function analyseRootHeader($curlResult, array $serverdata)
2007 if ($curlResult->getHeader('server') == 'Mastodon') {
2008 $serverdata['platform'] = 'mastodon';
2009 $serverdata['network'] = Protocol::ACTIVITYPUB;
2010 } elseif ($curlResult->inHeader('x-diaspora-version')) {
2011 $serverdata['platform'] = 'diaspora';
2012 $serverdata['network'] = Protocol::DIASPORA;
2013 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2014 } elseif ($curlResult->inHeader('x-friendica-version')) {
2015 $serverdata['platform'] = 'friendica';
2016 $serverdata['network'] = Protocol::DFRN;
2017 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
2022 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
2023 $serverdata['detection-method'] = self::DETECT_HEADER;
2030 * Update GServer entries
2032 public static function discover()
2034 // Update the server list
2035 self::discoverFederation();
2039 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
2041 if ($requery_days == 0) {
2045 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
2047 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
2048 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
2049 ['order' => ['RAND()']]);
2051 while ($gserver = DBA::fetch($gservers)) {
2052 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2053 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2055 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2056 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
2058 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
2059 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
2061 if (--$no_of_queries == 0) {
2066 DBA::close($gservers);
2070 * Discover federated servers
2072 private static function discoverFederation()
2074 $last = DI::config()->get('poco', 'last_federation_discovery');
2077 $next = $last + (24 * 60 * 60);
2079 if ($next > time()) {
2084 // Discover federated servers
2085 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
2086 foreach ($protocols as $protocol) {
2087 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
2088 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
2089 if (!empty($curlResult)) {
2090 $data = json_decode($curlResult, true);
2091 if (!empty($data['data']['nodes'])) {
2092 foreach ($data['data']['nodes'] as $server) {
2093 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
2094 self::add('https://' . $server['host'], true);
2100 // Disvover Mastodon servers
2101 $accesstoken = DI::config()->get('system', 'instances_social_key');
2103 if (!empty($accesstoken)) {
2104 $api = 'https://instances.social/api/1.0/instances/list?count=0';
2105 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
2106 if ($curlResult->isSuccess()) {
2107 $servers = json_decode($curlResult->getBody(), true);
2109 foreach ($servers['instances'] as $server) {
2110 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
2116 DI::config()->set('poco', 'last_federation_discovery', time());
2120 * Set the protocol for the given server
2122 * @param int $gsid Server id
2123 * @param int $protocol Protocol id
2127 public static function setProtocol(int $gsid, int $protocol)
2133 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2134 if (!DBA::isResult($gserver)) {
2138 $old = $gserver['protocol'];
2140 if (!is_null($old)) {
2142 The priority for the protocols is:
2144 2. DFRN via Diaspora
2150 // We don't need to change it when nothing is to be changed
2151 if ($old == $protocol) {
2155 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2156 if ($protocol == Post\DeliveryData::OSTATUS) {
2160 // If the server is marked as ActivityPub then we won't change it to anything different
2161 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2165 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2166 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2170 // Don't change it to Diaspora when it is a legacy DFRN server
2171 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2176 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2177 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
2181 * Fetch the protocol of the given server
2183 * @param int $gsid Server id
2187 public static function getProtocol(int $gsid)
2193 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2194 if (DBA::isResult($gserver)) {
2195 return $gserver['protocol'];