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\Protocol\Relay;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
46 * This class handles GServer related functions
53 const DT_MASTODON = 2;
55 // Methods to detect server types
57 // Non endpoint specific methods
58 const DETECT_MANUAL = 0;
59 const DETECT_HEADER = 1;
60 const DETECT_BODY = 2;
62 // Implementation specific endpoints
63 const DETECT_FRIENDIKA = 10;
64 const DETECT_FRIENDICA = 11;
65 const DETECT_STATUSNET = 12;
66 const DETECT_GNUSOCIAL = 13;
67 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
68 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
69 const DETECT_MASTODON_API = 16;
70 const DETECT_STATUS_PHP = 17; // Nextcloud
71 const DETECT_V1_CONFIG = 18;
72 const DETECT_PUMPIO = 19;
74 // Standardized endpoints
75 const DETECT_STATISTICS_JSON = 100;
76 const DETECT_NODEINFO_1 = 101;
77 const DETECT_NODEINFO_2 = 102;
80 * Check for the existance of a server and adds it in the background if not existant
83 * @param boolean $only_nodeinfo
86 public static function add(string $url, bool $only_nodeinfo = false)
88 if (self::getID($url, false)) {
92 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
96 * Get the ID for the given server URL
99 * @param boolean $no_check Don't check if the server hadn't been found
100 * @return int|null gserver id or NULL on empty URL or failed check
102 public static function getID(string $url, bool $no_check = false)
108 $url = self::cleanURL($url);
110 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
111 if (DBA::isResult($gserver)) {
112 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
113 return $gserver['id'];
116 if ($no_check || !self::check($url)) {
120 return self::getID($url, true);
124 * Retrieves all the servers which base domain are matching the provided domain pattern
126 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
128 * @param string $pattern
132 public static function listByDomainPattern(string $pattern): array
134 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
136 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
137 // eventual server path and keep only the server domain which we're matching against the pattern.
138 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
140 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
141 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
142 AND NOT `gserver`.`failed`
143 GROUP BY `gserver`.`id`";
145 $stmt = DI::dba()->p($sql, $likePattern);
147 return DI::dba()->toArray($stmt);
151 * Checks if the given server is reachable
153 * @param string $profile URL of the given profile
154 * @param string $server URL of the given server (If empty, taken from profile)
155 * @param string $network Network value that is used, when detection failed
156 * @param boolean $force Force an update.
158 * @return boolean 'true' if server seems vital
160 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false): bool
163 $contact = Contact::getByURL($profile, null, ['baseurl']);
164 if (!empty($contact['baseurl'])) {
165 $server = $contact['baseurl'];
173 return self::check($server, $network, $force);
176 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = ''): string
178 // On successful contact process check again next week
180 return DateTimeFormat::utc('now +7 day');
183 $now = strtotime(DateTimeFormat::utcNow());
185 if ($created > $last_contact) {
186 $contact_time = strtotime($created);
188 $contact_time = strtotime($last_contact);
191 // If the last contact was less than 6 hours before then try again in 6 hours
192 if (($now - $contact_time) < (60 * 60 * 6)) {
193 return DateTimeFormat::utc('now +6 hour');
196 // If the last contact was less than 12 hours before then try again in 12 hours
197 if (($now - $contact_time) < (60 * 60 * 12)) {
198 return DateTimeFormat::utc('now +12 hour');
201 // If the last contact was less than 24 hours before then try tomorrow again
202 if (($now - $contact_time) < (60 * 60 * 24)) {
203 return DateTimeFormat::utc('now +1 day');
206 // If the last contact was less than a week before then try again in a week
207 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
208 return DateTimeFormat::utc('now +1 week');
211 // If the last contact was less than two weeks before then try again in two week
212 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
213 return DateTimeFormat::utc('now +2 week');
216 // If the last contact was less than a month before then try again in a month
217 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
218 return DateTimeFormat::utc('now +1 month');
221 // The system hadn't been successul contacted for more than a month, so try again in three months
222 return DateTimeFormat::utc('now +3 month');
226 * Checks the state of the given server.
228 * @param string $server_url URL of the given server
229 * @param string $network Network value that is used, when detection failed
230 * @param boolean $force Force an update.
231 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
233 * @return boolean 'true' if server seems vital
235 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
237 $server_url = self::cleanURL($server_url);
238 if ($server_url == '') {
242 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
243 if (DBA::isResult($gserver)) {
244 if ($gserver['created'] <= DBA::NULL_DATETIME) {
245 $fields = ['created' => DateTimeFormat::utcNow()];
246 $condition = ['nurl' => Strings::normaliseLink($server_url)];
247 self::update($fields, $condition);
250 if (!$force && (strtotime($gserver['next_contact']) > time())) {
251 Logger::info('No update needed', ['server' => $server_url]);
252 return (!$gserver['failed']);
254 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
256 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
259 return self::detect($server_url, $network, $only_nodeinfo);
263 * Set failed server status
267 public static function setFailure(string $url)
269 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
270 if (DBA::isResult($gserver)) {
271 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
272 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
273 'next_contact' => $next_update, 'detection-method' => null],
274 ['nurl' => Strings::normaliseLink($url)]);
275 Logger::info('Set failed status for existing server', ['url' => $url]);
278 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
279 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
280 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
281 Logger::info('Set failed status for new server', ['url' => $url]);
285 * Remove unwanted content from the given URL
288 * @return string cleaned URL
290 public static function cleanURL(string $url): string
292 $url = trim($url, '/');
293 $url = str_replace('/index.php', '', $url);
295 $urlparts = parse_url($url);
296 unset($urlparts['user']);
297 unset($urlparts['pass']);
298 unset($urlparts['query']);
299 unset($urlparts['fragment']);
300 return Network::unparseURL($urlparts);
304 * Return the base URL
307 * @return string base URL
309 private static function getBaseURL(string $url): string
311 $urlparts = parse_url(self::cleanURL($url));
312 unset($urlparts['path']);
313 return Network::unparseURL($urlparts);
317 * Detect server data (type, protocol, version number, ...)
318 * The detected data is then updated or inserted in the gserver table.
320 * @param string $url URL of the given server
321 * @param string $network Network value that is used, when detection failed
322 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
324 * @return boolean 'true' if server could be detected
326 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
328 Logger::info('Detect server type', ['server' => $url]);
329 $serverdata = ['detection-method' => self::DETECT_MANUAL];
331 $original_url = $url;
333 // Remove URL content that is not supposed to exist for a server url
334 $url = self::cleanURL($url);
337 $baseurl = self::getBaseURL($url);
339 // If the URL missmatches, then we mark the old entry as failure
340 if ($url != $original_url) {
341 /// @todo What to do with "next_contact" here?
342 self::update(['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
343 ['nurl' => Strings::normaliseLink($original_url)]);
346 // When a nodeinfo is present, we don't need to dig further
347 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
348 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
349 if ($curlResult->isTimeout()) {
350 self::setFailure($url);
354 // On a redirect follow the new host but mark the old one as failure
355 if ($curlResult->isSuccess() && !empty($curlResult->getRedirectUrl()) && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
356 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
357 if (!empty($curlResult->getRedirectUrl()) && parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
358 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
359 self::setFailure($url);
360 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
365 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
366 if ($only_nodeinfo && empty($nodeinfo)) {
367 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
368 self::setFailure($url);
372 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
373 if (empty($nodeinfo)) {
374 $nodeinfo = self::fetchStatistics($url);
377 // If that didn't work out well, we use some protocol specific endpoints
378 // For Friendica and Zot based networks we have to dive deeper to reveal more details
379 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
380 if (!empty($nodeinfo['detection-method'])) {
381 $serverdata['detection-method'] = $nodeinfo['detection-method'];
383 foreach (['registered-users', 'active_users_monthly', 'active-halfyear-users', 'local-posts'] as $field) {
384 if (!empty($nodeinfo[$field])) {
385 $serverdata[$field] = $nodeinfo[$field];
390 // Fetch the landing page, possibly it reveals some data
391 if (empty($nodeinfo['network'])) {
392 if ($baseurl == $url) {
393 $basedata = $serverdata;
395 $basedata = ['detection-method' => self::DETECT_MANUAL];
398 $curlResult = DI::httpClient()->get($baseurl, HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
399 if ($curlResult->isSuccess()) {
400 if (!empty($curlResult->getRedirectUrl()) && (parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
401 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
402 self::setFailure($url);
403 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
407 $basedata = self::analyseRootHeader($curlResult, $basedata);
408 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
411 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
412 self::setFailure($url);
416 if ($baseurl == $url) {
417 $serverdata = $basedata;
419 // When the base path doesn't seem to contain a social network we try the complete path.
420 // Most detectable system have to be installed in the root directory.
421 // We checked the base to avoid false positives.
422 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
423 if ($curlResult->isSuccess()) {
424 $urldata = self::analyseRootHeader($curlResult, $serverdata);
425 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
427 $comparebase = $basedata;
428 unset($comparebase['info']);
429 unset($comparebase['site_name']);
430 $compareurl = $urldata;
431 unset($compareurl['info']);
432 unset($compareurl['site_name']);
434 // We assume that no one will install the identical system in the root and a subfolder
435 if (!empty(array_diff($comparebase, $compareurl))) {
436 $serverdata = $urldata;
442 if (empty($nodeinfo['network']) && (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB))) {
443 $serverdata = self::detectMastodonAlikes($url, $serverdata);
446 // All following checks are done for systems that always have got a "host-meta" endpoint.
447 // With this check we don't have to waste time and ressources for dead systems.
448 // Also this hopefully prevents us from receiving abuse messages.
449 $validHostMeta = self::validHostMeta($url);
451 if (empty($serverdata['network']) && !$validHostMeta) {
452 $serverdata = self::detectFromContacts($url, $serverdata);
455 if (empty($serverdata['network']) && !$validHostMeta) {
456 self::setFailure($url);
460 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
461 $serverdata = self::detectFriendica($url, $serverdata);
464 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
465 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
466 $serverdata = self::fetchSiteinfo($url, $serverdata);
469 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
470 if (empty($serverdata['network'])) {
471 $serverdata = self::detectHubzilla($url, $serverdata);
474 if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
475 $serverdata = self::detectPeertube($url, $serverdata);
478 if (empty($serverdata['network'])) {
479 $serverdata = self::detectNextcloud($url, $serverdata);
482 if (empty($nodeinfo['network']) && empty($serverdata['network'])) {
483 $serverdata = self::detectGNUSocial($url, $serverdata);
486 if (empty($serverdata['network'])) {
487 $serverdata = self::detectPumpIO($url, $serverdata);
490 $serverdata = array_merge($nodeinfo, $serverdata);
492 $serverdata = $nodeinfo;
495 // Detect the directory type
496 $serverdata['directory-type'] = self::DT_NONE;
498 $serverdata = self::checkMastodonDirectory($url, $serverdata);
500 if ($serverdata['directory-type'] == self::DT_NONE) {
501 $serverdata = self::checkPoCo($url, $serverdata);
504 // We can't detect the network type. Possibly it is some system that we don't know yet
505 if (empty($serverdata['network'])) {
506 $serverdata['network'] = Protocol::PHANTOM;
509 // When we hadn't been able to detect the network type, we use the hint from the parameter
510 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
511 $serverdata['network'] = $network;
514 $serverdata['url'] = $url;
515 $serverdata['nurl'] = Strings::normaliseLink($url);
517 if (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
518 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
521 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
522 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
525 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
527 // On an active server there has to be at least a single user
528 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
529 $serverdata['registered-users'] = 1;
530 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
531 $serverdata['registered-users'] = 0;
534 $serverdata['next_contact'] = self::getNextUpdateDate(true);
536 $serverdata['last_contact'] = DateTimeFormat::utcNow();
537 $serverdata['failed'] = false;
539 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => $serverdata['nurl']]);
540 if (!DBA::isResult($gserver)) {
541 $serverdata['created'] = DateTimeFormat::utcNow();
542 $ret = DBA::insert('gserver', $serverdata);
543 $id = DBA::lastInsertId();
545 $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
546 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
547 if (DBA::isResult($gserver)) {
548 $id = $gserver['id'];
552 // Count the number of known contacts from this server
553 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
554 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
555 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
556 $max_users = max($apcontacts, $contacts);
557 if ($max_users > $serverdata['registered-users']) {
558 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
559 self::update(['registered-users' => $max_users], ['id' => $id]);
562 if (empty($serverdata['active-month-users'])) {
563 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
565 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
566 self::update(['active-month-users' => $contacts], ['id' => $id]);
570 if (empty($serverdata['active-halfyear-users'])) {
571 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
573 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
574 self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
579 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
580 self::discoverRelay($url);
587 * Fetch relay data from a given server url
589 * @param string $server_url address of the server
591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
593 private static function discoverRelay(string $server_url)
595 Logger::info('Discover relay data', ['server' => $server_url]);
597 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
598 if (!$curlResult->isSuccess()) {
602 $data = json_decode($curlResult->getBody(), true);
603 if (!is_array($data)) {
607 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
608 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
610 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
612 $data['subscribe'] = false;
616 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
617 if (!DBA::isResult($gserver)) {
621 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
622 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
623 self::update($fields, ['id' => $gserver['id']]);
626 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
628 if ($data['scope'] == 'tags') {
631 foreach ($data['tags'] as $tag) {
632 $tag = mb_strtolower($tag);
633 if (strlen($tag) < 100) {
638 foreach ($tags as $tag) {
639 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
643 // Create or update the relay contact
645 if (isset($data['protocols'])) {
646 if (isset($data['protocols']['diaspora'])) {
647 $fields['network'] = Protocol::DIASPORA;
649 if (isset($data['protocols']['diaspora']['receive'])) {
650 $fields['batch'] = $data['protocols']['diaspora']['receive'];
651 } elseif (is_string($data['protocols']['diaspora'])) {
652 $fields['batch'] = $data['protocols']['diaspora'];
656 if (isset($data['protocols']['dfrn'])) {
657 $fields['network'] = Protocol::DFRN;
659 if (isset($data['protocols']['dfrn']['receive'])) {
660 $fields['batch'] = $data['protocols']['dfrn']['receive'];
661 } elseif (is_string($data['protocols']['dfrn'])) {
662 $fields['batch'] = $data['protocols']['dfrn'];
666 if (isset($data['protocols']['activitypub'])) {
667 $fields['network'] = Protocol::ACTIVITYPUB;
669 if (!empty($data['protocols']['activitypub']['actor'])) {
670 $fields['url'] = $data['protocols']['activitypub']['actor'];
672 if (!empty($data['protocols']['activitypub']['receive'])) {
673 $fields['batch'] = $data['protocols']['activitypub']['receive'];
678 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
680 Relay::updateContact($gserver, $fields);
684 * Fetch server data from '/statistics.json' on the given server
686 * @param string $url URL of the given server
687 * @return array server data
689 private static function fetchStatistics(string $url): array
691 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
692 if (!$curlResult->isSuccess()) {
696 $data = json_decode($curlResult->getBody(), true);
701 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
703 if (!empty($data['version'])) {
704 $serverdata['version'] = $data['version'];
705 // Version numbers on statistics.json are presented with additional info, e.g.:
706 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
707 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
710 if (!empty($data['name'])) {
711 $serverdata['site_name'] = $data['name'];
714 if (!empty($data['network'])) {
715 $serverdata['platform'] = strtolower($data['network']);
717 if ($serverdata['platform'] == 'diaspora') {
718 $serverdata['network'] = Protocol::DIASPORA;
719 } elseif ($serverdata['platform'] == 'friendica') {
720 $serverdata['network'] = Protocol::DFRN;
721 } elseif ($serverdata['platform'] == 'hubzilla') {
722 $serverdata['network'] = Protocol::ZOT;
723 } elseif ($serverdata['platform'] == 'redmatrix') {
724 $serverdata['network'] = Protocol::ZOT;
728 if (!empty($data['total_users'])) {
729 $serverdata['registered-users'] = max($data['total_users'], 1);
732 if (!empty($data['active_users_monthly'])) {
733 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
736 if (!empty($data['active_users_halfyear'])) {
737 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
740 if (!empty($data['local_posts'])) {
741 $serverdata['local-posts'] = max($data['local_posts'], 0);
744 if (!empty($data['registrations_open'])) {
745 $serverdata['register_policy'] = Register::OPEN;
747 $serverdata['register_policy'] = Register::CLOSED;
754 * Detect server type by using the nodeinfo data
756 * @param string $url address of the server
757 * @param ICanHandleHttpResponses $httpResult
759 * @return array Server data
760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
762 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
764 if (!$httpResult->isSuccess()) {
768 $nodeinfo = json_decode($httpResult->getBody(), true);
770 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
777 foreach ($nodeinfo['links'] as $link) {
778 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
779 Logger::info('Invalid nodeinfo format', ['url' => $url]);
782 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
783 $nodeinfo1_url = $link['href'];
784 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
785 $nodeinfo2_url = $link['href'];
789 if ($nodeinfo1_url . $nodeinfo2_url == '') {
795 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
796 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
797 $server = self::parseNodeinfo2($nodeinfo2_url);
800 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
801 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
802 $server = self::parseNodeinfo1($nodeinfo1_url);
811 * @param string $nodeinfo_url address of the nodeinfo path
812 * @return array Server data
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 private static function parseNodeinfo1(string $nodeinfo_url): array
817 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
818 if (!$curlResult->isSuccess()) {
822 $nodeinfo = json_decode($curlResult->getBody(), true);
824 if (!is_array($nodeinfo)) {
828 $server = ['detection-method' => self::DETECT_NODEINFO_1,
829 'register_policy' => Register::CLOSED];
831 if (!empty($nodeinfo['openRegistrations'])) {
832 $server['register_policy'] = Register::OPEN;
835 if (is_array($nodeinfo['software'])) {
836 if (!empty($nodeinfo['software']['name'])) {
837 $server['platform'] = strtolower($nodeinfo['software']['name']);
840 if (!empty($nodeinfo['software']['version'])) {
841 $server['version'] = $nodeinfo['software']['version'];
842 // Version numbers on Nodeinfo are presented with additional info, e.g.:
843 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
844 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
848 if (!empty($nodeinfo['metadata']['nodeName'])) {
849 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
852 if (!empty($nodeinfo['usage']['users']['total'])) {
853 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
856 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
857 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
860 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
861 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
864 if (!empty($nodeinfo['usage']['localPosts'])) {
865 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
868 if (!empty($nodeinfo['usage']['localComments'])) {
869 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
872 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
874 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
875 $protocols[$protocol] = true;
878 if (!empty($protocols['friendica'])) {
879 $server['network'] = Protocol::DFRN;
880 } elseif (!empty($protocols['activitypub'])) {
881 $server['network'] = Protocol::ACTIVITYPUB;
882 } elseif (!empty($protocols['diaspora'])) {
883 $server['network'] = Protocol::DIASPORA;
884 } elseif (!empty($protocols['ostatus'])) {
885 $server['network'] = Protocol::OSTATUS;
886 } elseif (!empty($protocols['gnusocial'])) {
887 $server['network'] = Protocol::OSTATUS;
888 } elseif (!empty($protocols['zot'])) {
889 $server['network'] = Protocol::ZOT;
893 if (empty($server)) {
903 * @see https://git.feneas.org/jaywink/nodeinfo2
904 * @param string $nodeinfo_url address of the nodeinfo path
905 * @return array Server data
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 private static function parseNodeinfo2(string $nodeinfo_url): array
910 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
911 if (!$curlResult->isSuccess()) {
915 $nodeinfo = json_decode($curlResult->getBody(), true);
917 if (!is_array($nodeinfo)) {
922 'detection-method' => self::DETECT_NODEINFO_2,
923 'register_policy' => Register::CLOSED,
924 'platform' => 'unknown',
927 if (!empty($nodeinfo['openRegistrations'])) {
928 $server['register_policy'] = Register::OPEN;
931 if (is_array($nodeinfo['software'])) {
932 if (!empty($nodeinfo['software']['name'])) {
933 $server['platform'] = strtolower($nodeinfo['software']['name']);
936 if (!empty($nodeinfo['software']['version'])) {
937 $server['version'] = $nodeinfo['software']['version'];
938 // Version numbers on Nodeinfo are presented with additional info, e.g.:
939 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
940 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
942 // qoto advertises itself as Mastodon
943 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
944 $server['platform'] = 'qoto';
949 if (!empty($nodeinfo['metadata']['nodeName'])) {
950 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
953 if (!empty($nodeinfo['usage']['users']['total'])) {
954 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
957 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
958 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
961 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
962 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
965 if (!empty($nodeinfo['usage']['localPosts'])) {
966 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
969 if (!empty($nodeinfo['usage']['localComments'])) {
970 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
973 if (!empty($nodeinfo['protocols'])) {
975 foreach ($nodeinfo['protocols'] as $protocol) {
976 if (is_string($protocol)) {
977 $protocols[$protocol] = true;
981 if (!empty($protocols['dfrn'])) {
982 $server['network'] = Protocol::DFRN;
983 } elseif (!empty($protocols['activitypub'])) {
984 $server['network'] = Protocol::ACTIVITYPUB;
985 } elseif (!empty($protocols['diaspora'])) {
986 $server['network'] = Protocol::DIASPORA;
987 } elseif (!empty($protocols['ostatus'])) {
988 $server['network'] = Protocol::OSTATUS;
989 } elseif (!empty($protocols['gnusocial'])) {
990 $server['network'] = Protocol::OSTATUS;
991 } elseif (!empty($protocols['zot'])) {
992 $server['network'] = Protocol::ZOT;
996 if (empty($server)) {
1004 * Fetch server information from a 'siteinfo.json' file on the given server
1006 * @param string $url URL of the given server
1007 * @param array $serverdata array with server data
1008 * @return array server data
1010 private static function fetchSiteinfo(string $url, array $serverdata): array
1012 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1013 if (!$curlResult->isSuccess()) {
1017 $data = json_decode($curlResult->getBody(), true);
1022 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1023 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1026 if (!empty($data['url'])) {
1027 $serverdata['platform'] = strtolower($data['platform']);
1028 $serverdata['version'] = $data['version'];
1031 if (!empty($data['plugins'])) {
1032 if (in_array('pubcrawl', $data['plugins'])) {
1033 $serverdata['network'] = Protocol::ACTIVITYPUB;
1034 } elseif (in_array('diaspora', $data['plugins'])) {
1035 $serverdata['network'] = Protocol::DIASPORA;
1036 } elseif (in_array('gnusoc', $data['plugins'])) {
1037 $serverdata['network'] = Protocol::OSTATUS;
1039 $serverdata['network'] = Protocol::ZOT;
1043 if (!empty($data['site_name'])) {
1044 $serverdata['site_name'] = $data['site_name'];
1047 if (!empty($data['channels_total'])) {
1048 $serverdata['registered-users'] = max($data['channels_total'], 1);
1051 if (!empty($data['channels_active_monthly'])) {
1052 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1055 if (!empty($data['channels_active_halfyear'])) {
1056 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1059 if (!empty($data['local_posts'])) {
1060 $serverdata['local-posts'] = max($data['local_posts'], 0);
1063 if (!empty($data['local_comments'])) {
1064 $serverdata['local-comments'] = max($data['local_comments'], 0);
1067 if (!empty($data['register_policy'])) {
1068 switch ($data['register_policy']) {
1069 case 'REGISTER_OPEN':
1070 $serverdata['register_policy'] = Register::OPEN;
1073 case 'REGISTER_APPROVE':
1074 $serverdata['register_policy'] = Register::APPROVE;
1077 case 'REGISTER_CLOSED':
1079 $serverdata['register_policy'] = Register::CLOSED;
1088 * Checks if the server contains a valid host meta file
1090 * @param string $url URL of the given server
1091 * @return boolean 'true' if the server seems to be vital
1093 private static function validHostMeta(string $url): bool
1095 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1096 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1097 if (!$curlResult->isSuccess()) {
1101 $xrd = XML::parseString($curlResult->getBody());
1102 if (!is_object($xrd)) {
1106 $elements = XML::elementToArray($xrd);
1107 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1112 foreach ($elements['xrd']['link'] as $link) {
1113 // When there is more than a single "link" element, the array looks slightly different
1114 if (!empty($link['@attributes'])) {
1115 $link = $link['@attributes'];
1118 if (empty($link['rel']) || empty($link['template'])) {
1122 if ($link['rel'] == 'lrdd') {
1123 // When the webfinger host is the same like the system host, it should be ok.
1124 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1132 * Detect the network of the given server via their known contacts
1134 * @param string $url URL of the given server
1135 * @param array $serverdata array with server data
1136 * @return array server data
1138 private static function detectNetworkViaContacts(string $url, array $serverdata): array
1142 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1143 while ($apcontact = DBA::fetch($apcontacts)) {
1144 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1146 DBA::close($apcontacts);
1148 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1149 while ($pcontact = DBA::fetch($pcontacts)) {
1150 $contacts[$pcontact['nurl']] = $pcontact['url'];
1152 DBA::close($pcontacts);
1154 if (empty($contacts)) {
1159 foreach ($contacts as $contact) {
1160 $probed = Contact::getByURL($contact, true);
1161 if (!empty($probed) && !$probed['failed'] && in_array($probed['network'], Protocol::FEDERATED)) {
1162 $serverdata['network'] = $probed['network'];
1164 } elseif ((time() - $time) > 10) {
1165 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1174 * Checks if the given server does have a '/poco' endpoint.
1175 * This is used for the 'PortableContact' functionality,
1176 * which is used by both Friendica and Hubzilla.
1178 * @param string $url URL of the given server
1179 * @param array $serverdata array with server data
1180 * @return array server data
1182 private static function checkPoCo(string $url, array $serverdata): array
1184 $serverdata['poco'] = '';
1186 $curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
1187 if (!$curlResult->isSuccess()) {
1191 $data = json_decode($curlResult->getBody(), true);
1196 if (!empty($data['totalResults'])) {
1197 $registeredUsers = $serverdata['registered-users'] ?? 0;
1198 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1199 $serverdata['directory-type'] = self::DT_POCO;
1200 $serverdata['poco'] = $url . '/poco';
1207 * Checks if the given server does have a Mastodon style directory endpoint.
1209 * @param string $url URL of the given server
1210 * @param array $serverdata array with server data
1211 * @return array server data
1213 public static function checkMastodonDirectory(string $url, array $serverdata): array
1215 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1216 if (!$curlResult->isSuccess()) {
1220 $data = json_decode($curlResult->getBody(), true);
1225 if (count($data) == 1) {
1226 $serverdata['directory-type'] = self::DT_MASTODON;
1233 * Detects Peertube via their known endpoint
1235 * @param string $url URL of the given server
1236 * @param array $serverdata array with server data
1238 * @return array server data
1240 private static function detectPeertube(string $url, array $serverdata): array
1242 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1243 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1247 $data = json_decode($curlResult->getBody(), true);
1252 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1253 $serverdata['platform'] = 'peertube';
1254 $serverdata['version'] = $data['serverVersion'];
1255 $serverdata['network'] = Protocol::ACTIVITYPUB;
1257 if (!empty($data['instance']['name'])) {
1258 $serverdata['site_name'] = $data['instance']['name'];
1261 if (!empty($data['instance']['shortDescription'])) {
1262 $serverdata['info'] = $data['instance']['shortDescription'];
1265 if (!empty($data['signup'])) {
1266 if (!empty($data['signup']['allowed'])) {
1267 $serverdata['register_policy'] = Register::OPEN;
1271 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1272 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1280 * Detects the version number of a given server when it was a NextCloud installation
1282 * @param string $url URL of the given server
1283 * @param array $serverdata array with server data
1284 * @return array server data
1286 private static function detectNextcloud(string $url, array $serverdata): array
1288 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1289 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1293 $data = json_decode($curlResult->getBody(), true);
1298 if (!empty($data['version'])) {
1299 $serverdata['platform'] = 'nextcloud';
1300 $serverdata['version'] = $data['version'];
1301 $serverdata['network'] = Protocol::ACTIVITYPUB;
1303 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1304 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1312 * Fetches weekly usage data
1314 * @param string $url URL of the given server
1315 * @param array $serverdata array with server data
1316 * @return array server data
1318 private static function fetchWeeklyUsage(string $url, array $serverdata): array
1320 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1321 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1325 $data = json_decode($curlResult->getBody(), true);
1331 foreach ($data as $week) {
1332 // Use only data from a full week
1333 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1337 // Most likely the data is sorted correctly. But we better are safe than sorry
1338 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1339 $current_week = $week;
1343 if (!empty($current_week['logins'])) {
1344 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1351 * Detects the server network type from contacts of that server
1353 * @param string $url URL of the given server
1354 * @param array $serverdata array with server data
1355 * @return array server data
1357 private static function detectFromContacts(string $url, array $serverdata): array
1359 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
1360 if (empty($gserver)) {
1364 $contact = Contact::selectFirst(['id'], ['uid' => 0, 'failed' => false, 'gsid' => $gserver['id']]);
1366 // Via probing we can be sure that the server is responding
1367 if (!empty($contact['id']) && Contact::updateFromProbe($contact['id'])) {
1368 $contact = Contact::selectFirst(['network', 'failed'], ['id' => $contact['id']]);
1369 if (!$contact['failed'] && in_array($contact['network'], Protocol::FEDERATED)) {
1370 $serverdata['network'] = $contact['network'];
1378 * Detects data from a given server url if it was a mastodon alike system
1380 * @param string $url URL of the given server
1381 * @param array $serverdata array with server data
1382 * @return array server data
1384 private static function detectMastodonAlikes(string $url, array $serverdata): array
1386 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1387 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1391 $data = json_decode($curlResult->getBody(), true);
1396 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1397 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1400 if (!empty($data['version'])) {
1401 $serverdata['platform'] = 'mastodon';
1402 $serverdata['version'] = $data['version'] ?? '';
1403 $serverdata['network'] = Protocol::ACTIVITYPUB;
1406 if (!empty($data['title'])) {
1407 $serverdata['site_name'] = $data['title'];
1410 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1411 $serverdata['platform'] = 'mastodon';
1412 $serverdata['network'] = Protocol::ACTIVITYPUB;
1415 if (!empty($data['description'])) {
1416 $serverdata['info'] = trim($data['description']);
1419 if (!empty($data['stats']['user_count'])) {
1420 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1423 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1424 $serverdata['platform'] = strtolower($matches[1]);
1425 $serverdata['version'] = $matches[2];
1428 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1429 $serverdata['platform'] = 'pleroma';
1430 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1433 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1434 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1435 $serverdata['platform'] = 'pleroma';
1442 * Detects data from typical Hubzilla endpoints
1444 * @param string $url URL of the given server
1445 * @param array $serverdata array with server data
1446 * @return array server data
1448 private static function detectHubzilla(string $url, array $serverdata): array
1450 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1451 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1455 $data = json_decode($curlResult->getBody(), true);
1456 if (empty($data) || empty($data['site'])) {
1460 if (!empty($data['site']['name'])) {
1461 $serverdata['site_name'] = $data['site']['name'];
1464 if (!empty($data['site']['platform'])) {
1465 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1466 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1467 $serverdata['network'] = Protocol::ZOT;
1470 if (!empty($data['site']['hubzilla'])) {
1471 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1472 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1473 $serverdata['network'] = Protocol::ZOT;
1476 if (!empty($data['site']['redmatrix'])) {
1477 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1478 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1479 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1480 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1483 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1484 $serverdata['network'] = Protocol::ZOT;
1488 $inviteonly = false;
1491 if (!empty($data['site']['closed'])) {
1492 $closed = self::toBoolean($data['site']['closed']);
1495 if (!empty($data['site']['private'])) {
1496 $private = self::toBoolean($data['site']['private']);
1499 if (!empty($data['site']['inviteonly'])) {
1500 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1503 if (!$closed && !$private and $inviteonly) {
1504 $serverdata['register_policy'] = Register::APPROVE;
1505 } elseif (!$closed && !$private) {
1506 $serverdata['register_policy'] = Register::OPEN;
1508 $serverdata['register_policy'] = Register::CLOSED;
1511 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1512 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1513 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1520 * Converts input value to a boolean value
1522 * @param string|integer $val
1525 private static function toBoolean($val): bool
1527 if (($val == 'true') || ($val == 1)) {
1529 } elseif (($val == 'false') || ($val == 0)) {
1537 * Detect if the URL belongs to a pump.io server
1539 * @param string $url URL of the given server
1540 * @param array $serverdata array with server data
1541 * @return array server data
1543 private static function detectPumpIO(string $url, array $serverdata): array
1545 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json', HttpClientAccept::JSON);
1546 if (!$curlResult->isSuccess()) {
1550 $data = json_decode($curlResult->getBody(), true);
1551 if (empty($data['links'])) {
1555 // We are looking for some endpoints that are typical for pump.io
1557 foreach ($data['links'] as $link) {
1558 if (empty($link['rel'])) {
1561 if (in_array($link['rel'], ['registration_endpoint', 'dialback', 'http://apinamespace.org/activitypub/whoami'])) {
1567 $serverdata['detection-method'] = self::DETECT_PUMPIO;
1569 $serverdata['platform'] = 'pumpio';
1570 $serverdata['version'] = '';
1571 $serverdata['network'] = Protocol::PUMPIO;
1573 $servers = $curlResult->getHeader('Server');
1574 foreach ($servers as $server) {
1575 if (preg_match("#pump.io/(.*)\s#U", $server, $matches)) {
1576 $serverdata['version'] = $matches[1];
1585 * Detect if the URL belongs to a GNU Social server
1587 * @param string $url URL of the given server
1588 * @param array $serverdata array with server data
1589 * @return array server data
1591 private static function detectGNUSocial(string $url, array $serverdata): array
1593 // Test for GNU Social
1594 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1595 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1596 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1597 $serverdata['platform'] = 'gnusocial';
1598 // Remove junk that some GNU Social servers return
1599 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1600 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1601 $serverdata['version'] = trim($serverdata['version'], '"');
1602 $serverdata['network'] = Protocol::OSTATUS;
1604 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1605 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1611 // Test for Statusnet
1612 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1613 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1614 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1616 // Remove junk that some GNU Social servers return
1617 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1618 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1619 $serverdata['version'] = trim($serverdata['version'], '"');
1621 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1622 $serverdata['platform'] = 'pleroma';
1623 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1624 $serverdata['network'] = Protocol::ACTIVITYPUB;
1626 $serverdata['platform'] = 'statusnet';
1627 $serverdata['network'] = Protocol::OSTATUS;
1630 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1631 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1639 * Detect if the URL belongs to a Friendica server
1641 * @param string $url URL of the given server
1642 * @param array $serverdata array with server data
1643 * @return array server data
1645 private static function detectFriendica(string $url, array $serverdata): array
1647 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1648 // Because of this me must not use ACCEPT_JSON here.
1649 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1650 if (!$curlResult->isSuccess()) {
1651 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1653 $platform = 'Friendika';
1656 $platform = 'Friendica';
1659 if (!$curlResult->isSuccess()) {
1663 $data = json_decode($curlResult->getBody(), true);
1664 if (empty($data) || empty($data['version'])) {
1668 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1669 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1672 $serverdata['network'] = Protocol::DFRN;
1673 $serverdata['version'] = $data['version'];
1675 if (!empty($data['no_scrape_url'])) {
1676 $serverdata['noscrape'] = $data['no_scrape_url'];
1679 if (!empty($data['site_name'])) {
1680 $serverdata['site_name'] = $data['site_name'];
1683 if (!empty($data['info'])) {
1684 $serverdata['info'] = trim($data['info']);
1687 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1688 switch ($register_policy) {
1689 case 'REGISTER_OPEN':
1690 $serverdata['register_policy'] = Register::OPEN;
1693 case 'REGISTER_APPROVE':
1694 $serverdata['register_policy'] = Register::APPROVE;
1697 case 'REGISTER_CLOSED':
1698 case 'REGISTER_INVITATION':
1699 $serverdata['register_policy'] = Register::CLOSED;
1702 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1703 $serverdata['register_policy'] = Register::CLOSED;
1707 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1713 * Analyses the landing page of a given server for hints about type and system of that server
1715 * @param object $curlResult result of curl execution
1716 * @param array $serverdata array with server data
1717 * @param string $url Server URL
1718 * @return array server data
1720 private static function analyseRootBody($curlResult, array $serverdata, string $url): array
1722 if (empty($curlResult->getBody())) {
1726 // Using only body information we cannot safely detect a lot of systems.
1727 // So we define a list of platforms that we can detect safely.
1728 $valid_platforms = ['friendica', 'friendika', 'diaspora', 'mastodon', 'hubzilla', 'misskey', 'peertube', 'wordpress', 'write.as'];
1730 $doc = new DOMDocument();
1731 @$doc->loadHTML($curlResult->getBody());
1732 $xpath = new DOMXPath($doc);
1734 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1735 if (!empty($title)) {
1736 $serverdata['site_name'] = $title;
1739 $list = $xpath->query('//meta[@name]');
1741 foreach ($list as $node) {
1743 if ($node->attributes->length) {
1744 foreach ($node->attributes as $attribute) {
1745 $value = trim($attribute->value);
1746 if (empty($value)) {
1750 $attr[$attribute->name] = $value;
1753 if (empty($attr['name']) || empty($attr['content'])) {
1758 if ($attr['name'] == 'description') {
1759 $serverdata['info'] = $attr['content'];
1762 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1763 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1764 $serverdata['platform'] = strtolower($attr['content']);
1765 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1766 $serverdata['network'] = Protocol::ACTIVITYPUB;
1769 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1770 $serverdata['platform'] = strtolower($attr['content']);
1771 $version_part = explode(' ', $attr['content']);
1773 if (count($version_part) == 2) {
1774 if (in_array($version_part[0], ['WordPress'])) {
1775 $serverdata['platform'] = 'wordpress';
1776 $serverdata['version'] = $version_part[1];
1778 // We still do need a reliable test if some AP plugin is activated
1779 // By now we just check in a later process for some known contacts
1780 $serverdata['network'] = Protocol::FEED;
1782 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1783 $serverdata['detection-method'] = self::DETECT_BODY;
1786 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1787 $serverdata['platform'] = strtolower($version_part[0]);
1788 $serverdata['version'] = $version_part[1];
1789 $serverdata['network'] = Protocol::DFRN;
1795 $list = $xpath->query('//meta[@property]');
1797 foreach ($list as $node) {
1799 if ($node->attributes->length) {
1800 foreach ($node->attributes as $attribute) {
1801 $value = trim($attribute->value);
1802 if (empty($value)) {
1806 $attr[$attribute->name] = $value;
1809 if (empty($attr['property']) || empty($attr['content'])) {
1814 if ($attr['property'] == 'og:site_name') {
1815 $serverdata['site_name'] = $attr['content'];
1818 if ($attr['property'] == 'og:description') {
1819 $serverdata['info'] = $attr['content'];
1822 if ($attr['property'] == 'og:platform') {
1823 $serverdata['platform'] = strtolower($attr['content']);
1825 if (in_array($attr['content'], ['PeerTube'])) {
1826 $serverdata['network'] = Protocol::ACTIVITYPUB;
1830 if ($attr['property'] == 'generator') {
1831 $serverdata['platform'] = strtolower($attr['content']);
1833 if (in_array($attr['content'], ['hubzilla'])) {
1834 // We later check which compatible protocol modules are loaded.
1835 $serverdata['network'] = Protocol::ZOT;
1840 if (!empty($serverdata['platform']) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY]) && !in_array($serverdata['platform'], $valid_platforms)) {
1841 $serverdata['network'] = Protocol::PHANTOM;
1842 $serverdata['version'] = '';
1843 $serverdata['detection-method'] = self::DETECT_MANUAL;
1844 } elseif (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1845 $serverdata['detection-method'] = self::DETECT_BODY;
1852 * Analyses the header data of a given server for hints about type and system of that server
1854 * @param object $curlResult result of curl execution
1855 * @param array $serverdata array with server data
1857 * @return array server data
1859 private static function analyseRootHeader($curlResult, array $serverdata): array
1861 if ($curlResult->getHeader('server') == 'Mastodon') {
1862 $serverdata['platform'] = 'mastodon';
1863 $serverdata['network'] = Protocol::ACTIVITYPUB;
1864 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1865 $serverdata['platform'] = 'diaspora';
1866 $serverdata['network'] = Protocol::DIASPORA;
1867 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1868 } elseif ($curlResult->inHeader('x-friendica-version')) {
1869 $serverdata['platform'] = 'friendica';
1870 $serverdata['network'] = Protocol::DFRN;
1871 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1876 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1877 $serverdata['detection-method'] = self::DETECT_HEADER;
1884 * Test if the body contains valid content
1886 * @param string $body
1889 private static function invalidBody(string $body)
1891 // Currently we only test for a HTML element.
1892 // Possibly we enhance this in the future.
1893 return !strpos($body, '>');
1897 * Update GServer entries
1899 public static function discover()
1901 // Update the server list
1902 self::discoverFederation();
1906 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1908 if ($requery_days == 0) {
1912 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1914 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
1915 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
1916 ['order' => ['RAND()']]);
1918 while ($gserver = DBA::fetch($gservers)) {
1919 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1920 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1922 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1923 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1925 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1926 self::update($fields, ['nurl' => $gserver['nurl']]);
1928 if (--$no_of_queries == 0) {
1933 DBA::close($gservers);
1937 * Discover federated servers
1939 private static function discoverFederation()
1941 $last = DI::config()->get('poco', 'last_federation_discovery');
1944 $next = $last + (24 * 60 * 60);
1946 if ($next > time()) {
1951 // Discover federated servers
1952 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1953 foreach ($protocols as $protocol) {
1954 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1955 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
1956 if (!empty($curlResult)) {
1957 $data = json_decode($curlResult, true);
1958 if (!empty($data['data']['nodes'])) {
1959 foreach ($data['data']['nodes'] as $server) {
1960 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1961 self::add('https://' . $server['host'], true);
1967 // Disvover Mastodon servers
1968 $accesstoken = DI::config()->get('system', 'instances_social_key');
1970 if (!empty($accesstoken)) {
1971 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1972 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1973 if ($curlResult->isSuccess()) {
1974 $servers = json_decode($curlResult->getBody(), true);
1976 foreach ($servers['instances'] as $server) {
1977 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1983 DI::config()->set('poco', 'last_federation_discovery', time());
1987 * Set the protocol for the given server
1989 * @param int $gsid Server id
1990 * @param int $protocol Protocol id
1994 public static function setProtocol(int $gsid, int $protocol)
2000 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2001 if (!DBA::isResult($gserver)) {
2005 $old = $gserver['protocol'];
2007 if (!is_null($old)) {
2009 The priority for the protocols is:
2011 2. DFRN via Diaspora
2017 // We don't need to change it when nothing is to be changed
2018 if ($old == $protocol) {
2022 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2023 if ($protocol == Post\DeliveryData::OSTATUS) {
2027 // If the server is marked as ActivityPub then we won't change it to anything different
2028 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2032 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2033 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2037 // Don't change it to Diaspora when it is a legacy DFRN server
2038 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2043 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2044 self::update(['protocol' => $protocol], ['id' => $gsid]);
2048 * Fetch the protocol of the given server
2050 * @param int $gsid Server id
2051 * @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2054 public static function getProtocol(int $gsid): ?int
2060 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2061 if (DBA::isResult($gserver)) {
2062 return $gserver['protocol'];
2069 * Enforces gserver table field maximum sizes to avoid "Data too long" database errors
2071 * @param array $fields
2072 * @param array $condition
2076 public static function update(array $fields, array $condition): bool
2078 $fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
2080 return DBA::update('gserver', $fields, $condition);