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;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
38 use Friendica\Protocol\Relay;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Network;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
45 * This class handles GServer related functions
52 const DT_MASTODON = 2;
54 // Methods to detect server types
56 // Non endpoint specific methods
57 const DETECT_MANUAL = 0;
58 const DETECT_HEADER = 1;
59 const DETECT_BODY = 2;
61 // Implementation specific endpoints
62 const DETECT_FRIENDIKA = 10;
63 const DETECT_FRIENDICA = 11;
64 const DETECT_STATUSNET = 12;
65 const DETECT_GNUSOCIAL = 13;
66 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
67 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
68 const DETECT_MASTODON_API = 16;
69 const DETECT_STATUS_PHP = 17; // Nextcloud
70 const DETECT_V1_CONFIG = 18;
71 const DETECT_PUMPIO = 19;
73 // Standardized endpoints
74 const DETECT_STATISTICS_JSON = 100;
75 const DETECT_NODEINFO_1 = 101;
76 const DETECT_NODEINFO_2 = 102;
79 * Check for the existance of a server and adds it in the background if not existant
82 * @param boolean $only_nodeinfo
85 public static function add(string $url, bool $only_nodeinfo = false)
87 if (self::getID($url, false)) {
91 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
95 * Get the ID for the given server URL
98 * @param boolean $no_check Don't check if the server hadn't been found
99 * @return int gserver id
101 public static function getID(string $url, bool $no_check = false)
107 $url = self::cleanURL($url);
109 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
110 if (DBA::isResult($gserver)) {
111 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
112 return $gserver['id'];
115 if ($no_check || !self::check($url)) {
119 return self::getID($url, true);
123 * Retrieves all the servers which base domain are matching the provided domain pattern
125 * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
127 * @param string $pattern
131 public static function listByDomainPattern(string $pattern): array
133 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
135 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
136 // eventual server path and keep only the server domain which we're matching against the pattern.
137 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
139 LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
140 WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
141 AND NOT `gserver`.`failed`
142 GROUP BY `gserver`.`id`";
144 $stmt = DI::dba()->p($sql, $likePattern);
146 return DI::dba()->toArray($stmt);
150 * Checks if the given server is reachable
152 * @param string $profile URL of the given profile
153 * @param string $server URL of the given server (If empty, taken from profile)
154 * @param string $network Network value that is used, when detection failed
155 * @param boolean $force Force an update.
157 * @return boolean 'true' if server seems vital
159 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
162 $contact = Contact::getByURL($profile, null, ['baseurl']);
163 if (!empty($contact['baseurl'])) {
164 $server = $contact['baseurl'];
172 return self::check($server, $network, $force);
175 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
177 // On successful contact process check again next week
179 return DateTimeFormat::utc('now +7 day');
182 $now = strtotime(DateTimeFormat::utcNow());
184 if ($created > $last_contact) {
185 $contact_time = strtotime($created);
187 $contact_time = strtotime($last_contact);
190 // If the last contact was less than 6 hours before then try again in 6 hours
191 if (($now - $contact_time) < (60 * 60 * 6)) {
192 return DateTimeFormat::utc('now +6 hour');
195 // If the last contact was less than 12 hours before then try again in 12 hours
196 if (($now - $contact_time) < (60 * 60 * 12)) {
197 return DateTimeFormat::utc('now +12 hour');
200 // If the last contact was less than 24 hours before then try tomorrow again
201 if (($now - $contact_time) < (60 * 60 * 24)) {
202 return DateTimeFormat::utc('now +1 day');
205 // If the last contact was less than a week before then try again in a week
206 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
207 return DateTimeFormat::utc('now +1 week');
210 // If the last contact was less than two weeks before then try again in two week
211 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
212 return DateTimeFormat::utc('now +2 week');
215 // If the last contact was less than a month before then try again in a month
216 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
217 return DateTimeFormat::utc('now +1 month');
220 // The system hadn't been successul contacted for more than a month, so try again in three months
221 return DateTimeFormat::utc('now +3 month');
225 * Checks the state of the given server.
227 * @param string $server_url URL of the given server
228 * @param string $network Network value that is used, when detection failed
229 * @param boolean $force Force an update.
230 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
232 * @return boolean 'true' if server seems vital
234 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
236 $server_url = self::cleanURL($server_url);
237 if ($server_url == '') {
241 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
242 if (DBA::isResult($gserver)) {
243 if ($gserver['created'] <= DBA::NULL_DATETIME) {
244 $fields = ['created' => DateTimeFormat::utcNow()];
245 $condition = ['nurl' => Strings::normaliseLink($server_url)];
246 DBA::update('gserver', $fields, $condition);
249 if (!$force && (strtotime($gserver['next_contact']) > time())) {
250 Logger::info('No update needed', ['server' => $server_url]);
251 return (!$gserver['failed']);
253 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
255 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
258 return self::detect($server_url, $network, $only_nodeinfo);
262 * Set failed server status
266 public static function setFailure(string $url)
268 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
269 if (DBA::isResult($gserver)) {
270 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
271 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
272 'next_contact' => $next_update, 'detection-method' => null],
273 ['nurl' => Strings::normaliseLink($url)]);
274 Logger::info('Set failed status for existing server', ['url' => $url]);
277 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
278 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
279 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
280 Logger::info('Set failed status for new server', ['url' => $url]);
284 * Remove unwanted content from the given URL
287 * @return string cleaned URL
289 public static function cleanURL(string $url)
291 $url = trim($url, '/');
292 $url = str_replace('/index.php', '', $url);
294 $urlparts = parse_url($url);
295 unset($urlparts['user']);
296 unset($urlparts['pass']);
297 unset($urlparts['query']);
298 unset($urlparts['fragment']);
299 return Network::unparseURL($urlparts);
303 * Return the base URL
306 * @return string base URL
308 private static function getBaseURL(string $url)
310 $urlparts = parse_url(self::cleanURL($url));
311 unset($urlparts['path']);
312 return Network::unparseURL($urlparts);
316 * Detect server data (type, protocol, version number, ...)
317 * The detected data is then updated or inserted in the gserver table.
319 * @param string $url URL of the given server
320 * @param string $network Network value that is used, when detection failed
321 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
323 * @return boolean 'true' if server could be detected
325 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
327 Logger::info('Detect server type', ['server' => $url]);
328 $serverdata = ['detection-method' => self::DETECT_MANUAL];
330 $original_url = $url;
332 // Remove URL content that is not supposed to exist for a server url
333 $url = self::cleanURL($url);
336 $baseurl = self::getBaseURL($url);
338 // If the URL missmatches, then we mark the old entry as failure
339 if ($url != $original_url) {
340 /// @todo What to do with "next_contact" here?
341 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
342 ['nurl' => Strings::normaliseLink($original_url)]);
345 // When a nodeinfo is present, we don't need to dig further
346 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
347 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
348 if ($curlResult->isTimeout()) {
349 self::setFailure($url);
353 // On a redirect follow the new host but mark the old one as failure
354 if ($curlResult->isSuccess() && !empty($curlResult->getRedirectUrl()) && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
355 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
356 if (!empty($curlResult->getRedirectUrl()) && parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
357 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
358 self::setFailure($url);
359 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
364 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
365 if ($only_nodeinfo && empty($nodeinfo)) {
366 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
367 self::setFailure($url);
371 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
372 if (empty($nodeinfo)) {
373 $nodeinfo = self::fetchStatistics($url);
376 // If that didn't work out well, we use some protocol specific endpoints
377 // For Friendica and Zot based networks we have to dive deeper to reveal more details
378 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
379 if (!empty($nodeinfo['detection-method'])) {
380 $serverdata['detection-method'] = $nodeinfo['detection-method'];
382 foreach (['registered-users', 'active_users_monthly', 'active-halfyear-users', 'local-posts'] as $field) {
383 if (!empty($nodeinfo[$field])) {
384 $serverdata[$field] = $nodeinfo[$field];
389 // Fetch the landing page, possibly it reveals some data
390 if (empty($nodeinfo['network'])) {
391 if ($baseurl == $url) {
392 $basedata = $serverdata;
394 $basedata = ['detection-method' => self::DETECT_MANUAL];
397 $curlResult = DI::httpClient()->get($baseurl, HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
398 if ($curlResult->isSuccess()) {
399 if (!empty($curlResult->getRedirectUrl()) && (parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
400 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
401 self::setFailure($url);
402 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
406 $basedata = self::analyseRootHeader($curlResult, $basedata);
407 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
410 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
411 self::setFailure($url);
415 if ($baseurl == $url) {
416 $serverdata = $basedata;
418 // When the base path doesn't seem to contain a social network we try the complete path.
419 // Most detectable system have to be installed in the root directory.
420 // We checked the base to avoid false positives.
421 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
422 if ($curlResult->isSuccess()) {
423 $urldata = self::analyseRootHeader($curlResult, $serverdata);
424 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
426 $comparebase = $basedata;
427 unset($comparebase['info']);
428 unset($comparebase['site_name']);
429 $compareurl = $urldata;
430 unset($compareurl['info']);
431 unset($compareurl['site_name']);
433 // We assume that no one will install the identical system in the root and a subfolder
434 if (!empty(array_diff($comparebase, $compareurl))) {
435 $serverdata = $urldata;
441 if (empty($nodeinfo['network']) && (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB))) {
442 $serverdata = self::detectMastodonAlikes($url, $serverdata);
445 // All following checks are done for systems that always have got a "host-meta" endpoint.
446 // With this check we don't have to waste time and ressources for dead systems.
447 // Also this hopefully prevents us from receiving abuse messages.
448 $validHostMeta = self::validHostMeta($url);
450 if (empty($serverdata['network']) && !$validHostMeta) {
451 $serverdata = self::detectFromContacts($url, $serverdata);
454 if (empty($serverdata['network']) && !$validHostMeta) {
455 self::setFailure($url);
459 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
460 $serverdata = self::detectFriendica($url, $serverdata);
463 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
464 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
465 $serverdata = self::fetchSiteinfo($url, $serverdata);
468 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
469 if (empty($serverdata['network'])) {
470 $serverdata = self::detectHubzilla($url, $serverdata);
473 if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
474 $serverdata = self::detectPeertube($url, $serverdata);
477 if (empty($serverdata['network'])) {
478 $serverdata = self::detectNextcloud($url, $serverdata);
481 if (empty($nodeinfo['network']) && empty($serverdata['network'])) {
482 $serverdata = self::detectGNUSocial($url, $serverdata);
485 if (empty($serverdata['network'])) {
486 $serverdata = self::detectPumpIO($url, $serverdata);
489 $serverdata = array_merge($nodeinfo, $serverdata);
491 $serverdata = $nodeinfo;
494 // Detect the directory type
495 $serverdata['directory-type'] = self::DT_NONE;
497 $serverdata = self::checkMastodonDirectory($url, $serverdata);
499 if ($serverdata['directory-type'] == self::DT_NONE) {
500 $serverdata = self::checkPoCo($url, $serverdata);
503 // We can't detect the network type. Possibly it is some system that we don't know yet
504 if (empty($serverdata['network'])) {
505 $serverdata['network'] = Protocol::PHANTOM;
508 // When we hadn't been able to detect the network type, we use the hint from the parameter
509 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
510 $serverdata['network'] = $network;
513 $serverdata['url'] = $url;
514 $serverdata['nurl'] = Strings::normaliseLink($url);
516 if (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
517 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
520 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
521 $serverdata = self::fetchWeeklyUsage($url, $serverdata);
524 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
526 // On an active server there has to be at least a single user
527 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
528 $serverdata['registered-users'] = 1;
529 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
530 $serverdata['registered-users'] = 0;
533 $serverdata['next_contact'] = self::getNextUpdateDate(true);
535 $serverdata['last_contact'] = DateTimeFormat::utcNow();
536 $serverdata['failed'] = false;
538 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
539 if (!DBA::isResult($gserver)) {
540 $serverdata['created'] = DateTimeFormat::utcNow();
541 $ret = DBA::insert('gserver', $serverdata);
542 $id = DBA::lastInsertId();
544 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
545 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
546 if (DBA::isResult($gserver)) {
547 $id = $gserver['id'];
551 // Count the number of known contacts from this server
552 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
553 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
554 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
555 $max_users = max($apcontacts, $contacts);
556 if ($max_users > $serverdata['registered-users']) {
557 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
558 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
561 if (empty($serverdata['active-month-users'])) {
562 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
564 Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
565 DBA::update('gserver', ['active-month-users' => $contacts], ['id' => $id]);
569 if (empty($serverdata['active-halfyear-users'])) {
570 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
572 Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
573 DBA::update('gserver', ['active-halfyear-users' => $contacts], ['id' => $id]);
578 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
579 self::discoverRelay($url);
586 * Fetch relay data from a given server url
588 * @param string $server_url address of the server
589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
591 private static function discoverRelay(string $server_url)
593 Logger::info('Discover relay data', ['server' => $server_url]);
595 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
596 if (!$curlResult->isSuccess()) {
600 $data = json_decode($curlResult->getBody(), true);
601 if (!is_array($data)) {
605 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
606 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
608 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
610 $data['subscribe'] = false;
614 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
615 if (!DBA::isResult($gserver)) {
619 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
620 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
621 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
624 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
626 if ($data['scope'] == 'tags') {
629 foreach ($data['tags'] as $tag) {
630 $tag = mb_strtolower($tag);
631 if (strlen($tag) < 100) {
636 foreach ($tags as $tag) {
637 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
641 // Create or update the relay contact
643 if (isset($data['protocols'])) {
644 if (isset($data['protocols']['diaspora'])) {
645 $fields['network'] = Protocol::DIASPORA;
647 if (isset($data['protocols']['diaspora']['receive'])) {
648 $fields['batch'] = $data['protocols']['diaspora']['receive'];
649 } elseif (is_string($data['protocols']['diaspora'])) {
650 $fields['batch'] = $data['protocols']['diaspora'];
654 if (isset($data['protocols']['dfrn'])) {
655 $fields['network'] = Protocol::DFRN;
657 if (isset($data['protocols']['dfrn']['receive'])) {
658 $fields['batch'] = $data['protocols']['dfrn']['receive'];
659 } elseif (is_string($data['protocols']['dfrn'])) {
660 $fields['batch'] = $data['protocols']['dfrn'];
664 if (isset($data['protocols']['activitypub'])) {
665 $fields['network'] = Protocol::ACTIVITYPUB;
667 if (!empty($data['protocols']['activitypub']['actor'])) {
668 $fields['url'] = $data['protocols']['activitypub']['actor'];
670 if (!empty($data['protocols']['activitypub']['receive'])) {
671 $fields['batch'] = $data['protocols']['activitypub']['receive'];
676 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
678 Relay::updateContact($gserver, $fields);
682 * Fetch server data from '/statistics.json' on the given server
684 * @param string $url URL of the given server
686 * @return array server data
688 private static function fetchStatistics(string $url)
690 $curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
691 if (!$curlResult->isSuccess()) {
695 $data = json_decode($curlResult->getBody(), true);
700 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
702 if (!empty($data['version'])) {
703 $serverdata['version'] = $data['version'];
704 // Version numbers on statistics.json are presented with additional info, e.g.:
705 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
706 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
709 if (!empty($data['name'])) {
710 $serverdata['site_name'] = $data['name'];
713 if (!empty($data['network'])) {
714 $serverdata['platform'] = strtolower($data['network']);
716 if ($serverdata['platform'] == 'diaspora') {
717 $serverdata['network'] = Protocol::DIASPORA;
718 } elseif ($serverdata['platform'] == 'friendica') {
719 $serverdata['network'] = Protocol::DFRN;
720 } elseif ($serverdata['platform'] == 'hubzilla') {
721 $serverdata['network'] = Protocol::ZOT;
722 } elseif ($serverdata['platform'] == 'redmatrix') {
723 $serverdata['network'] = Protocol::ZOT;
727 if (!empty($data['total_users'])) {
728 $serverdata['registered-users'] = max($data['total_users'], 1);
731 if (!empty($data['active_users_monthly'])) {
732 $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
735 if (!empty($data['active_users_halfyear'])) {
736 $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
739 if (!empty($data['local_posts'])) {
740 $serverdata['local-posts'] = max($data['local_posts'], 0);
743 if (!empty($data['registrations_open'])) {
744 $serverdata['register_policy'] = Register::OPEN;
746 $serverdata['register_policy'] = Register::CLOSED;
753 * Detect server type by using the nodeinfo data
755 * @param string $url address of the server
756 * @param ICanHandleHttpResponses $httpResult
758 * @return array Server data
759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
761 private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
763 if (!$httpResult->isSuccess()) {
767 $nodeinfo = json_decode($httpResult->getBody(), true);
769 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
776 foreach ($nodeinfo['links'] as $link) {
777 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
778 Logger::info('Invalid nodeinfo format', ['url' => $url]);
781 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
782 $nodeinfo1_url = $link['href'];
783 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
784 $nodeinfo2_url = $link['href'];
788 if ($nodeinfo1_url . $nodeinfo2_url == '') {
794 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
795 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
796 $server = self::parseNodeinfo2($nodeinfo2_url);
799 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
800 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
801 $server = self::parseNodeinfo1($nodeinfo1_url);
810 * @param string $nodeinfo_url address of the nodeinfo path
811 * @return array Server data
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 private static function parseNodeinfo1(string $nodeinfo_url)
816 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
817 if (!$curlResult->isSuccess()) {
821 $nodeinfo = json_decode($curlResult->getBody(), true);
823 if (!is_array($nodeinfo)) {
827 $server = ['detection-method' => self::DETECT_NODEINFO_1,
828 'register_policy' => Register::CLOSED];
830 if (!empty($nodeinfo['openRegistrations'])) {
831 $server['register_policy'] = Register::OPEN;
834 if (is_array($nodeinfo['software'])) {
835 if (!empty($nodeinfo['software']['name'])) {
836 $server['platform'] = strtolower($nodeinfo['software']['name']);
839 if (!empty($nodeinfo['software']['version'])) {
840 $server['version'] = $nodeinfo['software']['version'];
841 // Version numbers on Nodeinfo are presented with additional info, e.g.:
842 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
843 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
847 if (!empty($nodeinfo['metadata']['nodeName'])) {
848 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
851 if (!empty($nodeinfo['usage']['users']['total'])) {
852 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
855 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
856 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
859 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
860 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
863 if (!empty($nodeinfo['usage']['localPosts'])) {
864 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
867 if (!empty($nodeinfo['usage']['localComments'])) {
868 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
871 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
873 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
874 $protocols[$protocol] = true;
877 if (!empty($protocols['friendica'])) {
878 $server['network'] = Protocol::DFRN;
879 } elseif (!empty($protocols['activitypub'])) {
880 $server['network'] = Protocol::ACTIVITYPUB;
881 } elseif (!empty($protocols['diaspora'])) {
882 $server['network'] = Protocol::DIASPORA;
883 } elseif (!empty($protocols['ostatus'])) {
884 $server['network'] = Protocol::OSTATUS;
885 } elseif (!empty($protocols['gnusocial'])) {
886 $server['network'] = Protocol::OSTATUS;
887 } elseif (!empty($protocols['zot'])) {
888 $server['network'] = Protocol::ZOT;
892 if (empty($server)) {
902 * @see https://git.feneas.org/jaywink/nodeinfo2
903 * @param string $nodeinfo_url address of the nodeinfo path
904 * @return array Server data
905 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
907 private static function parseNodeinfo2(string $nodeinfo_url)
909 $curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
910 if (!$curlResult->isSuccess()) {
914 $nodeinfo = json_decode($curlResult->getBody(), true);
916 if (!is_array($nodeinfo)) {
920 $server = ['detection-method' => self::DETECT_NODEINFO_2,
921 'register_policy' => Register::CLOSED];
923 if (!empty($nodeinfo['openRegistrations'])) {
924 $server['register_policy'] = Register::OPEN;
927 if (is_array($nodeinfo['software'])) {
928 if (!empty($nodeinfo['software']['name'])) {
929 $server['platform'] = strtolower($nodeinfo['software']['name']);
932 if (!empty($nodeinfo['software']['version'])) {
933 $server['version'] = $nodeinfo['software']['version'];
934 // Version numbers on Nodeinfo are presented with additional info, e.g.:
935 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
936 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
938 // qoto advertises itself as Mastodon
939 if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
940 $server['platform'] = 'qoto';
945 if (!empty($nodeinfo['metadata']['nodeName'])) {
946 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
949 if (!empty($nodeinfo['usage']['users']['total'])) {
950 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
953 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
954 $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
957 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
958 $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
961 if (!empty($nodeinfo['usage']['localPosts'])) {
962 $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
965 if (!empty($nodeinfo['usage']['localComments'])) {
966 $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
969 if (!empty($nodeinfo['protocols'])) {
971 foreach ($nodeinfo['protocols'] as $protocol) {
972 if (is_string($protocol)) {
973 $protocols[$protocol] = true;
977 if (!empty($protocols['dfrn'])) {
978 $server['network'] = Protocol::DFRN;
979 } elseif (!empty($protocols['activitypub'])) {
980 $server['network'] = Protocol::ACTIVITYPUB;
981 } elseif (!empty($protocols['diaspora'])) {
982 $server['network'] = Protocol::DIASPORA;
983 } elseif (!empty($protocols['ostatus'])) {
984 $server['network'] = Protocol::OSTATUS;
985 } elseif (!empty($protocols['gnusocial'])) {
986 $server['network'] = Protocol::OSTATUS;
987 } elseif (!empty($protocols['zot'])) {
988 $server['network'] = Protocol::ZOT;
992 if (empty($server)) {
1000 * Fetch server information from a 'siteinfo.json' file on the given server
1002 * @param string $url URL of the given server
1003 * @param array $serverdata array with server data
1005 * @return array server data
1007 private static function fetchSiteinfo(string $url, array $serverdata)
1009 $curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
1010 if (!$curlResult->isSuccess()) {
1014 $data = json_decode($curlResult->getBody(), true);
1019 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1020 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1023 if (!empty($data['url'])) {
1024 $serverdata['platform'] = strtolower($data['platform']);
1025 $serverdata['version'] = $data['version'];
1028 if (!empty($data['plugins'])) {
1029 if (in_array('pubcrawl', $data['plugins'])) {
1030 $serverdata['network'] = Protocol::ACTIVITYPUB;
1031 } elseif (in_array('diaspora', $data['plugins'])) {
1032 $serverdata['network'] = Protocol::DIASPORA;
1033 } elseif (in_array('gnusoc', $data['plugins'])) {
1034 $serverdata['network'] = Protocol::OSTATUS;
1036 $serverdata['network'] = Protocol::ZOT;
1040 if (!empty($data['site_name'])) {
1041 $serverdata['site_name'] = $data['site_name'];
1044 if (!empty($data['channels_total'])) {
1045 $serverdata['registered-users'] = max($data['channels_total'], 1);
1048 if (!empty($data['channels_active_monthly'])) {
1049 $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1052 if (!empty($data['channels_active_halfyear'])) {
1053 $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1056 if (!empty($data['local_posts'])) {
1057 $serverdata['local-posts'] = max($data['local_posts'], 0);
1060 if (!empty($data['local_comments'])) {
1061 $serverdata['local-comments'] = max($data['local_comments'], 0);
1064 if (!empty($data['register_policy'])) {
1065 switch ($data['register_policy']) {
1066 case 'REGISTER_OPEN':
1067 $serverdata['register_policy'] = Register::OPEN;
1070 case 'REGISTER_APPROVE':
1071 $serverdata['register_policy'] = Register::APPROVE;
1074 case 'REGISTER_CLOSED':
1076 $serverdata['register_policy'] = Register::CLOSED;
1085 * Checks if the server contains a valid host meta file
1087 * @param string $url URL of the given server
1089 * @return boolean 'true' if the server seems to be vital
1091 private static function validHostMeta(string $url)
1093 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1094 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1095 if (!$curlResult->isSuccess()) {
1099 $xrd = XML::parseString($curlResult->getBody());
1100 if (!is_object($xrd)) {
1104 $elements = XML::elementToArray($xrd);
1105 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1110 foreach ($elements['xrd']['link'] as $link) {
1111 // When there is more than a single "link" element, the array looks slightly different
1112 if (!empty($link['@attributes'])) {
1113 $link = $link['@attributes'];
1116 if (empty($link['rel']) || empty($link['template'])) {
1120 if ($link['rel'] == 'lrdd') {
1121 // When the webfinger host is the same like the system host, it should be ok.
1122 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1130 * Detect the network of the given server via their known contacts
1132 * @param string $url URL of the given server
1133 * @param array $serverdata array with server data
1135 * @return array server data
1137 private static function detectNetworkViaContacts(string $url, array $serverdata)
1141 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1142 while ($apcontact = DBA::fetch($apcontacts)) {
1143 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1145 DBA::close($apcontacts);
1147 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1148 while ($pcontact = DBA::fetch($pcontacts)) {
1149 $contacts[$pcontact['nurl']] = $pcontact['url'];
1151 DBA::close($pcontacts);
1153 if (empty($contacts)) {
1158 foreach ($contacts as $contact) {
1159 $probed = Contact::getByURL($contact, true);
1160 if (!empty($probed) && !$probed['failed'] && in_array($probed['network'], Protocol::FEDERATED)) {
1161 $serverdata['network'] = $probed['network'];
1163 } elseif ((time() - $time) > 10) {
1164 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1173 * Checks if the given server does have a '/poco' endpoint.
1174 * This is used for the 'PortableContact' functionality,
1175 * which is used by both Friendica and Hubzilla.
1177 * @param string $url URL of the given server
1178 * @param array $serverdata array with server data
1180 * @return array server data
1182 private static function checkPoCo(string $url, array $serverdata)
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
1212 * @return array server data
1214 public static function checkMastodonDirectory(string $url, array $serverdata)
1216 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
1217 if (!$curlResult->isSuccess()) {
1221 $data = json_decode($curlResult->getBody(), true);
1226 if (count($data) == 1) {
1227 $serverdata['directory-type'] = self::DT_MASTODON;
1234 * Detects Peertube via their known endpoint
1236 * @param string $url URL of the given server
1237 * @param array $serverdata array with server data
1239 * @return array server data
1241 private static function detectPeertube(string $url, array $serverdata)
1243 $curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
1244 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1248 $data = json_decode($curlResult->getBody(), true);
1253 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1254 $serverdata['platform'] = 'peertube';
1255 $serverdata['version'] = $data['serverVersion'];
1256 $serverdata['network'] = Protocol::ACTIVITYPUB;
1258 if (!empty($data['instance']['name'])) {
1259 $serverdata['site_name'] = $data['instance']['name'];
1262 if (!empty($data['instance']['shortDescription'])) {
1263 $serverdata['info'] = $data['instance']['shortDescription'];
1266 if (!empty($data['signup'])) {
1267 if (!empty($data['signup']['allowed'])) {
1268 $serverdata['register_policy'] = Register::OPEN;
1272 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1273 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1281 * Detects the version number of a given server when it was a NextCloud installation
1283 * @param string $url URL of the given server
1284 * @param array $serverdata array with server data
1286 * @return array server data
1288 private static function detectNextcloud(string $url, array $serverdata)
1290 $curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
1291 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1295 $data = json_decode($curlResult->getBody(), true);
1300 if (!empty($data['version'])) {
1301 $serverdata['platform'] = 'nextcloud';
1302 $serverdata['version'] = $data['version'];
1303 $serverdata['network'] = Protocol::ACTIVITYPUB;
1305 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1306 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1313 private static function fetchWeeklyUsage(string $url, array $serverdata) {
1314 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
1315 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1319 $data = json_decode($curlResult->getBody(), true);
1325 foreach ($data as $week) {
1326 // Use only data from a full week
1327 if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1331 // Most likely the data is sorted correctly. But we better are safe than sorry
1332 if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1333 $current_week = $week;
1337 if (!empty($current_week['logins'])) {
1338 $serverdata['active-week-users'] = max($current_week['logins'], 0);
1345 * Detects the server network type from contacts of that server
1347 * @param string $url URL of the given server
1348 * @param array $serverdata array with server data
1350 * @return array server data
1352 private static function detectFromContacts(string $url, array $serverdata)
1354 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
1355 if (empty($gserver)) {
1359 $contact = Contact::selectFirst(['id'], ['uid' => 0, 'failed' => false, 'gsid' => $gserver['id']]);
1361 // Via probing we can be sure that the server is responding
1362 if (!empty($contact['id']) && Contact::updateFromProbe($contact['id'])) {
1363 $contact = Contact::selectFirst(['network', 'failed'], ['id' => $contact['id']]);
1364 if (!$contact['failed'] && in_array($contact['network'], Protocol::FEDERATED)) {
1365 $serverdata['network'] = $contact['network'];
1373 * Detects data from a given server url if it was a mastodon alike system
1375 * @param string $url URL of the given server
1376 * @param array $serverdata array with server data
1378 * @return array server data
1380 private static function detectMastodonAlikes(string $url, array $serverdata)
1382 $curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
1383 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1387 $data = json_decode($curlResult->getBody(), true);
1392 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1393 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1396 if (!empty($data['version'])) {
1397 $serverdata['platform'] = 'mastodon';
1398 $serverdata['version'] = $data['version'] ?? '';
1399 $serverdata['network'] = Protocol::ACTIVITYPUB;
1402 if (!empty($data['title'])) {
1403 $serverdata['site_name'] = $data['title'];
1406 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1407 $serverdata['platform'] = 'mastodon';
1408 $serverdata['network'] = Protocol::ACTIVITYPUB;
1411 if (!empty($data['description'])) {
1412 $serverdata['info'] = trim($data['description']);
1415 if (!empty($data['stats']['user_count'])) {
1416 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1419 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1420 $serverdata['platform'] = strtolower($matches[1]);
1421 $serverdata['version'] = $matches[2];
1424 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1425 $serverdata['platform'] = 'pleroma';
1426 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1429 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1430 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1431 $serverdata['platform'] = 'pleroma';
1438 * Detects data from typical Hubzilla endpoints
1440 * @param string $url URL of the given server
1441 * @param array $serverdata array with server data
1443 * @return array server data
1445 private static function detectHubzilla(string $url, array $serverdata)
1447 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
1448 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1452 $data = json_decode($curlResult->getBody(), true);
1453 if (empty($data) || empty($data['site'])) {
1457 if (!empty($data['site']['name'])) {
1458 $serverdata['site_name'] = $data['site']['name'];
1461 if (!empty($data['site']['platform'])) {
1462 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1463 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1464 $serverdata['network'] = Protocol::ZOT;
1467 if (!empty($data['site']['hubzilla'])) {
1468 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1469 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1470 $serverdata['network'] = Protocol::ZOT;
1473 if (!empty($data['site']['redmatrix'])) {
1474 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1475 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1476 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1477 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1480 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1481 $serverdata['network'] = Protocol::ZOT;
1485 $inviteonly = false;
1488 if (!empty($data['site']['closed'])) {
1489 $closed = self::toBoolean($data['site']['closed']);
1492 if (!empty($data['site']['private'])) {
1493 $private = self::toBoolean($data['site']['private']);
1496 if (!empty($data['site']['inviteonly'])) {
1497 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1500 if (!$closed && !$private and $inviteonly) {
1501 $serverdata['register_policy'] = Register::APPROVE;
1502 } elseif (!$closed && !$private) {
1503 $serverdata['register_policy'] = Register::OPEN;
1505 $serverdata['register_policy'] = Register::CLOSED;
1508 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1509 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1510 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1517 * Converts input value to a boolean value
1519 * @param string|integer $val
1523 private static function toBoolean($val)
1525 if (($val == 'true') || ($val == 1)) {
1527 } elseif (($val == 'false') || ($val == 0)) {
1535 * Detect if the URL belongs to a pump.io server
1537 * @param string $url URL of the given server
1538 * @param array $serverdata array with server data
1540 * @return array server data
1542 private static function detectPumpIO(string $url, array $serverdata)
1544 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json', HttpClientAccept::JSON);
1545 if (!$curlResult->isSuccess()) {
1549 $data = json_decode($curlResult->getBody(), true);
1550 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
1590 * @return array server data
1592 private static function detectGNUSocial(string $url, array $serverdata)
1594 // Test for GNU Social
1595 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
1596 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1597 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1598 $serverdata['platform'] = 'gnusocial';
1599 // Remove junk that some GNU Social servers return
1600 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1601 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1602 $serverdata['version'] = trim($serverdata['version'], '"');
1603 $serverdata['network'] = Protocol::OSTATUS;
1605 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1606 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1612 // Test for Statusnet
1613 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
1614 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1615 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1617 // Remove junk that some GNU Social servers return
1618 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1619 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1620 $serverdata['version'] = trim($serverdata['version'], '"');
1622 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1623 $serverdata['platform'] = 'pleroma';
1624 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1625 $serverdata['network'] = Protocol::ACTIVITYPUB;
1627 $serverdata['platform'] = 'statusnet';
1628 $serverdata['network'] = Protocol::OSTATUS;
1631 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1632 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1640 * Detect if the URL belongs to a Friendica server
1642 * @param string $url URL of the given server
1643 * @param array $serverdata array with server data
1645 * @return array server data
1647 private static function detectFriendica(string $url, array $serverdata)
1649 // There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
1650 // Because of this me must not use ACCEPT_JSON here.
1651 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1652 if (!$curlResult->isSuccess()) {
1653 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1655 $platform = 'Friendika';
1658 $platform = 'Friendica';
1661 if (!$curlResult->isSuccess()) {
1665 $data = json_decode($curlResult->getBody(), true);
1666 if (empty($data) || empty($data['version'])) {
1670 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1671 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1674 $serverdata['network'] = Protocol::DFRN;
1675 $serverdata['version'] = $data['version'];
1677 if (!empty($data['no_scrape_url'])) {
1678 $serverdata['noscrape'] = $data['no_scrape_url'];
1681 if (!empty($data['site_name'])) {
1682 $serverdata['site_name'] = $data['site_name'];
1685 if (!empty($data['info'])) {
1686 $serverdata['info'] = trim($data['info']);
1689 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1690 switch ($register_policy) {
1691 case 'REGISTER_OPEN':
1692 $serverdata['register_policy'] = Register::OPEN;
1695 case 'REGISTER_APPROVE':
1696 $serverdata['register_policy'] = Register::APPROVE;
1699 case 'REGISTER_CLOSED':
1700 case 'REGISTER_INVITATION':
1701 $serverdata['register_policy'] = Register::CLOSED;
1704 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1705 $serverdata['register_policy'] = Register::CLOSED;
1709 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1715 * Analyses the landing page of a given server for hints about type and system of that server
1717 * @param object $curlResult result of curl execution
1718 * @param array $serverdata array with server data
1719 * @param string $url Server URL
1721 * @return array server data
1723 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1725 if (empty($curlResult->getBody())) {
1729 // Using only body information we cannot safely detect a lot of systems.
1730 // So we define a list of platforms that we can detect safely.
1731 $valid_platforms = ['friendica', 'friendika', 'diaspora', 'mastodon', 'hubzilla', 'misskey', 'peertube', 'wordpress', 'write.as'];
1733 $doc = new DOMDocument();
1734 @$doc->loadHTML($curlResult->getBody());
1735 $xpath = new DOMXPath($doc);
1737 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1738 if (!empty($title)) {
1739 $serverdata['site_name'] = $title;
1742 $list = $xpath->query('//meta[@name]');
1744 foreach ($list as $node) {
1746 if ($node->attributes->length) {
1747 foreach ($node->attributes as $attribute) {
1748 $value = trim($attribute->value);
1749 if (empty($value)) {
1753 $attr[$attribute->name] = $value;
1756 if (empty($attr['name']) || empty($attr['content'])) {
1761 if ($attr['name'] == 'description') {
1762 $serverdata['info'] = $attr['content'];
1765 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1766 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1767 $serverdata['platform'] = strtolower($attr['content']);
1768 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1769 $serverdata['network'] = Protocol::ACTIVITYPUB;
1772 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1773 $serverdata['platform'] = strtolower($attr['content']);
1774 $version_part = explode(' ', $attr['content']);
1776 if (count($version_part) == 2) {
1777 if (in_array($version_part[0], ['WordPress'])) {
1778 $serverdata['platform'] = 'wordpress';
1779 $serverdata['version'] = $version_part[1];
1781 // We still do need a reliable test if some AP plugin is activated
1782 // By now we just check in a later process for some known contacts
1783 $serverdata['network'] = Protocol::FEED;
1785 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1786 $serverdata['detection-method'] = self::DETECT_BODY;
1789 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1790 $serverdata['platform'] = strtolower($version_part[0]);
1791 $serverdata['version'] = $version_part[1];
1792 $serverdata['network'] = Protocol::DFRN;
1798 $list = $xpath->query('//meta[@property]');
1800 foreach ($list as $node) {
1802 if ($node->attributes->length) {
1803 foreach ($node->attributes as $attribute) {
1804 $value = trim($attribute->value);
1805 if (empty($value)) {
1809 $attr[$attribute->name] = $value;
1812 if (empty($attr['property']) || empty($attr['content'])) {
1817 if ($attr['property'] == 'og:site_name') {
1818 $serverdata['site_name'] = $attr['content'];
1821 if ($attr['property'] == 'og:description') {
1822 $serverdata['info'] = $attr['content'];
1825 if ($attr['property'] == 'og:platform') {
1826 $serverdata['platform'] = strtolower($attr['content']);
1828 if (in_array($attr['content'], ['PeerTube'])) {
1829 $serverdata['network'] = Protocol::ACTIVITYPUB;
1833 if ($attr['property'] == 'generator') {
1834 $serverdata['platform'] = strtolower($attr['content']);
1836 if (in_array($attr['content'], ['hubzilla'])) {
1837 // We later check which compatible protocol modules are loaded.
1838 $serverdata['network'] = Protocol::ZOT;
1843 if (!empty($serverdata['platform']) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY]) && !in_array($serverdata['platform'], $valid_platforms)) {
1844 $serverdata['network'] = Protocol::PHANTOM;
1845 $serverdata['version'] = '';
1846 $serverdata['detection-method'] = self::DETECT_MANUAL;
1847 } elseif (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1848 $serverdata['detection-method'] = self::DETECT_BODY;
1855 * Analyses the header data of a given server for hints about type and system of that server
1857 * @param object $curlResult result of curl execution
1858 * @param array $serverdata array with server data
1860 * @return array server data
1862 private static function analyseRootHeader($curlResult, array $serverdata)
1864 if ($curlResult->getHeader('server') == 'Mastodon') {
1865 $serverdata['platform'] = 'mastodon';
1866 $serverdata['network'] = Protocol::ACTIVITYPUB;
1867 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1868 $serverdata['platform'] = 'diaspora';
1869 $serverdata['network'] = Protocol::DIASPORA;
1870 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1871 } elseif ($curlResult->inHeader('x-friendica-version')) {
1872 $serverdata['platform'] = 'friendica';
1873 $serverdata['network'] = Protocol::DFRN;
1874 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1879 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1880 $serverdata['detection-method'] = self::DETECT_HEADER;
1887 * Test if the body contains valid content
1889 * @param string $body
1892 private static function invalidBody(string $body)
1894 // Currently we only test for a HTML element.
1895 // Possibly we enhance this in the future.
1896 return !strpos($body, '>');
1900 * Update GServer entries
1902 public static function discover()
1904 // Update the server list
1905 self::discoverFederation();
1909 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1911 if ($requery_days == 0) {
1915 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1917 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
1918 ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
1919 ['order' => ['RAND()']]);
1921 while ($gserver = DBA::fetch($gservers)) {
1922 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1923 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1925 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1926 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1928 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1929 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1931 if (--$no_of_queries == 0) {
1936 DBA::close($gservers);
1940 * Discover federated servers
1942 private static function discoverFederation()
1944 $last = DI::config()->get('poco', 'last_federation_discovery');
1947 $next = $last + (24 * 60 * 60);
1949 if ($next > time()) {
1954 // Discover federated servers
1955 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1956 foreach ($protocols as $protocol) {
1957 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1958 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
1959 if (!empty($curlResult)) {
1960 $data = json_decode($curlResult, true);
1961 if (!empty($data['data']['nodes'])) {
1962 foreach ($data['data']['nodes'] as $server) {
1963 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1964 self::add('https://' . $server['host'], true);
1970 // Disvover Mastodon servers
1971 $accesstoken = DI::config()->get('system', 'instances_social_key');
1973 if (!empty($accesstoken)) {
1974 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1975 $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1976 if ($curlResult->isSuccess()) {
1977 $servers = json_decode($curlResult->getBody(), true);
1979 foreach ($servers['instances'] as $server) {
1980 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1986 DI::config()->set('poco', 'last_federation_discovery', time());
1990 * Set the protocol for the given server
1992 * @param int $gsid Server id
1993 * @param int $protocol Protocol id
1997 public static function setProtocol(int $gsid, int $protocol)
2003 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
2004 if (!DBA::isResult($gserver)) {
2008 $old = $gserver['protocol'];
2010 if (!is_null($old)) {
2012 The priority for the protocols is:
2014 2. DFRN via Diaspora
2020 // We don't need to change it when nothing is to be changed
2021 if ($old == $protocol) {
2025 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
2026 if ($protocol == Post\DeliveryData::OSTATUS) {
2030 // If the server is marked as ActivityPub then we won't change it to anything different
2031 if ($old == Post\DeliveryData::ACTIVITYPUB) {
2035 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
2036 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
2040 // Don't change it to Diaspora when it is a legacy DFRN server
2041 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2046 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2047 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
2051 * Fetch the protocol of the given server
2053 * @param int $gsid Server id
2057 public static function getProtocol(int $gsid)
2063 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2064 if (DBA::isResult($gserver)) {
2065 return $gserver['protocol'];